import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { basename, dirname, posix, resolve } from "node:path";
import assert from "node:assert/strict";

import {
  analyzeIniRuntimeBoundaries,
  createLinuxCncInterpSdk,
  planSimConfigStaging,
} from "../../../runtime/sdk/src/index.js";

function parseTsv(text, expectedHeaders = null) {
  const [headerLine, ...rows] = text.trim().split("\n");
  const headers = headerLine.split("\t");
  if (expectedHeaders) {
    assert.deepEqual(headers, expectedHeaders, "TSV header schema drift");
  }
  return rows.filter(Boolean).map((row) => {
    const values = row.split("\t");
    return Object.fromEntries(headers.map((header, index) => [header, values[index] ?? ""]));
  });
}

function verifyExpectedOutput(fixtureName, output, expectedText) {
  const expectedLines = expectedText.split("\n").filter(Boolean);

  for (const expectedLine of expectedLines) {
    if (expectedLine.startsWith("absent=")) {
      const forbidden = expectedLine.slice("absent=".length);
      assert.equal(
        output.includes(forbidden),
        false,
        `${fixtureName}: unexpected ${forbidden}`,
      );
      continue;
    }

    assert.equal(
      output.includes(expectedLine),
      true,
      `${fixtureName}: ${expectedLine}`,
    );
  }
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = resolve(__dirname, "../../..");
const workspaceRoot = resolve(rootDir, "..");
const wasmPath = resolve(rootDir, "build/wasm/core/linuxcnc_interp.wasm");
const vendorRoot = resolve(rootDir, "vendor/linuxcnc");
const linuxCncSimRoot = resolve(workspaceRoot, "linuxcnc/configs/sim");
const manifestText = readFileSync(resolve(rootDir, "tools/source-manifest.txt"), "utf8");
const nativeSummaryPath = resolve(rootDir, "build/native/sim-configs/summary.tsv");
const nativeClassSummaryPath = resolve(rootDir, "build/native/sim-configs/class-summary.tsv");
const nativePathMatrixPath = resolve(rootDir, "build/native/sim-configs/path-matrix.tsv");
const nativeSourceProofSummaryPath = resolve(rootDir, "build/native/native-source-proof-summary.tsv");
const nativeRuntimeProbeSummarySourcePath = resolve(rootDir, "build/native/native-runtime-probe-summary.tsv");
const compatibilityValidationPath = resolve(rootDir, "docs/compatibility-validation.md");
const trackedMatrixPath = resolve(rootDir, "docs/sim-configs-coverage-matrix.md");
const fullProcessBoundaryDesignPath = resolve(rootDir, "docs/full-process-boundary-design.md");
const browserInterpSmokePath = resolve(rootDir, "tests/browser/interp_smoke.html");
const buildDir = resolve(rootDir, "build/wasm/sim-configs-inventory");
const summaryPath = resolve(buildDir, "summary.tsv");
const skipSummaryPath = resolve(buildDir, "skip-summary.tsv");
const boundarySummaryPath = resolve(buildDir, "boundary-summary.tsv");
const iniBoundarySummaryPath = resolve(buildDir, "ini-boundary-summary.tsv");
const blockedDependencySummaryPath = resolve(buildDir, "blocked-dependency-summary.tsv");
const fullProcessBoundarySummaryPath = resolve(buildDir, "full-process-boundary-summary.tsv");
const userMProcessBoundarySummaryPath = resolve(buildDir, "user-m-process-boundary-summary.tsv");
const userMProcessStateTargetsPath = resolve(buildDir, "user-m-process-state-targets.tsv");
const userMProcessTransitionPlanPath = resolve(buildDir, "user-m-process-transition-plan.tsv");
const userMProcessNativeStateAlignmentPath = resolve(buildDir, "user-m-process-native-state-alignment.tsv");
const userMProcessNativeTransitionAlignmentPath = resolve(buildDir, "user-m-process-native-transition-alignment.tsv");
const userMProcessNativeRuntimeStatePlanPath = resolve(buildDir, "user-m-process-native-runtime-state-plan.tsv");
const userMProcessNativeRuntimeReadinessPath = resolve(buildDir, "user-m-process-native-runtime-readiness.tsv");
const userMProcessNativeRuntimeProbeGatePath = resolve(buildDir, "user-m-process-native-runtime-probe-gate.tsv");
const toolDbProcessBoundarySummaryPath = resolve(buildDir, "tool-db-process-boundary-summary.tsv");
const toolDbProcessProtocolGatesPath = resolve(buildDir, "tool-db-process-protocol-gates.tsv");
const toolDbProcessTransactionPlanPath = resolve(buildDir, "tool-db-process-transaction-plan.tsv");
const toolDbProcessNativeProtocolAlignmentPath = resolve(buildDir, "tool-db-process-native-protocol-alignment.tsv");
const toolDbProcessNativeRuntimeReadinessPath = resolve(buildDir, "tool-db-process-native-runtime-readiness.tsv");
const toolDbProcessNativeRuntimeProbeGatePath = resolve(buildDir, "tool-db-process-native-runtime-probe-gate.tsv");
const pythonRemapBoundarySummaryPath = resolve(buildDir, "python-remap-boundary-summary.tsv");
const pythonRemapRuntimeGatesPath = resolve(buildDir, "python-remap-runtime-gates.tsv");
const pythonRemapNativeRuntimeAlignmentPath = resolve(buildDir, "python-remap-native-runtime-alignment.tsv");
const pythonRemapNativeRuntimeReadinessPath = resolve(buildDir, "python-remap-native-runtime-readiness.tsv");
const pythonRemapNativeRuntimeProbeGatePath = resolve(buildDir, "python-remap-native-runtime-probe-gate.tsv");
const pythonRemapNativeRuntimeStatePlanPath = resolve(buildDir, "python-remap-native-runtime-state-plan.tsv");
const pythonRemapNativeRuntimeFixturePlanPath = resolve(buildDir, "python-remap-native-runtime-fixture-plan.tsv");
const pythonRemapFamilySummaryPath = resolve(buildDir, "python-remap-family-summary.tsv");
const pythonRemapRuntimeContractPath = resolve(buildDir, "python-remap-runtime-contract.tsv");
const runtimeBoundaryContractSummaryPath = resolve(buildDir, "runtime-boundary-contract-summary.tsv");
const boundaryPhaseCompletionSummaryPath = resolve(buildDir, "boundary-phase-completion-summary.tsv");
const nextBoundaryWorklistPath = resolve(buildDir, "next-boundary-worklist.tsv");
const boundaryProofGatesPath = resolve(buildDir, "boundary-proof-gates.tsv");
const nativeProofAlignmentSummaryPath = resolve(buildDir, "native-proof-alignment-summary.tsv");
const nativeRuntimeProbeSummaryPath = resolve(buildDir, "native-runtime-probe-summary.tsv");
const runtimeBoundaryNativeAlignmentSummaryPath = resolve(buildDir, "runtime-boundary-native-alignment-summary.tsv");
const runtimeProbeGateAlignmentPath = resolve(buildDir, "runtime-probe-gate-alignment.tsv");
const nativeRuntimeProbeExecutionPlanPath = resolve(buildDir, "native-runtime-probe-execution-plan.tsv");
const nativeRuntimeProbePassEvidenceContractPath = resolve(buildDir, "native-runtime-probe-pass-evidence-contract.tsv");
const blockedRuntimePromotionLockPath = resolve(buildDir, "blocked-runtime-promotion-lock.tsv");
const runtimeBoundaryPromotionReadinessPath = resolve(buildDir, "runtime-boundary-promotion-readiness.tsv");
const runtimeBoundaryPromotionBlockersPath = resolve(buildDir, "runtime-boundary-promotion-blockers.tsv");
const runtimeBoundaryPostNativePassGatesPath = resolve(buildDir, "runtime-boundary-post-native-pass-gates.tsv");
const runtimeBoundaryHostPreflightPath = resolve(buildDir, "runtime-boundary-host-preflight.tsv");
const runtimeBoundaryHostRequirementSummaryPath = resolve(buildDir, "runtime-boundary-host-requirement-summary.tsv");
const runtimeBoundaryHostUnblockPlanPath = resolve(buildDir, "runtime-boundary-host-unblock-plan.tsv");
const runtimeBoundaryFamilyHostReadinessPath = resolve(buildDir, "runtime-boundary-family-host-readiness.tsv");
const runtimeBoundaryHostReadinessRollupPath = resolve(buildDir, "runtime-boundary-host-readiness-rollup.tsv");
const runtimeBoundaryOptInProbeDispatchPlanPath = resolve(buildDir, "runtime-boundary-opt-in-probe-dispatch-plan.tsv");
const runtimeBoundaryOptInProbeDispatchRollupPath = resolve(buildDir, "runtime-boundary-opt-in-probe-dispatch-rollup.tsv");
const runtimeBoundaryOptInProbeSkipEvidenceContractPath = resolve(buildDir, "runtime-boundary-opt-in-probe-skip-evidence-contract.tsv");
const runtimeBoundaryOptInProbeSkipEvidenceRollupPath = resolve(buildDir, "runtime-boundary-opt-in-probe-skip-evidence-rollup.tsv");
const runtimeBoundaryNativeEvidenceAcceptanceGatePath = resolve(buildDir, "runtime-boundary-native-evidence-acceptance-gate.tsv");
const nextBoundaryRecommendationsPath = resolve(buildDir, "next-boundary-recommendations.tsv");
const generatedSimConfigInventoryArtifactPaths = [
  summaryPath,
  skipSummaryPath,
  boundarySummaryPath,
  iniBoundarySummaryPath,
  blockedDependencySummaryPath,
  fullProcessBoundarySummaryPath,
  userMProcessBoundarySummaryPath,
  userMProcessStateTargetsPath,
  userMProcessTransitionPlanPath,
  userMProcessNativeStateAlignmentPath,
  userMProcessNativeTransitionAlignmentPath,
  userMProcessNativeRuntimeStatePlanPath,
  userMProcessNativeRuntimeReadinessPath,
  userMProcessNativeRuntimeProbeGatePath,
  toolDbProcessBoundarySummaryPath,
  toolDbProcessProtocolGatesPath,
  toolDbProcessTransactionPlanPath,
  toolDbProcessNativeProtocolAlignmentPath,
  toolDbProcessNativeRuntimeReadinessPath,
  toolDbProcessNativeRuntimeProbeGatePath,
  pythonRemapBoundarySummaryPath,
  pythonRemapRuntimeGatesPath,
  pythonRemapNativeRuntimeAlignmentPath,
  pythonRemapNativeRuntimeReadinessPath,
  pythonRemapNativeRuntimeProbeGatePath,
  pythonRemapNativeRuntimeStatePlanPath,
  pythonRemapNativeRuntimeFixturePlanPath,
  pythonRemapFamilySummaryPath,
  pythonRemapRuntimeContractPath,
  runtimeBoundaryContractSummaryPath,
  boundaryPhaseCompletionSummaryPath,
  nextBoundaryWorklistPath,
  boundaryProofGatesPath,
  nativeProofAlignmentSummaryPath,
  nativeRuntimeProbeSummaryPath,
  runtimeBoundaryNativeAlignmentSummaryPath,
  runtimeProbeGateAlignmentPath,
  nativeRuntimeProbeExecutionPlanPath,
  nativeRuntimeProbePassEvidenceContractPath,
  blockedRuntimePromotionLockPath,
  runtimeBoundaryPromotionReadinessPath,
  runtimeBoundaryPromotionBlockersPath,
  runtimeBoundaryPostNativePassGatesPath,
  runtimeBoundaryHostPreflightPath,
  runtimeBoundaryHostRequirementSummaryPath,
  runtimeBoundaryHostUnblockPlanPath,
  runtimeBoundaryFamilyHostReadinessPath,
  runtimeBoundaryHostReadinessRollupPath,
  runtimeBoundaryOptInProbeDispatchPlanPath,
  runtimeBoundaryOptInProbeDispatchRollupPath,
  runtimeBoundaryOptInProbeSkipEvidenceContractPath,
  runtimeBoundaryOptInProbeSkipEvidenceRollupPath,
  runtimeBoundaryNativeEvidenceAcceptanceGatePath,
  nextBoundaryRecommendationsPath,
];

mkdirSync(buildDir, { recursive: true });

const interp = await createLinuxCncInterpSdk({
  wasmBinary: readFileSync(wasmPath),
  print() {},
  printErr(message) {
    console.error(message);
  },
});

function simMachine(machineRel, iniFile, programFile, nativeToolTableRel) {
  const iniText = readFileSync(
    resolve(vendorRoot, `configs/sim/${machineRel}/${iniFile}`),
    "utf8",
  );
  const expectedWasmDir = `/work/sim-inventory/${machineRel}`;
  const plan = planSimConfigStaging({
    manifestText,
    machineRel,
    iniFile,
    iniText,
    programFile,
    wasmDir: expectedWasmDir,
  });
  assertSimConfigStagingPlan(machineRel, plan, expectedWasmDir);
  const machine = {
    ...plan,
    files: plan.files.map((file) => ({
      path: file.path,
      text: readFileSync(resolve(vendorRoot, file.sourceRel), "utf8"),
      executable:
        file.executable || (statSync(resolve(vendorRoot, file.sourceRel)).mode & 0o111) !== 0,
    })),
  };
  return withNativeToolTableFallback(machine, iniText, nativeToolTableRel);
}

function assertSimConfigStagingPlan(machineRel, plan, expectedWasmDir) {
  assert.equal(plan.wasmDir, expectedWasmDir, `${machineRel}: sim staging root drift`);
  assert.ok(
    plan.iniPath.startsWith(`${expectedWasmDir}/`),
    `${machineRel}: sim INI staging path drift`,
  );
  if (plan.programPath !== null) {
    assert.ok(
      plan.programPath.startsWith(`${expectedWasmDir}/`),
      `${machineRel}: sim program staging path drift`,
    );
  }

  const paths = [];
  for (const file of plan.files) {
    assert.equal(file.path, file.wasmPath, `${file.sourceRel}: path/wasmPath drift`);
    assert.ok(
      file.wasmPath.startsWith(`${expectedWasmDir}/`),
      `${file.sourceRel}: sim file staging root drift`,
    );
    assert.ok(
      file.sourceRel.startsWith("configs/sim/"),
      `${file.sourceRel}: sim source root drift`,
    );
    paths.push(file.wasmPath);
  }

  assert.deepEqual(
    paths.filter((path, index) => paths.indexOf(path) !== index),
    [],
    `${machineRel}: duplicate sim staging paths`,
  );
}

function firstIniValue(iniText, section, key) {
  let activeSection = "";
  for (const rawLine of iniText.split("\n")) {
    const sectionMatch = rawLine.match(/^\s*\[([^\]]+)\]/);
    if (sectionMatch) {
      activeSection = sectionMatch[1].trim().toUpperCase();
      continue;
    }

    if (activeSection !== section.toUpperCase()) {
      continue;
    }

    const line = rawLine.replace(/[;#].*$/, "");
    const equals = line.indexOf("=");
    if (equals === -1) {
      continue;
    }
    const name = line.slice(0, equals).trim().toUpperCase();
    if (name === key.toUpperCase()) {
      return line.slice(equals + 1).trim();
    }
  }
  return "";
}

function withNativeToolTableFallback(machine, iniText, nativeToolTableRel) {
  const toolTable = firstIniValue(iniText, "EMCIO", "TOOL_TABLE");
  if (!toolTable || toolTable.startsWith("/") || !nativeToolTableRel) {
    return machine;
  }

  const targetPath = `${machine.wasmDir}/${posix.normalize(toolTable)}`;
  if (machine.files.some((file) => file.path === targetPath)) {
    return machine;
  }

  const sourceRel = `configs/sim/${nativeToolTableRel}`;
  if (!vendoredConfigPathExists(sourceRel)) {
    return machine;
  }

  return {
    ...machine,
    files: [
      ...machine.files,
      {
        path: targetPath,
        text: readFileSync(resolve(vendorRoot, sourceRel), "utf8"),
        executable: false,
      },
    ],
  };
}

function vendoredConfigPathExists(relPath) {
  try {
    statSync(resolve(vendorRoot, relPath));
    return true;
  } catch {
    return false;
  }
}

function sortedPaths(records) {
  return records.map((record) => record.path).sort();
}

function verifyUniquePaths(label, records) {
  const counts = new Map();
  for (const record of records) {
    counts.set(record.path, (counts.get(record.path) ?? 0) + 1);
  }
  const duplicates = [...counts.entries()]
    .filter(([, count]) => count > 1)
    .map(([path, count]) => `${path}:${count}`);
  assert.deepEqual(duplicates, [], `${label}: duplicate paths are not allowed`);
}

function parseTrackedMatrix(markdownText) {
  return markdownText
    .split("\n")
    .map((line) => {
      const match = line.match(
        /^\| `([^`]+\.ngc)` \| `([^`]+)` \| `([^`]+)` \| `([^`]+)` \| `([^`]+)` \| `([^`]+)` \| `([^`]+)` \| `([^`]+)` \| `([^`]+)` \| (.+) \|$/,
      );
      if (!match) {
        return null;
      }
      return {
        path: match[1],
        family: match[2],
        class: match[3],
        nativeStatus: match[4],
        expectedFailure: match[5],
        layer3: match[6],
        layer4Node: match[7],
        layer4Browser: match[8],
        blocked: match[9],
        notes: match[10].trim(),
      };
    })
    .filter(Boolean);
}

function parseTrackedSummaryTable(markdownText, sectionTitle, keyName) {
  const lines = markdownText.split("\n");
  const sectionIndex = lines.findIndex((line) => line.trim() === `## ${sectionTitle}`);
  assert.notEqual(sectionIndex, -1, `tracked matrix missing ${sectionTitle}`);
  const rows = [];

  for (let index = sectionIndex + 1; index < lines.length; index += 1) {
    const line = lines[index].trim();
    if (line.startsWith("## ") && rows.length > 0) {
      break;
    }
    const match = line.match(/^\| `([^`]+)` \| `([0-9]+)` \|$/);
    if (match) {
      rows.push({ [keyName]: match[1], count: match[2] });
    }
  }

  assert.notEqual(rows.length, 0, `tracked matrix ${sectionTitle} is empty`);
  return rows;
}

function numberFromTrackedBaseline(markdownText, pattern, label) {
  const match = markdownText.match(pattern);
  assert.ok(match, `tracked matrix baseline missing ${label}`);
  return Number(match[1]);
}

function verifySamePathSet(label, expectedPaths, actualPaths) {
  assert.deepEqual(
    actualPaths,
    expectedPaths,
    `${label}: path set must match native summary.tsv`,
  );
}

function verifyTrackedMatrixFields(trackedRecords, pathMatrixByPath) {
  const trackedByPath = new Map(trackedRecords.map((record) => [record.path, record]));

  for (const [path, generated] of pathMatrixByPath) {
    const tracked = trackedByPath.get(path);
    assert.ok(tracked, `tracked matrix missing generated path: ${path}`);
    assert.ok(
      generated.runtime_family === tracked.family ||
        generated.runtime_family.startsWith(`${tracked.family}/`),
      `${path}: tracked family ${tracked.family} does not cover runtime family ${generated.runtime_family}`,
    );
    assert.equal(tracked.class, generated.class, `${path}: tracked class drift`);
    assert.equal(tracked.nativeStatus, generated.status, `${path}: tracked native status drift`);
    assert.equal(
      tracked.expectedFailure,
      generated.expected_failure,
      `${path}: tracked expected failure drift`,
    );
    assert.equal(tracked.blocked, generated.blocked, `${path}: tracked blocked kind drift`);
  }
}

function verifyPathMatrixFields(nativeRecords, pathMatrixByPath) {
  for (const nativeRecord of nativeRecords) {
    const generated = pathMatrixByPath.get(nativeRecord.path);
    assert.ok(generated, `path matrix missing native path ${nativeRecord.path}`);
    assert.equal(generated.class, nativeRecord.class, `${nativeRecord.path}: class drift`);
    assert.equal(generated.status, nativeRecord.status, `${nativeRecord.path}: status drift`);
    assert.equal(
      generated.expected_failure,
      nativeRecord.expected_failure || "-",
      `${nativeRecord.path}: expected failure drift`,
    );
    assert.equal(generated.ini, nativeRecord.ini, `${nativeRecord.path}: INI drift`);
    assert.equal(generated.tbl, nativeRecord.tbl, `${nativeRecord.path}: tool table drift`);
    assert.equal(
      generated.runtime_family,
      posix.dirname(nativeRecord.path),
      `${nativeRecord.path}: runtime family drift`,
    );
  }
}

function verifyClassesAndStatuses(records) {
  const allowedClasses = new Set(["main", "macro_load", "remap_subroutine"]);
  const allowedStatuses = new Set(["PASS", "FAIL", "TIMEOUT"]);

  for (const record of records) {
    const status = record.status ?? record.nativeStatus;
    assert.ok(allowedClasses.has(record.class), `${record.path}: unknown class ${record.class}`);
    assert.ok(allowedStatuses.has(status), `${record.path}: unknown native status ${status}`);
  }
}

function verifyBlockedKinds(records) {
  const allowedBlockedKinds = new Set([
    "-",
    "ASSET-ONLY",
    "L4-TOOL-DB",
    "L4-USER-M-PROCESS",
    "L4-PYTHON-REMAP",
    "UPSTREAM-DEMO",
  ]);
  for (const record of records) {
    assert.ok(
      allowedBlockedKinds.has(record.blocked),
      `${record.path}: unknown blocked kind ${record.blocked}`,
    );
  }
}

function verifyLayerMarkers(records) {
  const allowedLayer3Markers = new Set([
    "-",
    "5AX-EXEC",
    "SIM-BRIDGE,5AX-EXEC",
    "SIM-EOFF",
    "SIM-FOAM",
    "SIM-XYZC",
  ]);
  const allowedLayer4NodeMarkers = new Set(["-", "INV", "N/A", "REP"]);
  const allowedLayer4BrowserMarkers = new Set(["-", "N/A", "REP"]);

  for (const record of records) {
    assert.ok(
      allowedLayer3Markers.has(record.layer3),
      `${record.path}: unknown Layer 3 marker ${record.layer3}`,
    );
    assert.ok(
      allowedLayer4NodeMarkers.has(record.layer4Node),
      `${record.path}: unknown Layer 4 Node marker ${record.layer4Node}`,
    );
    assert.ok(
      allowedLayer4BrowserMarkers.has(record.layer4Browser),
      `${record.path}: unknown Layer 4 Browser marker ${record.layer4Browser}`,
    );
    if (record.layer4Browser === "REP") {
      assert.equal(record.layer4Node, "REP", `${record.path}: browser REP must also be Node REP`);
    }
    if (record.layer4Node === "N/A" || record.layer4Browser === "N/A") {
      assert.equal(record.class, "remap_subroutine", `${record.path}: N/A marker requires subroutine class`);
      assert.equal(record.blocked, "ASSET-ONLY", `${record.path}: N/A marker requires ASSET-ONLY`);
    }
    if (record.layer4Node === "REP" || record.layer4Node === "INV" || record.layer4Browser === "REP") {
      assert.equal(record.blocked, "-", `${record.path}: covered row must not be blocked`);
    }
  }
}

function verifyTrackedMatrixNotes(records) {
  for (const record of records) {
    assert.notEqual(record.notes, "", `${record.path}: tracked matrix note is required`);
  }
}

function verifyTrackedSummaryTables(trackedRecords, classSummaryRows, familySummaryRows) {
  const classCounts = new Map();
  const familyCounts = new Map();

  for (const record of trackedRecords) {
    classCounts.set(record.class, (classCounts.get(record.class) ?? 0) + 1);
    familyCounts.set(record.family, (familyCounts.get(record.family) ?? 0) + 1);
  }

  assert.deepEqual(
    classSummaryRows.map((row) => `${row.class}\t${row.count}`).sort(),
    [...classCounts.entries()].map(([className, count]) => `${className}\t${count}`).sort(),
    "tracked matrix class summary must match program matrix",
  );
  assert.deepEqual(
    familySummaryRows.map((row) => `${row.family}\t${row.count}`).sort(),
    [...familyCounts.entries()].map(([family, count]) => `${family}\t${count}`).sort(),
    "tracked matrix family summary must match program matrix",
  );
}

function verifyTrackedBaselineText(markdownText, nativeRecords, inventory, skipReasonCounts) {
  const nativePass = nativeRecords.filter((record) => record.status === "PASS").length;
  const nativeExpectedFail = nativeRecords.filter((record) => record.expected_failure).length;
  const nativeUnexpectedFail = nativeRecords.filter(
    (record) => record.status !== "PASS" && !record.expected_failure,
  ).length;

  assert.equal(
    numberFromTrackedBaseline(markdownText, /- Total records: `([0-9]+)`/, "total records"),
    nativeRecords.length,
    "tracked matrix total records drift",
  );
  assert.equal(
    numberFromTrackedBaseline(markdownText, /Native result: `pass ([0-9]+)`/, "native pass"),
    nativePass,
    "tracked matrix native pass drift",
  );
  assert.equal(
    numberFromTrackedBaseline(markdownText, /`expected_fail ([0-9]+)`/, "native expected_fail"),
    nativeExpectedFail,
    "tracked matrix native expected_fail drift",
  );
  assert.equal(
    numberFromTrackedBaseline(markdownText, /`unexpected_fail ([0-9]+)`/, "native unexpected_fail"),
    nativeUnexpectedFail,
    "tracked matrix native unexpected_fail drift",
  );
  assert.equal(
    numberFromTrackedBaseline(markdownText, /Current Node inventory: `executed ([0-9]+)`/, "Node executed"),
    inventory.executed,
    "tracked matrix Node executed drift",
  );
  assert.equal(
    numberFromTrackedBaseline(markdownText, /`passed ([0-9]+)`/, "Node passed"),
    inventory.passed,
    "tracked matrix Node passed drift",
  );
  assert.equal(
    numberFromTrackedBaseline(markdownText, /`skipped ([0-9]+)`/, "Node skipped"),
    inventory.skipped,
    "tracked matrix Node skipped drift",
  );
  assert.equal(
    numberFromTrackedBaseline(markdownText, /`unexpected_fail ([0-9]+)`/, "Node unexpected_fail"),
    inventory.unexpectedFail,
    "tracked matrix Node unexpected_fail drift",
  );

  for (const [reason, count] of skipReasonCounts) {
    const escapedReason = reason.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    assert.equal(
      numberFromTrackedBaseline(
        markdownText,
        new RegExp(`${escapedReason} ([0-9]+)`),
        `Node skip ${reason}`,
      ),
      count,
      `tracked matrix Node skip count drift for ${reason}`,
    );
  }
}

function verifyRequiredClassRepresentatives(records) {
  const byPath = new Map(records.map((record) => [record.path, record]));
  const requiredBrowserReps = [
    "axis/external_offsets/circles.ngc",
    "axis/foam/foam.ngc",
    "axis/geometry/xyzc.ngc",
    "axis/gladevcp/probe.ngc",
    "axis/vismach/5axis/bridgemill/5axisgui.ngc",
    "axis/vismach/5axis/table-dual-rotary/demos/xyzab-tdr-demo.ngc",
    "axis/vismach/5axis/table-rotary-tilting/demos/xyzac_switchkins.ngc",
    "axis/vismach/melfa-sim/example.ngc",
    "axis/vismach/puma/puma_cube.ngc",
    "woodpecker/on_abort.ngc",
  ];
  const requiredPythonRemapBlocked = [
    "axis/laser/raster_test.ngc",
    "axis/vismach/5axis/table-rotary_spindle-rotary-nutating/demos/circular_pocket.ngc",
    "gmoccapy/macros/on_abort.ngc",
  ];
  const requiredFullProcessBlocked = new Map([
    ["axis/db_demo/base.ngc", "L4-TOOL-DB"],
    ["axis/vismach/millturn/example.ngc", "L4-USER-M-PROCESS"],
  ]);

  for (const path of requiredBrowserReps) {
    const record = byPath.get(path);
    assert.ok(record, `${path}: required browser representative missing`);
    assert.equal(record.layer4Node, "REP", `${path}: required Node representative marker`);
    assert.equal(record.layer4Browser, "REP", `${path}: required browser representative marker`);
    assert.equal(record.blocked, "-", `${path}: browser representative must not be blocked`);
  }

  for (const path of requiredPythonRemapBlocked) {
    const record = byPath.get(path);
    assert.ok(record, `${path}: required Python-remap blocked row missing`);
    assert.equal(record.layer4Node, "-", `${path}: Python-remap blocked row is not Node REP`);
    assert.equal(record.layer4Browser, "-", `${path}: Python-remap blocked row is not browser REP`);
    assert.equal(record.blocked, "L4-PYTHON-REMAP", `${path}: Python-remap blocked kind drift`);
  }

  for (const [path, blocked] of requiredFullProcessBlocked) {
    const record = byPath.get(path);
    assert.ok(record, `${path}: required full-process blocked row missing`);
    assert.equal(record.layer4Node, "-", `${path}: full-process blocked row is not Node REP`);
    assert.equal(record.layer4Browser, "-", `${path}: full-process blocked row is not browser REP`);
    assert.equal(record.blocked, blocked, `${path}: full-process blocked kind drift`);
  }
}

function verifyNativeExpectedFailures(records) {
  const allowedExpectedFailures = new Set([
    "ini-axis-mask-UV",
    "ini-axis-mask-W",
    "user-m-code-M110",
    "user-m-code-M111",
    "upstream-demo-missing-motion-gcode",
  ]);

  for (const record of records) {
    if (record.status === "PASS") {
      assert.equal(record.expected_failure, "", `${record.path}: PASS row has expected failure`);
      continue;
    }

    assert.ok(
      allowedExpectedFailures.has(record.expected_failure),
      `${record.path}: unknown native expected failure ${record.expected_failure}`,
    );
  }
}

function verifyMatrixExpectedFailures(records) {
  const allowedExpectedFailures = new Set([
    "-",
    "ini-axis-mask-UV",
    "ini-axis-mask-W",
    "user-m-code-M110",
    "user-m-code-M111",
    "upstream-demo-missing-motion-gcode",
  ]);

  for (const record of records) {
    const status = record.status ?? record.nativeStatus;
    const expectedFailure = record.expected_failure ?? record.expectedFailure;
    assert.ok(
      allowedExpectedFailures.has(expectedFailure),
      `${record.path}: unknown matrix expected failure ${expectedFailure}`,
    );
    if (status === "PASS") {
      assert.equal(expectedFailure, "-", `${record.path}: PASS row has expected failure`);
    } else {
      assert.notEqual(expectedFailure, "-", `${record.path}: non-PASS row lacks expected failure`);
    }
  }
}

function classSummaryRowsFromNativeRecords(records) {
  const counts = new Map();

  function increment(className, status, expectedFailure) {
    const key = [className, status, expectedFailure].join("\t");
    counts.set(key, (counts.get(key) ?? 0) + 1);
  }

  for (const record of records) {
    increment(record.class, "ALL", "-");
    increment(record.class, record.status, "-");
    if (record.expected_failure) {
      increment(record.class, "EXPECTED_FAIL", record.expected_failure);
    }
  }

  return [...counts.entries()]
    .map(([key, count]) => `${key}\t${count}`)
    .sort();
}

function classSummaryRowsFromGenerated(records) {
  return records
    .map((record) =>
      [
        record.class,
        record.status,
        record.expected_failure || "-",
        record.count,
      ].join("\t"),
    )
    .sort();
}

function verifyClassSummaryRows(records) {
  const allowedClasses = new Set(["main", "macro_load", "remap_subroutine"]);
  const allowedStatuses = new Set(["ALL", "EXPECTED_FAIL", "PASS", "FAIL", "TIMEOUT"]);
  const allowedExpectedFailures = new Set([
    "-",
    "ini-axis-mask-UV",
    "ini-axis-mask-W",
    "user-m-code-M110",
    "user-m-code-M111",
    "upstream-demo-missing-motion-gcode",
  ]);

  for (const record of records) {
    assert.ok(allowedClasses.has(record.class), `${record.class}: unknown class-summary class`);
    assert.ok(
      allowedStatuses.has(record.status),
      `${record.class}: unknown class-summary status ${record.status}`,
    );
    assert.ok(
      allowedExpectedFailures.has(record.expected_failure),
      `${record.class}: unknown class-summary expected failure ${record.expected_failure}`,
    );
    assert.ok(
      /^[1-9][0-9]*$/.test(record.count),
      `${record.class}/${record.status}: invalid class-summary count ${record.count}`,
    );

    if (record.status === "EXPECTED_FAIL") {
      assert.notEqual(
        record.expected_failure,
        "-",
        `${record.class}: EXPECTED_FAIL row lacks expected failure`,
      );
    } else {
      assert.equal(
        record.expected_failure,
        "-",
        `${record.class}/${record.status}: non-EXPECTED_FAIL row has expected failure`,
      );
    }
  }
}

function blockedKind(record, pathMatrixByPath) {
  const generatedBlocked = pathMatrixByPath.get(record.path)?.blocked ?? "-";
  if (generatedBlocked !== "-") {
    return generatedBlocked;
  }
  if (record.class !== "main") {
    return "NON_MAIN_CLASS";
  }
  return "";
}

function missingVendoredConfig(record) {
  const iniRel = `configs/sim/${record.ini}`;
  if (!vendoredConfigPathExists(iniRel)) {
    return iniRel;
  }
  return "";
}

function executionTextsForBoundary(record) {
  const rels = [record.path];
  if (record.path === "axis/external_offsets/opa_demo.ngc") {
    rels.push("axis/external_offsets/circles.ngc");
  }
  if (record.path === "axis/vismach/millturn/example.ngc") {
    rels.push(
      "axis/vismach/millturn/remap_subs/428remap.ngc",
      "axis/vismach/millturn/remap_subs/429remap.ngc",
    );
  }
  return rels
    .filter((rel) => vendoredConfigPathExists(`configs/sim/${rel}`))
    .map((rel) => readFileSync(resolve(vendorRoot, `configs/sim/${rel}`), "utf8"));
}

function runtimeBoundaryForRecord(record) {
  const missingVendoredRel = missingVendoredConfig(record);
  if (missingVendoredRel) {
    return {
      available: false,
      missingVendoredRel,
      boundary: null,
    };
  }

  const machineRel = posix.dirname(record.ini);
  const iniFile = basename(record.ini);
  const iniRel = `configs/sim/${machineRel}/${iniFile}`;
  if (!vendoredConfigPathExists(iniRel)) {
    return {
      available: false,
      missingVendoredRel: iniRel,
      boundary: null,
    };
  }

  return {
    available: true,
    missingVendoredRel: "",
    boundary: analyzeIniRuntimeBoundaries({
      manifestText,
      sourceRootRel: `configs/sim/${machineRel}`,
      sourceSearchRootRel: "configs/sim",
      iniFile,
      iniText: readFileSync(resolve(vendorRoot, iniRel), "utf8"),
      executionTexts: executionTextsForBoundary(record),
    }),
  };
}

function verifyRuntimeBoundaryPolicy(nativeRecords, pathMatrixByPath) {
  for (const record of nativeRecords) {
    const boundaryReport = runtimeBoundaryForRecord(record);
    if (!boundaryReport.available) {
      continue;
    }

    const boundary = boundaryReport.boundary;
    const matrixBlocked = pathMatrixByPath.get(record.path)?.blocked ?? "-";

    if (matrixBlocked === "ASSET-ONLY") {
      continue;
    }

    if (boundary.recommendedBlockedKind !== "-") {
      assert.equal(
        matrixBlocked,
        boundary.recommendedBlockedKind,
        `${record.path}: runtime-boundary policy drift`,
      );
    }
    if (matrixBlocked === "L4-TOOL-DB") {
      assert.equal(
        boundary.toolDatabaseProgram !== "",
        true,
        `${record.path}: L4-TOOL-DB row must declare DB_PROGRAM`,
      );
    }
    if (matrixBlocked === "L4-USER-M-PROCESS") {
      assert.equal(
        boundary.userMRuntime.requiresExternalProcess,
        true,
        `${record.path}: L4-USER-M-PROCESS row must execute unstaged user-M process`,
      );
    }
  }
}

function listValue(values) {
  return values.length > 0 ? values.join(",") : "-";
}

function flagValue(value) {
  return value ? "1" : "0";
}

function tsvValue(value) {
  const text = String(value ?? "-").replace(/\s+/g, " ").trim();
  return text || "-";
}

function sourceConfigPathExists(relPath) {
  try {
    statSync(resolve(linuxCncSimRoot, relPath));
    return true;
  } catch {
    return false;
  }
}

function linuxCncSourcePathExists(relPath) {
  try {
    statSync(resolve(workspaceRoot, "linuxcnc", relPath));
    return true;
  } catch {
    return false;
  }
}

function verifyLinuxCncOwnerPaths(label, linuxCncOwner) {
  assert.notEqual(linuxCncOwner, "-", `${label}: LinuxCNC owner is required`);
  for (const ownerPath of linuxCncOwner.split(",").filter(Boolean)) {
    if (ownerPath.includes("*")) {
      continue;
    }
    assert.ok(
      linuxCncSourcePathExists(ownerPath),
      `${label}: LinuxCNC owner path does not exist: ${ownerPath}`,
    );
  }
}

function readSourceConfigText(relPath) {
  return readFileSync(resolve(linuxCncSimRoot, relPath), "utf8");
}

function readLinuxCncSourceText(relPath) {
  return readFileSync(resolve(workspaceRoot, "linuxcnc", relPath), "utf8");
}

function stripIniLineComment(line) {
  return line.replace(/[;#].*$/, "");
}

function parseIniEntries(iniText) {
  const entries = [];
  let section = "";
  for (const rawLine of iniText.split("\n")) {
    const sectionMatch = rawLine.match(/^\s*\[([^\]]+)\]/);
    if (sectionMatch) {
      section = sectionMatch[1].trim().toUpperCase();
      continue;
    }
    const line = stripIniLineComment(rawLine);
    const equals = line.indexOf("=");
    if (equals === -1 || !section) {
      continue;
    }
    const key = line.slice(0, equals).trim().toUpperCase();
    const value = line.slice(equals + 1).trim();
    if (key && value) {
      entries.push({ section, key, value });
    }
  }
  return entries;
}

function iniValues(entries, section, key) {
  return entries
    .filter((entry) => entry.section === section.toUpperCase() && entry.key === key.toUpperCase())
    .map((entry) => entry.value);
}

function iniSectionValues(entries, section) {
  return entries.filter((entry) => entry.section === section.toUpperCase());
}

function normalizeSourceRel(relPath) {
  return posix.normalize(relPath).replace(/^(\.\.\/)+/, "");
}

function sourceRelForIniReference(iniRel, reference) {
  if (!reference || reference.startsWith("/") || reference.startsWith("LIB:")) {
    return "";
  }
  return normalizeSourceRel(posix.join(posix.dirname(iniRel), reference));
}

function sourceDirPythonFiles(dirRel) {
  const absDir = resolve(linuxCncSimRoot, dirRel);
  try {
    return readdirSync(absDir, { withFileTypes: true })
      .filter((entry) => entry.isFile() && entry.name.endsWith(".py"))
      .map((entry) => normalizeSourceRel(posix.join(dirRel, entry.name)))
      .sort();
  } catch {
    return [];
  }
}

function uniqueSorted(values) {
  return [...new Set(values.filter(Boolean))].sort();
}

function remapDetails(entries) {
  return iniValues(entries, "RS274NGC", "REMAP").map((value) => {
    const code = value.match(/^\s*([A-Z][0-9]+(?:\.[0-9]+)?)/i)?.[1]?.toUpperCase() ?? "";
    return {
      value,
      code,
      python: value.match(/(?:^|\s)python=([^\s]+)/i)?.[1] ?? "",
      prolog: value.match(/(?:^|\s)prolog=([^\s]+)/i)?.[1] ?? "",
      epilog: value.match(/(?:^|\s)epilog=([^\s]+)/i)?.[1] ?? "",
      ngc: value.match(/(?:^|\s)ngc=([^\s]+)/i)?.[1] ?? "",
    };
  });
}

function pythonFilesForIni(iniRel, entries) {
  const explicitFiles = [];
  const pythonDirs = [];
  const iniDir = posix.dirname(iniRel);

  for (const entry of iniSectionValues(entries, "PYTHON")) {
    if (entry.key === "PATH_APPEND" || entry.key === "PATH_PREPEND") {
      for (const dirEntry of entry.value.split(":").map((value) => value.trim()).filter(Boolean)) {
        const dirRel = sourceRelForIniReference(iniRel, dirEntry);
        if (dirRel) {
          pythonDirs.push(dirRel);
        }
      }
    } else if (entry.value.endsWith(".py")) {
      const fileRel = sourceRelForIniReference(iniRel, entry.value);
      if (fileRel) {
        explicitFiles.push(fileRel);
      }
    }
  }

  for (const entry of [
    ...iniSectionValues(entries, "DISPLAY"),
    ...iniSectionValues(entries, "EMCIO"),
  ]) {
    const match = entry.value.match(/(?:^|\s)([^"'\s]+\.py)(?:\s|$)/i);
    if (match) {
      const fileRel = sourceRelForIniReference(iniRel, match[1]);
      if (fileRel) {
        explicitFiles.push(fileRel);
      }
    }
  }

  return uniqueSorted([
    ...explicitFiles,
    ...pythonDirs.flatMap(sourceDirPythonFiles),
    ...sourceDirPythonFiles(posix.join(iniDir, "python")),
  ]);
}

function functionOwners(functionNames, pythonFiles) {
  return uniqueSorted(functionNames.map((functionName) => {
    const pattern = new RegExp(`^\\s*def\\s+${functionName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*\\(`, "m");
    const owner = pythonFiles.find((fileRel) =>
      sourceConfigPathExists(fileRel) && pattern.test(readSourceConfigText(fileRel)),
    );
    return `${functionName}@${owner || "UNRESOLVED"}`;
  }));
}

function remapNgcSourceFiles(iniRel, entries, details) {
  const subroutineDirs = iniValues(entries, "RS274NGC", "SUBROUTINE_PATH")
    .flatMap((value) => value.split(":"))
    .map((value) => value.trim())
    .filter(Boolean);
  const iniDir = posix.dirname(iniRel);

  return uniqueSorted(details.map((detail) => {
    if (!detail.ngc) {
      return "";
    }
    const fileName = `${detail.ngc}.ngc`;
    for (const dirEntry of subroutineDirs) {
      const sourceRel = sourceRelForIniReference(iniRel, posix.join(dirEntry, fileName));
      if (sourceRel && sourceConfigPathExists(sourceRel)) {
        return sourceRel;
      }
    }
    const sameDirRel = normalizeSourceRel(posix.join(iniDir, fileName));
    return sourceConfigPathExists(sameDirRel) ? sameDirRel : `${fileName}@UNRESOLVED`;
  }));
}

function sourceExecutionTextsForBlocked(record) {
  const rels = [record.path];
  if (record.path === "axis/vismach/millturn/example.ngc") {
    rels.push(
      "axis/vismach/millturn/remap_subs/428remap.ngc",
      "axis/vismach/millturn/remap_subs/429remap.ngc",
    );
  }
  return rels
    .filter(sourceConfigPathExists)
    .map(readSourceConfigText);
}

function userMCodesInExecutionText(text) {
  const codes = new Set();
  for (const match of text.matchAll(/(?<![A-Za-z0-9_])M\s*(1\d\d)(?![0-9])/gi)) {
    codes.add(`M${match[1]}`);
  }
  return [...codes].sort();
}

function userMProcessFilesForCodes(iniRel, entries, userMCodes) {
  const userMPathValues = iniValues(entries, "RS274NGC", "USER_M_PATH")
    .flatMap((value) => value.split(":"))
    .map((value) => value.trim())
    .filter(Boolean);
  return uniqueSorted(userMCodes.map((code) => {
    for (const dirEntry of userMPathValues) {
      const sourceRel = sourceRelForIniReference(iniRel, posix.join(dirEntry, code));
      if (sourceRel && sourceConfigPathExists(sourceRel)) {
        return sourceRel;
      }
    }
    return `${code}@UNRESOLVED`;
  }));
}

function userMProcessEffectsForFile(sourceRel) {
  if (!sourceRel || sourceRel.includes("@UNRESOLVED") || !sourceConfigPathExists(sourceRel)) {
    return [];
  }

  const text = readSourceConfigText(sourceRel);
  const effects = [];
  if (
    text.includes("#!/usr/bin/tclsh") &&
    text.includes("package require Linuxcnc") &&
    text.includes("package require Hal")
  ) {
    effects.push("tcl_hal_runtime");
  }
  if (text.includes("parse_ini $::env(INI_FILE_NAME)")) {
    effects.push("ini_file_parse");
  }
  if (/hal\s+getp\s+kinstype\.is-[01]/.test(text)) {
    effects.push("kinstype_guard");
  }
  if (
    text.includes("hal setp ini.$l.min_limit") &&
    text.includes("hal setp ini.$l.max_limit") &&
    text.includes("hal setp ini.$l.min_velocity") &&
    text.includes("hal setp ini.$l.max_acceleration")
  ) {
    effects.push("ini_axis_limit_hal_setp");
  }
  if (text.includes("MIN_LIMIT_TURN") && text.includes("MAX_LIMIT_TURN")) {
    effects.push("turn_limit_values");
  }
  if (
    text.includes("(MIN_LIMIT)") &&
    text.includes("(MAX_LIMIT)") &&
    !text.includes("MIN_LIMIT_TURN")
  ) {
    effects.push("mill_limit_values");
  }
  return effects;
}

function userMProcessEffectsForFiles(sourceRels) {
  return uniqueSorted(sourceRels.flatMap((sourceRel) =>
    userMProcessEffectsForFile(sourceRel).map((effect) => `${basename(sourceRel)}:${effect}`),
  ));
}

function userMRemapCallsForCode(record, code) {
  return sourceExecutionTextsForBlocked(record)
    .map((text, index) => {
      if (!new RegExp(`(?:^|[^A-Za-z0-9_])${code}(?:[^0-9]|$)`, "i").test(text)) {
        return "";
      }
      if (index === 0) {
        return record.path;
      }
      if (record.path === "axis/vismach/millturn/example.ngc") {
        return [
          "axis/vismach/millturn/remap_subs/428remap.ngc",
          "axis/vismach/millturn/remap_subs/429remap.ngc",
        ][index - 1] ?? "";
      }
      return "";
    })
    .filter(Boolean);
}

function userMProcessStateTargetsForFile(sourceRel, iniRel) {
  if (!sourceRel || sourceRel.includes("@UNRESOLVED") || !sourceConfigPathExists(sourceRel)) {
    return [];
  }

  const text = readSourceConfigText(sourceRel);
  const entries = parseIniEntries(readSourceConfigText(iniRel));
  const code = basename(sourceRel).toUpperCase();
  const stateMode = text.includes("MIN_LIMIT_TURN") ? "turn" : "mill";
  const guard = text.match(/hal\s+getp\s+(kinstype\.is-[01])/i)?.[1] ?? "";
  const sourceField = stateMode === "turn" ? "MIN_LIMIT_TURN/MAX_LIMIT_TURN" : "MIN_LIMIT/MAX_LIMIT";
  const targets = [];

  for (const axis of ["x", "y", "z"]) {
    const section = `AXIS_${axis.toUpperCase()}`;
    const minLimit = iniValues(entries, section, stateMode === "turn" ? "MIN_LIMIT_TURN" : "MIN_LIMIT")[0] ?? "";
    const maxLimit = iniValues(entries, section, stateMode === "turn" ? "MAX_LIMIT_TURN" : "MAX_LIMIT")[0] ?? "";
    const maxVelocity = iniValues(entries, section, "MAX_VELOCITY")[0] ?? "";
    const maxAcceleration = iniValues(entries, section, "MAX_ACCELERATION")[0] ?? "";
    for (const [pinSuffix, value, source] of [
      ["min_limit", minLimit, sourceField],
      ["max_limit", maxLimit, sourceField],
      ["min_velocity", maxVelocity, "MAX_VELOCITY"],
      ["max_acceleration", maxAcceleration, "MAX_ACCELERATION"],
    ]) {
      targets.push(`${code}:guard=${guard}:ini.${axis}.${pinSuffix}<=${section}.${source}:${value}`);
    }
  }

  return targets;
}

function userMProcessStateTargetRows(row) {
  if (row.blocked !== "L4-USER-M-PROCESS") {
    return [];
  }

  const entries = parseIniEntries(readSourceConfigText(row.ini));
  const userMCodes = splitSummaryList(row.user_m_execution_codes);
  const userMFilesByCode = new Map(
    userMProcessFilesForCodes(row.ini, entries, userMCodes)
      .map((sourceRel) => [basename(sourceRel).toUpperCase(), sourceRel]),
  );

  return userMCodes.flatMap((code) => {
    const sourceRel = userMFilesByCode.get(code) ?? "";
    if (!sourceRel || sourceRel.includes("@UNRESOLVED") || !sourceConfigPathExists(sourceRel)) {
      return [];
    }

    const text = readSourceConfigText(sourceRel);
    const stateMode = text.includes("MIN_LIMIT_TURN") ? "turn" : "mill";
    const guardPin = text.match(/hal\s+getp\s+(kinstype\.is-[01])/i)?.[1] ?? "";
    const sourceLimitField = stateMode === "turn" ? "MIN_LIMIT_TURN/MAX_LIMIT_TURN" : "MIN_LIMIT/MAX_LIMIT";
    const remapCallers = userMRemapCallsForCode({ path: row.path, ini: row.ini }, code);

    return ["x", "y", "z"].flatMap((axis) => {
      const section = `AXIS_${axis.toUpperCase()}`;
      const minLimit = iniValues(entries, section, stateMode === "turn" ? "MIN_LIMIT_TURN" : "MIN_LIMIT")[0] ?? "";
      const maxLimit = iniValues(entries, section, stateMode === "turn" ? "MAX_LIMIT_TURN" : "MAX_LIMIT")[0] ?? "";
      const maxVelocity = iniValues(entries, section, "MAX_VELOCITY")[0] ?? "";
      const maxAcceleration = iniValues(entries, section, "MAX_ACCELERATION")[0] ?? "";
      return [
        ["min_limit", minLimit, sourceLimitField],
        ["max_limit", maxLimit, sourceLimitField],
        ["min_velocity", maxVelocity, "MAX_VELOCITY"],
        ["max_acceleration", maxAcceleration, "MAX_ACCELERATION"],
      ].map(([pinSuffix, expectedValue, sourceField]) => [
        row.path,
        row.ini,
        row.blocked,
        code,
        sourceRel,
        listValue(remapCallers),
        stateMode,
        guardPin,
        `ini.${axis}.${pinSuffix}`,
        section,
        sourceField,
        expectedValue,
        "hal_setp_from_config_script",
        "pending",
        "0",
        "0",
      ].map(tsvValue).join("\t"));
    });
  });
}

function verifyUserMProcessStateTargetRows(rows, blockedRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "user_m_code",
    "source_file",
    "remap_callers",
    "state_mode",
    "guard_pin",
    "target_pin",
    "source_section",
    "source_field",
    "expected_value",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedBlockedRows = blockedRows.filter((row) => row.blocked === "L4-USER-M-PROCESS");

  assert.equal(expectedBlockedRows.length, 1, "expected one user-M process blocked row");
  assert.equal(parsedRows.length, 24, "M128/M129 state target rows must cover 2 codes * 3 axes * 4 pins");

  const rowsByCode = new Map();
  for (const row of parsedRows) {
    const existing = rowsByCode.get(row.user_m_code) ?? [];
    existing.push(row);
    rowsByCode.set(row.user_m_code, existing);

    assert.equal(row.blocked, "L4-USER-M-PROCESS", `${row.target_pin}: blocked kind drift`);
    assert.ok(["M128", "M129"].includes(row.user_m_code), `${row.target_pin}: unexpected user-M code`);
    assert.ok(row.source_file.endsWith(`mcodes/${row.user_m_code}`), `${row.target_pin}: source file drift`);
    assert.ok(row.remap_callers.includes("axis/vismach/millturn/remap_subs/"), `${row.target_pin}: missing remap caller`);
    assert.ok(["mill", "turn"].includes(row.state_mode), `${row.target_pin}: invalid state mode`);
    assert.ok(["kinstype.is-0", "kinstype.is-1"].includes(row.guard_pin), `${row.target_pin}: invalid guard pin`);
    assert.ok(/^ini\.[xyz]\.(min_limit|max_limit|min_velocity|max_acceleration)$/.test(row.target_pin), `${row.target_pin}: invalid target pin`);
    assert.ok(/^AXIS_[XYZ]$/.test(row.source_section), `${row.target_pin}: invalid source section`);
    assert.notEqual(row.expected_value, "-", `${row.target_pin}: missing expected value`);
    assert.equal(row.proof_kind, "hal_setp_from_config_script", `${row.target_pin}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.target_pin}: state target proof must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.target_pin}: state target must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.target_pin}: state target must not allow promotion`);
  }

  assert.equal(rowsByCode.get("M128")?.length, 12, "M128 must have 12 state target rows");
  assert.equal(rowsByCode.get("M129")?.length, 12, "M129 must have 12 state target rows");
  assert.ok(
    parsedRows.some((row) =>
      row.user_m_code === "M128" &&
      row.guard_pin === "kinstype.is-0" &&
      row.state_mode === "mill" &&
      row.target_pin === "ini.x.min_limit" &&
      row.expected_value === "-300",
    ),
    "M128 mill X min limit target drift",
  );
  assert.ok(
    parsedRows.some((row) =>
      row.user_m_code === "M129" &&
      row.guard_pin === "kinstype.is-1" &&
      row.state_mode === "turn" &&
      row.target_pin === "ini.z.max_limit" &&
      row.expected_value === "300",
    ),
    "M129 turn Z max limit target drift",
  );

  return parsedRows;
}

function userMProcessTransitionPlanRows(stateTargetRows) {
  const byCode = new Map();
  for (const row of stateTargetRows) {
    const existing = byCode.get(row.user_m_code) ?? [];
    existing.push(row);
    byCode.set(row.user_m_code, existing);
  }

  const transitionRows = [];
  for (const code of [...byCode.keys()].sort()) {
    const rows = byCode.get(code);
    const first = rows[0];
    const remapCaller = splitSummaryList(first.remap_callers)[0] ?? "";
    const remapText = remapCaller ? readSourceConfigText(remapCaller) : "";
    const remapCode = basename(remapCaller).match(/^(\d+)remap\.ngc$/)?.[1] ?? "";
    const switchkinsTarget = remapText.match(/#<kinstype>\s*=\s*([01])/i)?.[1] ?? "";
    const switchkinsPin = remapText.match(/#<SWITCHKINS_PIN>\s*=\s*([0-9]+)/i)?.[1] ?? "";
    const workOffsetPocket = remapText.match(/G10\s+L2\s+P([0-9]+)/i)?.[1] ?? "";
    const activeG5x = remapText.match(/\b(G59\.[12])\b/i)?.[1]?.toUpperCase() ?? "";
    const expectedPins = uniqueSorted(rows.map((row) => row.target_pin));

    transitionRows.push([
      first.path,
      first.ini,
      first.blocked,
      String(transitionRows.length + 1),
      remapCode ? `M${remapCode}` : "-",
      code,
      remapCaller,
      switchkinsPin ? `motion.analog-out-0${switchkinsPin}` : "-",
      switchkinsTarget,
      activeG5x,
      workOffsetPocket ? `P${workOffsetPocket}` : "-",
      first.guard_pin,
      first.state_mode,
      String(rows.length),
      listValue(expectedPins),
      "state_transition_contract_only",
      "pending",
      "0",
      "0",
      "no_process_execution_no_hal_runtime_promotion",
    ].map(tsvValue).join("\t"));
  }

  return transitionRows;
}

function verifyUserMProcessTransitionPlanRows(rows, stateTargetRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "transition_step",
    "remap_code",
    "user_m_code",
    "remap_caller",
    "switchkins_output_pin",
    "switchkins_target",
    "active_g5x",
    "work_offset_pocket",
    "guard_pin",
    "state_mode",
    "state_target_count",
    "expected_state_pins",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  assert.equal(parsedRows.length, 2, "millturn user-M transition plan must cover M428/M429");
  verifySamePathSet(
    "wasm_user_m_process_transition_plan",
    uniqueSorted(stateTargetRows.map((row) => row.user_m_code)),
    parsedRows.map((row) => row.user_m_code).sort(),
  );

  const expectedByCode = new Map([
    [
      "M128",
      {
        remapCode: "M428",
        switchkinsTarget: "0",
        activeG5x: "G59.1",
        workOffsetPocket: "P7",
        guardPin: "kinstype.is-0",
        stateMode: "mill",
      },
    ],
    [
      "M129",
      {
        remapCode: "M429",
        switchkinsTarget: "1",
        activeG5x: "G59.2",
        workOffsetPocket: "P8",
        guardPin: "kinstype.is-1",
        stateMode: "turn",
      },
    ],
  ]);

  for (const row of parsedRows) {
    const expected = expectedByCode.get(row.user_m_code);
    assert.ok(expected, `${row.user_m_code}: unexpected transition plan user-M code`);
    assert.equal(row.path, "axis/vismach/millturn/example.ngc", `${row.user_m_code}: path drift`);
    assert.equal(row.ini, "axis/vismach/millturn/millturn.ini", `${row.user_m_code}: INI drift`);
    assert.equal(row.blocked, "L4-USER-M-PROCESS", `${row.user_m_code}: blocked kind drift`);
    assert.ok(/^[12]$/.test(row.transition_step), `${row.user_m_code}: invalid transition step`);
    assert.equal(row.remap_code, expected.remapCode, `${row.user_m_code}: remap code drift`);
    assert.ok(
      row.remap_caller.endsWith(`${row.remap_code.slice(1)}remap.ngc`),
      `${row.user_m_code}: remap caller drift`,
    );
    assert.equal(row.switchkins_output_pin, "motion.analog-out-03", `${row.user_m_code}: switchkins output pin drift`);
    assert.equal(row.switchkins_target, expected.switchkinsTarget, `${row.user_m_code}: switchkins target drift`);
    assert.equal(row.active_g5x, expected.activeG5x, `${row.user_m_code}: active G5x drift`);
    assert.equal(row.work_offset_pocket, expected.workOffsetPocket, `${row.user_m_code}: work offset pocket drift`);
    assert.equal(row.guard_pin, expected.guardPin, `${row.user_m_code}: guard pin drift`);
    assert.equal(row.state_mode, expected.stateMode, `${row.user_m_code}: state mode drift`);
    assert.equal(row.state_target_count, "12", `${row.user_m_code}: state target count drift`);
    for (const pin of [
      "ini.x.min_limit",
      "ini.x.max_limit",
      "ini.x.min_velocity",
      "ini.x.max_acceleration",
      "ini.y.min_limit",
      "ini.z.max_limit",
    ]) {
      assert.ok(row.expected_state_pins.includes(pin), `${row.user_m_code}: missing state pin ${pin}`);
    }
    assert.equal(row.proof_kind, "state_transition_contract_only", `${row.user_m_code}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.user_m_code}: proof status must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.user_m_code}: transition plan must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.user_m_code}: transition plan must not allow promotion`);
    assert.ok(row.notes.includes("no_process_execution"), `${row.user_m_code}: missing non-execution note`);
  }

  return parsedRows;
}

function userMProcessBoundarySummaryRow(row) {
  if (row.blocked !== "L4-USER-M-PROCESS") {
    return null;
  }

  const record = { path: row.path, ini: row.ini };
  const entries = parseIniEntries(readSourceConfigText(row.ini));
  const userMCodes = splitSummaryList(row.user_m_execution_codes);
  const userMFiles = userMProcessFilesForCodes(row.ini, entries, userMCodes);
  const stateTargets = uniqueSorted(userMFiles.flatMap((sourceRel) =>
    userMProcessStateTargetsForFile(sourceRel, row.ini),
  ));
  const remapCallChain = uniqueSorted(userMCodes.flatMap((code) =>
    userMRemapCallsForCode(record, code).map((sourceRel) => `${code}@${sourceRel}`),
  ));

  return [
    row.path,
    row.ini,
    row.blocked,
    "designed_blocked",
    "external_user_m_process",
    row.linuxcnc_owner,
    row.user_m_execution_codes,
    listValue(userMFiles),
    listValue(remapCallChain),
    listValue(stateTargets),
    row.user_m_process_effects,
    "kinstype_guard_and_ini_xyz_hal_pin_state",
    "linuxcnc_owned_state_boundary_not_user_m_event_only",
    "browser_after_node_state_proof_no_full_process_claim",
    "0",
    "0",
    "keep_blocked_until_m128_m129_state_proof",
  ].map(tsvValue).join("\t");
}

function verifyUserMProcessBoundarySummaryRows(rows, blockedRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "design_status",
    "boundary_kind",
    "linuxcnc_owner",
    "user_m_execution_codes",
    "user_m_process_files",
    "remap_call_chain",
    "state_targets",
    "runtime_owner_evidence",
    "required_native_proof",
    "required_node_proof",
    "required_browser_proof",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRows = blockedRows.filter((row) => row.blocked === "L4-USER-M-PROCESS");

  verifySamePathSet(
    "wasm_user_m_process_boundary_summary",
    expectedRows.map((row) => row.path).sort(),
    parsedRows.map((row) => row.path).sort(),
  );

  for (const row of parsedRows) {
    assert.equal(row.design_status, "designed_blocked", `${row.path}: user-M design status drift`);
    assert.equal(row.boundary_kind, "external_user_m_process", `${row.path}: user-M boundary kind drift`);
    assert.equal(row.execution_enabled, "0", `${row.path}: user-M boundary must remain disabled`);
    assert.equal(row.promotion_allowed, "0", `${row.path}: user-M boundary must not allow promotion`);
    verifyLinuxCncOwnerPaths(row.path, row.linuxcnc_owner);
    for (const token of ["M128", "M129"]) {
      assert.ok(row.user_m_execution_codes.includes(token), `${row.path}: missing execution code ${token}`);
      assert.ok(row.user_m_process_files.includes(`mcodes/${token}`), `${row.path}: missing process file ${token}`);
      assert.ok(row.remap_call_chain.includes(`${token}@axis/vismach/millturn/remap_subs/`), `${row.path}: missing remap caller ${token}`);
    }
    for (const token of [
      "M128:guard=kinstype.is-0:ini.x.min_limit<=AXIS_X.MIN_LIMIT/MAX_LIMIT:-300",
      "M128:guard=kinstype.is-0:ini.z.max_limit<=AXIS_Z.MIN_LIMIT/MAX_LIMIT:0",
      "M129:guard=kinstype.is-1:ini.x.min_limit<=AXIS_X.MIN_LIMIT_TURN/MAX_LIMIT_TURN:-240",
      "M129:guard=kinstype.is-1:ini.z.max_limit<=AXIS_Z.MIN_LIMIT_TURN/MAX_LIMIT_TURN:300",
      "ini.y.min_velocity<=AXIS_Y.MAX_VELOCITY:60.0",
      "ini.z.max_acceleration<=AXIS_Z.MAX_ACCELERATION:400.0",
    ]) {
      assert.ok(row.state_targets.includes(token), `${row.path}: missing state target ${token}`);
    }
    assert.ok(
      row.runtime_owner_evidence.includes("tcl_hal_runtime") &&
        row.runtime_owner_evidence.includes("ini_axis_limit_hal_setp"),
      `${row.path}: user-M row lacks runtime owner evidence`,
    );
    assert.ok(row.required_node_proof.includes("not_user_m_event_only"), `${row.path}: event-only proof is insufficient`);
    assert.ok(row.notes.includes("m128_m129_state_proof"), `${row.path}: missing M128/M129 proof note`);
  }

  return parsedRows;
}

function toolDbProtocolEvidence({ iniText, dbProgram }) {
  if (!dbProgram) {
    return [];
  }

  const taskText = readLinuxCncSourceText("src/emc/task/taskclass.cc");
  const tooldataDbText = readLinuxCncSourceText("src/emc/tooldata/tooldata_db.cc");
  const dbProgramText = readSourceConfigText("axis/db_demo/db.py");
  const evidence = [];

  if (iniText.includes("DB_PROGRAM") && dbProgram.includes("db_nonran.py")) {
    evidence.push("ini_db_program_declared");
  }
  if (iniText.includes("TOOL_TABLE= is not used with DB_PROGRAM")) {
    evidence.push("ini_tool_table_replaced");
  }
  if (
    taskText.includes('findString("DB_PROGRAM", "EMCIO")') &&
    taskText.includes("tooldata_set_db(db_mode)") &&
    taskText.includes("tooldata_db_init(db_program, random_toolchanger)")
  ) {
    evidence.push("task_db_mode_init");
  }
  if (
    taskText.includes("tooldata_db_notify(SPINDLE_UNLOAD") &&
    taskText.includes("tooldata_db_notify(SPINDLE_LOAD")
  ) {
    evidence.push("task_load_unload_notify");
  }
  if (
    tooldataDbText.includes('#define DB_VERSION "v2.1"') &&
    tooldataDbText.includes("read_reply(reply,sizeof(reply))") &&
    tooldataDbText.includes("strncmp(reply,DB_VERSION")
  ) {
    evidence.push("tooldata_db_v2_1_handshake");
  }
  if (
    tooldataDbText.includes("pipe2(pipes[PARENT_READ_PIPE]") &&
    tooldataDbText.includes("pipe2(pipes[PARENT_WRITE_PIPE]") &&
    tooldataDbText.includes("execv(myargv[0], myargv)")
  ) {
    evidence.push("tooldata_db_child_process");
  }
  if (
    tooldataDbText.includes('send_request((char*)"g\\n")') &&
    tooldataDbText.includes('strstr(reply,"FINI")') &&
    tooldataDbText.includes("tooldata_read_entry(reply)")
  ) {
    evidence.push("tooldata_db_getall_g_fini");
  }
  if (
    tooldataDbText.includes('snprintf(msg,sizeof(msg),"l %s\\n",buffer)') &&
    tooldataDbText.includes('snprintf(msg,sizeof(msg),"u %s\\n",buffer)') &&
    tooldataDbText.includes('snprintf(msg,sizeof(msg),"p %s\\n",buffer)')
  ) {
    evidence.push("tooldata_db_notify_l_u_p");
  }
  if (
    dbProgramText.includes("from tooldb import tooldb_callbacks") &&
    dbProgramText.includes("from tooldb import tooldb_tools") &&
    dbProgramText.includes("from tooldb import tooldb_loop")
  ) {
    evidence.push("db_program_tooldb_module");
  }
  if (
    dbProgramText.includes("def user_get_tool(tno):") &&
    dbProgramText.includes("def user_put_tool(tno,params):")
  ) {
    evidence.push("db_program_get_put_callbacks");
  }
  if (
    dbProgramText.includes("def user_load_spindle_nonran_tc(tno,params):") &&
    dbProgramText.includes("def user_unload_spindle_nonran_tc(tno,params):")
  ) {
    evidence.push("db_program_nonran_load_unload_callbacks");
  }
  if (
    dbProgramText.includes('db_nonran_savefile = "/tmp/db_nonran_file"') &&
    dbProgramText.includes("save_tools_to_file(db_savefile")
  ) {
    evidence.push("db_program_persistent_flatfile_state");
  }
  if (
    dbProgramText.includes("tooldb_callbacks(user_get_tool") &&
    dbProgramText.includes("tooldb_tools(toollist)")
  ) {
    evidence.push("db_program_callback_registration");
  }

  return uniqueSorted(evidence);
}

function toolDbProtocolMessages() {
  const tooldataDbText = readLinuxCncSourceText("src/emc/tooldata/tooldata_db.cc");
  const messages = [];

  if (
    tooldataDbText.includes('#define DB_VERSION "v2.1"') &&
    tooldataDbText.includes("strncmp(reply,DB_VERSION")
  ) {
    messages.push("startup:expect_reply=v2.1");
  }
  if (
    tooldataDbText.includes('send_request((char*)"g\\n")') &&
    tooldataDbText.includes('strstr(reply,"FINI")')
  ) {
    messages.push("request:g:get_all_until_FINI");
  }
  if (tooldataDbText.includes('snprintf(msg,sizeof(msg),"l %s\\n",buffer)')) {
    messages.push("notify:l:SPINDLE_LOAD");
  }
  if (tooldataDbText.includes('snprintf(msg,sizeof(msg),"u %s\\n",buffer)')) {
    messages.push("notify:u:SPINDLE_UNLOAD");
  }
  if (tooldataDbText.includes('snprintf(msg,sizeof(msg),"p %s\\n",buffer)')) {
    messages.push("notify:p:TOOL_OFFSET");
  }

  return uniqueSorted(messages);
}

function toolDbProgramCallbacks() {
  const dbProgramText = readSourceConfigText("axis/db_demo/db.py");
  const callbacks = [];

  if (
    dbProgramText.includes("tooldb_callbacks(user_get_tool") &&
    dbProgramText.includes("tooldb_tools(toollist)") &&
    dbProgramText.includes("tooldb_loop()")
  ) {
    callbacks.push("registration:tooldb_callbacks_tools_loop");
  }
  for (const [command, functionName] of [
    ["g", "user_get_tool"],
    ["p", "user_put_tool"],
    ["l", "user_load_spindle_nonran_tc"],
    ["u", "user_unload_spindle_nonran_tc"],
  ]) {
    if (dbProgramText.includes(`def ${functionName}(`)) {
      callbacks.push(`${command}:${functionName}`);
    }
  }

  return uniqueSorted(callbacks);
}

function toolDbStateTargets(row) {
  const iniText = readSourceConfigText(row.ini);
  const entries = parseIniEntries(iniText);
  const dbProgramText = readSourceConfigText("axis/db_demo/db.py");
  const randomToolchanger = iniValues(entries, "EMCIO", "RANDOM_TOOLCHANGER")[0] ?? "";
  const dbProgram = iniValues(entries, "EMCIO", "DB_PROGRAM")[0] ?? "";
  const targets = [];

  if (randomToolchanger) {
    targets.push(`ini.EMCIO.RANDOM_TOOLCHANGER=${randomToolchanger}`);
  }
  if (dbProgram) {
    targets.push(`ini.EMCIO.DB_PROGRAM=${dbProgram}`);
  }
  if (iniText.includes("TOOL_TABLE= is not used with DB_PROGRAM")) {
    targets.push("ini.EMCIO.TOOL_TABLE_IGNORED_WITH_DB_PROGRAM=1");
  }
  if (dbProgramText.includes('db_nonran_savefile = "/tmp/db_nonran_file"')) {
    targets.push("db_program.savefile=/tmp/db_nonran_file");
  }
  if (dbProgramText.includes("toolno_min = 10") && dbProgramText.includes("toolno_max = 19")) {
    targets.push("db_program.initial_tools=T10..T19");
  }
  if (dbProgramText.includes("nonran_pno(tno)") && dbProgramText.includes("pocket_offset      = 100")) {
    targets.push("db_program.nonrandom_startup_pockets=tno+100");
  }
  if (
    dbProgramText.includes("D['P'] = \"0\"") &&
    dbProgramText.includes("nonran_restore_pocket(spindle_tool)")
  ) {
    targets.push("db_program.nonrandom_load_sets_spindle_pocket_0_and_unload_restores_pocket");
  }
  if (dbProgramText.includes("apply_db_rules()") && dbProgramText.includes("G10L0")) {
    targets.push("db_program.reload_applies_db_rules");
  }
  if (dbProgramText.includes("linuxcnc.command().load_tool_table")) {
    targets.push("db_program.host_sync=linuxcnc.command.load_tool_table");
  }

  return uniqueSorted(targets);
}

function toolDbProcessProtocolGateRows(row) {
  if (row.blocked !== "L4-TOOL-DB") {
    return [];
  }

  const gateRows = [];
  for (const message of toolDbProtocolMessages()) {
    gateRows.push([
      row.path,
      row.ini,
      row.blocked,
      "protocol_message",
      message,
      row.db_program,
      row.linuxcnc_owner,
      row.tool_db_protocol_evidence,
      "linuxcnc_tooldata_db_protocol",
      "pending",
      "0",
      "0",
    ].map(tsvValue).join("\t"));
  }
  for (const callback of toolDbProgramCallbacks()) {
    gateRows.push([
      row.path,
      row.ini,
      row.blocked,
      "db_program_callback",
      callback,
      row.db_program,
      row.linuxcnc_owner,
      row.tool_db_protocol_evidence,
      "config_db_program_callback",
      "pending",
      "0",
      "0",
    ].map(tsvValue).join("\t"));
  }
  for (const target of toolDbStateTargets(row)) {
    gateRows.push([
      row.path,
      row.ini,
      row.blocked,
      "state_target",
      target,
      row.db_program,
      row.linuxcnc_owner,
      row.tool_db_protocol_evidence,
      "db_protocol_state_target",
      "pending",
      "0",
      "0",
    ].map(tsvValue).join("\t"));
  }

  return gateRows;
}

function verifyToolDbProcessProtocolGateRows(rows, blockedRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "gate_kind",
    "gate",
    "db_program",
    "linuxcnc_owner",
    "runtime_owner_evidence",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRows = blockedRows.filter((row) => row.blocked === "L4-TOOL-DB");

  assert.equal(expectedRows.length, 1, "expected one tool DB blocked row");
  assert.ok(parsedRows.length >= 18, "tool DB protocol gates must cover protocol, callbacks, and state targets");

  const byKind = new Map();
  for (const row of parsedRows) {
    const existing = byKind.get(row.gate_kind) ?? [];
    existing.push(row);
    byKind.set(row.gate_kind, existing);

    assert.equal(row.blocked, "L4-TOOL-DB", `${row.gate}: blocked kind drift`);
    assert.equal(row.db_program, "./db_nonran.py", `${row.gate}: DB_PROGRAM drift`);
    verifyLinuxCncOwnerPaths(row.gate, row.linuxcnc_owner);
    assert.notEqual(row.runtime_owner_evidence, "-", `${row.gate}: missing runtime owner evidence`);
    assert.equal(row.proof_status, "pending", `${row.gate}: tool DB proof gate must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.gate}: tool DB proof gate must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.gate}: tool DB proof gate must not allow promotion`);
  }

  assert.equal(byKind.get("protocol_message")?.length, 5, "tool DB protocol message gate count drift");
  assert.equal(byKind.get("db_program_callback")?.length, 5, "tool DB callback gate count drift");
  assert.ok((byKind.get("state_target")?.length ?? 0) >= 8, "tool DB state target gate count drift");

  for (const gate of [
    "startup:expect_reply=v2.1",
    "request:g:get_all_until_FINI",
    "notify:l:SPINDLE_LOAD",
    "notify:u:SPINDLE_UNLOAD",
    "notify:p:TOOL_OFFSET",
    "registration:tooldb_callbacks_tools_loop",
    "g:user_get_tool",
    "p:user_put_tool",
    "l:user_load_spindle_nonran_tc",
    "u:user_unload_spindle_nonran_tc",
    "ini.EMCIO.TOOL_TABLE_IGNORED_WITH_DB_PROGRAM=1",
    "db_program.initial_tools=T10..T19",
    "db_program.nonrandom_startup_pockets=tno+100",
    "db_program.nonrandom_load_sets_spindle_pocket_0_and_unload_restores_pocket",
    "db_program.host_sync=linuxcnc.command.load_tool_table",
  ]) {
    assert.ok(parsedRows.some((row) => row.gate === gate), `tool DB protocol gate missing ${gate}`);
  }

  for (const row of parsedRows.filter((entry) => entry.gate_kind === "protocol_message")) {
    assert.equal(row.proof_kind, "linuxcnc_tooldata_db_protocol", `${row.gate}: protocol proof kind drift`);
  }
  for (const row of parsedRows.filter((entry) => entry.gate_kind === "db_program_callback")) {
    assert.equal(row.proof_kind, "config_db_program_callback", `${row.gate}: callback proof kind drift`);
  }
  for (const row of parsedRows.filter((entry) => entry.gate_kind === "state_target")) {
    assert.equal(row.proof_kind, "db_protocol_state_target", `${row.gate}: state proof kind drift`);
  }

  return parsedRows;
}

function toolDbProcessTransactionPlanRows(gateRows) {
  const first = gateRows[0];
  if (!first) {
    return [];
  }

  const gates = new Set(gateRows.map((row) => row.gate));
  const stateTargets = (values) => values.filter((value) => gates.has(value));
  const steps = [
    {
      phase: "startup_handshake",
      protocolMessage: "startup:expect_reply=v2.1",
      callback: "registration:tooldb_callbacks_tools_loop",
      stateTargets: [
        "ini.EMCIO.DB_PROGRAM=./db_nonran.py",
        "ini.EMCIO.RANDOM_TOOLCHANGER=0",
        "ini.EMCIO.TOOL_TABLE_IGNORED_WITH_DB_PROGRAM=1",
        "db_program.savefile=/tmp/db_nonran_file",
      ],
      nativeProof: "tool_db_v2_1_handshake",
      nodeProof: "linuxcnc_tooldata_db_protocol_not_tbl_fallback",
      browserProof: "opfs_persistence_only_no_db_process_claim",
    },
    {
      phase: "initial_get_all",
      protocolMessage: "request:g:get_all_until_FINI",
      callback: "g:user_get_tool",
      stateTargets: [
        "db_program.initial_tools=T10..T19",
        "db_program.nonrandom_startup_pockets=tno+100",
      ],
      nativeProof: "tool_db_getall_g_until_fini",
      nodeProof: "get_all_uses_db_protocol_not_tbl_load",
      browserProof: "browser_after_node_protocol_proof_only",
    },
    {
      phase: "spindle_load_notify",
      protocolMessage: "notify:l:SPINDLE_LOAD",
      callback: "l:user_load_spindle_nonran_tc",
      stateTargets: [
        "db_program.nonrandom_load_sets_spindle_pocket_0_and_unload_restores_pocket",
      ],
      nativeProof: "tool_db_notify_l_u_p_protocol",
      nodeProof: "load_notify_uses_db_protocol",
      browserProof: "browser_after_node_protocol_proof_only",
    },
    {
      phase: "tool_offset_notify",
      protocolMessage: "notify:p:TOOL_OFFSET",
      callback: "p:user_put_tool",
      stateTargets: [
        "db_program.reload_applies_db_rules",
        "db_program.host_sync=linuxcnc.command.load_tool_table",
      ],
      nativeProof: "tool_db_notify_l_u_p_protocol",
      nodeProof: "put_notify_uses_db_protocol",
      browserProof: "browser_after_node_protocol_proof_only",
    },
    {
      phase: "spindle_unload_notify",
      protocolMessage: "notify:u:SPINDLE_UNLOAD",
      callback: "u:user_unload_spindle_nonran_tc",
      stateTargets: [
        "db_program.nonrandom_load_sets_spindle_pocket_0_and_unload_restores_pocket",
        "db_program.host_sync=linuxcnc.command.load_tool_table",
      ],
      nativeProof: "tool_db_notify_l_u_p_protocol",
      nodeProof: "unload_notify_uses_db_protocol",
      browserProof: "browser_after_node_protocol_proof_only",
    },
  ];

  return steps.map((step, index) => [
    first.path,
    first.ini,
    first.blocked,
    String(index + 1),
    step.phase,
    step.protocolMessage,
    step.callback,
    listValue(stateTargets(step.stateTargets)),
    first.db_program,
    step.nativeProof,
    step.nodeProof,
    step.browserProof,
    "db_protocol_transaction_contract_only",
    "pending",
    "0",
    "0",
    "no_db_process_execution_no_tool_table_fallback_no_promotion",
  ].map(tsvValue).join("\t"));
}

function verifyToolDbProcessTransactionPlanRows(rows, gateRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "transaction_step",
    "transaction_phase",
    "protocol_message",
    "db_program_callback",
    "state_targets",
    "db_program",
    "required_native_proof",
    "required_node_proof",
    "required_browser_proof",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const gateKeys = new Set(gateRows.map((row) => row.gate));
  const expectedPhases = [
    "startup_handshake",
    "initial_get_all",
    "spindle_load_notify",
    "tool_offset_notify",
    "spindle_unload_notify",
  ];
  const expectedProtocolByPhase = new Map([
    ["startup_handshake", "startup:expect_reply=v2.1"],
    ["initial_get_all", "request:g:get_all_until_FINI"],
    ["spindle_load_notify", "notify:l:SPINDLE_LOAD"],
    ["tool_offset_notify", "notify:p:TOOL_OFFSET"],
    ["spindle_unload_notify", "notify:u:SPINDLE_UNLOAD"],
  ]);
  const expectedCallbackByPhase = new Map([
    ["startup_handshake", "registration:tooldb_callbacks_tools_loop"],
    ["initial_get_all", "g:user_get_tool"],
    ["spindle_load_notify", "l:user_load_spindle_nonran_tc"],
    ["tool_offset_notify", "p:user_put_tool"],
    ["spindle_unload_notify", "u:user_unload_spindle_nonran_tc"],
  ]);

  assert.equal(parsedRows.length, 5, "tool DB transaction plan must cover startup/get/load/put/unload");
  assert.deepEqual(
    parsedRows.map((row) => row.transaction_phase),
    expectedPhases,
    "tool DB transaction phase order drift",
  );

  for (const [index, row] of parsedRows.entries()) {
    assert.equal(row.path, "axis/db_demo/base.ngc", `${row.transaction_phase}: path drift`);
    assert.equal(row.ini, "axis/db_demo/db_nonran.ini", `${row.transaction_phase}: INI drift`);
    assert.equal(row.blocked, "L4-TOOL-DB", `${row.transaction_phase}: blocked kind drift`);
    assert.equal(row.transaction_step, String(index + 1), `${row.transaction_phase}: step drift`);
    assert.equal(row.db_program, "./db_nonran.py", `${row.transaction_phase}: DB_PROGRAM drift`);
    assert.equal(
      row.protocol_message,
      expectedProtocolByPhase.get(row.transaction_phase),
      `${row.transaction_phase}: protocol message drift`,
    );
    assert.equal(
      row.db_program_callback,
      expectedCallbackByPhase.get(row.transaction_phase),
      `${row.transaction_phase}: DB callback drift`,
    );
    assert.ok(gateKeys.has(row.protocol_message), `${row.transaction_phase}: protocol gate missing`);
    assert.ok(gateKeys.has(row.db_program_callback), `${row.transaction_phase}: callback gate missing`);
    assert.notEqual(row.state_targets, "-", `${row.transaction_phase}: missing transaction state targets`);
    for (const target of splitSummaryList(row.state_targets)) {
      assert.ok(gateKeys.has(target), `${row.transaction_phase}: state target lacks gate ${target}`);
    }
    assert.notEqual(row.required_native_proof, "-", `${row.transaction_phase}: missing native proof`);
    assert.notEqual(row.required_node_proof, "-", `${row.transaction_phase}: missing Node proof`);
    assert.notEqual(row.required_browser_proof, "-", `${row.transaction_phase}: missing browser proof`);
    assert.equal(row.proof_kind, "db_protocol_transaction_contract_only", `${row.transaction_phase}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.transaction_phase}: proof status must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.transaction_phase}: transaction plan must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.transaction_phase}: transaction plan must not allow promotion`);
    assert.ok(row.notes.includes("no_db_process_execution"), `${row.transaction_phase}: missing non-execution note`);
    assert.ok(row.notes.includes("no_tool_table_fallback"), `${row.transaction_phase}: missing no-fallback note`);
  }

  return parsedRows;
}

function sourceConfigExecutable(relPath) {
  try {
    return (statSync(resolve(linuxCncSimRoot, relPath)).mode & 0o111) !== 0;
  } catch {
    return false;
  }
}

function linuxCncSourceExecutable(relPath) {
  try {
    return (statSync(resolve(workspaceRoot, "linuxcnc", relPath)).mode & 0o111) !== 0;
  } catch {
    return false;
  }
}

function toolDbProcessNativeRuntimeReadinessRows(transactionRows) {
  const first = transactionRows[0];
  if (!first) {
    return [];
  }

  const requirements = [
    {
      kind: "host_command",
      requirement: "python3",
      purpose: "execute_config_db_program_shebang",
      available: commandPath("python3") !== "",
      evidence: commandPath("python3"),
    },
    {
      kind: "host_command",
      requirement: "linuxcnc",
      purpose: "provide_linuxcnc_python_runtime_and_task_context",
      available: commandPath("linuxcnc") !== "",
      evidence: commandPath("linuxcnc"),
    },
    {
      kind: "host_command",
      requirement: "milltask",
      purpose: "own_db_program_startup_and_tooldata_protocol",
      available: commandPath("milltask") !== "",
      evidence: commandPath("milltask"),
    },
    {
      kind: "host_command",
      requirement: "halcmd",
      purpose: "provide_linuxcnc_runtime_environment_for_db_program_sync",
      available: commandPath("halcmd") !== "",
      evidence: commandPath("halcmd"),
    },
    {
      kind: "source_config_file",
      requirement: "axis/db_demo/db_nonran.py",
      purpose: "configured_db_program",
      available: sourceConfigPathExists("axis/db_demo/db_nonran.py") &&
        sourceConfigExecutable("axis/db_demo/db_nonran.py"),
      evidence: "configs/sim/axis/db_demo/db_nonran.py",
    },
    {
      kind: "linuxcnc_python_module",
      requirement: "linuxcnc.so",
      purpose: "db_program_import_linuxcnc",
      available: linuxCncSourcePathExists("lib/python/linuxcnc.so"),
      evidence: "lib/python/linuxcnc.so",
    },
    {
      kind: "linuxcnc_python_module",
      requirement: "tooldb.py",
      purpose: "db_program_protocol_callbacks",
      available: linuxCncSourcePathExists("lib/python/tooldb.py"),
      evidence: "lib/python/tooldb.py",
    },
  ];
  const allAvailable = requirements.every((row) => row.available);
  const nativeRuntimeStatus = allAvailable
    ? "host_runtime_available_probe_not_implemented"
    : "blocked_missing_host_runtime";

  return requirements.map((row) => [
    first.path,
    first.ini,
    first.blocked,
    "linuxcnc_tooldata_db_process",
    row.kind,
    row.requirement,
    row.purpose,
    flagValue(row.available),
    row.available ? row.evidence : "-",
    first.db_program,
    nativeRuntimeStatus,
    "native_db_process_protocol_probe_required",
    "pending",
    "0",
    "0",
    allAvailable
      ? "runtime_requirements_available_but_probe_still_not_implemented"
      : "missing_host_runtime_keep_tool_db_blocked",
  ].map(tsvValue).join("\t"));
}

function verifyToolDbProcessNativeRuntimeReadinessRows(rows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "required_runtime",
    "requirement_kind",
    "requirement",
    "purpose",
    "available",
    "evidence",
    "db_program",
    "native_runtime_status",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRequirements = [
    "python3",
    "linuxcnc",
    "milltask",
    "halcmd",
    "axis/db_demo/db_nonran.py",
    "linuxcnc.so",
    "tooldb.py",
  ];

  assert.deepEqual(
    parsedRows.map((row) => row.requirement),
    expectedRequirements,
    "tool DB native runtime readiness requirements drift",
  );

  for (const row of parsedRows) {
    assert.equal(row.path, "axis/db_demo/base.ngc", `${row.requirement}: path drift`);
    assert.equal(row.ini, "axis/db_demo/db_nonran.ini", `${row.requirement}: INI drift`);
    assert.equal(row.blocked, "L4-TOOL-DB", `${row.requirement}: blocked kind drift`);
    assert.equal(row.required_runtime, "linuxcnc_tooldata_db_process", `${row.requirement}: runtime drift`);
    assert.ok(
      ["host_command", "source_config_file", "linuxcnc_python_module"].includes(row.requirement_kind),
      `${row.requirement}: readiness kind drift`,
    );
    assert.ok(["0", "1"].includes(row.available), `${row.requirement}: invalid availability`);
    assert.notEqual(row.purpose, "-", `${row.requirement}: missing purpose`);
    if (row.available === "1") {
      assert.notEqual(row.evidence, "-", `${row.requirement}: available requirement lacks evidence`);
    }
    assert.equal(row.db_program, "./db_nonran.py", `${row.requirement}: DB_PROGRAM drift`);
    assert.ok(
      ["blocked_missing_host_runtime", "host_runtime_available_probe_not_implemented"].includes(row.native_runtime_status),
      `${row.requirement}: invalid runtime status`,
    );
    assert.equal(row.proof_kind, "native_db_process_protocol_probe_required", `${row.requirement}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.requirement}: readiness proof must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.requirement}: readiness must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.requirement}: readiness must not allow promotion`);
    assert.ok(
      row.notes.includes("keep_tool_db_blocked") ||
        row.notes.includes("probe_still_not_implemented"),
      `${row.requirement}: missing blocked/probe note`,
    );
  }

  assert.ok(
    parsedRows.some((row) => row.requirement === "python3" && row.available === "1"),
    "python3 must be available for the DB program readiness check",
  );
  assert.ok(
    parsedRows.some((row) =>
      row.requirement === "axis/db_demo/db_nonran.py" && row.available === "1",
    ),
    "db_nonran.py must be available for the DB program readiness check",
  );
  assert.ok(
    parsedRows.some((row) => row.requirement === "tooldb.py" && row.available === "1"),
    "tooldb.py must be available for the DB program readiness check",
  );

  return parsedRows;
}

function toolDbProcessNativeRuntimeProbeGateRows({
  transactionRows,
  readinessRows,
}) {
  const first = transactionRows[0];
  if (!first) {
    return [];
  }

  const readinessByRequirement = new Map(
    readinessRows.map((row) => [row.requirement, row]),
  );
  const hostRequirements = ["python3", "linuxcnc", "milltask", "halcmd"];
  const dbSourceRequirements = ["axis/db_demo/db_nonran.py"];
  const pythonModuleRequirements = ["linuxcnc.so", "tooldb.py"];
  const requiredRequirements = [
    ...hostRequirements,
    ...dbSourceRequirements,
    ...pythonModuleRequirements,
  ];
  const missingRequirements = requiredRequirements.filter((requirement) =>
    readinessByRequirement.get(requirement)?.available !== "1",
  );
  const dbProgramSourceReady = dbSourceRequirements.every((requirement) =>
    readinessByRequirement.get(requirement)?.available === "1",
  );
  const pythonModulesReady = pythonModuleRequirements.every((requirement) =>
    readinessByRequirement.get(requirement)?.available === "1",
  );
  const protocolContractReady = (
    transactionRows.length === 5 &&
    transactionRows.every((row) =>
      row.db_program === "./db_nonran.py" &&
        row.protocol_message !== "-" &&
        row.db_program_callback !== "-" &&
        row.state_targets !== "-" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeReady = missingRequirements.length === 0;
  const sourceProofReady = (
    dbProgramSourceReady &&
    pythonModulesReady &&
    protocolContractReady
  );
  const gateStatus = runtimeReady && sourceProofReady
    ? "ready_to_implement_protocol_probe"
    : "blocked_missing_host_runtime";

  return [[
    first.path,
    first.ini,
    first.blocked,
    first.db_program,
    "linuxcnc_tooldata_db_process",
    readinessByRequirement.get("python3")?.available ?? "0",
    "0",
    "0",
    flagValue(dbProgramSourceReady),
    flagValue(pythonModulesReady),
    flagValue(protocolContractReady),
    listValue(transactionRows.map((row) => `${row.transaction_phase}:${row.protocol_message}`)),
    listValue(requiredRequirements.map((requirement) =>
      `${requirement}:${readinessByRequirement.get(requirement)?.available ?? "0"}`,
    )),
    listValue(missingRequirements),
    flagValue(runtimeReady),
    flagValue(sourceProofReady),
    "native_db_process_protocol_probe_required",
    gateStatus,
    "pending",
    "0",
    "0",
    runtimeReady
      ? "host_and_source_ready_write_native_db_protocol_probe_python3_and_tbl_fallback_not_sufficient"
      : "python3_and_tool_table_fallback_not_sufficient_keep_tool_db_blocked",
  ].map(tsvValue).join("\t")];
}

function verifyToolDbProcessNativeRuntimeProbeGateRows({
  rows,
  transactionRows,
  readinessRows,
}) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "db_program",
    "required_runtime",
    "python3_available",
    "python3_sufficient",
    "tool_table_fallback_sufficient",
    "db_program_source_ready",
    "linuxcnc_python_modules_ready",
    "protocol_contract_ready",
    "protocol_transactions",
    "runtime_requirements",
    "missing_requirements",
    "runtime_ready",
    "source_proof_ready",
    "required_native_proof",
    "gate_status",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  assert.equal(parsedRows.length, 1, "tool DB runtime probe gate must have one db_demo row");
  const row = parsedRows[0];
  assert.equal(row.path, "axis/db_demo/base.ngc", "tool DB probe gate path drift");
  assert.equal(row.ini, "axis/db_demo/db_nonran.ini", "tool DB probe gate INI drift");
  assert.equal(row.blocked, "L4-TOOL-DB", "tool DB probe gate blocked kind drift");
  assert.equal(row.db_program, "./db_nonran.py", "tool DB probe gate DB_PROGRAM drift");
  assert.equal(row.required_runtime, "linuxcnc_tooldata_db_process", "tool DB probe gate runtime drift");
  assert.ok(["0", "1"].includes(row.python3_available), "invalid tool DB python3 availability");
  assert.equal(row.python3_sufficient, "0", "python3 alone must not satisfy tool DB runtime readiness");
  assert.equal(row.tool_table_fallback_sufficient, "0", "tool-table fallback must not satisfy DB_PROGRAM readiness");
  assert.equal(row.db_program_source_ready, "1", "db_nonran.py source must be ready");
  assert.equal(row.linuxcnc_python_modules_ready, "1", "linuxcnc/tooldb Python modules must be source-ready");
  assert.equal(row.protocol_contract_ready, "1", "tool DB protocol contract must be ready");
  for (const phase of [
    "startup_handshake",
    "initial_get_all",
    "spindle_load_notify",
    "tool_offset_notify",
    "spindle_unload_notify",
  ]) {
    assert.ok(row.protocol_transactions.includes(`${phase}:`), `tool DB probe gate missing transaction ${phase}`);
  }

  const expectedRequirements = [
    "python3",
    "linuxcnc",
    "milltask",
    "halcmd",
    "axis/db_demo/db_nonran.py",
    "linuxcnc.so",
    "tooldb.py",
  ];
  const readinessByRequirement = new Map(readinessRows.map((entry) => [entry.requirement, entry]));
  const expectedMissing = expectedRequirements.filter((requirement) =>
    readinessByRequirement.get(requirement)?.available !== "1",
  );
  const allRuntimeReady = expectedMissing.length === 0;
  for (const requirement of expectedRequirements) {
    assert.ok(row.runtime_requirements.includes(`${requirement}:`), `tool DB probe gate missing ${requirement}`);
  }
  assert.equal(row.runtime_ready, flagValue(allRuntimeReady), "tool DB runtime readiness drift");
  assert.equal(row.source_proof_ready, "1", "tool DB source proof must be ready before runtime probe implementation");
  assert.equal(row.required_native_proof, "native_db_process_protocol_probe_required", "tool DB native proof drift");
  assert.equal(row.proof_status, "pending", "tool DB probe gate must remain pending");
  assert.equal(row.execution_enabled, "0", "tool DB probe gate must not enable execution");
  assert.equal(row.promotion_allowed, "0", "tool DB probe gate must not allow promotion");

  if (allRuntimeReady) {
    assert.equal(row.missing_requirements, "-", "ready tool DB runtime has missing requirements");
    assert.equal(row.gate_status, "ready_to_implement_protocol_probe", "ready tool DB gate status drift");
  } else {
    assert.deepEqual(
      splitSummaryList(row.missing_requirements).sort(),
      expectedMissing.sort(),
      "tool DB missing runtime requirements drift",
    );
    assert.equal(row.gate_status, "blocked_missing_host_runtime", "missing tool DB runtime gate status drift");
  }
  assert.ok(
    row.notes.includes("python3") &&
      row.notes.includes("fallback_not_sufficient"),
    "tool DB probe gate must record python3/fallback insufficiency",
  );
  assert.equal(transactionRows.length, 5, "tool DB probe gate must consume every transaction row");

  return parsedRows;
}

function toolDbNativeProofKeyForGate(row) {
  if (row.gate_kind === "protocol_message") {
    if (row.gate === "startup:expect_reply=v2.1") {
      return "tool_db_v2_1_handshake";
    }
    if (row.gate === "request:g:get_all_until_FINI") {
      return "tool_db_getall_g_until_fini";
    }
    if (row.gate.startsWith("notify:")) {
      return "tool_db_notify_l_u_p_protocol";
    }
  }

  if (row.gate_kind === "db_program_callback") {
    if (row.gate === "registration:tooldb_callbacks_tools_loop") {
      return "tool_db_program_tooldb_module";
    }
    return "tool_db_program_nonran_callbacks";
  }

  if (row.gate_kind === "state_target") {
    if (row.gate === "ini.EMCIO.RANDOM_TOOLCHANGER=0") {
      return "db_nonran_EMCIO.RANDOM_TOOLCHANGER_ok";
    }
    if (row.gate === "ini.EMCIO.DB_PROGRAM=./db_nonran.py") {
      return "db_nonran_EMCIO.DB_PROGRAM_ok";
    }
    if (row.gate === "ini.EMCIO.TOOL_TABLE_IGNORED_WITH_DB_PROGRAM=1") {
      return "db_nonran_tool_table_ignored_with_db_program";
    }
    if (row.gate === "db_program.reload_applies_db_rules") {
      return "tool_db_program_reload_rules";
    }
    return "tool_db_program_nonran_state_targets";
  }

  return "";
}

function toolDbProcessNativeProtocolAlignmentRows(gateRows) {
  const nativeProofUnavailableRows = () => gateRows.map((row) => [
    row.path,
    row.ini,
    row.blocked,
    row.gate_kind,
    row.gate,
    row.proof_kind,
    "0",
    "-",
    "-",
    "-",
    "0",
    row.execution_enabled,
    row.promotion_allowed,
    "pending",
    "native_tool_db_probe_stdout_unavailable",
  ].map(tsvValue).join("\t"));

  if (!existsSync(nativeSourceProofSummaryPath)) {
    return nativeProofUnavailableRows();
  }

  const nativeProofRows = parseTsv(
    readFileSync(nativeSourceProofSummaryPath, "utf8"),
    [
      "boundary_class",
      "proof_key",
      "proof_value",
      "execution_enabled",
      "promotion_allowed",
      "stdout_log",
    ],
  );
  const toolDbProof = nativeProofRows.find((row) => row.boundary_class === "L4-TOOL-DB");
  if (!toolDbProof?.stdout_log) {
    return nativeProofUnavailableRows();
  }

  const stdoutPath = resolve(dirname(nativeSourceProofSummaryPath), toolDbProof.stdout_log);
  if (!existsSync(stdoutPath)) {
    return nativeProofUnavailableRows();
  }

  const stdoutValues = keyValuesFromText(readFileSync(stdoutPath, "utf8"));
  return gateRows.map((row) => {
    const nativeProofKey = toolDbNativeProofKeyForGate(row);
    const nativeProofValue = stdoutValues.get(nativeProofKey) ?? "-";
    const aligned = (
      toolDbProof.proof_key === "tool_db_native_source_protocol_proof" &&
      toolDbProof.proof_value === "1" &&
      toolDbProof.execution_enabled === "0" &&
      toolDbProof.promotion_allowed === "0" &&
      nativeProofKey !== "" &&
      nativeProofValue === "1" &&
      row.execution_enabled === "0" &&
      row.promotion_allowed === "0"
    );

    return [
      row.path,
      row.ini,
      row.blocked,
      row.gate_kind,
      row.gate,
      row.proof_kind,
      "1",
      nativeProofKey,
      nativeProofValue,
      "tool_db_native_source_protocol_proof",
      flagValue(aligned),
      row.execution_enabled,
      row.promotion_allowed,
      "pending",
      "native_source_protocol_alignment_only_no_db_process_execution",
    ].map(tsvValue).join("\t");
  });
}

function verifyToolDbProcessNativeProtocolAlignmentRows(rows, gateRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "gate_kind",
    "gate",
    "proof_kind",
    "native_stdout_available",
    "native_proof_key",
    "native_proof_value",
    "source_proof_key",
    "alignment_ok",
    "execution_enabled",
    "promotion_allowed",
    "proof_status",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_tool_db_process_native_protocol_alignment",
    gateRows.map((row) => `${row.path}:${row.gate_kind}:${row.gate}`).sort(),
    parsedRows.map((row) => `${row.path}:${row.gate_kind}:${row.gate}`).sort(),
  );
  assert.ok(parsedRows.length >= 18, "tool DB native protocol alignment must cover every generated gate");

  const stdoutAvailable = parsedRows.some((row) => row.native_stdout_available === "1");
  if (!stdoutAvailable) {
    for (const row of parsedRows) {
      assert.equal(row.native_stdout_available, "0", `${row.gate}: mixed native stdout availability`);
      assert.equal(row.alignment_ok, "0", `${row.gate}: unavailable native stdout cannot align`);
      assert.equal(row.execution_enabled, "0", `${row.gate}: alignment must not enable execution`);
      assert.equal(row.promotion_allowed, "0", `${row.gate}: alignment must not allow promotion`);
      assert.equal(row.proof_status, "pending", `${row.gate}: proof must remain pending`);
    }
    return parsedRows;
  }

  const byKind = new Map();
  for (const row of parsedRows) {
    const existing = byKind.get(row.gate_kind) ?? [];
    existing.push(row);
    byKind.set(row.gate_kind, existing);

    assert.equal(row.native_stdout_available, "1", `${row.gate}: native stdout must be available`);
    assert.equal(row.blocked, "L4-TOOL-DB", `${row.gate}: blocked kind drift`);
    assert.ok(
      ["protocol_message", "db_program_callback", "state_target"].includes(row.gate_kind),
      `${row.gate}: invalid gate kind`,
    );
    assert.notEqual(row.native_proof_key, "-", `${row.gate}: missing native proof key`);
    assert.equal(row.native_proof_value, "1", `${row.gate}: native proof value drift`);
    assert.equal(row.source_proof_key, "tool_db_native_source_protocol_proof", `${row.gate}: source proof key drift`);
    assert.equal(row.alignment_ok, "1", `${row.gate}: native protocol alignment failed`);
    assert.equal(row.execution_enabled, "0", `${row.gate}: alignment must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.gate}: alignment must not allow promotion`);
    assert.equal(row.proof_status, "pending", `${row.gate}: proof must remain pending`);
    assert.ok(
      row.notes.includes("no_db_process_execution"),
      `${row.gate}: alignment row must remain non-executing`,
    );
  }

  assert.equal(byKind.get("protocol_message")?.length, 5, "tool DB protocol alignment count drift");
  assert.equal(byKind.get("db_program_callback")?.length, 5, "tool DB callback alignment count drift");
  assert.ok((byKind.get("state_target")?.length ?? 0) >= 8, "tool DB state target alignment count drift");

  for (const row of parsedRows.filter((entry) => entry.gate_kind === "protocol_message")) {
    assert.ok(
      [
        "tool_db_v2_1_handshake",
        "tool_db_getall_g_until_fini",
        "tool_db_notify_l_u_p_protocol",
      ].includes(row.native_proof_key),
      `${row.gate}: protocol gate native proof key drift`,
    );
  }
  for (const row of parsedRows.filter((entry) => entry.gate_kind === "db_program_callback")) {
    assert.ok(
      [
        "tool_db_program_tooldb_module",
        "tool_db_program_nonran_callbacks",
      ].includes(row.native_proof_key),
      `${row.gate}: callback gate native proof key drift`,
    );
  }
  for (const row of parsedRows.filter((entry) => entry.gate_kind === "state_target")) {
    assert.ok(
      [
        "db_nonran_EMCIO.RANDOM_TOOLCHANGER_ok",
        "db_nonran_EMCIO.DB_PROGRAM_ok",
        "db_nonran_tool_table_ignored_with_db_program",
        "tool_db_program_nonran_state_targets",
        "tool_db_program_reload_rules",
      ].includes(row.native_proof_key),
      `${row.gate}: state target native proof key drift`,
    );
  }

  return parsedRows;
}

function toolDbProcessBoundarySummaryRow(row) {
  if (row.blocked !== "L4-TOOL-DB") {
    return null;
  }

  return [
    row.path,
    row.ini,
    row.blocked,
    "designed_blocked",
    "tool_database_process",
    row.linuxcnc_owner,
    row.db_program,
    listValue(toolDbProtocolMessages()),
    listValue(toolDbProgramCallbacks()),
    listValue(toolDbStateTargets(row)),
    row.tool_db_protocol_evidence,
    "db_program_v2_1_handshake_getall_load_unload_or_put",
    "linuxcnc_tooldata_db_protocol_not_tbl_fallback",
    "browser_after_node_protocol_proof_opfs_persistence_only",
    "0",
    "0",
    "keep_blocked_until_db_protocol_state_proof",
  ].map(tsvValue).join("\t");
}

function verifyToolDbProcessBoundarySummaryRows(rows, blockedRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "design_status",
    "boundary_kind",
    "linuxcnc_owner",
    "db_program",
    "protocol_messages",
    "db_program_callbacks",
    "state_targets",
    "runtime_owner_evidence",
    "required_native_proof",
    "required_node_proof",
    "required_browser_proof",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRows = blockedRows.filter((row) => row.blocked === "L4-TOOL-DB");

  verifySamePathSet(
    "wasm_tool_db_process_boundary_summary",
    expectedRows.map((row) => row.path).sort(),
    parsedRows.map((row) => row.path).sort(),
  );

  for (const row of parsedRows) {
    assert.equal(row.design_status, "designed_blocked", `${row.path}: tool DB design status drift`);
    assert.equal(row.boundary_kind, "tool_database_process", `${row.path}: tool DB boundary kind drift`);
    assert.equal(row.execution_enabled, "0", `${row.path}: tool DB boundary must remain disabled`);
    assert.equal(row.promotion_allowed, "0", `${row.path}: tool DB boundary must not allow promotion`);
    assert.equal(row.db_program, "./db_nonran.py", `${row.path}: DB_PROGRAM drift`);
    verifyLinuxCncOwnerPaths(row.path, row.linuxcnc_owner);
    for (const token of [
      "startup:expect_reply=v2.1",
      "request:g:get_all_until_FINI",
      "notify:l:SPINDLE_LOAD",
      "notify:u:SPINDLE_UNLOAD",
      "notify:p:TOOL_OFFSET",
    ]) {
      assert.ok(row.protocol_messages.includes(token), `${row.path}: missing protocol message ${token}`);
    }
    for (const token of [
      "registration:tooldb_callbacks_tools_loop",
      "g:user_get_tool",
      "p:user_put_tool",
      "l:user_load_spindle_nonran_tc",
      "u:user_unload_spindle_nonran_tc",
    ]) {
      assert.ok(row.db_program_callbacks.includes(token), `${row.path}: missing DB callback ${token}`);
    }
    for (const token of [
      "ini.EMCIO.RANDOM_TOOLCHANGER=0",
      "ini.EMCIO.DB_PROGRAM=./db_nonran.py",
      "ini.EMCIO.TOOL_TABLE_IGNORED_WITH_DB_PROGRAM=1",
      "db_program.savefile=/tmp/db_nonran_file",
      "db_program.initial_tools=T10..T19",
      "db_program.nonrandom_startup_pockets=tno+100",
      "db_program.nonrandom_load_sets_spindle_pocket_0_and_unload_restores_pocket",
      "db_program.host_sync=linuxcnc.command.load_tool_table",
    ]) {
      assert.ok(row.state_targets.includes(token), `${row.path}: missing state target ${token}`);
    }
    assert.ok(
      row.runtime_owner_evidence.includes("tooldata_db_v2_1_handshake") &&
        row.runtime_owner_evidence.includes("tooldata_db_notify_l_u_p") &&
        row.runtime_owner_evidence.includes("db_program_nonran_load_unload_callbacks"),
      `${row.path}: tool DB row lacks runtime owner evidence`,
    );
    assert.ok(row.required_node_proof.includes("not_tbl_fallback"), `${row.path}: tbl fallback proof is insufficient`);
    assert.ok(row.notes.includes("db_protocol_state_proof"), `${row.path}: missing DB protocol proof note`);
  }

  return parsedRows;
}

function pythonRuntimeEvidence() {
  const interpPythonText = readLinuxCncSourceText("src/emc/rs274ngc/interp_python.cc");
  const pythonPluginText = readLinuxCncSourceText("src/emc/pythonplugin/python_plugin.cc");
  const evidence = [];

  if (
    interpPythonText.includes("PythonPlugin *python_plugin") &&
    interpPythonText.includes("Interp::pycall") &&
    interpPythonText.includes("python_plugin->call(module,funcname")
  ) {
    evidence.push("interp_python_pycall_dispatch");
  }
  if (
    interpPythonText.includes("PY_PROLOG") &&
    interpPythonText.includes("PY_BODY") &&
    interpPythonText.includes("PY_EPILOG")
  ) {
    evidence.push("interp_python_remap_phases");
  }
  if (
    interpPythonText.includes("PyGen_Check(retval.ptr())") &&
    interpPythonText.includes("PY_FINISH_PROLOG") &&
    interpPythonText.includes("PY_FINISH_EPILOG")
  ) {
    evidence.push("interp_python_generator_finish");
  }
  if (
    interpPythonText.includes("Interp::is_pycallable") &&
    interpPythonText.includes("python_plugin->is_callable(module,funcname)")
  ) {
    evidence.push("interp_python_callable_lookup");
  }
  if (
    interpPythonText.includes("Interp::py_execute") &&
    interpPythonText.includes("python_plugin->run_string(cmd, retval, as_file)")
  ) {
    evidence.push("interp_python_execute_runtime");
  }
  if (
    pythonPluginText.includes("Py_InitializeFromConfig(&config)") &&
    pythonPluginText.includes("PyConfig_InitPythonConfig(&config)")
  ) {
    evidence.push("python_plugin_initializes_python");
  }
  if (
    pythonPluginText.includes('findString("TOPLEVEL", section)') &&
    pythonPluginText.includes("bp::exec_file(abs_path, main_namespace, main_namespace)")
  ) {
    evidence.push("python_plugin_toplevel_exec_file");
  }
  if (
    pythonPluginText.includes('findString(n, "PATH_PREPEND", "PYTHON")') &&
    pythonPluginText.includes('findString(n, "PATH_APPEND", "PYTHON")') &&
    pythonPluginText.includes("PyRun_SimpleString(pycmd)")
  ) {
    evidence.push("python_plugin_ini_python_path");
  }
  if (
    pythonPluginText.includes("PythonPlugin::call") &&
    pythonPluginText.includes("PyObject_Call(function.ptr(), tupleargs.ptr(), kwargs.ptr())")
  ) {
    evidence.push("python_plugin_callable_invoke");
  }
  if (
    pythonPluginText.includes("PythonPlugin::reload") &&
    pythonPluginText.includes("reload_on_change")
  ) {
    evidence.push("python_plugin_reload_on_change");
  }

  return uniqueSorted(evidence);
}

function linuxCncOwnerForBlockedKind(blocked) {
  if (blocked === "L4-TOOL-DB") {
    return [
      "src/emc/task/taskclass.cc",
      "src/emc/tooldata/tooldata_db.cc",
      "src/emc/tooldata/tooldata_common.cc",
      "configs/sim/axis/db_demo/db.py",
    ].join(",");
  }
  if (blocked === "L4-USER-M-PROCESS") {
    return [
      "src/emc/task/emctask.cc",
      "src/emc/usr_intf/halui.cc",
      "configs/sim/axis/vismach/millturn/mcodes/M128",
      "configs/sim/axis/vismach/millturn/mcodes/M129",
    ].join(",");
  }
  if (blocked === "L4-PYTHON-REMAP") {
    return "src/emc/rs274ngc/interp_python.cc,src/emc/pythonplugin/python_plugin.cc,configs/sim/*/python/*.py";
  }
  return "-";
}

function blockedDependencySummaryRow(record, pathMatrixByPath) {
  const blocked = pathMatrixByPath.get(record.path)?.blocked ?? "-";
  const sourceAvailable = sourceConfigPathExists(record.ini);
  if (!sourceAvailable) {
    return [
      record.path,
      record.ini,
      blocked,
      posix.dirname(record.path),
      "0",
      "-",
      "-",
      "-",
      "-",
      "-",
      "-",
      "0",
      "0",
      "0",
      "-",
      "-",
      "-",
      "-",
      "-",
      "-",
      "missing_source_ini",
    ].map(tsvValue).join("\t");
  }

  const iniText = readSourceConfigText(record.ini);
  const entries = parseIniEntries(iniText);
  const details = remapDetails(entries);
  const pythonFiles = pythonFilesForIni(record.ini, entries);
  const pythonRemapFunctions = uniqueSorted(details.map((detail) => detail.python));
  const prologFunctions = uniqueSorted(details.map((detail) => detail.prolog));
  const epilogFunctions = uniqueSorted(details.map((detail) => detail.epilog));
  const remapNgcFiles = remapNgcSourceFiles(record.ini, entries, details);
  const ngcOnlyRemaps = remapNgcSourceFiles(
    record.ini,
    entries,
    details.filter((detail) => detail.ngc && !detail.python && !detail.prolog && !detail.epilog),
  );
  const halProcess = [
    ...iniValues(entries, "HAL", "HALFILE"),
    ...iniValues(entries, "HAL", "HALCMD"),
    ...iniValues(entries, "HAL", "POSTGUI_HALFILE"),
    ...iniValues(entries, "HAL", "HALUI"),
  ].length > 0;
  const displayValues = [
    ...iniValues(entries, "DISPLAY", "DISPLAY"),
    ...iniValues(entries, "DISPLAY", "PYVCP"),
    ...iniValues(entries, "DISPLAY", "GLADEVCP"),
    ...iniValues(entries, "DISPLAY", "EMBED_TAB_COMMAND"),
  ];
  const uiProcess = displayValues.some((value) => !/^axis$/i.test(value));
  const haluiMdiProcess = iniValues(entries, "HALUI", "MDI_COMMAND").length > 0;
  const dbProgram = iniValues(entries, "EMCIO", "DB_PROGRAM")[0] ?? "";
  const toolDbEvidence = toolDbProtocolEvidence({ iniText, dbProgram });
  const userMCodes = uniqueSorted(sourceExecutionTextsForBlocked(record).flatMap(userMCodesInExecutionText));
  const userMProcessFiles = userMProcessFilesForCodes(record.ini, entries, userMCodes);
  const userMProcessEffects = userMProcessEffectsForFiles(userMProcessFiles);
  const notes = [];

  if (blocked === "L4-PYTHON-REMAP") {
    notes.push("dependency_inventory_only_no_execution");
  }
  if (blocked === "L4-TOOL-DB") {
    notes.push("tool_database_process_boundary_required");
  }
  if (blocked === "L4-USER-M-PROCESS") {
    notes.push("external_user_m_process_boundary_required");
  }
  if (ngcOnlyRemaps.length > 0 && (pythonRemapFunctions.length > 0 || prologFunctions.length > 0 || epilogFunctions.length > 0)) {
    notes.push("mixed_ngc_and_python_remaps_do_not_promote_subpaths_blindly");
  }

  return [
    record.path,
    record.ini,
    blocked,
    posix.dirname(record.path),
    "1",
    listValue(pythonFiles),
    listValue(functionOwners(pythonRemapFunctions, pythonFiles)),
    listValue(functionOwners(prologFunctions, pythonFiles)),
    listValue(functionOwners(epilogFunctions, pythonFiles)),
    listValue(remapNgcFiles),
    listValue(ngcOnlyRemaps),
    flagValue(halProcess),
    flagValue(uiProcess),
    flagValue(haluiMdiProcess),
    dbProgram || "-",
    listValue(toolDbEvidence),
    listValue(userMCodes),
    listValue(userMProcessFiles),
    listValue(userMProcessEffects),
    linuxCncOwnerForBlockedKind(blocked),
    listValue(notes),
  ].map(tsvValue).join("\t");
}

function verifyBlockedDependencySummaryRows(rows, expectedRecords) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "family",
    "source_available",
    "python_modules",
    "python_remap_functions",
    "prolog_functions",
    "epilog_functions",
    "remap_ngc_files",
    "ngc_only_subpaths",
    "hal_process",
    "ui_process",
    "halui_mdi_process",
    "db_program",
    "tool_db_protocol_evidence",
    "user_m_execution_codes",
    "user_m_process_files",
    "user_m_process_effects",
    "linuxcnc_owner",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedPaths = expectedRecords.map((record) => record.path).sort();

  verifySamePathSet(
    "wasm_blocked_dependency_summary",
    expectedPaths,
    parsedRows.map((record) => record.path).sort(),
  );

  for (const row of parsedRows) {
    assert.equal(row.source_available, "1", `${row.path}: blocked source INI must be readable`);
    for (const field of ["hal_process", "ui_process", "halui_mdi_process"]) {
      assert.ok(["0", "1"].includes(row[field]), `${row.path}: invalid ${field} flag`);
    }
    assert.notEqual(row.linuxcnc_owner, "-", `${row.path}: blocked row lacks LinuxCNC owner`);
    for (const ownerPath of row.linuxcnc_owner.split(",").filter(Boolean)) {
      if (ownerPath.includes("*")) {
        continue;
      }
      assert.ok(
        linuxCncSourcePathExists(ownerPath),
        `${row.path}: LinuxCNC owner path does not exist: ${ownerPath}`,
      );
    }
    if (row.blocked === "L4-PYTHON-REMAP") {
      assert.notEqual(
        [row.python_modules, row.python_remap_functions, row.prolog_functions, row.epilog_functions]
          .join(","),
        "-,-,-,-",
        `${row.path}: Python-remap row lacks Python dependency evidence`,
      );
      assert.equal(
        [row.python_remap_functions, row.prolog_functions, row.epilog_functions]
          .join(",")
          .includes("@UNRESOLVED"),
        false,
        `${row.path}: Python-remap row has unresolved callable owner`,
      );
      assert.ok(
        row.notes.includes("dependency_inventory_only_no_execution"),
        `${row.path}: Python-remap row must remain inventory-only`,
      );
    }
    if (row.blocked === "L4-TOOL-DB") {
      assert.notEqual(row.db_program, "-", `${row.path}: tool DB row lacks DB_PROGRAM`);
      assert.notEqual(row.tool_db_protocol_evidence, "-", `${row.path}: tool DB row lacks protocol evidence`);
      for (const evidence of [
        "ini_db_program_declared",
        "ini_tool_table_replaced",
        "task_db_mode_init",
        "task_load_unload_notify",
        "tooldata_db_v2_1_handshake",
        "tooldata_db_child_process",
        "tooldata_db_getall_g_fini",
        "tooldata_db_notify_l_u_p",
        "db_program_tooldb_module",
        "db_program_get_put_callbacks",
        "db_program_nonran_load_unload_callbacks",
        "db_program_persistent_flatfile_state",
        "db_program_callback_registration",
      ]) {
        assert.ok(
          row.tool_db_protocol_evidence.includes(evidence),
          `${row.path}: tool DB row lacks ${evidence} evidence`,
        );
      }
      assert.ok(
        row.linuxcnc_owner.includes("src/emc/tooldata/tooldata_db.cc"),
        `${row.path}: tool DB row lacks LinuxCNC owner`,
      );
    }
    if (row.blocked === "L4-USER-M-PROCESS") {
      assert.notEqual(row.user_m_execution_codes, "-", `${row.path}: user-M process row lacks M-code evidence`);
      assert.notEqual(row.user_m_process_files, "-", `${row.path}: user-M process row lacks process file evidence`);
      assert.notEqual(row.user_m_process_effects, "-", `${row.path}: user-M process row lacks side-effect evidence`);
      assert.ok(
        row.user_m_process_files.includes("mcodes/M128") &&
          row.user_m_process_files.includes("mcodes/M129"),
        `${row.path}: user-M process row lacks M128/M129 source files`,
      );
      for (const effect of [
        "M128:tcl_hal_runtime",
        "M128:ini_file_parse",
        "M128:kinstype_guard",
        "M128:ini_axis_limit_hal_setp",
        "M128:mill_limit_values",
        "M129:tcl_hal_runtime",
        "M129:ini_file_parse",
        "M129:kinstype_guard",
        "M129:ini_axis_limit_hal_setp",
        "M129:turn_limit_values",
      ]) {
        assert.ok(
          row.user_m_process_effects.includes(effect),
          `${row.path}: user-M process row lacks ${effect} evidence`,
        );
      }
      assert.ok(
        row.linuxcnc_owner.includes("src/emc/task/emctask.cc"),
        `${row.path}: user-M process row lacks LinuxCNC task owner`,
      );
      assert.equal(row.hal_process, "1", `${row.path}: user-M process row lacks HAL dependency`);
      assert.equal(row.halui_mdi_process, "1", `${row.path}: user-M process row lacks HALUI dependency`);
    }
  }

  return parsedRows;
}

function verifyFullProcessBoundaryDesign(markdownText, rows) {
  const rowsByPath = new Map(rows.map((row) => [row.path, row]));
  const requiredRows = [
    {
      path: "axis/vismach/millturn/example.ngc",
      blocked: "L4-USER-M-PROCESS",
      tokens: [
        "External User-M Process Boundary",
        "configs/sim/axis/vismach/millturn/mcodes/M128",
        "configs/sim/axis/vismach/millturn/mcodes/M129",
        "src/emc/task/emctask.cc",
        "src/emc/task/emctaskmain.cc",
        "src/emc/usr_intf/halui.cc",
        "user-m-process-boundary-summary.tsv",
        "kinstype.is-0",
        "kinstype.is-1",
        "ini.[xyz].min_limit",
        "ini.[xyz].max_acceleration",
        "promotion_allowed=0",
        "`USER_M_COMMAND` event alone is not sufficient",
      ],
    },
    {
      path: "axis/db_demo/base.ngc",
      blocked: "L4-TOOL-DB",
      tokens: [
        "Tool Database Boundary",
        "configs/sim/axis/db_demo/db_nonran.ini",
        "configs/sim/axis/db_demo/db.py",
        "src/emc/task/taskclass.cc",
        "src/emc/tooldata/tooldata_db.cc",
        "src/emc/tooldata/tooldata_common.cc",
        "tool-db-process-boundary-summary.tsv",
        "v2.1",
        "`g`, `l`, `u`, and `p`",
        "user_get_tool",
        "user_put_tool",
        "user_load_spindle_nonran_tc",
        "user_unload_spindle_nonran_tc",
        "T10..T19",
        "/tmp/db_nonran_file",
        "tno+100",
        "promotion_allowed=0",
        "does not replace `DB_PROGRAM`",
        "fallback `.tbl`",
      ],
    },
  ];

  for (const required of requiredRows) {
    const row = rowsByPath.get(required.path);
    assert.ok(row, `${required.path}: blocked dependency row missing for design guard`);
    assert.equal(row.blocked, required.blocked, `${required.path}: design guard blocked kind drift`);
    assert.ok(
      markdownText.includes(`\`${required.path}\``),
      `${required.path}: full-process boundary design missing path`,
    );
    assert.ok(
      markdownText.includes(required.blocked),
      `${required.path}: full-process boundary design missing blocked kind`,
    );
    for (const token of required.tokens) {
      assert.ok(
        markdownText.includes(token),
        `${required.path}: full-process boundary design missing token ${token}`,
      );
    }
  }

  assert.ok(
    markdownText.includes("Python-remap rows remain inventory-only"),
    "full-process boundary design must keep Python-remap rows inventory-only",
  );
  for (const token of [
    "next-boundary-worklist.tsv",
    "`execution_enabled=0`",
    "`promotion_allowed=0`",
    "records the LinuxCNC owner set",
    "names the next boundary-design",
    "action before promotion",
    "native-proof-alignment-summary.tsv",
    "consumed by generated worklist and native proof-gate",
    "`external_user_m_process` for `axis/vismach/millturn/example.ngc`",
    "`tool_database_process` for `axis/db_demo/base.ngc`",
    "Python runtime family rows follow as inventory-only targets",
  ]) {
    assert.ok(
      markdownText.includes(token),
      `full-process boundary design missing next-worklist token ${token}`,
    );
  }
  assert.ok(
    markdownText.includes("Do not implement HAL, task, HALUI, Tcl, Python, tool-database, or external"),
    "full-process boundary design must preserve non-goal guard",
  );
}

function fullProcessBoundarySummaryRow(row) {
  if (row.blocked === "L4-USER-M-PROCESS") {
    return [
      row.path,
      row.ini,
      row.blocked,
      "designed_blocked",
      "external_user_m_process",
      row.linuxcnc_owner,
      row.user_m_process_effects,
      "kinstype_guard_and_ini_xyz_hal_pin_state",
      "linuxcnc_owned_state_boundary_not_user_m_event_only",
      "sdk_wasm_boundary_after_node_state_proof",
      "browser_after_node_state_proof_no_full_process_claim",
      "0",
      "keep_blocked_until_m128_m129_state_proof",
    ].map(tsvValue).join("\t");
  }

  if (row.blocked === "L4-TOOL-DB") {
    return [
      row.path,
      row.ini,
      row.blocked,
      "designed_blocked",
      "tool_database_process",
      row.linuxcnc_owner,
      row.tool_db_protocol_evidence,
      "db_program_v2_1_handshake_getall_load_unload_or_put",
      "linuxcnc_tooldata_db_protocol_not_tbl_fallback",
      "sdk_wasm_boundary_after_protocol_proof",
      "browser_after_node_protocol_proof_opfs_persistence_only",
      "0",
      "keep_blocked_until_db_protocol_state_proof",
    ].map(tsvValue).join("\t");
  }

  return null;
}

function verifyFullProcessBoundarySummaryRows(rows, blockedRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "design_status",
    "boundary_kind",
    "linuxcnc_owner",
    "runtime_owner_evidence",
    "required_native_proof",
    "required_node_proof",
    "required_browser_proof",
    "browser_policy",
    "execution_enabled",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRows = blockedRows.filter((row) =>
    ["L4-TOOL-DB", "L4-USER-M-PROCESS"].includes(row.blocked),
  );

  verifySamePathSet(
    "wasm_full_process_boundary_summary",
    expectedRows.map((row) => row.path).sort(),
    parsedRows.map((row) => row.path).sort(),
  );

  for (const row of parsedRows) {
    assert.equal(row.design_status, "designed_blocked", `${row.path}: design status drift`);
    assert.equal(row.execution_enabled, "0", `${row.path}: full-process boundary must remain disabled`);
    assert.notEqual(row.linuxcnc_owner, "-", `${row.path}: full-process row lacks owner`);

    if (row.blocked === "L4-USER-M-PROCESS") {
      assert.equal(
        row.boundary_kind,
        "external_user_m_process",
        `${row.path}: user-M boundary kind drift`,
      );
      assert.ok(
        row.required_native_proof.includes("ini_xyz_hal_pin_state"),
        `${row.path}: user-M row lacks HAL pin state proof`,
      );
      assert.ok(
        row.runtime_owner_evidence.includes("tcl_hal_runtime") &&
          row.runtime_owner_evidence.includes("kinstype_guard") &&
          row.runtime_owner_evidence.includes("ini_axis_limit_hal_setp"),
        `${row.path}: user-M row lacks runtime owner evidence`,
      );
      assert.ok(
        row.required_node_proof.includes("not_user_m_event_only"),
        `${row.path}: user-M row must reject event-only proof`,
      );
      assert.ok(
        row.notes.includes("m128_m129_state_proof"),
        `${row.path}: user-M row lacks M128/M129 proof note`,
      );
    } else if (row.blocked === "L4-TOOL-DB") {
      assert.equal(
        row.boundary_kind,
        "tool_database_process",
        `${row.path}: tool DB boundary kind drift`,
      );
      assert.ok(
        row.required_native_proof.includes("v2_1_handshake"),
        `${row.path}: tool DB row lacks protocol handshake proof`,
      );
      assert.ok(
        row.runtime_owner_evidence.includes("tooldata_db_v2_1_handshake") &&
          row.runtime_owner_evidence.includes("tooldata_db_getall_g_fini") &&
          row.runtime_owner_evidence.includes("tooldata_db_notify_l_u_p"),
        `${row.path}: tool DB row lacks runtime owner evidence`,
      );
      assert.ok(
        row.required_node_proof.includes("not_tbl_fallback"),
        `${row.path}: tool DB row must reject tbl fallback proof`,
      );
      assert.ok(
        row.notes.includes("db_protocol_state_proof"),
        `${row.path}: tool DB row lacks protocol proof note`,
      );
    } else {
      throw new Error(`${row.path}: unexpected full-process blocked kind ${row.blocked}`);
    }
  }

  return parsedRows;
}

function pythonRemapBoundarySummaryRow(row) {
  if (row.blocked !== "L4-PYTHON-REMAP") {
    return null;
  }

  return [
    row.path,
    row.ini,
    row.blocked,
    "inventory_only",
    row.python_modules,
    row.python_remap_functions,
    row.prolog_functions,
    row.epilog_functions,
    row.remap_ngc_files,
    row.ngc_only_subpaths,
    row.hal_process,
    row.ui_process,
    row.halui_mdi_process,
    row.linuxcnc_owner,
    listValue(pythonRuntimeEvidence()),
    "python_runtime_boundary_required",
    "0",
    row.notes,
  ].map(tsvValue).join("\t");
}

function verifyPythonRemapBoundarySummaryRows(rows, blockedRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "design_status",
    "python_modules",
    "python_remap_functions",
    "prolog_functions",
    "epilog_functions",
    "remap_ngc_files",
    "ngc_only_subpaths",
    "hal_process",
    "ui_process",
    "halui_mdi_process",
    "linuxcnc_owner",
    "python_runtime_evidence",
    "required_boundary",
    "execution_enabled",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRows = blockedRows.filter((row) => row.blocked === "L4-PYTHON-REMAP");

  verifySamePathSet(
    "wasm_python_remap_boundary_summary",
    expectedRows.map((row) => row.path).sort(),
    parsedRows.map((row) => row.path).sort(),
  );

  for (const row of parsedRows) {
    assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.path}: Python boundary blocked kind drift`);
    assert.equal(row.design_status, "inventory_only", `${row.path}: Python boundary design status drift`);
    assert.equal(row.required_boundary, "python_runtime_boundary_required", `${row.path}: Python boundary type drift`);
    assert.equal(row.execution_enabled, "0", `${row.path}: Python remap execution must remain disabled`);
    assert.ok(
      row.notes.includes("dependency_inventory_only_no_execution"),
      `${row.path}: Python boundary row must remain inventory-only`,
    );
    assert.notEqual(
      [row.python_modules, row.python_remap_functions, row.prolog_functions, row.epilog_functions]
        .join(","),
      "-,-,-,-",
      `${row.path}: Python boundary row lacks Python dependency evidence`,
    );
    assert.ok(
      row.linuxcnc_owner.includes("src/emc/rs274ngc/interp_python.cc"),
      `${row.path}: Python boundary row lacks interpreter Python owner`,
    );
    assert.notEqual(
      row.python_runtime_evidence,
      "-",
      `${row.path}: Python boundary row lacks runtime owner evidence`,
    );
    for (const evidence of [
      "interp_python_pycall_dispatch",
      "interp_python_remap_phases",
      "interp_python_generator_finish",
      "interp_python_callable_lookup",
      "interp_python_execute_runtime",
      "python_plugin_initializes_python",
      "python_plugin_toplevel_exec_file",
      "python_plugin_ini_python_path",
      "python_plugin_callable_invoke",
      "python_plugin_reload_on_change",
    ]) {
      assert.ok(
        row.python_runtime_evidence.includes(evidence),
        `${row.path}: Python boundary row lacks ${evidence} evidence`,
      );
    }
    for (const field of ["hal_process", "ui_process", "halui_mdi_process"]) {
      assert.ok(["0", "1"].includes(row[field]), `${row.path}: invalid ${field} flag`);
    }
  }

  return parsedRows;
}

function pythonRemapRuntimeGateRows(row) {
  if (row.blocked !== "L4-PYTHON-REMAP") {
    return [];
  }

  const gateRows = [];
  const addGates = (gateKind, values, proofKind) => {
    for (const value of splitSummaryList(values)) {
      gateRows.push([
        row.path,
        row.ini,
        row.blocked,
        gateKind,
        value,
        row.linuxcnc_owner,
        row.python_runtime_evidence,
        proofKind,
        "pending",
        "0",
        "0",
        row.notes,
      ].map(tsvValue).join("\t"));
    }
  };

  addGates("python_module", row.python_modules, "python_module_dependency");
  addGates("python_remap_callable", row.python_remap_functions, "python_runtime_callable");
  addGates("python_prolog_callable", row.prolog_functions, "python_runtime_callable");
  addGates("python_epilog_callable", row.epilog_functions, "python_runtime_callable");
  addGates("remap_ngc_file", row.remap_ngc_files, "linuxcnc_ngc_remap_subpath");
  addGates("ngc_only_subpath", row.ngc_only_subpaths, "separable_ngc_subpath_inventory_only");

  for (const [field, enabled] of [
    ["hal_process", row.hal_process],
    ["ui_process", row.ui_process],
    ["halui_mdi_process", row.halui_mdi_process],
  ]) {
    if (enabled === "1") {
      gateRows.push([
        row.path,
        row.ini,
        row.blocked,
        "process_assumption",
        field,
        row.linuxcnc_owner,
        row.python_runtime_evidence,
        "full_process_dependency_assumption",
        "pending",
        "0",
        "0",
        row.notes,
      ].map(tsvValue).join("\t"));
    }
  }

  for (const evidence of splitSummaryList(row.python_runtime_evidence)) {
    gateRows.push([
      row.path,
      row.ini,
      row.blocked,
      "python_runtime_owner_evidence",
      evidence,
      row.linuxcnc_owner,
      row.python_runtime_evidence,
      "linuxcnc_python_runtime_owner",
      "pending",
      "0",
      "0",
      row.notes,
    ].map(tsvValue).join("\t"));
  }

  return gateRows;
}

function verifyPythonRemapRuntimeGateRows(rows, pythonRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "gate_kind",
    "gate",
    "linuxcnc_owner",
    "runtime_owner_evidence",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedPaths = pythonRows.map((row) => row.path).sort();
  const actualPaths = uniqueSorted(parsedRows.map((row) => row.path));

  assert.deepEqual(actualPaths, expectedPaths, "Python runtime gates must cover every Python-remap row");
  assert.ok(parsedRows.length > pythonRows.length, "Python runtime gates must expand dependency rows");

  const allowedGateKinds = new Set([
    "python_module",
    "python_remap_callable",
    "python_prolog_callable",
    "python_epilog_callable",
    "remap_ngc_file",
    "ngc_only_subpath",
    "process_assumption",
    "python_runtime_owner_evidence",
  ]);
  const allowedProofKinds = new Set([
    "python_module_dependency",
    "python_runtime_callable",
    "linuxcnc_ngc_remap_subpath",
    "separable_ngc_subpath_inventory_only",
    "full_process_dependency_assumption",
    "linuxcnc_python_runtime_owner",
  ]);

  const rowsByPath = new Map();
  for (const row of parsedRows) {
    const existing = rowsByPath.get(row.path) ?? [];
    existing.push(row);
    rowsByPath.set(row.path, existing);

    assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.path}: Python runtime gate blocked kind drift`);
    assert.ok(allowedGateKinds.has(row.gate_kind), `${row.path}: unknown Python runtime gate kind ${row.gate_kind}`);
    assert.notEqual(row.gate, "-", `${row.path}: Python runtime gate missing value`);
    verifyLinuxCncOwnerPaths(row.path, row.linuxcnc_owner);
    assert.notEqual(row.runtime_owner_evidence, "-", `${row.path}: Python runtime gate lacks owner evidence`);
    assert.ok(allowedProofKinds.has(row.proof_kind), `${row.path}: unknown Python runtime proof kind ${row.proof_kind}`);
    assert.equal(row.proof_status, "pending", `${row.path}: Python runtime proof gate must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.path}: Python runtime gate must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.path}: Python runtime gate must not allow promotion`);
    assert.ok(
      row.notes.includes("dependency_inventory_only_no_execution"),
      `${row.path}: Python runtime gate must remain inventory-only`,
    );
  }

  for (const row of pythonRows) {
    const pathRows = rowsByPath.get(row.path) ?? [];
    assert.ok(
      pathRows.some((gate) => gate.gate_kind === "python_runtime_owner_evidence"),
      `${row.path}: Python runtime owner gate missing`,
    );
    assert.ok(
      pathRows.some((gate) =>
        ["python_module", "python_remap_callable", "python_prolog_callable", "python_epilog_callable"].includes(gate.gate_kind),
      ),
      `${row.path}: Python dependency gate missing`,
    );
    if (row.ngc_only_subpaths !== "-") {
      assert.ok(
        pathRows.some((gate) => gate.gate_kind === "ngc_only_subpath"),
        `${row.path}: NGC-only subpath gate missing`,
      );
      assert.ok(
        row.notes.includes("mixed_ngc_and_python_remaps_do_not_promote_subpaths_blindly") ||
          (row.python_remap_functions === "-" && row.prolog_functions === "-" && row.epilog_functions === "-"),
        `${row.path}: NGC-only subpaths require mixed-remap note or pure NGC accounting`,
      );
    }
    for (const field of ["hal_process", "ui_process", "halui_mdi_process"]) {
      if (row[field] === "1") {
        assert.ok(
          pathRows.some((gate) => gate.gate_kind === "process_assumption" && gate.gate === field),
          `${row.path}: missing ${field} process-assumption gate`,
        );
      }
    }
  }

  return parsedRows;
}

function pythonNativeRuntimeKeyForEvidence(evidence) {
  return new Map([
    ["interp_python_pycall_dispatch", "python_runtime_pycall_dispatch"],
    ["interp_python_remap_phases", "python_runtime_remap_phases"],
    ["interp_python_generator_finish", "python_runtime_generator_finish"],
    ["interp_python_callable_lookup", "python_runtime_callable_lookup"],
    ["interp_python_execute_runtime", "python_runtime_execute_runtime"],
    ["python_plugin_initializes_python", "python_plugin_initializes_python"],
    ["python_plugin_toplevel_exec_file", "python_plugin_toplevel_exec_file"],
    ["python_plugin_ini_python_path", "python_plugin_ini_python_path"],
    ["python_plugin_callable_invoke", "python_plugin_callable_invoke"],
    ["python_plugin_reload_on_change", "python_plugin_reload_on_change"],
  ]).get(evidence) ?? "";
}

function pythonNativeInventoryKeyForGate(row) {
  if (row.path.startsWith("axis/laser/")) {
    return "python_family_axis_laser_inventory";
  }
  if (row.path.startsWith("axis/vismach/5axis/table-rotary_spindle-rotary-nutating/")) {
    return "python_family_twp_nutating_inventory";
  }
  if (row.path.startsWith("axis/remap/cycle/")) {
    return "python_family_axis_remap_cycle_inventory";
  }
  if (row.path.startsWith("gmoccapy/")) {
    return "python_family_gmoccapy_stdglue_inventory";
  }
  return "python_remap_native_source_inventory_proof";
}

function pythonRemapNativeRuntimeAlignmentRows(gateRows) {
  const nativeProofUnavailableRows = () => gateRows.map((row) => [
    row.path,
    row.ini,
    row.blocked,
    row.gate_kind,
    row.gate,
    row.proof_kind,
    "0",
    "-",
    "-",
    "-",
    "0",
    row.execution_enabled,
    row.promotion_allowed,
    "pending",
    "native_python_probe_stdout_unavailable",
  ].map(tsvValue).join("\t"));

  if (!existsSync(nativeSourceProofSummaryPath)) {
    return nativeProofUnavailableRows();
  }

  const nativeProofRows = parseTsv(
    readFileSync(nativeSourceProofSummaryPath, "utf8"),
    [
      "boundary_class",
      "proof_key",
      "proof_value",
      "execution_enabled",
      "promotion_allowed",
      "stdout_log",
    ],
  );
  const pythonProof = nativeProofRows.find((row) => row.boundary_class === "L4-PYTHON-REMAP");
  if (!pythonProof?.stdout_log) {
    return nativeProofUnavailableRows();
  }

  const stdoutPath = resolve(dirname(nativeSourceProofSummaryPath), pythonProof.stdout_log);
  if (!existsSync(stdoutPath)) {
    return nativeProofUnavailableRows();
  }

  const stdoutValues = keyValuesFromText(readFileSync(stdoutPath, "utf8"));
  return gateRows.map((row) => {
    const nativeProofKey = row.gate_kind === "python_runtime_owner_evidence"
      ? pythonNativeRuntimeKeyForEvidence(row.gate)
      : pythonNativeInventoryKeyForGate(row);
    const nativeProofValue = stdoutValues.get(nativeProofKey) ?? "-";
    const aligned = (
      pythonProof.proof_key === "python_remap_native_source_inventory_proof" &&
      pythonProof.proof_value === "1" &&
      pythonProof.execution_enabled === "0" &&
      pythonProof.promotion_allowed === "0" &&
      nativeProofKey !== "" &&
      nativeProofValue === "1" &&
      row.execution_enabled === "0" &&
      row.promotion_allowed === "0"
    );

    return [
      row.path,
      row.ini,
      row.blocked,
      row.gate_kind,
      row.gate,
      row.proof_kind,
      "1",
      nativeProofKey,
      nativeProofValue,
      "python_remap_native_source_inventory_proof",
      flagValue(aligned),
      row.execution_enabled,
      row.promotion_allowed,
      "pending",
      "native_source_python_runtime_alignment_only_no_python_execution",
    ].map(tsvValue).join("\t");
  });
}

function verifyPythonRemapNativeRuntimeAlignmentRows(rows, gateRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "gate_kind",
    "gate",
    "proof_kind",
    "native_stdout_available",
    "native_proof_key",
    "native_proof_value",
    "source_proof_key",
    "alignment_ok",
    "execution_enabled",
    "promotion_allowed",
    "proof_status",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_python_remap_native_runtime_alignment",
    gateRows.map((row) => `${row.path}:${row.gate_kind}:${row.gate}`).sort(),
    parsedRows.map((row) => `${row.path}:${row.gate_kind}:${row.gate}`).sort(),
  );
  assert.ok(parsedRows.length > gateRows.length - 1, "Python native runtime alignment must cover every generated gate");

  const stdoutAvailable = parsedRows.some((row) => row.native_stdout_available === "1");
  if (!stdoutAvailable) {
    for (const row of parsedRows) {
      assert.equal(row.native_stdout_available, "0", `${row.gate}: mixed native stdout availability`);
      assert.equal(row.alignment_ok, "0", `${row.gate}: unavailable native stdout cannot align`);
      assert.equal(row.execution_enabled, "0", `${row.gate}: alignment must not enable execution`);
      assert.equal(row.promotion_allowed, "0", `${row.gate}: alignment must not allow promotion`);
      assert.equal(row.proof_status, "pending", `${row.gate}: proof must remain pending`);
    }
    return parsedRows;
  }

  const runtimeOwnerRows = parsedRows.filter((row) => row.gate_kind === "python_runtime_owner_evidence");
  assert.ok(runtimeOwnerRows.length > 0, "Python runtime owner alignment rows are required");

  for (const row of parsedRows) {
    assert.equal(row.native_stdout_available, "1", `${row.gate}: native stdout must be available`);
    assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.gate}: blocked kind drift`);
    assert.notEqual(row.native_proof_key, "-", `${row.gate}: missing native proof key`);
    assert.equal(row.native_proof_value, "1", `${row.gate}: native proof value drift`);
    assert.equal(
      row.source_proof_key,
      "python_remap_native_source_inventory_proof",
      `${row.gate}: source proof key drift`,
    );
    assert.equal(row.alignment_ok, "1", `${row.gate}: native Python runtime alignment failed`);
    assert.equal(row.execution_enabled, "0", `${row.gate}: alignment must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.gate}: alignment must not allow promotion`);
    assert.equal(row.proof_status, "pending", `${row.gate}: proof must remain pending`);
    assert.ok(
      row.notes.includes("no_python_execution"),
      `${row.gate}: alignment row must remain non-executing`,
    );

    if (row.gate_kind === "python_runtime_owner_evidence") {
      assert.equal(
        row.native_proof_key,
        pythonNativeRuntimeKeyForEvidence(row.gate),
        `${row.gate}: runtime owner native key drift`,
      );
    } else {
      assert.ok(
        [
          "python_family_axis_laser_inventory",
          "python_family_twp_nutating_inventory",
          "python_family_axis_remap_cycle_inventory",
          "python_family_gmoccapy_stdglue_inventory",
          "python_remap_native_source_inventory_proof",
        ].includes(row.native_proof_key),
        `${row.gate}: dependency native inventory key drift`,
      );
    }
  }

  for (const key of [
    "python_runtime_pycall_dispatch",
    "python_runtime_remap_phases",
    "python_runtime_generator_finish",
    "python_runtime_callable_lookup",
    "python_runtime_execute_runtime",
    "python_plugin_initializes_python",
    "python_plugin_toplevel_exec_file",
    "python_plugin_ini_python_path",
    "python_plugin_callable_invoke",
    "python_plugin_reload_on_change",
  ]) {
    assert.ok(
      runtimeOwnerRows.some((row) => row.native_proof_key === key),
      `Python runtime owner alignment missing ${key}`,
    );
  }

  return parsedRows;
}

function splitSummaryList(value) {
  return value === "-" ? [] : value.split(",").filter(Boolean);
}

function pythonRemapFamilySummaryRows(rows) {
  const byFamily = new Map();
  for (const row of rows) {
    const family = posix.dirname(row.path);
    const existing = byFamily.get(family) ?? [];
    existing.push(row);
    byFamily.set(family, existing);
  }

  return [...byFamily.entries()]
    .sort(([left], [right]) => left.localeCompare(right))
    .map(([family, familyRows]) => {
      const aggregateField = (field) =>
        listValue(uniqueSorted(familyRows.flatMap((row) => splitSummaryList(row[field]))));
      return [
        family,
        familyRows.length,
        new Set(familyRows.map((row) => row.ini)).size,
        aggregateField("python_modules"),
        aggregateField("python_remap_functions"),
        aggregateField("prolog_functions"),
        aggregateField("epilog_functions"),
        aggregateField("ngc_only_subpaths"),
        aggregateField("python_runtime_evidence"),
        flagValue(familyRows.some((row) => row.hal_process === "1")),
        flagValue(familyRows.some((row) => row.ui_process === "1")),
        flagValue(familyRows.some((row) => row.halui_mdi_process === "1")),
        flagValue(familyRows.some((row) => row.execution_enabled !== "0")),
        listValue(uniqueSorted(familyRows.flatMap((row) => splitSummaryList(row.notes)))),
      ].map(tsvValue).join("\t");
    });
}

function verifyPythonRemapFamilySummaryRows(rows, pythonRows) {
  const expectedHeaders = [
    "family",
    "row_count",
    "ini_count",
    "python_modules",
    "python_remap_functions",
    "prolog_functions",
    "epilog_functions",
    "ngc_only_subpaths",
    "python_runtime_evidence",
    "hal_process",
    "ui_process",
    "halui_mdi_process",
    "execution_enabled",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedFamilies = uniqueSorted(pythonRows.map((row) => posix.dirname(row.path)));

  assert.deepEqual(
    parsedRows.map((row) => row.family).sort(),
    expectedFamilies,
    "python-remap family summary family set drift",
  );
  assert.equal(
    parsedRows.reduce((count, row) => count + Number(row.row_count), 0),
    pythonRows.length,
    "python-remap family summary row counts must cover all Python rows",
  );

  const requiredFamilies = new Set([
    "axis/laser",
    "axis/remap/extend-builtins/nc_files",
    "axis/vismach/5axis/table-rotary_spindle-rotary-nutating/demos",
    "gmoccapy/macros",
  ]);
  for (const family of requiredFamilies) {
    assert.ok(
      parsedRows.some((row) => row.family === family),
      `${family}: required Python-remap family summary row missing`,
    );
  }

  for (const row of parsedRows) {
    assert.ok(/^[1-9][0-9]*$/.test(row.row_count), `${row.family}: invalid row count`);
    assert.ok(/^[1-9][0-9]*$/.test(row.ini_count), `${row.family}: invalid INI count`);
    assert.notEqual(row.python_modules, "-", `${row.family}: family lacks Python module evidence`);
    assert.equal(
      [row.python_remap_functions, row.prolog_functions, row.epilog_functions]
        .join(",")
        .includes("@UNRESOLVED"),
      false,
      `${row.family}: family has unresolved Python callable owner`,
    );
    assert.notEqual(row.python_runtime_evidence, "-", `${row.family}: family lacks Python runtime evidence`);
    assert.ok(
      row.python_runtime_evidence.includes("interp_python_pycall_dispatch") &&
        row.python_runtime_evidence.includes("python_plugin_callable_invoke"),
      `${row.family}: family lacks LinuxCNC Python runtime owner evidence`,
    );
    assert.equal(row.execution_enabled, "0", `${row.family}: Python family execution must remain disabled`);
    assert.ok(
      row.notes.includes("dependency_inventory_only_no_execution"),
      `${row.family}: Python family must remain inventory-only`,
    );
    for (const field of ["hal_process", "ui_process", "halui_mdi_process"]) {
      assert.ok(["0", "1"].includes(row[field]), `${row.family}: invalid ${field} flag`);
    }
    if (row.ngc_only_subpaths !== "-") {
      assert.ok(
        row.notes.includes("mixed_ngc_and_python_remaps_do_not_promote_subpaths_blindly") ||
          row.python_remap_functions === "-" && row.prolog_functions === "-" && row.epilog_functions === "-",
        `${row.family}: NGC-only subpaths need mixed-remap note or pure NGC accounting`,
      );
    }
  }

  return parsedRows;
}

function pythonRuntimePhases(evidenceText) {
  const evidence = new Set(splitSummaryList(evidenceText));
  const phases = [];
  const add = (evidenceKey, phase) => {
    if (evidence.has(evidenceKey)) {
      phases.push(phase);
    }
  };

  add("python_plugin_initializes_python", "initialize_python");
  add("python_plugin_ini_python_path", "apply_ini_python_path");
  add("python_plugin_toplevel_exec_file", "execute_toplevel");
  add("interp_python_callable_lookup", "callable_lookup");
  add("interp_python_pycall_dispatch", "pycall_dispatch");
  add("python_plugin_callable_invoke", "callable_invoke");
  add("interp_python_remap_phases", "remap_phase_dispatch");
  add("interp_python_generator_finish", "generator_finish");
  add("interp_python_execute_runtime", "execute_python_runtime");
  add("python_plugin_reload_on_change", "reload_on_change");

  return phases;
}

function pythonRemapRuntimeContractRows(familyRows) {
  return familyRows.map((row) => {
    const callables = uniqueSorted([
      ...splitSummaryList(row.python_remap_functions),
      ...splitSummaryList(row.prolog_functions),
      ...splitSummaryList(row.epilog_functions),
    ]);
    const processAssumptions = [];
    if (row.hal_process === "1") {
      processAssumptions.push("hal_process");
    }
    if (row.ui_process === "1") {
      processAssumptions.push("ui_process");
    }
    if (row.halui_mdi_process === "1") {
      processAssumptions.push("halui_mdi_process");
    }
    const notes = uniqueSorted([
      ...splitSummaryList(row.notes),
      "python_runtime_contract_only_no_execution",
    ]);

    return [
      row.family,
      "L4-PYTHON-REMAP",
      "inventory_only",
      row.row_count,
      row.ini_count,
      listValue(pythonRuntimePhases(row.python_runtime_evidence)),
      row.python_modules,
      listValue(callables),
      row.ngc_only_subpaths,
      listValue(processAssumptions),
      row.python_runtime_evidence,
      "python_runtime_owner_and_fixture",
      "linuxcnc_python_runtime_boundary_not_js_semantics",
      "browser_after_node_python_boundary_no_full_process_claim",
      "pending",
      "0",
      "0",
      listValue(notes),
    ].map(tsvValue).join("\t");
  });
}

function verifyPythonRemapRuntimeContractRows(rows, familyRows) {
  const expectedHeaders = [
    "family",
    "blocked",
    "design_status",
    "row_count",
    "ini_count",
    "runtime_phases",
    "python_modules",
    "python_callables",
    "ngc_only_subpaths",
    "process_assumptions",
    "runtime_owner_evidence",
    "required_native_proof",
    "required_node_proof",
    "required_browser_proof",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  assert.deepEqual(
    parsedRows.map((row) => row.family).sort(),
    familyRows.map((row) => row.family).sort(),
    "Python runtime contract family set drift",
  );

  const requiredFamilies = new Set([
    "axis/laser",
    "axis/remap/extend-builtins/nc_files",
    "axis/vismach/5axis/table-rotary_spindle-rotary-nutating/demos",
    "gmoccapy/macros",
  ]);
  for (const family of requiredFamilies) {
    assert.ok(
      parsedRows.some((row) => row.family === family),
      `${family}: required Python runtime contract row missing`,
    );
  }

  const familyByName = new Map(familyRows.map((row) => [row.family, row]));
  for (const row of parsedRows) {
    const family = familyByName.get(row.family);
    assert.ok(family, `${row.family}: contract row lacks family summary`);
    assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.family}: blocked kind drift`);
    assert.equal(row.design_status, "inventory_only", `${row.family}: design status drift`);
    assert.equal(row.row_count, family.row_count, `${row.family}: row count drift`);
    assert.equal(row.ini_count, family.ini_count, `${row.family}: INI count drift`);
    assert.notEqual(row.runtime_phases, "-", `${row.family}: missing runtime phases`);
    for (const phase of [
      "initialize_python",
      "apply_ini_python_path",
      "execute_toplevel",
      "callable_lookup",
      "pycall_dispatch",
      "callable_invoke",
      "remap_phase_dispatch",
    ]) {
      assert.ok(row.runtime_phases.includes(phase), `${row.family}: missing runtime phase ${phase}`);
    }
    assert.notEqual(row.python_modules, "-", `${row.family}: contract lacks Python modules`);
    assert.notEqual(row.runtime_owner_evidence, "-", `${row.family}: contract lacks runtime owner evidence`);
    assert.equal(row.required_native_proof, "python_runtime_owner_and_fixture", `${row.family}: native proof drift`);
    assert.equal(row.required_node_proof, "linuxcnc_python_runtime_boundary_not_js_semantics", `${row.family}: Node proof drift`);
    assert.equal(row.required_browser_proof, "browser_after_node_python_boundary_no_full_process_claim", `${row.family}: browser proof drift`);
    assert.equal(row.proof_status, "pending", `${row.family}: proof status must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.family}: Python contract must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.family}: Python contract must not allow promotion`);
    assert.ok(
      row.notes.includes("python_runtime_contract_only_no_execution") &&
        row.notes.includes("dependency_inventory_only_no_execution"),
      `${row.family}: missing non-execution notes`,
    );
    if (
      family.python_remap_functions !== "-" ||
      family.prolog_functions !== "-" ||
      family.epilog_functions !== "-"
    ) {
      assert.notEqual(row.python_callables, "-", `${row.family}: contract lacks callable inventory`);
    }
    if (family.ngc_only_subpaths !== "-") {
      assert.equal(row.ngc_only_subpaths, family.ngc_only_subpaths, `${row.family}: NGC-only subpath drift`);
    }
    const expectedProcessAssumptions = [];
    if (family.hal_process === "1") {
      expectedProcessAssumptions.push("hal_process");
    }
    if (family.ui_process === "1") {
      expectedProcessAssumptions.push("ui_process");
    }
    if (family.halui_mdi_process === "1") {
      expectedProcessAssumptions.push("halui_mdi_process");
    }
    assert.equal(
      row.process_assumptions,
      listValue(expectedProcessAssumptions),
      `${row.family}: process assumption drift`,
    );
  }

  return parsedRows;
}

function pythonRemapNativeRuntimeReadinessRows(contractRows) {
  return contractRows.flatMap((contract) => {
    const requirements = [
      {
        kind: "host_command",
        requirement: "python3",
        purpose: "provide_embedded_python_runtime_for_future_probe",
        available: commandPath("python3") !== "",
        evidence: commandPath("python3"),
      },
      {
        kind: "host_command",
        requirement: "linuxcnc",
        purpose: "provide_linuxcnc_task_interpreter_python_context",
        available: commandPath("linuxcnc") !== "",
        evidence: commandPath("linuxcnc"),
      },
      {
        kind: "linuxcnc_source_file",
        requirement: "src/emc/rs274ngc/interp_python.cc",
        purpose: "own_python_remap_phase_dispatch",
        available: linuxCncSourcePathExists("src/emc/rs274ngc/interp_python.cc"),
        evidence: "src/emc/rs274ngc/interp_python.cc",
      },
      {
        kind: "linuxcnc_source_file",
        requirement: "src/emc/pythonplugin/python_plugin.cc",
        purpose: "own_python_plugin_lifecycle_and_callable_dispatch",
        available: linuxCncSourcePathExists("src/emc/pythonplugin/python_plugin.cc"),
        evidence: "src/emc/pythonplugin/python_plugin.cc",
      },
      ...splitSummaryList(contract.python_modules).map((modulePath) => ({
        kind: "source_config_python_module",
        requirement: modulePath,
        purpose: "configured_python_module_dependency",
        available: sourceConfigPathExists(modulePath),
        evidence: `configs/sim/${modulePath}`,
      })),
    ];
    const allAvailable = requirements.every((row) => row.available);
    const nativeRuntimeStatus = allAvailable
      ? "host_runtime_available_probe_not_implemented"
      : "blocked_missing_host_runtime";

    return requirements.map((row) => [
      contract.family,
      contract.blocked,
      "linuxcnc_python_remap_runtime",
      row.kind,
      row.requirement,
      row.purpose,
      flagValue(row.available),
      row.available ? row.evidence : "-",
      nativeRuntimeStatus,
      "native_python_runtime_probe_required",
      "pending",
      "0",
      "0",
      allAvailable
        ? "runtime_requirements_available_but_probe_still_not_implemented"
        : "missing_host_runtime_keep_python_remap_blocked",
    ].map(tsvValue).join("\t"));
  });
}

function verifyPythonRemapNativeRuntimeReadinessRows(rows, contractRows) {
  const expectedHeaders = [
    "family",
    "blocked",
    "required_runtime",
    "requirement_kind",
    "requirement",
    "purpose",
    "available",
    "evidence",
    "native_runtime_status",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const contractFamilies = contractRows.map((row) => row.family).sort();
  const readinessFamilies = uniqueSorted(parsedRows.map((row) => row.family));

  assert.deepEqual(
    readinessFamilies,
    contractFamilies,
    "Python native runtime readiness family set drift",
  );
  assert.ok(
    parsedRows.length > contractRows.length * 4,
    "Python native runtime readiness must include host/source and module rows",
  );

  const rowsByFamily = new Map();
  for (const row of parsedRows) {
    const existing = rowsByFamily.get(row.family) ?? [];
    existing.push(row);
    rowsByFamily.set(row.family, existing);

    assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.family}: Python readiness blocked kind drift`);
    assert.equal(row.required_runtime, "linuxcnc_python_remap_runtime", `${row.family}: Python runtime drift`);
    assert.ok(
      [
        "host_command",
        "linuxcnc_source_file",
        "source_config_python_module",
      ].includes(row.requirement_kind),
      `${row.family}: readiness kind drift`,
    );
    assert.notEqual(row.requirement, "-", `${row.family}: readiness requirement missing`);
    assert.notEqual(row.purpose, "-", `${row.family}: readiness purpose missing`);
    assert.ok(["0", "1"].includes(row.available), `${row.family}: invalid readiness availability`);
    if (row.available === "1") {
      assert.notEqual(row.evidence, "-", `${row.family}: available readiness row lacks evidence`);
    }
    assert.ok(
      ["blocked_missing_host_runtime", "host_runtime_available_probe_not_implemented"].includes(row.native_runtime_status),
      `${row.family}: invalid Python runtime readiness status`,
    );
    assert.equal(row.proof_kind, "native_python_runtime_probe_required", `${row.family}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.family}: readiness proof must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.family}: readiness must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.family}: readiness must not allow promotion`);
    assert.ok(
      row.notes.includes("keep_python_remap_blocked") ||
        row.notes.includes("probe_still_not_implemented"),
      `${row.family}: readiness must keep Python-remap blocked`,
    );
  }

  const contractByFamily = new Map(contractRows.map((row) => [row.family, row]));
  for (const [family, familyRows] of rowsByFamily) {
    const contract = contractByFamily.get(family);
    assert.ok(contract, `${family}: readiness row lacks contract`);
    const requirements = new Set(familyRows.map((row) => row.requirement));
    for (const requirement of [
      "python3",
      "linuxcnc",
      "src/emc/rs274ngc/interp_python.cc",
      "src/emc/pythonplugin/python_plugin.cc",
      ...splitSummaryList(contract.python_modules),
    ]) {
      assert.ok(requirements.has(requirement), `${family}: missing readiness requirement ${requirement}`);
    }
    assert.ok(
      familyRows.some((row) => row.requirement === "python3" && row.available === "1"),
      `${family}: python3 must be available for Python runtime readiness`,
    );
    assert.ok(
      familyRows.some((row) =>
        row.requirement === "src/emc/rs274ngc/interp_python.cc" && row.available === "1",
      ),
      `${family}: interp_python.cc must be available for Python runtime readiness`,
    );
    assert.ok(
      familyRows.some((row) =>
        row.requirement === "src/emc/pythonplugin/python_plugin.cc" && row.available === "1",
      ),
      `${family}: python_plugin.cc must be available for Python runtime readiness`,
    );
    for (const modulePath of splitSummaryList(contract.python_modules)) {
      assert.ok(
        familyRows.some((row) => row.requirement === modulePath && row.available === "1"),
        `${family}: configured Python module missing from source tree: ${modulePath}`,
      );
    }
  }

  return parsedRows;
}

function pythonRemapNativeRuntimeStatePlanRows({
  contractRows,
  readinessRows,
  alignmentRows,
}) {
  const readinessByFamily = new Map();
  for (const row of readinessRows) {
    const existing = readinessByFamily.get(row.family) ?? [];
    existing.push(row);
    readinessByFamily.set(row.family, existing);
  }

  const alignmentByFamily = new Map();
  for (const row of alignmentRows) {
    for (const contract of contractRows) {
      if (row.path === contract.family || row.path.startsWith(`${contract.family}/`)) {
        const existing = alignmentByFamily.get(contract.family) ?? [];
        existing.push(row);
        alignmentByFamily.set(contract.family, existing);
      }
    }
  }

  return contractRows.map((contract) => {
    const readiness = readinessByFamily.get(contract.family) ?? [];
    const alignment = alignmentByFamily.get(contract.family) ?? [];
    const readinessAvailableCount = readiness.filter((row) => row.available === "1").length;
    const sourceAlignmentOk = (
      alignment.length > 0 &&
      alignment.every((row) =>
        row.native_stdout_available === "1" &&
          row.alignment_ok === "1" &&
          row.execution_enabled === "0" &&
          row.promotion_allowed === "0",
      )
    );
    const requiredStateProbe = uniqueSorted([
      ...splitSummaryList(contract.runtime_phases).map((phase) => `phase:${phase}`),
      ...splitSummaryList(contract.python_modules).map((modulePath) => `module:${modulePath}`),
      ...splitSummaryList(contract.python_callables).map((callable) => `callable:${callable}`),
      ...splitSummaryList(contract.ngc_only_subpaths).map((subpath) => `ngc_only:${subpath}`),
      ...splitSummaryList(contract.process_assumptions).map((process) => `process:${process}`),
    ]);

    return [
      contract.family,
      contract.blocked,
      "linuxcnc_python_remap_runtime",
      contract.runtime_phases,
      contract.python_modules,
      contract.python_callables,
      contract.ngc_only_subpaths,
      contract.process_assumptions,
      "python3,linuxcnc,interp_python.cc,python_plugin.cc,configured_python_modules",
      String(readiness.length),
      String(readinessAvailableCount),
      "python-remap-native-runtime-alignment.tsv,python-remap-native-runtime-readiness.tsv",
      flagValue(sourceAlignmentOk),
      "pending_native_python_runtime_probe",
      listValue(requiredStateProbe),
      "native_python_runtime_state_probe_required",
      "pending",
      "0",
      "0",
      listValue(uniqueSorted([
        ...splitSummaryList(contract.notes),
        "native_runtime_not_executed_keep_python_remap_blocked",
      ])),
    ].map(tsvValue).join("\t");
  });
}

function verifyPythonRemapNativeRuntimeStatePlanRows({
  rows,
  contractRows,
  readinessRows,
}) {
  const expectedHeaders = [
    "family",
    "blocked",
    "required_runtime",
    "runtime_phases",
    "python_modules",
    "python_callables",
    "ngc_only_subpaths",
    "process_assumptions",
    "required_environment",
    "readiness_requirement_count",
    "readiness_available_count",
    "source_alignment_artifacts",
    "source_alignment_ok",
    "native_runtime_status",
    "required_state_probe",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const readinessCountByFamily = new Map();
  for (const row of readinessRows) {
    readinessCountByFamily.set(row.family, (readinessCountByFamily.get(row.family) ?? 0) + 1);
  }
  const readinessAvailableByFamily = new Map();
  for (const row of readinessRows.filter((entry) => entry.available === "1")) {
    readinessAvailableByFamily.set(row.family, (readinessAvailableByFamily.get(row.family) ?? 0) + 1);
  }

  assert.deepEqual(
    parsedRows.map((row) => row.family).sort(),
    contractRows.map((row) => row.family).sort(),
    "Python native runtime state plan family set drift",
  );
  assert.equal(parsedRows.length, 12, "Python native runtime state plan must cover every blocked family");

  const contractByFamily = new Map(contractRows.map((row) => [row.family, row]));
  for (const row of parsedRows) {
    const contract = contractByFamily.get(row.family);
    assert.ok(contract, `${row.family}: state plan lacks contract row`);
    assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.family}: state plan blocked kind drift`);
    assert.equal(row.required_runtime, "linuxcnc_python_remap_runtime", `${row.family}: required runtime drift`);
    assert.equal(row.runtime_phases, contract.runtime_phases, `${row.family}: runtime phase drift`);
    assert.equal(row.python_modules, contract.python_modules, `${row.family}: Python module drift`);
    assert.equal(row.python_callables, contract.python_callables, `${row.family}: Python callable drift`);
    assert.equal(row.ngc_only_subpaths, contract.ngc_only_subpaths, `${row.family}: NGC-only subpath drift`);
    assert.equal(row.process_assumptions, contract.process_assumptions, `${row.family}: process assumption drift`);
    for (const token of [
      "python3",
      "linuxcnc",
      "interp_python.cc",
      "python_plugin.cc",
      "configured_python_modules",
    ]) {
      assert.ok(row.required_environment.includes(token), `${row.family}: missing environment token ${token}`);
    }
    assert.equal(
      row.readiness_requirement_count,
      String(readinessCountByFamily.get(row.family) ?? 0),
      `${row.family}: readiness requirement count drift`,
    );
    assert.equal(
      row.readiness_available_count,
      String(readinessAvailableByFamily.get(row.family) ?? 0),
      `${row.family}: readiness available count drift`,
    );
    assert.ok(
      row.source_alignment_artifacts.includes("python-remap-native-runtime-alignment.tsv") &&
        row.source_alignment_artifacts.includes("python-remap-native-runtime-readiness.tsv"),
      `${row.family}: missing source alignment artifact references`,
    );
    assert.equal(row.source_alignment_ok, "1", `${row.family}: source alignment must be complete before runtime plan`);
    assert.equal(row.native_runtime_status, "pending_native_python_runtime_probe", `${row.family}: runtime status drift`);
    for (const phase of [
      "phase:initialize_python",
      "phase:apply_ini_python_path",
      "phase:execute_toplevel",
      "phase:callable_lookup",
      "phase:pycall_dispatch",
      "phase:callable_invoke",
      "phase:remap_phase_dispatch",
    ]) {
      assert.ok(row.required_state_probe.includes(phase), `${row.family}: missing required probe ${phase}`);
    }
    assert.ok(row.required_state_probe.includes("module:"), `${row.family}: state plan lacks module proof target`);
    if (contract.python_callables !== "-") {
      assert.ok(row.required_state_probe.includes("callable:"), `${row.family}: state plan lacks callable proof target`);
    }
    if (contract.ngc_only_subpaths !== "-") {
      assert.ok(row.required_state_probe.includes("ngc_only:"), `${row.family}: state plan lacks NGC-only proof target`);
    }
    assert.equal(row.proof_kind, "native_python_runtime_state_probe_required", `${row.family}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.family}: runtime state plan must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.family}: runtime state plan must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.family}: runtime state plan must not allow promotion`);
    assert.ok(
      row.notes.includes("native_runtime_not_executed_keep_python_remap_blocked"),
      `${row.family}: runtime state plan must keep Python-remap blocked`,
    );
  }

  return parsedRows;
}

function pythonRemapNativeRuntimeFixturePlanRows(statePlanRows) {
  const selectedFamily = "axis/remap/stop-lookahead/nc_files";
  const row = statePlanRows.find((entry) => entry.family === selectedFamily);
  assert.ok(row, `${selectedFamily}: missing Python runtime state-plan row`);

  return [[
    row.family,
    row.blocked,
    row.required_runtime,
    "selected_minimal_python_runtime_lifecycle_fixture",
    "stop_lookahead_python_runtime_lifecycle",
    "no_python_callables_no_ngc_only_subpaths",
    row.runtime_phases,
    row.python_modules,
    row.process_assumptions,
    row.required_environment,
    row.readiness_requirement_count,
    row.readiness_available_count,
    row.source_alignment_artifacts,
    row.source_alignment_ok,
    listValue([
      "initialize_python",
      "apply_ini_python_path",
      "execute_toplevel",
      "callable_lookup",
      "pycall_dispatch",
      "callable_invoke",
      "remap_phase_dispatch",
      "generator_finish",
      "execute_python_runtime",
      "reload_on_change",
    ]),
    listValue(splitSummaryList(row.python_modules).map((modulePath) => `module:${modulePath}`)),
    "linuxcnc_python_runtime_lifecycle_probe_required",
    "pending",
    "0",
    "0",
    "fixture_plan_only_no_python_execution_no_promotion",
  ].map(tsvValue).join("\t")];
}

function verifyPythonRemapNativeRuntimeFixturePlanRows(rows, statePlanRows) {
  const expectedHeaders = [
    "family",
    "blocked",
    "required_runtime",
    "selection_reason",
    "fixture_id",
    "fixture_scope",
    "runtime_phases",
    "python_modules",
    "process_assumptions",
    "required_environment",
    "readiness_requirement_count",
    "readiness_available_count",
    "source_alignment_artifacts",
    "source_alignment_ok",
    "expected_runtime_observations",
    "expected_module_inputs",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  assert.equal(parsedRows.length, 1, "Python runtime fixture plan must start with one fixture");
  const row = parsedRows[0];
  const statePlan = statePlanRows.find((entry) => entry.family === row.family);
  assert.ok(statePlan, `${row.family}: fixture plan lacks state-plan source row`);
  assert.equal(row.family, "axis/remap/stop-lookahead/nc_files", "Python fixture family drift");
  assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.family}: fixture blocked kind drift`);
  assert.equal(row.required_runtime, "linuxcnc_python_remap_runtime", `${row.family}: fixture runtime drift`);
  assert.equal(
    row.selection_reason,
    "selected_minimal_python_runtime_lifecycle_fixture",
    `${row.family}: fixture selection reason drift`,
  );
  assert.equal(row.fixture_id, "stop_lookahead_python_runtime_lifecycle", `${row.family}: fixture id drift`);
  assert.equal(row.fixture_scope, "no_python_callables_no_ngc_only_subpaths", `${row.family}: fixture scope drift`);
  assert.equal(row.runtime_phases, statePlan.runtime_phases, `${row.family}: fixture runtime phase drift`);
  assert.equal(row.python_modules, statePlan.python_modules, `${row.family}: fixture module drift`);
  assert.equal(row.process_assumptions, "hal_process", `${row.family}: fixture process assumption drift`);
  assert.equal(statePlan.python_callables, "-", `${row.family}: fixture must avoid Python callable rows`);
  assert.equal(statePlan.ngc_only_subpaths, "-", `${row.family}: fixture must avoid NGC-only subpaths`);
  for (const token of [
    "python3",
    "linuxcnc",
    "interp_python.cc",
    "python_plugin.cc",
    "configured_python_modules",
  ]) {
    assert.ok(row.required_environment.includes(token), `${row.family}: missing fixture environment ${token}`);
  }
  assert.equal(row.readiness_requirement_count, statePlan.readiness_requirement_count, `${row.family}: readiness count drift`);
  assert.equal(row.readiness_available_count, statePlan.readiness_available_count, `${row.family}: readiness availability drift`);
  assert.ok(
    row.source_alignment_artifacts.includes("python-remap-native-runtime-alignment.tsv") &&
      row.source_alignment_artifacts.includes("python-remap-native-runtime-readiness.tsv"),
    `${row.family}: fixture source artifacts drift`,
  );
  assert.equal(row.source_alignment_ok, "1", `${row.family}: fixture source alignment must be ready`);
  for (const observation of [
    "initialize_python",
    "apply_ini_python_path",
    "execute_toplevel",
    "callable_lookup",
    "pycall_dispatch",
    "callable_invoke",
    "remap_phase_dispatch",
  ]) {
    assert.ok(row.expected_runtime_observations.includes(observation), `${row.family}: missing observation ${observation}`);
  }
  for (const modulePath of splitSummaryList(row.python_modules)) {
    assert.ok(
      row.expected_module_inputs.includes(`module:${modulePath}`),
      `${row.family}: missing module input ${modulePath}`,
    );
  }
  assert.equal(row.proof_kind, "linuxcnc_python_runtime_lifecycle_probe_required", `${row.family}: fixture proof kind drift`);
  assert.equal(row.proof_status, "pending", `${row.family}: fixture proof must remain pending`);
  assert.equal(row.execution_enabled, "0", `${row.family}: fixture must not enable execution`);
  assert.equal(row.promotion_allowed, "0", `${row.family}: fixture must not allow promotion`);
  assert.ok(row.notes.includes("no_python_execution"), `${row.family}: fixture must remain non-executing`);

  return parsedRows;
}

function pythonRemapNativeRuntimeProbeGateRows({
  fixturePlanRows,
  readinessRows,
}) {
  const fixture = fixturePlanRows[0];
  if (!fixture) {
    return [];
  }

  const readinessForFamily = readinessRows.filter((row) => row.family === fixture.family);
  const readinessByRequirement = new Map(
    readinessForFamily.map((row) => [row.requirement, row]),
  );
  const representativeModules = splitSummaryList(fixture.python_modules);
  const runtimeOwnerSources = [
    "src/emc/rs274ngc/interp_python.cc",
    "src/emc/pythonplugin/python_plugin.cc",
  ];
  const hostRequirements = ["python3", "linuxcnc"];
  const requiredRequirements = [
    ...hostRequirements,
    ...runtimeOwnerSources,
    ...representativeModules,
  ];
  const missingRequirements = requiredRequirements.filter((requirement) =>
    readinessByRequirement.get(requirement)?.available !== "1",
  );
  const runtimeOwnerSourcesReady = runtimeOwnerSources.every((requirement) =>
    readinessByRequirement.get(requirement)?.available === "1",
  );
  const representativeModulesReady = representativeModules.every((requirement) =>
    readinessByRequirement.get(requirement)?.available === "1",
  );
  const runtimeReady = missingRequirements.length === 0;
  const sourceProofReady = (
    fixture.source_alignment_ok === "1" &&
    runtimeOwnerSourcesReady &&
    representativeModulesReady &&
    fixture.execution_enabled === "0" &&
    fixture.promotion_allowed === "0"
  );
  const python3Available = readinessByRequirement.get("python3")?.available ?? "0";
  const linuxcncAvailable = readinessByRequirement.get("linuxcnc")?.available ?? "0";
  const gateStatus = runtimeReady && sourceProofReady
    ? "ready_to_implement_lifecycle_probe"
    : "blocked_missing_host_runtime";

  return [[
    fixture.family,
    fixture.blocked,
    fixture.fixture_id,
    fixture.required_runtime,
    python3Available,
    "0",
    linuxcncAvailable,
    flagValue(runtimeOwnerSourcesReady),
    listValue(representativeModules.map((modulePath) => `import:${modulePath}`)),
    flagValue(representativeModulesReady),
    listValue(requiredRequirements.map((requirement) =>
      `${requirement}:${readinessByRequirement.get(requirement)?.available ?? "0"}`,
    )),
    listValue(missingRequirements),
    flagValue(runtimeReady),
    flagValue(sourceProofReady),
    fixture.proof_kind,
    gateStatus,
    "pending",
    "0",
    "0",
    runtimeReady
      ? "host_and_source_ready_write_linuxcnc_python_lifecycle_probe_python3_alone_not_sufficient"
      : "python3_alone_not_sufficient_keep_python_remap_blocked",
  ].map(tsvValue).join("\t")];
}

function verifyPythonRemapNativeRuntimeProbeGateRows({
  rows,
  fixturePlanRows,
  readinessRows,
}) {
  const expectedHeaders = [
    "family",
    "blocked",
    "fixture_id",
    "required_runtime",
    "python3_available",
    "python3_sufficient",
    "linuxcnc_available",
    "runtime_owner_sources_ready",
    "representative_module_imports",
    "representative_modules_ready",
    "runtime_requirements",
    "missing_requirements",
    "runtime_ready",
    "source_proof_ready",
    "required_native_proof",
    "gate_status",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  assert.equal(parsedRows.length, 1, "Python runtime probe gate must start with one selected fixture");
  const row = parsedRows[0];
  const fixture = fixturePlanRows[0];
  assert.ok(fixture, "Python runtime probe gate lacks fixture source row");
  assert.equal(row.family, fixture.family, `${row.family}: probe gate family drift`);
  assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.family}: probe gate blocked kind drift`);
  assert.equal(row.fixture_id, "stop_lookahead_python_runtime_lifecycle", `${row.family}: probe gate fixture drift`);
  assert.equal(row.required_runtime, "linuxcnc_python_remap_runtime", `${row.family}: probe gate runtime drift`);
  assert.ok(["0", "1"].includes(row.python3_available), `${row.family}: invalid python3 availability`);
  assert.equal(row.python3_sufficient, "0", `${row.family}: python3 alone must never satisfy remap readiness`);
  assert.ok(["0", "1"].includes(row.linuxcnc_available), `${row.family}: invalid linuxcnc availability`);
  assert.equal(row.runtime_owner_sources_ready, "1", `${row.family}: LinuxCNC Python runtime owner sources must be ready`);
  assert.equal(row.representative_modules_ready, "1", `${row.family}: representative Python modules must be source-ready`);
  assert.notEqual(row.representative_module_imports, "-", `${row.family}: probe gate lacks representative module imports`);
  for (const modulePath of splitSummaryList(fixture.python_modules)) {
    assert.ok(
      row.representative_module_imports.includes(`import:${modulePath}`),
      `${row.family}: missing representative import ${modulePath}`,
    );
  }

  const readinessByRequirement = new Map(
    readinessRows
      .filter((entry) => entry.family === row.family)
      .map((entry) => [entry.requirement, entry]),
  );
  const expectedRequirements = [
    "python3",
    "linuxcnc",
    "src/emc/rs274ngc/interp_python.cc",
    "src/emc/pythonplugin/python_plugin.cc",
    ...splitSummaryList(fixture.python_modules),
  ];
  const expectedMissing = expectedRequirements.filter((requirement) =>
    readinessByRequirement.get(requirement)?.available !== "1",
  );
  const allRuntimeReady = expectedMissing.length === 0;
  for (const requirement of expectedRequirements) {
    assert.ok(row.runtime_requirements.includes(`${requirement}:`), `${row.family}: missing runtime requirement ${requirement}`);
  }
  assert.equal(row.runtime_ready, flagValue(allRuntimeReady), `${row.family}: runtime readiness drift`);
  assert.equal(row.source_proof_ready, "1", `${row.family}: source proof must be ready before runtime probe implementation`);
  assert.equal(row.required_native_proof, "linuxcnc_python_runtime_lifecycle_probe_required", `${row.family}: native proof drift`);
  assert.equal(row.proof_status, "pending", `${row.family}: probe gate must remain pending`);
  assert.equal(row.execution_enabled, "0", `${row.family}: probe gate must not enable execution`);
  assert.equal(row.promotion_allowed, "0", `${row.family}: probe gate must not allow promotion`);

  if (allRuntimeReady) {
    assert.equal(row.missing_requirements, "-", `${row.family}: ready runtime has missing requirements`);
    assert.equal(row.gate_status, "ready_to_implement_lifecycle_probe", `${row.family}: ready gate status drift`);
    assert.ok(row.notes.includes("python3_alone_not_sufficient"), `${row.family}: ready gate must still reject python3-only proof`);
  } else {
    assert.deepEqual(
      splitSummaryList(row.missing_requirements).sort(),
      expectedMissing.sort(),
      `${row.family}: missing runtime requirements drift`,
    );
    assert.equal(row.gate_status, "blocked_missing_host_runtime", `${row.family}: missing runtime gate status drift`);
    assert.ok(row.notes.includes("python3_alone_not_sufficient"), `${row.family}: missing runtime gate must reject python3-only proof`);
  }

  return parsedRows;
}

function runtimeBoundaryNativeAlignmentSummaryRows({
  userMRows,
  toolDbRows,
  pythonRows,
}) {
  const groups = [
    {
      boundaryClass: "L4-USER-M-PROCESS",
      boundaryKind: "external_user_m_process",
      artifact: "user-m-process-native-state-alignment.tsv",
      rows: userMRows,
    },
    {
      boundaryClass: "L4-TOOL-DB",
      boundaryKind: "tool_database_process",
      artifact: "tool-db-process-native-protocol-alignment.tsv",
      rows: toolDbRows,
    },
    {
      boundaryClass: "L4-PYTHON-REMAP",
      boundaryKind: "python_runtime",
      artifact: "python-remap-native-runtime-alignment.tsv",
      rows: pythonRows,
    },
  ];

  return groups.map((group) => {
    const nativeAvailableCount = group.rows.filter((row) => row.native_stdout_available === "1").length;
    const alignmentOkCount = group.rows.filter((row) => row.alignment_ok === "1").length;
    const pendingCount = group.rows.filter((row) => row.proof_status === "pending").length;
    const executionDisabledCount = group.rows.filter((row) => row.execution_enabled === "0").length;
    const promotionDisabledCount = group.rows.filter((row) => row.promotion_allowed === "0").length;
    const rowCount = group.rows.length;
    const summaryOk = (
      rowCount > 0 &&
      nativeAvailableCount === rowCount &&
      alignmentOkCount === rowCount &&
      pendingCount === rowCount &&
      executionDisabledCount === rowCount &&
      promotionDisabledCount === rowCount
    );

    return [
      group.boundaryClass,
      group.boundaryKind,
      String(rowCount),
      String(nativeAvailableCount),
      String(alignmentOkCount),
      String(pendingCount),
      String(executionDisabledCount),
      String(promotionDisabledCount),
      group.artifact,
      flagValue(summaryOk),
      "native_alignment_summary_only_no_runtime_execution",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryNativeAlignmentSummaryRows(rows) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "row_count",
    "native_stdout_available_count",
    "alignment_ok_count",
    "pending_count",
    "execution_disabled_count",
    "promotion_disabled_count",
    "artifact",
    "summary_ok",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];

  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    expectedClasses,
    "runtime native alignment summary class order drift",
  );

  for (const row of parsedRows) {
    assert.ok(/^[1-9][0-9]*$/.test(row.row_count), `${row.boundary_class}: invalid row count`);
    assert.equal(row.native_stdout_available_count, row.row_count, `${row.boundary_class}: native stdout availability incomplete`);
    assert.equal(row.alignment_ok_count, row.row_count, `${row.boundary_class}: native alignment incomplete`);
    assert.equal(row.pending_count, row.row_count, `${row.boundary_class}: native alignment rows must remain pending`);
    assert.equal(row.execution_disabled_count, row.row_count, `${row.boundary_class}: native alignment rows must not enable execution`);
    assert.equal(row.promotion_disabled_count, row.row_count, `${row.boundary_class}: native alignment rows must not allow promotion`);
    assert.equal(row.summary_ok, "1", `${row.boundary_class}: runtime native alignment summary failed`);
    assert.ok(row.artifact.endsWith(".tsv"), `${row.boundary_class}: alignment artifact missing`);
    assert.ok(
      row.notes.includes("no_runtime_execution"),
      `${row.boundary_class}: alignment summary must remain non-executing`,
    );
  }

  return parsedRows;
}

function runtimeBoundaryContractSummaryRows({
  userMRows,
  toolDbRows,
  pythonRows,
  runtimeNativeAlignmentRows,
}) {
  const runtimeAlignmentByKind = new Map(
    runtimeNativeAlignmentRows.map((row) => [row.boundary_kind, row]),
  );
  const groups = [
    {
      boundaryClass: "L4-USER-M-PROCESS",
      boundaryKind: "external_user_m_process",
      contractArtifact: "user-m-process-transition-plan.tsv",
      contractScope: "millturn_m428_m429_state_transition",
      rows: userMRows,
    },
    {
      boundaryClass: "L4-TOOL-DB",
      boundaryKind: "tool_database_process",
      contractArtifact: "tool-db-process-transaction-plan.tsv",
      contractScope: "db_demo_tooldata_transaction_protocol",
      rows: toolDbRows,
    },
    {
      boundaryClass: "L4-PYTHON-REMAP",
      boundaryKind: "python_runtime",
      contractArtifact: "python-remap-runtime-contract.tsv",
      contractScope: "python_remap_family_runtime_contracts",
      rows: pythonRows,
    },
  ];

  return groups.map((group) => {
    const runtimeAlignment = runtimeAlignmentByKind.get(group.boundaryKind);
    const rowCount = group.rows.length;
    const pendingCount = group.rows.filter((row) => row.proof_status === "pending").length;
    const executionDisabledCount = group.rows.filter((row) => row.execution_enabled === "0").length;
    const promotionDisabledCount = group.rows.filter((row) => row.promotion_allowed === "0").length;
    const contractOk = (
      rowCount > 0 &&
      pendingCount === rowCount &&
      executionDisabledCount === rowCount &&
      promotionDisabledCount === rowCount &&
      runtimeAlignment?.summary_ok === "1"
    );

    return [
      group.boundaryClass,
      group.boundaryKind,
      group.contractArtifact,
      group.contractScope,
      String(rowCount),
      String(pendingCount),
      String(executionDisabledCount),
      String(promotionDisabledCount),
      runtimeAlignment?.artifact ?? "-",
      runtimeAlignment?.row_count ?? "0",
      runtimeAlignment?.summary_ok ?? "0",
      flagValue(contractOk),
      "contract_summary_only_no_runtime_execution_no_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryContractSummaryRows(rows) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "contract_artifact",
    "contract_scope",
    "contract_row_count",
    "pending_count",
    "execution_disabled_count",
    "promotion_disabled_count",
    "runtime_alignment_artifact",
    "runtime_alignment_row_count",
    "runtime_alignment_ok",
    "contract_ok",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expected = new Map([
    [
      "L4-USER-M-PROCESS",
      {
        boundaryKind: "external_user_m_process",
        contractArtifact: "user-m-process-transition-plan.tsv",
        contractScope: "millturn_m428_m429_state_transition",
        rowCount: "2",
        runtimeArtifact: "user-m-process-native-state-alignment.tsv",
      },
    ],
    [
      "L4-TOOL-DB",
      {
        boundaryKind: "tool_database_process",
        contractArtifact: "tool-db-process-transaction-plan.tsv",
        contractScope: "db_demo_tooldata_transaction_protocol",
        rowCount: "5",
        runtimeArtifact: "tool-db-process-native-protocol-alignment.tsv",
      },
    ],
    [
      "L4-PYTHON-REMAP",
      {
        boundaryKind: "python_runtime",
        contractArtifact: "python-remap-runtime-contract.tsv",
        contractScope: "python_remap_family_runtime_contracts",
        rowCount: "12",
        runtimeArtifact: "python-remap-native-runtime-alignment.tsv",
      },
    ],
  ]);

  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    [...expected.keys()],
    "runtime boundary contract summary class order drift",
  );

  for (const row of parsedRows) {
    const expectedRow = expected.get(row.boundary_class);
    assert.ok(expectedRow, `${row.boundary_class}: unexpected contract summary row`);
    assert.equal(row.boundary_kind, expectedRow.boundaryKind, `${row.boundary_class}: boundary kind drift`);
    assert.equal(row.contract_artifact, expectedRow.contractArtifact, `${row.boundary_class}: contract artifact drift`);
    assert.equal(row.contract_scope, expectedRow.contractScope, `${row.boundary_class}: contract scope drift`);
    assert.equal(row.contract_row_count, expectedRow.rowCount, `${row.boundary_class}: contract row count drift`);
    assert.equal(row.pending_count, row.contract_row_count, `${row.boundary_class}: contract rows must remain pending`);
    assert.equal(row.execution_disabled_count, row.contract_row_count, `${row.boundary_class}: contract rows must not enable execution`);
    assert.equal(row.promotion_disabled_count, row.contract_row_count, `${row.boundary_class}: contract rows must not allow promotion`);
    assert.equal(row.runtime_alignment_artifact, expectedRow.runtimeArtifact, `${row.boundary_class}: runtime alignment artifact drift`);
    assert.ok(/^[1-9][0-9]*$/.test(row.runtime_alignment_row_count), `${row.boundary_class}: invalid runtime alignment row count`);
    assert.equal(row.runtime_alignment_ok, "1", `${row.boundary_class}: runtime alignment summary failed`);
    assert.equal(row.contract_ok, "1", `${row.boundary_class}: contract summary failed`);
    assert.ok(
      row.notes.includes("no_runtime_execution") && row.notes.includes("no_promotion"),
      `${row.boundary_class}: contract summary must remain non-executing`,
    );
  }

  return parsedRows;
}

function boundaryPhaseCompletionSummaryRows({
  generatedArtifactPaths,
  documentationPaths,
  boundaryRows,
  iniBoundaryRows,
  blockedRows,
  fullProcessRows,
  userMTransitionRows,
  userMRuntimeStatePlanRows,
  userMRuntimeReadinessRows,
  userMRuntimeProbeGateRows,
  toolDbTransactionRows,
  toolDbRuntimeReadinessRows,
  toolDbRuntimeProbeGateRows,
  pythonFamilyRows,
  pythonRuntimeContractRows,
  pythonRuntimeReadinessRows,
  pythonRuntimeProbeGateRows,
  pythonRuntimeStatePlanRows,
  pythonRuntimeFixturePlanRows,
  runtimeContractSummaryRows,
  runtimeFamilyContractAlignmentConsistencyOk,
  nativeProofAlignmentRows,
  nativeRuntimeProbeRows,
  runtimeNativeAlignmentRows,
  runtimeProbeGateAlignmentRows,
  blockedRuntimeWorklistRecommendationConsistencyOk,
  nativeRuntimeProbeExecutionPlanRows,
  nativeRuntimeProbePassEvidenceRows,
  blockedRuntimeProbeExecutionConsistencyOk,
  runtimeBoundaryPromotionReadinessRows,
  runtimeBoundaryPromotionBlockerRows,
  runtimeBoundaryPostNativePassGateRows,
  blockedRuntimePromotionGateConsistencyOk,
  runtimeBoundaryHostPreflightRows,
  runtimeBoundaryHostRequirementSummaryRows,
  runtimeBoundaryHostUnblockPlanRows,
  runtimeBoundaryFamilyHostReadinessRows,
  runtimeBoundaryHostReadinessRollupRows,
  blockedRuntimeHostRequirementConsistencyOk,
  runtimeBoundaryOptInProbeDispatchPlanRows,
  runtimeBoundaryOptInProbeDispatchRollupRows,
  runtimeBoundaryOptInProbeSkipEvidenceContractRows,
  runtimeBoundaryOptInProbeSkipEvidenceRollupRows,
  runtimeBoundaryNativeEvidenceAcceptanceGateRows,
  nextBoundaryRecommendationRows,
  blockedRuntimeRollupConsistencyOk,
  trackedRows,
  inventoryRows,
}) {
  const hardBlockedKinds = new Set([
    "L4-TOOL-DB",
    "L4-USER-M-PROCESS",
    "L4-PYTHON-REMAP",
  ]);
  const vendoredBoundaryRows = iniBoundaryRows.filter((row) => row.vendored === "1");
  const hardBlockedRows = blockedRows.filter((row) => hardBlockedKinds.has(row.blocked));
  const safeRepresentatives = [
    "axis/gladevcp/probe.ngc",
    "woodpecker/on_abort.ngc",
    "axis/vismach/puma/puma_cube.ngc",
    "axis/vismach/melfa-sim/example.ngc",
  ];
  const trackedByPath = new Map(trackedRows.map((row) => [row.path, row]));
  const inventoryByPath = new Map(inventoryRows.map((row) => {
    const [path, inventoryStatus, reason] = row.split("\t");
    return [path, { inventoryStatus, reason }];
  }));
  const documentationText = documentationPaths
    .map((documentationPath) => readFileSync(documentationPath, "utf8"))
    .join("\n");
  const wasmArtifactNames = [...new Set(generatedArtifactPaths.map((artifactPath) => basename(artifactPath)))].sort();
  const wasmArtifactDocumentationOk = (
    wasmArtifactNames.length === generatedArtifactPaths.length &&
    wasmArtifactNames.length > 0 &&
    wasmArtifactNames.every((artifactName) => documentationText.includes(artifactName))
  );
  const nativeArtifactTokens = generatedTsvArtifactTokens(resolve(rootDir, "build/native"));
  const nativeArtifactDocumentationOk = (
    nativeArtifactTokens.length > 0 &&
    nativeArtifactTokens.every((artifactToken) => documentationText.includes(artifactToken))
  );

  const vendoredBoundaryOk = vendoredBoundaryRows.every((row) => row.report_available === "1");
  const hardBlockedEvidenceOk = hardBlockedRows.every((row) => {
    if (row.blocked === "L4-TOOL-DB") {
      return row.db_program !== "-" && row.tool_db_protocol_evidence !== "-";
    }
    if (row.blocked === "L4-USER-M-PROCESS") {
      return (
        row.user_m_execution_codes !== "-" &&
        row.user_m_process_files !== "-" &&
        row.user_m_process_effects !== "-"
      );
    }
    if (row.blocked === "L4-PYTHON-REMAP") {
      return (
        row.python_modules !== "-" ||
        row.python_remap_functions !== "-" ||
        row.prolog_functions !== "-" ||
        row.epilog_functions !== "-"
      );
    }
    return false;
  });
  const safeRepresentativeOk = safeRepresentatives.every((path) => {
    const boundary = boundaryRows.find((row) => row.path === path);
    const tracked = trackedByPath.get(path);
    return (
      boundary &&
      tracked &&
      boundary.blocked === "-" &&
      boundary.dependencies !== "-" &&
      tracked.layer4Node === "REP" &&
      tracked.layer4Browser === "REP"
    );
  });
  const blockedFamiliesUnpromotedOk = hardBlockedRows.every((row) => {
    const tracked = trackedByPath.get(row.path);
    const inventory = inventoryByPath.get(row.path);
    return (
      tracked &&
      inventory &&
      tracked.layer4Node === "-" &&
      tracked.layer4Browser === "-" &&
      inventory.inventoryStatus === "SKIP" &&
      inventory.reason === row.blocked
    );
  }) && fullProcessRows.every((row) => row.execution_enabled === "0") &&
    pythonFamilyRows.every((row) => row.execution_enabled === "0");
  const linuxCncRuntimeOwnerProofOk = (
    hardBlockedRows
      .filter((row) => row.blocked === "L4-USER-M-PROCESS")
      .every((row) =>
        row.user_m_process_effects.includes("tcl_hal_runtime") &&
        row.user_m_process_effects.includes("kinstype_guard") &&
        row.user_m_process_effects.includes("ini_axis_limit_hal_setp"),
      ) &&
    hardBlockedRows
      .filter((row) => row.blocked === "L4-TOOL-DB")
      .every((row) =>
        row.tool_db_protocol_evidence.includes("tooldata_db_v2_1_handshake") &&
        row.tool_db_protocol_evidence.includes("tooldata_db_getall_g_fini") &&
        row.tool_db_protocol_evidence.includes("tooldata_db_notify_l_u_p"),
      ) &&
    pythonFamilyRows.every((row) =>
      row.python_runtime_evidence.includes("interp_python_pycall_dispatch") &&
      row.python_runtime_evidence.includes("python_plugin_callable_invoke"),
    )
  );
  const nativeSourceProofAlignmentOk = nativeProofAlignmentRows.every((row) => {
    if (row.native_summary_available === "0") {
      return row.alignment_ok === "0" &&
        row.notes === "native_source_proof_summary_unavailable";
    }
    return row.alignment_ok === "1" &&
      row.proof_value === "1" &&
      row.execution_enabled === "0" &&
      row.promotion_allowed === "0" &&
      row.matching_worklist_count !== "0" &&
      row.matching_native_gate_count !== "0";
  });
  const runtimeNativeAlignmentOk = runtimeNativeAlignmentRows.every((row) =>
    row.summary_ok === "1" &&
      row.row_count !== "0" &&
      row.native_stdout_available_count === row.row_count &&
      row.alignment_ok_count === row.row_count &&
      row.pending_count === row.row_count &&
      row.execution_disabled_count === row.row_count &&
      row.promotion_disabled_count === row.row_count,
  );
  const userMTransitionContractOk = (
    userMTransitionRows.length === 2 &&
    userMTransitionRows.every((row) =>
      row.blocked === "L4-USER-M-PROCESS" &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0" &&
        row.switchkins_output_pin === "motion.analog-out-03" &&
        row.expected_state_pins !== "-",
    )
  );
  const userMRuntimeStatePlanOk = (
    userMRuntimeStatePlanRows.length === 2 &&
    userMRuntimeStatePlanRows.every((row) =>
      row.blocked === "L4-USER-M-PROCESS" &&
        row.required_runtime === "linuxcnc_task_hal_tcl_user_m_process" &&
        row.source_alignment_ok === "1" &&
        row.native_runtime_status === "pending_native_hal_tcl_process_probe" &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0" &&
        row.expected_state_values !== "-",
    )
  );
  const userMRuntimeReadinessOk = (
    userMRuntimeReadinessRows.length === 4 &&
    userMRuntimeReadinessRows.every((row) =>
      row.blocked === "L4-USER-M-PROCESS" &&
        row.required_runtime === "linuxcnc_task_hal_tcl_user_m_process" &&
        row.requirement_kind === "host_command" &&
        ["0", "1"].includes(row.available) &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const userMRuntimeProbeGateOk = (
    userMRuntimeProbeGateRows.length === 2 &&
    userMRuntimeProbeGateRows.every((row) =>
      row.blocked === "L4-USER-M-PROCESS" &&
        row.required_runtime === "linuxcnc_task_hal_tcl_user_m_process" &&
        row.source_proof_ready === "1" &&
        ["0", "1"].includes(row.runtime_ready) &&
        ["blocked_missing_host_runtime", "ready_to_implement_probe"].includes(row.gate_status) &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const toolDbTransactionContractOk = (
    toolDbTransactionRows.length === 5 &&
    toolDbTransactionRows.every((row) =>
      row.blocked === "L4-TOOL-DB" &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0" &&
        row.db_program === "./db_nonran.py" &&
        row.protocol_message !== "-" &&
        row.db_program_callback !== "-" &&
        row.state_targets !== "-",
    )
  );
  const toolDbRuntimeReadinessOk = (
    toolDbRuntimeReadinessRows.length === 7 &&
    toolDbRuntimeReadinessRows.every((row) =>
      row.blocked === "L4-TOOL-DB" &&
        row.required_runtime === "linuxcnc_tooldata_db_process" &&
        ["host_command", "source_config_file", "linuxcnc_python_module"].includes(row.requirement_kind) &&
        ["0", "1"].includes(row.available) &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const toolDbRuntimeProbeGateOk = (
    toolDbRuntimeProbeGateRows.length === 1 &&
    toolDbRuntimeProbeGateRows.every((row) =>
      row.path === "axis/db_demo/base.ngc" &&
        row.blocked === "L4-TOOL-DB" &&
        row.required_runtime === "linuxcnc_tooldata_db_process" &&
        row.python3_sufficient === "0" &&
        row.tool_table_fallback_sufficient === "0" &&
        row.db_program_source_ready === "1" &&
        row.linuxcnc_python_modules_ready === "1" &&
        row.protocol_contract_ready === "1" &&
        row.source_proof_ready === "1" &&
        ["0", "1"].includes(row.runtime_ready) &&
        ["blocked_missing_host_runtime", "ready_to_implement_protocol_probe"].includes(row.gate_status) &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const pythonRuntimeContractOk = (
    pythonRuntimeContractRows.length === pythonFamilyRows.length &&
    pythonRuntimeContractRows.every((row) =>
      row.blocked === "L4-PYTHON-REMAP" &&
        row.design_status === "inventory_only" &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0" &&
        row.runtime_phases !== "-" &&
        row.python_modules !== "-" &&
        row.runtime_owner_evidence !== "-",
    )
  );
  const pythonRuntimeReadinessOk = (
    pythonRuntimeReadinessRows.length > pythonRuntimeContractRows.length * 4 &&
    pythonRuntimeReadinessRows.every((row) =>
      row.blocked === "L4-PYTHON-REMAP" &&
        row.required_runtime === "linuxcnc_python_remap_runtime" &&
        ["host_command", "linuxcnc_source_file", "source_config_python_module"].includes(row.requirement_kind) &&
        ["0", "1"].includes(row.available) &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const pythonRuntimeProbeGateOk = (
    pythonRuntimeProbeGateRows.length === 1 &&
    pythonRuntimeProbeGateRows.every((row) =>
      row.family === "axis/remap/stop-lookahead/nc_files" &&
        row.blocked === "L4-PYTHON-REMAP" &&
        row.required_runtime === "linuxcnc_python_remap_runtime" &&
        row.python3_sufficient === "0" &&
        row.runtime_owner_sources_ready === "1" &&
        row.representative_modules_ready === "1" &&
        row.source_proof_ready === "1" &&
        ["0", "1"].includes(row.runtime_ready) &&
        ["blocked_missing_host_runtime", "ready_to_implement_lifecycle_probe"].includes(row.gate_status) &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const pythonRuntimeStatePlanOk = (
    pythonRuntimeStatePlanRows.length === pythonRuntimeContractRows.length &&
    pythonRuntimeStatePlanRows.every((row) =>
      row.blocked === "L4-PYTHON-REMAP" &&
        row.required_runtime === "linuxcnc_python_remap_runtime" &&
        row.source_alignment_ok === "1" &&
        row.native_runtime_status === "pending_native_python_runtime_probe" &&
        row.required_state_probe !== "-" &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const pythonRuntimeFixturePlanOk = (
    pythonRuntimeFixturePlanRows.length === 1 &&
    pythonRuntimeFixturePlanRows.every((row) =>
      row.family === "axis/remap/stop-lookahead/nc_files" &&
        row.blocked === "L4-PYTHON-REMAP" &&
        row.required_runtime === "linuxcnc_python_remap_runtime" &&
        row.fixture_id === "stop_lookahead_python_runtime_lifecycle" &&
        row.proof_status === "pending" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeContractSummaryOk = (
    runtimeContractSummaryRows.length === 3 &&
    runtimeContractSummaryRows.every((row) =>
      row.contract_ok === "1" &&
        row.pending_count === row.contract_row_count &&
        row.execution_disabled_count === row.contract_row_count &&
        row.promotion_disabled_count === row.contract_row_count &&
        row.runtime_alignment_ok === "1",
    )
  );
  const nativeRuntimeProbeSummaryOk = (
    nativeRuntimeProbeRows.length === 3 &&
    nativeRuntimeProbeRows.every((row) =>
      row.source_proof_ready === "1" &&
        ["0", "1"].includes(row.runtime_ready) &&
        [
          "skipped_missing_host_runtime",
          "ready_disabled_by_default",
          "not_implemented_full_process_guard",
          "runtime_state_probe_passed",
          "runtime_protocol_probe_passed",
          "runtime_lifecycle_probe_passed",
        ].includes(row.probe_status) &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeProbeGateAlignmentOk = (
    runtimeProbeGateAlignmentRows.length === 3 &&
    runtimeProbeGateAlignmentRows.every((row) =>
      row.gate_runtime_ready === row.native_runtime_ready &&
        row.gate_source_proof_ready === "1" &&
        row.native_source_proof_ready === "1" &&
        row.missing_requirements_match === "1" &&
        row.execution_disabled_match === "1" &&
        row.promotion_disabled_match === "1" &&
        row.status_compatible === "1" &&
        row.alignment_ok === "1",
    )
  );
  const nativeRuntimeProbeExecutionPlanOk = (
    nativeRuntimeProbeExecutionPlanRows.length === 3 &&
    nativeRuntimeProbeExecutionPlanRows.every((row) =>
      row.source_proof_ready === "1" &&
        row.gate_alignment_ok === "1" &&
        /^ENABLE_[A-Z0-9_]+=1$/.test(row.opt_in_env) &&
        row.execution_command.includes(row.opt_in_env) &&
        row.execution_command.includes("wasm-port/tests/native/") &&
        row.promotion_requires.includes(`native:${row.expected_pass_status}`) &&
        row.promotion_requires.includes("node:inventory_gate_alignment_after_native_pass") &&
        row.promotion_requires.includes("browser:smoke_gate_alignment_after_node_pass") &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const nativeRuntimeProbePassEvidenceOk = (
    nativeRuntimeProbePassEvidenceRows.length === 3 &&
    nativeRuntimeProbePassEvidenceRows.every((row) =>
      row.expected_evidence_keys !== "-" &&
        (
          (row.current_probe_status === row.expected_pass_status &&
            row.evidence_required_now === "1" &&
            row.observed_evidence_ready === "1" &&
            row.missing_evidence_keys === "-" &&
            row.evidence_status === "native_pass_evidence_observed") ||
          (row.current_probe_status !== row.expected_pass_status &&
            row.evidence_required_now === "0" &&
            row.observed_evidence_ready === "0" &&
            row.missing_evidence_keys === "-" &&
            row.evidence_status === "pending_until_native_pass")
        ) &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryPromotionReadinessOk = (
    runtimeBoundaryPromotionReadinessRows.length === 3 &&
    runtimeBoundaryPromotionReadinessRows.every((row) =>
      row.native_evidence_status !== "-" &&
        row.node_inventory_gate_complete === "0" &&
        row.browser_smoke_gate_complete === "0" &&
        row.promotion_lock_active === "1" &&
        row.manual_lock_update_required === "1" &&
        row.promotion_ready === "0" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0" &&
        row.blocking_reason !== "-",
    )
  );
  const runtimeBoundaryPromotionBlockersOk = (
    runtimeBoundaryPromotionBlockerRows.length === 3 &&
    runtimeBoundaryPromotionBlockerRows.every((row) =>
      row.promotion_ready === "0" &&
        /^[1-9][0-9]*$/.test(row.blocker_count) &&
        row.blocker_keys !== "-" &&
        row.next_unblock_action !== "-" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryPostNativePassGatesOk = (
    runtimeBoundaryPostNativePassGateRows.length === 3 &&
    runtimeBoundaryPostNativePassGateRows.every((row) =>
      row.native_pass_ready === "0" &&
        row.native_evidence_ready === "0" &&
        row.node_gate_status === "blocked_until_native_pass_evidence" &&
        row.browser_gate_status === "blocked_until_node_gate_complete" &&
        row.manual_lock_update_required === "1" &&
        row.promotion_lock_active === "1" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0" &&
        row.gate_status === "blocked_before_native_pass",
    )
  );
  const runtimeBoundaryHostPreflightOk = (
    runtimeBoundaryHostPreflightRows.length === 3 &&
    runtimeBoundaryHostPreflightRows.every((row) =>
      row.source_proof_ready === "1" &&
        ["0", "1"].includes(row.runtime_ready) &&
        row.required_runtime !== "-" &&
        row.runtime_requirements !== "-" &&
        row.required_native_proof !== "-" &&
        /^ENABLE_[A-Z0-9_]+=1$/.test(row.opt_in_env) &&
        row.execution_command.includes(row.opt_in_env) &&
        (
          (row.runtime_ready === "1" &&
            row.missing_requirements === "-" &&
            row.preflight_status === "ready_to_run_opt_in_native_probe") ||
          (row.runtime_ready === "0" &&
            row.missing_requirements !== "-" &&
            row.preflight_status === "blocked_missing_host_runtime")
        ) &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryHostRequirementSummaryOk = (
    runtimeBoundaryHostRequirementSummaryRows.length >= 8 &&
    runtimeBoundaryHostRequirementSummaryRows.every((row) =>
      ["host_command", "source_or_module", "runtime_input"].includes(row.requirement_kind) &&
        ["0", "1"].includes(row.available) &&
        /^[1-9][0-9]*$/.test(row.required_by_count) &&
        row.required_by !== "-" &&
        row.blocked_families !== "-" &&
        row.opt_in_envs !== "-" &&
        (
          (row.available === "0" &&
            row.missing_for !== "-" &&
            row.missing_blocks_runtime === "1") ||
          (row.available === "1" &&
            row.missing_for === "-" &&
            row.missing_blocks_runtime === "0")
        ) &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryHostUnblockPlanOk = (
    runtimeBoundaryHostUnblockPlanRows.length === 4 &&
    runtimeBoundaryHostUnblockPlanRows.every((row) =>
      row.requirement_kind === "host_command" &&
        row.available === "0" &&
        row.missing_for !== "-" &&
        row.affected_targets !== "-" &&
        row.opt_in_envs !== "-" &&
        row.affected_execution_commands !== "-" &&
        row.remaining_missing_after_requirement !== "-" &&
        row.unblocks_when_available === "partial_unblock_other_requirements_remain" &&
        row.next_action === "provide_missing_host_requirement" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryFamilyHostReadinessOk = (
    runtimeBoundaryFamilyHostReadinessRows.length === 3 &&
    runtimeBoundaryFamilyHostReadinessRows.every((row) =>
      /^[1-9][0-9]*$/.test(row.missing_requirement_count) &&
        row.missing_host_requirements !== "-" &&
        /^[1-9][0-9]*$/.test(row.available_requirement_count) &&
        row.available_requirements !== "-" &&
        /^ENABLE_[A-Z0-9_]+=1$/.test(row.opt_in_env) &&
        row.execution_command.includes(row.opt_in_env) &&
        row.preflight_status === "blocked_missing_host_runtime" &&
        row.family_host_status === "blocked_missing_host_requirements" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryHostReadinessRollupOk = (
    runtimeBoundaryHostReadinessRollupRows.length === 1 &&
    runtimeBoundaryHostReadinessRollupRows.every((row) =>
      row.scope === "blocked_runtime_host_readiness" &&
        row.family_count === "3" &&
        row.host_ready_family_count === "0" &&
        row.host_blocked_family_count === "3" &&
        row.blocked_families !== "-" &&
        row.missing_host_requirements !== "-" &&
        row.missing_host_requirement_count === "4" &&
        row.ready_opt_in_command_count === "0" &&
        row.ready_opt_in_commands === "-" &&
        row.blocked_opt_in_commands !== "-" &&
        row.host_readiness_status === "host_blocked_for_all_opt_in_native_probes" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryOptInProbeDispatchPlanOk = (
    runtimeBoundaryOptInProbeDispatchPlanRows.length === 3 &&
    runtimeBoundaryOptInProbeDispatchPlanRows.every((row) =>
      /^ENABLE_[A-Z0-9_]+=1$/.test(row.opt_in_env) &&
        row.execution_command.includes(row.opt_in_env) &&
        row.family_host_status === "blocked_missing_host_requirements" &&
        row.missing_host_requirements !== "-" &&
        row.host_action === "skip_missing_host_requirements" &&
        row.dispatch_allowed === "0" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryOptInProbeDispatchRollupOk = (
    runtimeBoundaryOptInProbeDispatchRollupRows.length === 1 &&
    runtimeBoundaryOptInProbeDispatchRollupRows.every((row) =>
      row.scope === "blocked_runtime_opt_in_probe_dispatch" &&
        row.probe_count === "3" &&
        row.dispatch_allowed_count === "0" &&
        row.dispatch_blocked_count === "3" &&
        row.dispatch_actions === "skip_missing_host_requirements" &&
        row.dispatch_status === "dispatch_blocked_for_all_opt_in_native_probes" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryOptInProbeSkipEvidenceContractOk = (
    runtimeBoundaryOptInProbeSkipEvidenceContractRows.length === 3 &&
    runtimeBoundaryOptInProbeSkipEvidenceContractRows.every((row) =>
      row.host_action === "skip_missing_host_requirements" &&
        row.skip_reason === "missing_host_requirements" &&
        row.missing_host_requirements !== "-" &&
        row.current_probe_status === "skipped_missing_host_runtime" &&
        row.evidence_required_now === "0" &&
        row.observed_evidence_ready === "0" &&
        row.skip_evidence_status === "skip_valid_until_host_requirements_available" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryOptInProbeSkipEvidenceRollupOk = (
    runtimeBoundaryOptInProbeSkipEvidenceRollupRows.length === 1 &&
    runtimeBoundaryOptInProbeSkipEvidenceRollupRows.every((row) =>
      row.scope === "blocked_runtime_opt_in_probe_skip_evidence" &&
        row.probe_count === "3" &&
        row.skip_count === "3" &&
        row.evidence_required_now_count === "0" &&
        row.observed_evidence_ready_count === "0" &&
        row.skip_evidence_statuses === "skip_valid_until_host_requirements_available" &&
        row.evidence_rollup_status === "no_native_pass_evidence_accepted_while_host_blocked" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const runtimeBoundaryNativeEvidenceAcceptanceGateOk = (
    runtimeBoundaryNativeEvidenceAcceptanceGateRows.length === 3 &&
    runtimeBoundaryNativeEvidenceAcceptanceGateRows.every((row) =>
      row.current_probe_status === "skipped_missing_host_runtime" &&
        row.native_evidence_status === "pending_until_native_pass" &&
        row.evidence_required_now === "0" &&
        row.observed_evidence_ready === "0" &&
        row.native_evidence_gate === "blocked_until_host_requirements_available" &&
        row.evidence_acceptance_allowed === "0" &&
        row.promotion_ready === "0" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    )
  );
  const expectedBlockedRuntimeClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];
  const classOrderMatches = (rows, field = "boundary_class") =>
    rows.map((row) => row[field]).join(",") === expectedBlockedRuntimeClasses.join(",");
  const blockedRuntimeOptInGateConsistencyOk = (
    classOrderMatches(nextBoundaryRecommendationRows, "blocked") &&
    classOrderMatches(nativeRuntimeProbeExecutionPlanRows) &&
    classOrderMatches(runtimeBoundaryPromotionReadinessRows) &&
    classOrderMatches(runtimeBoundaryPromotionBlockerRows) &&
    classOrderMatches(runtimeBoundaryPostNativePassGateRows) &&
    classOrderMatches(runtimeBoundaryHostPreflightRows) &&
    classOrderMatches(runtimeBoundaryFamilyHostReadinessRows) &&
    classOrderMatches(runtimeBoundaryOptInProbeDispatchPlanRows) &&
    classOrderMatches(runtimeBoundaryOptInProbeSkipEvidenceContractRows) &&
    classOrderMatches(runtimeBoundaryNativeEvidenceAcceptanceGateRows) &&
    runtimeBoundaryOptInProbeDispatchPlanRows.every((row) =>
      row.dispatch_allowed === "0" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    ) &&
    runtimeBoundaryNativeEvidenceAcceptanceGateRows.every((row) =>
      row.evidence_acceptance_allowed === "0" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    ) &&
    runtimeBoundaryPromotionBlockerRows.every((row) =>
      row.blocker_keys.includes("host_runtime_requirements_missing") &&
        row.blocker_keys.includes("promotion_lock_active") &&
        row.blocker_keys.includes("manual_lock_update_required"),
    )
  );
  const nativeSourceProofRuntimeProbeConsistencyOk = (
    classOrderMatches(nativeProofAlignmentRows) &&
    classOrderMatches(nativeRuntimeProbeRows) &&
    classOrderMatches(runtimeProbeGateAlignmentRows) &&
    nativeProofAlignmentRows.every((row) =>
      row.alignment_ok === "1" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    ) &&
    nativeRuntimeProbeRows.every((row) =>
      row.source_proof_ready === "1" &&
        row.execution_enabled === "0" &&
        row.promotion_allowed === "0",
    ) &&
    runtimeProbeGateAlignmentRows.every((row) =>
      row.native_source_proof_ready === "1" &&
        row.gate_source_proof_ready === "1" &&
        row.execution_disabled_match === "1" &&
        row.promotion_disabled_match === "1" &&
        row.alignment_ok === "1",
    )
  );

  return [
    [
      "vendored_runtime_boundary_reports",
      flagValue(vendoredBoundaryOk),
      String(vendoredBoundaryRows.length),
      "vendored INI rows have classifier reports in ini-boundary-summary.tsv",
    ],
    [
      "hard_block_dependency_evidence",
      flagValue(hardBlockedEvidenceOk),
      String(hardBlockedRows.length),
      "hard blocked rows carry dependency-backed evidence, not path-only labels",
    ],
    [
      "safe_hal_ui_representatives",
      flagValue(safeRepresentativeOk),
      String(safeRepresentatives.length),
      "safe HAL/UI representatives remain Node/browser reps with declared process dependencies",
    ],
    [
      "blocked_families_not_promoted",
      flagValue(blockedFamiliesUnpromotedOk),
      String(hardBlockedRows.length),
      "blocked families remain skipped/non-representative with execution disabled until a LinuxCNC-owned boundary exists",
    ],
    [
      "linuxcnc_runtime_owner_proof",
      flagValue(linuxCncRuntimeOwnerProofOk),
      String(hardBlockedRows.length + pythonFamilyRows.length),
      "blocked runtime families carry LinuxCNC-owned user-M, tool DB, and Python runtime proof fields",
    ],
    [
      "native_source_proof_alignment",
      flagValue(nativeSourceProofAlignmentOk),
      String(nativeProofAlignmentRows.length),
      "native source proof summary is consumed by generated worklist/native proof gates when available",
    ],
    [
      "runtime_native_alignment_artifacts",
      flagValue(runtimeNativeAlignmentOk),
      String(runtimeNativeAlignmentRows.length),
      "native stdout alignment artifacts cover user-M, tool DB, and Python runtime gates without enabling execution",
    ],
    [
      "native_runtime_probe_summary",
      flagValue(nativeRuntimeProbeSummaryOk),
      String(nativeRuntimeProbeRows.length),
      "native runtime probe summary records current host readiness and disabled runtime probe status",
    ],
    [
      "runtime_probe_gate_alignment",
      flagValue(runtimeProbeGateAlignmentOk),
      String(runtimeProbeGateAlignmentRows.length),
      "native runtime probe summary agrees with generated runtime probe gates before any blocked boundary can be promoted",
    ],
    [
      "blocked_runtime_worklist_recommendation_consistency",
      flagValue(blockedRuntimeWorklistRecommendationConsistencyOk),
      String(nextBoundaryRecommendationRows.length),
      "blocked runtime recommendations agree with next-boundary worklist, proof gates, promotion locks, and runtime contract summaries",
    ],
    [
      "native_runtime_probe_execution_plan",
      flagValue(nativeRuntimeProbeExecutionPlanOk),
      String(nativeRuntimeProbeExecutionPlanRows.length),
      "native runtime probe execution plan records exact opt-in commands and expected pass states while keeping promotion locked",
    ],
    [
      "native_runtime_probe_pass_evidence_contract",
      flagValue(nativeRuntimeProbePassEvidenceOk),
      String(nativeRuntimeProbePassEvidenceRows.length),
      "native runtime probe pass evidence contract records stdout evidence required after each native pass before Node/browser promotion work",
    ],
    [
      "blocked_runtime_probe_execution_consistency",
      flagValue(blockedRuntimeProbeExecutionConsistencyOk),
      String(nativeRuntimeProbeExecutionPlanRows.length),
      "blocked runtime execution plan, pass evidence, preflight, dispatch, and skip-evidence contracts agree while probes remain host-blocked",
    ],
    [
      "runtime_boundary_promotion_readiness",
      flagValue(runtimeBoundaryPromotionReadinessOk),
      String(runtimeBoundaryPromotionReadinessRows.length),
      "runtime boundary promotion readiness keeps every blocked runtime family unpromoted until native pass evidence, Node/browser gates, and manual lock update complete",
    ],
    [
      "runtime_boundary_promotion_blockers",
      flagValue(runtimeBoundaryPromotionBlockersOk),
      String(runtimeBoundaryPromotionBlockerRows.length),
      "runtime boundary promotion blockers summarize remaining host/runtime/evidence/Node/browser/manual-lock blockers per blocked family",
    ],
    [
      "runtime_boundary_post_native_pass_gates",
      flagValue(runtimeBoundaryPostNativePassGatesOk),
      String(runtimeBoundaryPostNativePassGateRows.length),
      "runtime boundary post-native-pass gates require Node/browser proof and manual lock updates before any promotion",
    ],
    [
      "blocked_runtime_promotion_gate_consistency",
      flagValue(blockedRuntimePromotionGateConsistencyOk),
      String(runtimeBoundaryPromotionReadinessRows.length),
      "blocked runtime promotion lock, readiness, blockers, post-native gates, evidence acceptance, and pass evidence contracts agree while promotion remains disabled",
    ],
    [
      "runtime_boundary_host_preflight",
      flagValue(runtimeBoundaryHostPreflightOk),
      String(runtimeBoundaryHostPreflightRows.length),
      "runtime boundary host preflight summarizes required runtimes, missing host requirements, and opt-in native probe commands without execution",
    ],
    [
      "runtime_boundary_host_requirement_summary",
      flagValue(runtimeBoundaryHostRequirementSummaryOk),
      String(runtimeBoundaryHostRequirementSummaryRows.length),
      "runtime boundary host requirement summary normalizes missing and available host requirements across blocked runtime families",
    ],
    [
      "runtime_boundary_host_unblock_plan",
      flagValue(runtimeBoundaryHostUnblockPlanOk),
      String(runtimeBoundaryHostUnblockPlanRows.length),
      "runtime boundary host unblock plan records which missing host commands affect which opt-in native probes without executing them",
    ],
    [
      "runtime_boundary_family_host_readiness",
      flagValue(runtimeBoundaryFamilyHostReadinessOk),
      String(runtimeBoundaryFamilyHostReadinessRows.length),
      "runtime boundary family host readiness records per-family missing and available host prerequisites before opt-in native probes",
    ],
    [
      "blocked_runtime_host_requirement_consistency",
      flagValue(blockedRuntimeHostRequirementConsistencyOk),
      String(runtimeBoundaryFamilyHostReadinessRows.length),
      "blocked runtime host requirement summary, unblock plan, and family readiness agree on missing requirements, targets, commands, and disabled execution/promotion",
    ],
    [
      "runtime_boundary_host_readiness_rollup",
      flagValue(runtimeBoundaryHostReadinessRollupOk),
      String(runtimeBoundaryHostReadinessRollupRows.length),
      "runtime boundary host readiness rollup records the aggregate host readiness decision for all blocked runtime opt-in probes",
    ],
    [
      "runtime_boundary_opt_in_probe_dispatch_plan",
      flagValue(runtimeBoundaryOptInProbeDispatchPlanOk),
      String(runtimeBoundaryOptInProbeDispatchPlanRows.length),
      "runtime boundary opt-in probe dispatch plan records the per-probe host action before any native runtime probe can run",
    ],
    [
      "runtime_boundary_opt_in_probe_dispatch_rollup",
      flagValue(runtimeBoundaryOptInProbeDispatchRollupOk),
      String(runtimeBoundaryOptInProbeDispatchRollupRows.length),
      "runtime boundary opt-in probe dispatch rollup records the aggregate dispatch switch for blocked runtime native probes",
    ],
    [
      "runtime_boundary_opt_in_probe_skip_evidence_contract",
      flagValue(runtimeBoundaryOptInProbeSkipEvidenceContractOk),
      String(runtimeBoundaryOptInProbeSkipEvidenceContractRows.length),
      "runtime boundary opt-in probe skip evidence contract records why skipped probes do not provide native pass evidence yet",
    ],
    [
      "runtime_boundary_opt_in_probe_skip_evidence_rollup",
      flagValue(runtimeBoundaryOptInProbeSkipEvidenceRollupOk),
      String(runtimeBoundaryOptInProbeSkipEvidenceRollupRows.length),
      "runtime boundary opt-in probe skip evidence rollup records the aggregate native evidence acceptance state while probes are skipped",
    ],
    [
      "blocked_runtime_rollup_consistency",
      flagValue(blockedRuntimeRollupConsistencyOk),
      String(expectedBlockedRuntimeClasses.length),
      "blocked runtime host readiness, dispatch, and skip-evidence rollups agree on counts, families, commands, missing requirements, and disabled execution/promotion",
    ],
    [
      "runtime_boundary_native_evidence_acceptance_gate",
      flagValue(runtimeBoundaryNativeEvidenceAcceptanceGateOk),
      String(runtimeBoundaryNativeEvidenceAcceptanceGateRows.length),
      "runtime boundary native evidence acceptance gate keeps native evidence and downstream promotion gates closed while opt-in probes are host-blocked",
    ],
    [
      "blocked_runtime_opt_in_gate_consistency",
      flagValue(blockedRuntimeOptInGateConsistencyOk),
      String(expectedBlockedRuntimeClasses.length),
      "blocked runtime opt-in target artifacts agree on class order, target gates, host blocking, dispatch blocking, evidence blocking, and promotion locks",
    ],
    [
      "native_source_proof_runtime_probe_consistency",
      flagValue(nativeSourceProofRuntimeProbeConsistencyOk),
      String(expectedBlockedRuntimeClasses.length),
      "native source proof alignment, native runtime probe summary, and runtime probe gate alignment agree while execution and promotion remain disabled",
    ],
    [
      "user_m_transition_contract",
      flagValue(userMTransitionContractOk),
      String(userMTransitionRows.length),
      "millturn M428/M429 transition contract records switchkins, G5x, guard pins, and state outputs without execution",
    ],
    [
      "user_m_native_runtime_state_plan",
      flagValue(userMRuntimeStatePlanOk),
      String(userMRuntimeStatePlanRows.length),
      "millturn native runnable state probe plan records required LinuxCNC task/HAL/Tcl runtime and expected state outputs while remaining disabled",
    ],
    [
      "user_m_native_runtime_readiness",
      flagValue(userMRuntimeReadinessOk),
      String(userMRuntimeReadinessRows.length),
      "millturn native runtime readiness records required host commands without enabling execution or promotion",
    ],
    [
      "user_m_native_runtime_probe_gate",
      flagValue(userMRuntimeProbeGateOk),
      String(userMRuntimeProbeGateRows.length),
      "millturn native runtime probe gate records host readiness and keeps M128/M129 blocked until HAL/Tcl runtime is available",
    ],
    [
      "tool_db_transaction_contract",
      flagValue(toolDbTransactionContractOk),
      String(toolDbTransactionRows.length),
      "db_demo tool DB transaction contract records v2.1, get-all, load, put, unload, callbacks, and state targets without execution",
    ],
    [
      "tool_db_native_runtime_readiness",
      flagValue(toolDbRuntimeReadinessOk),
      String(toolDbRuntimeReadinessRows.length),
      "db_demo native runtime readiness records required DB process commands and Python modules without enabling execution or promotion",
    ],
    [
      "tool_db_native_runtime_probe_gate",
      flagValue(toolDbRuntimeProbeGateOk),
      String(toolDbRuntimeProbeGateRows.length),
      "db_demo native runtime probe gate records host readiness, DB_PROGRAM source, Python modules, and protocol contract while rejecting python3 or tbl fallback promotion",
    ],
    [
      "python_runtime_contract",
      flagValue(pythonRuntimeContractOk),
      String(pythonRuntimeContractRows.length),
      "Python-remap family runtime contracts record LinuxCNC Python phases, dependencies, process assumptions, and proof requirements without execution",
    ],
    [
      "python_native_runtime_readiness",
      flagValue(pythonRuntimeReadinessOk),
      String(pythonRuntimeReadinessRows.length),
      "Python-remap native runtime readiness records host commands, LinuxCNC Python owner source, and configured Python modules without enabling execution or promotion",
    ],
    [
      "python_native_runtime_probe_gate",
      flagValue(pythonRuntimeProbeGateOk),
      String(pythonRuntimeProbeGateRows.length),
      "Python-remap runtime probe gate records python3, linuxcnc, owner source, and representative module-import readiness while rejecting python3-only promotion",
    ],
    [
      "python_native_runtime_state_plan",
      flagValue(pythonRuntimeStatePlanOk),
      String(pythonRuntimeStatePlanRows.length),
      "Python-remap native runtime state plan records required runtime phases, modules, callables, process assumptions, and proof targets without executing Python",
    ],
    [
      "python_native_runtime_fixture_plan",
      flagValue(pythonRuntimeFixturePlanOk),
      String(pythonRuntimeFixturePlanRows.length),
      "Python-remap native runtime fixture plan selects the minimal stop-lookahead lifecycle fixture without executing Python or enabling promotion",
    ],
    [
      "runtime_contract_summary",
      flagValue(runtimeContractSummaryOk),
      String(runtimeContractSummaryRows.length),
      "Runtime boundary contract summary unifies user-M, tool DB, and Python contracts with pending disabled proof state",
    ],
    [
      "runtime_family_contract_alignment_consistency",
      flagValue(runtimeFamilyContractAlignmentConsistencyOk),
      String(runtimeContractSummaryRows.length),
      "Family-specific user-M, tool DB, and Python contract/readiness/probe artifacts agree with runtime contract and native alignment summaries",
    ],
    [
      "wasm_inventory_artifact_documentation_coverage",
      flagValue(wasmArtifactDocumentationOk),
      String(wasmArtifactNames.length),
      "Every generated WASM sim-config inventory TSV artifact is referenced by the compatibility, matrix, or full-process boundary docs",
    ],
    [
      "native_artifact_documentation_coverage",
      flagValue(nativeArtifactDocumentationOk),
      String(nativeArtifactTokens.length),
      "Every generated native TSV artifact is referenced by relative path in the compatibility, matrix, or full-process boundary docs",
    ],
  ].map((row) => row.map(tsvValue).join("\t"));
}

function verifyBoundaryPhaseCompletionSummaryRows(rows) {
  const expectedHeaders = ["criterion", "passed", "count", "evidence"];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedCriteria = [
    "vendored_runtime_boundary_reports",
    "hard_block_dependency_evidence",
    "safe_hal_ui_representatives",
    "blocked_families_not_promoted",
    "linuxcnc_runtime_owner_proof",
    "native_source_proof_alignment",
    "runtime_native_alignment_artifacts",
    "native_runtime_probe_summary",
    "runtime_probe_gate_alignment",
    "blocked_runtime_worklist_recommendation_consistency",
    "native_runtime_probe_execution_plan",
    "native_runtime_probe_pass_evidence_contract",
    "blocked_runtime_probe_execution_consistency",
    "runtime_boundary_promotion_readiness",
    "runtime_boundary_promotion_blockers",
    "runtime_boundary_post_native_pass_gates",
    "blocked_runtime_promotion_gate_consistency",
    "runtime_boundary_host_preflight",
    "runtime_boundary_host_requirement_summary",
    "runtime_boundary_host_unblock_plan",
    "runtime_boundary_family_host_readiness",
    "blocked_runtime_host_requirement_consistency",
    "runtime_boundary_host_readiness_rollup",
    "runtime_boundary_opt_in_probe_dispatch_plan",
    "runtime_boundary_opt_in_probe_dispatch_rollup",
    "runtime_boundary_opt_in_probe_skip_evidence_contract",
    "runtime_boundary_opt_in_probe_skip_evidence_rollup",
    "blocked_runtime_rollup_consistency",
    "runtime_boundary_native_evidence_acceptance_gate",
    "blocked_runtime_opt_in_gate_consistency",
    "native_source_proof_runtime_probe_consistency",
    "user_m_transition_contract",
    "user_m_native_runtime_state_plan",
    "user_m_native_runtime_readiness",
    "user_m_native_runtime_probe_gate",
    "tool_db_transaction_contract",
    "tool_db_native_runtime_readiness",
    "tool_db_native_runtime_probe_gate",
    "python_runtime_contract",
    "python_native_runtime_readiness",
    "python_native_runtime_probe_gate",
    "python_native_runtime_state_plan",
    "python_native_runtime_fixture_plan",
    "runtime_contract_summary",
    "runtime_family_contract_alignment_consistency",
    "wasm_inventory_artifact_documentation_coverage",
    "native_artifact_documentation_coverage",
  ];

  assert.deepEqual(
    parsedRows.map((row) => row.criterion),
    expectedCriteria,
    "boundary phase completion criteria drift",
  );
  for (const row of parsedRows) {
    assert.equal(row.passed, "1", `${row.criterion}: completion criterion failed`);
    assert.ok(/^[1-9][0-9]*$/.test(row.count), `${row.criterion}: invalid criterion count`);
    assert.notEqual(row.evidence, "-", `${row.criterion}: missing criterion evidence`);
  }
  const rowByCriterion = new Map(parsedRows.map((row) => [row.criterion, row]));
  assert.equal(
    rowByCriterion.get("wasm_inventory_artifact_documentation_coverage")?.count,
    "54",
    "WASM artifact documentation completion count must match generated artifact baseline",
  );
  assert.equal(
    rowByCriterion.get("native_artifact_documentation_coverage")?.count,
    "8",
    "native artifact documentation completion count must match generated artifact baseline",
  );

  return parsedRows;
}

function nextBoundaryWorklistRows({ fullProcessRows, pythonFamilyRows }) {
  const fullProcessPriority = new Map([
    ["external_user_m_process", 1],
    ["tool_database_process", 2],
  ]);
  const fullProcessNextAction = new Map([
    ["external_user_m_process", "design_m128_m129_linuxcnc_state_boundary"],
    ["tool_database_process", "design_tooldata_db_protocol_boundary"],
  ]);
  const fullProcessItems = fullProcessRows
    .map((row) => [
      String(fullProcessPriority.get(row.boundary_kind) ?? 50),
      row.boundary_kind,
      row.path,
      row.blocked,
      row.design_status,
      row.linuxcnc_owner,
      row.runtime_owner_evidence,
      row.required_native_proof,
      row.required_node_proof,
      listValue(uniqueSorted([row.required_browser_proof, row.browser_policy])),
      row.execution_enabled,
      "0",
      fullProcessNextAction.get(row.boundary_kind) ?? "design_linuxcnc_owned_runtime_boundary",
      row.notes,
    ]);
  const pythonItems = [...pythonFamilyRows]
    .sort((left, right) =>
      Number(right.row_count) - Number(left.row_count) || left.family.localeCompare(right.family),
    )
    .map((row, index) => [
      String(100 + index),
      "python_runtime",
      row.family,
      "L4-PYTHON-REMAP",
      "inventory_only",
      "src/emc/rs274ngc/interp_python.cc,src/emc/pythonplugin/python_plugin.cc,configs/sim/*/python/*.py",
      row.python_runtime_evidence,
      "python_runtime_owner_and_fixture",
      "linuxcnc_python_runtime_boundary_not_js_semantics",
      "browser_after_node_python_boundary_no_full_process_claim",
      row.execution_enabled,
      "0",
      "design_linuxcnc_python_runtime_boundary",
      row.notes,
    ]);

  return [...fullProcessItems, ...pythonItems]
    .sort((left, right) => Number(left[0]) - Number(right[0]))
    .map((row) => row.map(tsvValue).join("\t"));
}

function verifyNextBoundaryWorklistRows(rows, fullProcessRows, pythonFamilyRows) {
  const expectedHeaders = [
    "priority",
    "boundary_kind",
    "target",
    "blocked",
    "design_status",
    "linuxcnc_owner",
    "runtime_owner_evidence",
    "required_native_proof",
    "required_node_proof",
    "required_browser_proof",
    "execution_enabled",
    "promotion_allowed",
    "next_action",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  assert.equal(
    parsedRows.length,
    fullProcessRows.length + pythonFamilyRows.length,
    "next boundary worklist must cover full-process rows and Python families",
  );
  assert.deepEqual(
    parsedRows.map((row) => row.priority),
    parsedRows.map((row) => row.priority).sort((left, right) => Number(left) - Number(right)),
    "next boundary worklist priorities must be sorted",
  );
  assert.deepEqual(
    parsedRows.slice(0, 2).map((row) => [row.boundary_kind, row.blocked, row.execution_enabled]),
    [
      ["external_user_m_process", "L4-USER-M-PROCESS", "0"],
      ["tool_database_process", "L4-TOOL-DB", "0"],
    ],
    "next boundary worklist must keep current full-process blockers first",
  );
  for (const row of parsedRows) {
    assert.equal(row.execution_enabled, "0", `${row.target}: worklist item must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.target}: worklist item must not allow promotion yet`);
    assert.notEqual(row.next_action, "-", `${row.target}: worklist item lacks next action`);
    verifyLinuxCncOwnerPaths(row.target, row.linuxcnc_owner);
    assert.notEqual(row.runtime_owner_evidence, "-", `${row.target}: worklist item lacks runtime owner evidence`);
    assert.notEqual(row.required_native_proof, "-", `${row.target}: worklist item lacks native proof`);
    assert.notEqual(row.required_node_proof, "-", `${row.target}: worklist item lacks Node proof`);
    assert.notEqual(row.required_browser_proof, "-", `${row.target}: worklist item lacks browser proof`);
    if (row.boundary_kind === "external_user_m_process") {
      assert.ok(
        row.runtime_owner_evidence.includes("kinstype_guard") &&
          row.runtime_owner_evidence.includes("ini_axis_limit_hal_setp"),
        `${row.target}: user-M work item lacks side-effect evidence`,
      );
    }
    if (row.boundary_kind === "tool_database_process") {
      assert.ok(
        row.runtime_owner_evidence.includes("tooldata_db_v2_1_handshake") &&
          row.runtime_owner_evidence.includes("tooldata_db_notify_l_u_p"),
        `${row.target}: tool DB work item lacks protocol evidence`,
      );
    }
    if (row.boundary_kind === "python_runtime") {
      assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.target}: Python work item block drift`);
      assert.equal(row.design_status, "inventory_only", `${row.target}: Python work item design drift`);
      assert.ok(
        row.runtime_owner_evidence.includes("interp_python_pycall_dispatch") &&
          row.runtime_owner_evidence.includes("python_plugin_callable_invoke"),
        `${row.target}: Python work item lacks runtime evidence`,
      );
      assert.equal(
        row.next_action,
        "design_linuxcnc_python_runtime_boundary",
        `${row.target}: Python work item next action drift`,
      );
      assert.ok(
        row.linuxcnc_owner.includes("src/emc/rs274ngc/interp_python.cc"),
        `${row.target}: Python work item lacks interpreter Python owner`,
      );
      assert.ok(
        row.notes.includes("dependency_inventory_only_no_execution"),
        `${row.target}: Python work item must remain inventory-only`,
      );
    }
  }

  return parsedRows;
}

function boundaryProofGateRows(worklistRows) {
  const layerField = new Map([
    ["native", "required_native_proof"],
    ["node", "required_node_proof"],
    ["browser", "required_browser_proof"],
  ]);

  return worklistRows.flatMap((row) =>
    [...layerField.entries()].map(([layer, proofField]) => {
      const requiredProof = layer === "browser"
        ? listValue(uniqueSorted([
            row[proofField],
            row.browser_policy,
          ]))
        : row[proofField];
      return [
      row.priority,
      row.boundary_kind,
      row.target,
      layer,
      row.blocked,
      row.design_status,
      row.linuxcnc_owner,
      row.runtime_owner_evidence,
      requiredProof,
      "pending",
      row.execution_enabled,
      row.promotion_allowed,
      row.next_action,
      row.notes,
      ].map(tsvValue).join("\t");
    }),
  );
}

function verifyBoundaryProofGateRows(rows, worklistRows) {
  const expectedHeaders = [
    "priority",
    "boundary_kind",
    "target",
    "proof_layer",
    "blocked",
    "design_status",
    "linuxcnc_owner",
    "runtime_owner_evidence",
    "required_proof",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "next_action",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedTargets = new Set(worklistRows.map((row) => row.target));
  const expectedLayers = ["native", "node", "browser"];

  assert.equal(
    parsedRows.length,
    worklistRows.length * expectedLayers.length,
    "boundary proof gates must include native, Node, and browser rows for every worklist item",
  );

  for (const target of expectedTargets) {
    const targetRows = parsedRows.filter((row) => row.target === target);
    assert.deepEqual(
      targetRows.map((row) => row.proof_layer).sort(),
      [...expectedLayers].sort(),
      `${target}: proof gate layer set drift`,
    );
  }

  for (const row of parsedRows) {
    assert.ok(expectedLayers.includes(row.proof_layer), `${row.target}: invalid proof layer ${row.proof_layer}`);
    assert.equal(row.proof_status, "pending", `${row.target}/${row.proof_layer}: proof gate must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.target}/${row.proof_layer}: proof gate must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.target}/${row.proof_layer}: proof gate must not allow promotion`);
    verifyLinuxCncOwnerPaths(row.target, row.linuxcnc_owner);
    assert.notEqual(row.runtime_owner_evidence, "-", `${row.target}/${row.proof_layer}: missing runtime owner evidence`);
    assert.notEqual(row.required_proof, "-", `${row.target}/${row.proof_layer}: missing required proof`);
    assert.notEqual(row.next_action, "-", `${row.target}/${row.proof_layer}: missing next action`);

    if (row.boundary_kind === "external_user_m_process") {
      if (row.proof_layer === "native") {
        assert.ok(
          row.required_proof.includes("ini_xyz_hal_pin_state"),
          `${row.target}: native user-M proof must require HAL pin state`,
        );
      }
      if (row.proof_layer === "node") {
        assert.ok(
          row.required_proof.includes("not_user_m_event_only"),
          `${row.target}: Node user-M proof must reject event-only coverage`,
        );
      }
      if (row.proof_layer === "browser") {
        assert.ok(
          row.required_proof.includes("no_full_process_claim"),
          `${row.target}: browser user-M proof must avoid full-process claim`,
        );
      }
    }

    if (row.boundary_kind === "tool_database_process") {
      if (row.proof_layer === "native") {
        assert.ok(
          row.required_proof.includes("v2_1_handshake"),
          `${row.target}: native tool DB proof must require protocol handshake`,
        );
      }
      if (row.proof_layer === "node") {
        assert.ok(
          row.required_proof.includes("not_tbl_fallback"),
          `${row.target}: Node tool DB proof must reject tbl fallback`,
        );
      }
      if (row.proof_layer === "browser") {
        assert.ok(
          row.required_proof.includes("opfs_persistence_only"),
          `${row.target}: browser tool DB proof must constrain OPFS to persistence`,
        );
      }
    }

    if (row.boundary_kind === "python_runtime") {
      assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.target}: Python proof gate blocked kind drift`);
      assert.equal(row.design_status, "inventory_only", `${row.target}: Python proof gate design status drift`);
      if (row.proof_layer === "native") {
        assert.ok(
          row.required_proof.includes("python_runtime_owner"),
          `${row.target}: native Python proof must require runtime owner`,
        );
      }
      if (row.proof_layer === "node") {
        assert.ok(
          row.required_proof.includes("not_js_semantics"),
          `${row.target}: Node Python proof must reject JS semantics`,
        );
      }
      if (row.proof_layer === "browser") {
        assert.ok(
          row.required_proof.includes("no_full_process_claim"),
          `${row.target}: browser Python proof must avoid full-process claim`,
        );
      }
    }
  }

  return parsedRows;
}

function blockedRuntimePromotionLockRows({
  worklistRows,
  proofGateRows,
  runtimeNativeAlignmentRows,
}) {
  const runtimeAlignmentByKind = new Map(
    runtimeNativeAlignmentRows.map((row) => [row.boundary_kind, row]),
  );

  return worklistRows.map((row) => {
    const gateRows = proofGateRows.filter((gate) =>
      gate.boundary_kind === row.boundary_kind && gate.target === row.target,
    );
    const runtimeAlignment = runtimeAlignmentByKind.get(row.boundary_kind);
    const nativeGatePending = gateRows.some((gate) =>
      gate.proof_layer === "native" &&
        gate.proof_status === "pending" &&
        gate.execution_enabled === "0" &&
        gate.promotion_allowed === "0",
    );
    const nodeGatePending = gateRows.some((gate) =>
      gate.proof_layer === "node" &&
        gate.proof_status === "pending" &&
        gate.execution_enabled === "0" &&
        gate.promotion_allowed === "0",
    );
    const browserGatePending = gateRows.some((gate) =>
      gate.proof_layer === "browser" &&
        gate.proof_status === "pending" &&
        gate.execution_enabled === "0" &&
        gate.promotion_allowed === "0",
    );
    const runtimeAlignmentOk = Boolean(runtimeAlignment) &&
      runtimeAlignment.summary_ok === "1" &&
      runtimeAlignment.pending_count === runtimeAlignment.row_count &&
      runtimeAlignment.execution_disabled_count === runtimeAlignment.row_count &&
      runtimeAlignment.promotion_disabled_count === runtimeAlignment.row_count;
    const lockActive = (
      row.execution_enabled === "0" &&
      row.promotion_allowed === "0" &&
      nativeGatePending &&
      nodeGatePending &&
      browserGatePending &&
      runtimeAlignmentOk
    );

    return [
      row.priority,
      row.boundary_kind,
      row.target,
      row.blocked,
      row.design_status,
      row.execution_enabled,
      row.promotion_allowed,
      flagValue(nativeGatePending),
      flagValue(nodeGatePending),
      flagValue(browserGatePending),
      runtimeAlignment?.artifact ?? "-",
      runtimeAlignment?.row_count ?? "0",
      flagValue(runtimeAlignmentOk),
      row.next_action,
      flagValue(lockActive),
      "blocked_until_linuxcnc_owned_runtime_boundary_replaces_pending_gates",
    ].map(tsvValue).join("\t");
  });
}

function verifyBlockedRuntimePromotionLockRows(rows, worklistRows) {
  const expectedHeaders = [
    "priority",
    "boundary_kind",
    "target",
    "blocked",
    "design_status",
    "execution_enabled",
    "promotion_allowed",
    "native_gate_pending",
    "node_gate_pending",
    "browser_gate_pending",
    "runtime_alignment_artifact",
    "runtime_alignment_row_count",
    "runtime_alignment_ok",
    "next_action",
    "lock_active",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_blocked_runtime_promotion_lock",
    worklistRows.map((row) => row.target).sort(),
    parsedRows.map((row) => row.target).sort(),
  );

  for (const row of parsedRows) {
    assert.equal(row.execution_enabled, "0", `${row.target}: promotion lock must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.target}: promotion lock must not allow promotion`);
    assert.equal(row.native_gate_pending, "1", `${row.target}: native gate must remain pending`);
    assert.equal(row.node_gate_pending, "1", `${row.target}: Node gate must remain pending`);
    assert.equal(row.browser_gate_pending, "1", `${row.target}: browser gate must remain pending`);
    assert.notEqual(row.runtime_alignment_artifact, "-", `${row.target}: missing runtime alignment artifact`);
    assert.ok(/^[1-9][0-9]*$/.test(row.runtime_alignment_row_count), `${row.target}: invalid runtime alignment count`);
    assert.equal(row.runtime_alignment_ok, "1", `${row.target}: runtime alignment summary failed`);
    assert.notEqual(row.next_action, "-", `${row.target}: promotion lock lacks next action`);
    assert.equal(row.lock_active, "1", `${row.target}: promotion lock is inactive`);
    assert.ok(
      row.notes.includes("blocked_until_linuxcnc_owned_runtime_boundary"),
      `${row.target}: promotion lock note drift`,
    );

    if (row.boundary_kind === "external_user_m_process") {
      assert.equal(row.blocked, "L4-USER-M-PROCESS", `${row.target}: user-M promotion lock blocked kind drift`);
      assert.equal(row.runtime_alignment_artifact, "user-m-process-native-state-alignment.tsv", `${row.target}: user-M alignment artifact drift`);
    } else if (row.boundary_kind === "tool_database_process") {
      assert.equal(row.blocked, "L4-TOOL-DB", `${row.target}: tool DB promotion lock blocked kind drift`);
      assert.equal(row.runtime_alignment_artifact, "tool-db-process-native-protocol-alignment.tsv", `${row.target}: tool DB alignment artifact drift`);
    } else if (row.boundary_kind === "python_runtime") {
      assert.equal(row.blocked, "L4-PYTHON-REMAP", `${row.target}: Python promotion lock blocked kind drift`);
      assert.equal(row.runtime_alignment_artifact, "python-remap-native-runtime-alignment.tsv", `${row.target}: Python alignment artifact drift`);
      assert.equal(row.design_status, "inventory_only", `${row.target}: Python promotion lock design status drift`);
    } else {
      throw new Error(`${row.target}: unexpected promotion lock boundary kind ${row.boundary_kind}`);
    }
  }

  return parsedRows;
}

function runtimeBoundaryPromotionReadinessRows({
  executionPlanRows,
  passEvidenceRows,
  promotionLockRows,
}) {
  const evidenceByClass = new Map(passEvidenceRows.map((row) => [row.boundary_class, row]));
  const lockByTarget = new Map(promotionLockRows.map((row) => [row.target, row]));

  return executionPlanRows.map((plan) => {
    const evidence = evidenceByClass.get(plan.boundary_class);
    const lock = lockByTarget.get(plan.target);
    const nativePassReady = plan.current_probe_status === plan.expected_pass_status;
    const nativeEvidenceReady = evidence?.observed_evidence_ready === "1";
    const nodeInventoryGateComplete = false;
    const browserSmokeGateComplete = false;
    const manualLockUpdateRequired = plan.promotion_requires.includes("manual:promotion_lock_update_required");
    const promotionReady = (
      nativePassReady &&
      nativeEvidenceReady &&
      nodeInventoryGateComplete &&
      browserSmokeGateComplete &&
      lock?.lock_active === "0" &&
      !manualLockUpdateRequired
    );
    const blockingReason = !nativePassReady
      ? "awaiting_native_runtime_probe_pass"
      : !nativeEvidenceReady
        ? "awaiting_native_pass_evidence"
        : lock?.lock_active === "1"
          ? "promotion_lock_active_pending_node_browser_manual_update"
          : "awaiting_node_browser_promotion_proof";

    return [
      plan.boundary_class,
      plan.boundary_kind,
      plan.target,
      lock?.blocked ?? "-",
      plan.current_probe_status,
      plan.expected_pass_status,
      flagValue(nativePassReady),
      evidence?.evidence_status ?? "-",
      flagValue(nativeEvidenceReady),
      "0",
      "0",
      lock?.lock_active ?? "1",
      flagValue(manualLockUpdateRequired),
      flagValue(promotionReady),
      "0",
      "0",
      blockingReason,
      "promotion_readiness_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryPromotionReadinessRows({
  rows,
  executionPlanRows,
  passEvidenceRows,
  promotionLockRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "current_probe_status",
    "expected_pass_status",
    "native_pass_ready",
    "native_evidence_status",
    "native_evidence_ready",
    "node_inventory_gate_complete",
    "browser_smoke_gate_complete",
    "promotion_lock_active",
    "manual_lock_update_required",
    "promotion_ready",
    "execution_enabled",
    "promotion_allowed",
    "blocking_reason",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expected = new Map([
    [
      "L4-USER-M-PROCESS",
      {
        boundaryKind: "external_user_m_process",
        target: "axis/vismach/millturn/example.ngc",
        blocked: "L4-USER-M-PROCESS",
        expectedPassStatus: "runtime_state_probe_passed",
      },
    ],
    [
      "L4-TOOL-DB",
      {
        boundaryKind: "tool_database_process",
        target: "axis/db_demo/base.ngc",
        blocked: "L4-TOOL-DB",
        expectedPassStatus: "runtime_protocol_probe_passed",
      },
    ],
    [
      "L4-PYTHON-REMAP",
      {
        boundaryKind: "python_runtime",
        target: "axis/remap/stop-lookahead/nc_files",
        blocked: "L4-PYTHON-REMAP",
        expectedPassStatus: "runtime_lifecycle_probe_passed",
      },
    ],
  ]);
  const planByClass = new Map(executionPlanRows.map((row) => [row.boundary_class, row]));
  const evidenceByClass = new Map(passEvidenceRows.map((row) => [row.boundary_class, row]));
  const lockByTarget = new Map(promotionLockRows.map((row) => [row.target, row]));

  assert.equal(parsedRows.length, expected.size, "runtime boundary promotion readiness row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    [...expected.keys()],
    "runtime boundary promotion readiness order drift",
  );

  for (const row of parsedRows) {
    const expectedRow = expected.get(row.boundary_class);
    const plan = planByClass.get(row.boundary_class);
    const evidence = evidenceByClass.get(row.boundary_class);
    const lock = lockByTarget.get(row.target);
    assert.ok(expectedRow, `${row.boundary_class}: unexpected promotion readiness row`);
    assert.ok(plan, `${row.boundary_class}: promotion readiness lacks execution plan`);
    assert.ok(evidence, `${row.boundary_class}: promotion readiness lacks pass evidence contract`);
    assert.ok(lock, `${row.boundary_class}: promotion readiness lacks promotion lock`);
    assert.equal(row.boundary_kind, expectedRow.boundaryKind, `${row.boundary_class}: promotion readiness kind drift`);
    assert.equal(row.target, expectedRow.target, `${row.boundary_class}: promotion readiness target drift`);
    assert.equal(row.blocked, expectedRow.blocked, `${row.boundary_class}: promotion readiness blocked kind drift`);
    assert.equal(row.current_probe_status, plan.current_probe_status, `${row.boundary_class}: promotion readiness probe status drift`);
    assert.equal(row.expected_pass_status, expectedRow.expectedPassStatus, `${row.boundary_class}: promotion readiness expected status drift`);
    assert.equal(row.expected_pass_status, plan.expected_pass_status, `${row.boundary_class}: promotion readiness plan status drift`);
    assert.equal(row.native_evidence_status, evidence.evidence_status, `${row.boundary_class}: promotion readiness evidence status drift`);
    assert.equal(row.native_evidence_ready, evidence.observed_evidence_ready, `${row.boundary_class}: promotion readiness evidence readiness drift`);
    assert.equal(row.promotion_lock_active, lock.lock_active, `${row.boundary_class}: promotion lock active drift`);
    assert.equal(row.manual_lock_update_required, "1", `${row.boundary_class}: manual lock update must remain required`);
    assert.equal(row.node_inventory_gate_complete, "0", `${row.boundary_class}: Node promotion gate must not be complete`);
    assert.equal(row.browser_smoke_gate_complete, "0", `${row.boundary_class}: browser promotion gate must not be complete`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: promotion readiness must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: promotion readiness must not allow promotion`);
    assert.equal(row.promotion_ready, "0", `${row.boundary_class}: promotion readiness must remain false`);
    assert.notEqual(row.blocking_reason, "-", `${row.boundary_class}: promotion readiness lacks blocking reason`);
    if (row.current_probe_status === row.expected_pass_status) {
      assert.equal(row.native_pass_ready, "1", `${row.boundary_class}: native pass flag drift`);
      assert.notEqual(row.blocking_reason, "awaiting_native_runtime_probe_pass", `${row.boundary_class}: passed probe has stale blocking reason`);
    } else {
      assert.equal(row.native_pass_ready, "0", `${row.boundary_class}: native pass flag drift`);
      assert.equal(row.blocking_reason, "awaiting_native_runtime_probe_pass", `${row.boundary_class}: missing native pass blocking reason drift`);
    }
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: promotion readiness note drift`);
  }

  return parsedRows;
}

function runtimeBoundaryPromotionBlockerRows({
  promotionReadinessRows,
  executionPlanRows,
}) {
  const planByClass = new Map(executionPlanRows.map((row) => [row.boundary_class, row]));

  return promotionReadinessRows.map((row) => {
    const plan = planByClass.get(row.boundary_class);
    const blockers = [];
    if (plan?.missing_requirements && plan.missing_requirements !== "-") {
      blockers.push("host_runtime_requirements_missing");
    }
    if (row.native_pass_ready !== "1") {
      blockers.push("native_runtime_probe_not_passed");
    }
    if (row.native_evidence_ready !== "1") {
      blockers.push("native_pass_evidence_not_ready");
    }
    if (row.node_inventory_gate_complete !== "1") {
      blockers.push("node_inventory_gate_not_complete");
    }
    if (row.browser_smoke_gate_complete !== "1") {
      blockers.push("browser_smoke_gate_not_complete");
    }
    if (row.promotion_lock_active === "1") {
      blockers.push("promotion_lock_active");
    }
    if (row.manual_lock_update_required === "1") {
      blockers.push("manual_lock_update_required");
    }

    const nextUnblockAction = plan?.missing_requirements && plan.missing_requirements !== "-"
      ? `provide_host_runtime_requirements:${plan.missing_requirements}`
      : row.native_pass_ready !== "1"
        ? "run_opt_in_native_runtime_probe"
        : row.native_evidence_ready !== "1"
          ? "collect_native_pass_stdout_evidence"
          : "complete_node_browser_promotion_gates_and_manual_lock_update";

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.blocked,
      row.promotion_ready,
      String(blockers.length),
      listValue(blockers),
      plan?.missing_requirements ?? "-",
      nextUnblockAction,
      row.execution_enabled,
      row.promotion_allowed,
      "promotion_blocker_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryPromotionBlockerRows({
  rows,
  promotionReadinessRows,
  executionPlanRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "promotion_ready",
    "blocker_count",
    "blocker_keys",
    "missing_runtime_requirements",
    "next_unblock_action",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const readinessByClass = new Map(promotionReadinessRows.map((row) => [row.boundary_class, row]));
  const planByClass = new Map(executionPlanRows.map((row) => [row.boundary_class, row]));
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];

  assert.equal(parsedRows.length, expectedClasses.length, "runtime boundary promotion blockers row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    expectedClasses,
    "runtime boundary promotion blockers order drift",
  );

  for (const row of parsedRows) {
    const readiness = readinessByClass.get(row.boundary_class);
    const plan = planByClass.get(row.boundary_class);
    assert.ok(readiness, `${row.boundary_class}: promotion blockers lack readiness row`);
    assert.ok(plan, `${row.boundary_class}: promotion blockers lack execution plan row`);
    assert.equal(row.boundary_kind, readiness.boundary_kind, `${row.boundary_class}: blocker kind drift`);
    assert.equal(row.target, readiness.target, `${row.boundary_class}: blocker target drift`);
    assert.equal(row.blocked, readiness.blocked, `${row.boundary_class}: blocker blocked kind drift`);
    assert.equal(row.promotion_ready, readiness.promotion_ready, `${row.boundary_class}: blocker promotion readiness drift`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: blocker summary must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: blocker summary must not allow promotion`);
    assert.ok(/^[1-9][0-9]*$/.test(row.blocker_count), `${row.boundary_class}: blocker count must be positive`);
    assert.notEqual(row.blocker_keys, "-", `${row.boundary_class}: blocker keys are required while not ready`);
    assert.equal(row.promotion_ready, "0", `${row.boundary_class}: runtime boundary must not be promotion-ready`);
    if (readiness.native_pass_ready !== "1") {
      assert.ok(row.blocker_keys.includes("native_runtime_probe_not_passed"), `${row.boundary_class}: native pass blocker missing`);
    }
    if (readiness.native_evidence_ready !== "1") {
      assert.ok(row.blocker_keys.includes("native_pass_evidence_not_ready"), `${row.boundary_class}: native evidence blocker missing`);
    }
    assert.ok(row.blocker_keys.includes("node_inventory_gate_not_complete"), `${row.boundary_class}: Node gate blocker missing`);
    assert.ok(row.blocker_keys.includes("browser_smoke_gate_not_complete"), `${row.boundary_class}: browser gate blocker missing`);
    assert.ok(row.blocker_keys.includes("promotion_lock_active"), `${row.boundary_class}: promotion lock blocker missing`);
    assert.ok(row.blocker_keys.includes("manual_lock_update_required"), `${row.boundary_class}: manual lock blocker missing`);
    if (plan.missing_requirements !== "-") {
      assert.equal(row.missing_runtime_requirements, plan.missing_requirements, `${row.boundary_class}: missing requirements drift`);
      assert.ok(row.blocker_keys.includes("host_runtime_requirements_missing"), `${row.boundary_class}: host runtime blocker missing`);
      assert.ok(row.next_unblock_action.includes(plan.missing_requirements), `${row.boundary_class}: unblock action must name missing requirements`);
    }
    assert.notEqual(row.next_unblock_action, "-", `${row.boundary_class}: blocker summary lacks next unblock action`);
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: blocker summary notes drift`);
  }

  return parsedRows;
}

function runtimeBoundaryPostNativePassGateRows({
  promotionReadinessRows,
  recommendationRows,
}) {
  const recommendationByKind = new Map(recommendationRows.map((row) => [row.boundary_kind, row]));

  return promotionReadinessRows.map((row) => {
    const recommendation = recommendationByKind.get(row.boundary_kind);
    const nodeGateStatus = row.native_evidence_ready === "1"
      ? "pending_node_inventory_promotion_gate"
      : "blocked_until_native_pass_evidence";
    const browserGateStatus = row.native_evidence_ready === "1"
      ? "blocked_until_node_gate_complete"
      : "blocked_until_node_gate_complete";
    const gateStatus = row.native_evidence_ready === "1"
      ? "waiting_for_node_browser_manual_promotion"
      : "blocked_before_native_pass";

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.blocked,
      row.current_probe_status,
      row.expected_pass_status,
      row.native_pass_ready,
      row.native_evidence_ready,
      recommendation?.required_node_proof ?? "-",
      recommendation?.required_browser_proof ?? "-",
      nodeGateStatus,
      browserGateStatus,
      row.manual_lock_update_required,
      row.promotion_lock_active,
      row.execution_enabled,
      row.promotion_allowed,
      gateStatus,
      "post_native_pass_gate_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryPostNativePassGateRows({
  rows,
  promotionReadinessRows,
  recommendationRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "current_probe_status",
    "expected_pass_status",
    "native_pass_ready",
    "native_evidence_ready",
    "required_node_proof",
    "required_browser_proof",
    "node_gate_status",
    "browser_gate_status",
    "manual_lock_update_required",
    "promotion_lock_active",
    "execution_enabled",
    "promotion_allowed",
    "gate_status",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const readinessByClass = new Map(promotionReadinessRows.map((row) => [row.boundary_class, row]));
  const recommendationByKind = new Map(recommendationRows.map((row) => [row.boundary_kind, row]));
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];

  assert.equal(parsedRows.length, expectedClasses.length, "post-native-pass gate row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    expectedClasses,
    "post-native-pass gate order drift",
  );

  for (const row of parsedRows) {
    const readiness = readinessByClass.get(row.boundary_class);
    const recommendation = recommendationByKind.get(row.boundary_kind);
    assert.ok(readiness, `${row.boundary_class}: post-native-pass gate lacks readiness row`);
    assert.ok(recommendation, `${row.boundary_class}: post-native-pass gate lacks recommendation row`);
    assert.equal(row.boundary_kind, readiness.boundary_kind, `${row.boundary_class}: post-native-pass kind drift`);
    assert.equal(row.target, readiness.target, `${row.boundary_class}: post-native-pass target drift`);
    assert.equal(row.blocked, readiness.blocked, `${row.boundary_class}: post-native-pass blocked drift`);
    assert.equal(row.current_probe_status, readiness.current_probe_status, `${row.boundary_class}: post-native-pass probe status drift`);
    assert.equal(row.expected_pass_status, readiness.expected_pass_status, `${row.boundary_class}: post-native-pass expected status drift`);
    assert.equal(row.native_pass_ready, readiness.native_pass_ready, `${row.boundary_class}: post-native-pass native pass drift`);
    assert.equal(row.native_evidence_ready, readiness.native_evidence_ready, `${row.boundary_class}: post-native-pass native evidence drift`);
    assert.equal(row.required_node_proof, recommendation.required_node_proof, `${row.boundary_class}: post-native-pass Node proof drift`);
    assert.equal(row.required_browser_proof, recommendation.required_browser_proof, `${row.boundary_class}: post-native-pass browser proof drift`);
    assert.notEqual(row.required_node_proof, "-", `${row.boundary_class}: post-native-pass gate lacks Node proof`);
    assert.notEqual(row.required_browser_proof, "-", `${row.boundary_class}: post-native-pass gate lacks browser proof`);
    assert.equal(row.manual_lock_update_required, "1", `${row.boundary_class}: post-native-pass manual lock update must remain required`);
    assert.equal(row.promotion_lock_active, "1", `${row.boundary_class}: post-native-pass promotion lock must remain active`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: post-native-pass gate must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: post-native-pass gate must not allow promotion`);
    if (row.native_evidence_ready === "1") {
      assert.equal(row.node_gate_status, "pending_node_inventory_promotion_gate", `${row.boundary_class}: post-native-pass Node gate status drift`);
      assert.equal(row.browser_gate_status, "blocked_until_node_gate_complete", `${row.boundary_class}: post-native-pass browser gate status drift`);
      assert.equal(row.gate_status, "waiting_for_node_browser_manual_promotion", `${row.boundary_class}: post-native-pass status drift`);
    } else {
      assert.equal(row.node_gate_status, "blocked_until_native_pass_evidence", `${row.boundary_class}: post-native-pass Node gate must wait for native evidence`);
      assert.equal(row.browser_gate_status, "blocked_until_node_gate_complete", `${row.boundary_class}: post-native-pass browser gate must wait for Node gate`);
      assert.equal(row.gate_status, "blocked_before_native_pass", `${row.boundary_class}: post-native-pass status drift`);
    }
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: post-native-pass note drift`);
  }

  return parsedRows;
}

function runtimeBoundaryHostPreflightRows({
  userMRuntimeProbeGateRows,
  toolDbRuntimeProbeGateRows,
  pythonRuntimeProbeGateRows,
  executionPlanRows,
}) {
  const planByClass = new Map(executionPlanRows.map((row) => [row.boundary_class, row]));
  const userMProbeGate = userMRuntimeProbeGateRows[0];
  const toolDbProbeGate = toolDbRuntimeProbeGateRows[0];
  const pythonProbeGate = pythonRuntimeProbeGateRows[0];
  const rows = [
    {
      boundaryClass: "L4-USER-M-PROCESS",
      boundaryKind: "external_user_m_process",
      target: userMProbeGate?.path ?? "axis/vismach/millturn/example.ngc",
      blocked: userMProbeGate?.blocked ?? "L4-USER-M-PROCESS",
      requiredRuntime: userMProbeGate?.required_runtime ?? "-",
      runtimeRequirements: userMProbeGate?.runtime_requirements ?? "-",
      missingRequirements: userMProbeGate?.missing_requirements ?? "-",
      runtimeReady: userMProbeGate?.runtime_ready ?? "0",
      sourceProofReady: userMProbeGate?.source_proof_ready ?? "0",
      requiredNativeProof: userMProbeGate?.required_native_proof ?? "-",
    },
    {
      boundaryClass: "L4-TOOL-DB",
      boundaryKind: "tool_database_process",
      target: toolDbProbeGate?.path ?? "axis/db_demo/base.ngc",
      blocked: toolDbProbeGate?.blocked ?? "L4-TOOL-DB",
      requiredRuntime: toolDbProbeGate?.required_runtime ?? "-",
      runtimeRequirements: toolDbProbeGate?.runtime_requirements ?? "-",
      missingRequirements: toolDbProbeGate?.missing_requirements ?? "-",
      runtimeReady: toolDbProbeGate?.runtime_ready ?? "0",
      sourceProofReady: toolDbProbeGate?.source_proof_ready ?? "0",
      requiredNativeProof: toolDbProbeGate?.required_native_proof ?? "-",
    },
    {
      boundaryClass: "L4-PYTHON-REMAP",
      boundaryKind: "python_runtime",
      target: pythonProbeGate?.family ?? "axis/remap/stop-lookahead/nc_files",
      blocked: pythonProbeGate?.blocked ?? "L4-PYTHON-REMAP",
      requiredRuntime: pythonProbeGate?.required_runtime ?? "-",
      runtimeRequirements: pythonProbeGate?.runtime_requirements ?? "-",
      missingRequirements: pythonProbeGate?.missing_requirements ?? "-",
      runtimeReady: pythonProbeGate?.runtime_ready ?? "0",
      sourceProofReady: pythonProbeGate?.source_proof_ready ?? "0",
      requiredNativeProof: pythonProbeGate?.required_native_proof ?? "-",
    },
  ];

  return rows.map((row) => {
    const plan = planByClass.get(row.boundaryClass);
    const preflightStatus = row.sourceProofReady !== "1"
      ? "blocked_missing_source_proof"
      : row.runtimeReady === "1"
        ? "ready_to_run_opt_in_native_probe"
        : "blocked_missing_host_runtime";

    return [
      row.boundaryClass,
      row.boundaryKind,
      row.target,
      row.blocked,
      row.requiredRuntime,
      row.runtimeRequirements,
      row.missingRequirements,
      row.runtimeReady,
      row.sourceProofReady,
      row.requiredNativeProof,
      plan?.opt_in_env ?? "-",
      plan?.execution_command ?? "-",
      plan?.current_probe_status ?? "-",
      preflightStatus,
      "0",
      "0",
      "host_preflight_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryHostPreflightRows({
  rows,
  userMRuntimeProbeGateRows,
  toolDbRuntimeProbeGateRows,
  pythonRuntimeProbeGateRows,
  executionPlanRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "required_runtime",
    "runtime_requirements",
    "missing_requirements",
    "runtime_ready",
    "source_proof_ready",
    "required_native_proof",
    "opt_in_env",
    "execution_command",
    "current_probe_status",
    "preflight_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expected = new Map([
    [
      "L4-USER-M-PROCESS",
      {
        boundaryKind: "external_user_m_process",
        target: "axis/vismach/millturn/example.ngc",
        blocked: "L4-USER-M-PROCESS",
        requiredRuntime: "linuxcnc_task_hal_tcl_user_m_process",
        requiredNativeProof: "native_runtime_state_probe_required",
        optInEnv: "ENABLE_MILLTURN_USER_M_RUNTIME_PROBE=1",
        gateRows: userMRuntimeProbeGateRows,
      },
    ],
    [
      "L4-TOOL-DB",
      {
        boundaryKind: "tool_database_process",
        target: "axis/db_demo/base.ngc",
        blocked: "L4-TOOL-DB",
        requiredRuntime: "linuxcnc_tooldata_db_process",
        requiredNativeProof: "native_db_process_protocol_probe_required",
        optInEnv: "ENABLE_TOOL_DB_RUNTIME_PROBE=1",
        gateRows: toolDbRuntimeProbeGateRows,
      },
    ],
    [
      "L4-PYTHON-REMAP",
      {
        boundaryKind: "python_runtime",
        target: "axis/remap/stop-lookahead/nc_files",
        blocked: "L4-PYTHON-REMAP",
        requiredRuntime: "linuxcnc_python_remap_runtime",
        requiredNativeProof: "linuxcnc_python_runtime_lifecycle_probe_required",
        optInEnv: "ENABLE_PYTHON_REMAP_RUNTIME_PROBE=1",
        gateRows: pythonRuntimeProbeGateRows,
      },
    ],
  ]);
  const planByClass = new Map(executionPlanRows.map((row) => [row.boundary_class, row]));

  assert.equal(parsedRows.length, expected.size, "host preflight row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    [...expected.keys()],
    "host preflight order drift",
  );

  for (const row of parsedRows) {
    const expectedRow = expected.get(row.boundary_class);
    const plan = planByClass.get(row.boundary_class);
    assert.ok(expectedRow, `${row.boundary_class}: unexpected host preflight row`);
    assert.ok(plan, `${row.boundary_class}: host preflight lacks execution plan`);
    assert.equal(row.boundary_kind, expectedRow.boundaryKind, `${row.boundary_class}: host preflight kind drift`);
    assert.equal(row.target, expectedRow.target, `${row.boundary_class}: host preflight target drift`);
    assert.equal(row.blocked, expectedRow.blocked, `${row.boundary_class}: host preflight blocked drift`);
    assert.equal(row.required_runtime, expectedRow.requiredRuntime, `${row.boundary_class}: host preflight runtime drift`);
    assert.equal(row.required_native_proof, expectedRow.requiredNativeProof, `${row.boundary_class}: host preflight native proof drift`);
    assert.equal(row.opt_in_env, expectedRow.optInEnv, `${row.boundary_class}: host preflight opt-in drift`);
    assert.equal(row.execution_command, plan.execution_command, `${row.boundary_class}: host preflight command drift`);
    assert.equal(row.current_probe_status, plan.current_probe_status, `${row.boundary_class}: host preflight probe status drift`);
    assert.equal(row.runtime_ready, plan.runtime_ready, `${row.boundary_class}: host preflight runtime readiness drift`);
    assert.equal(row.source_proof_ready, plan.source_proof_ready, `${row.boundary_class}: host preflight source readiness drift`);
    assert.equal(row.missing_requirements, plan.missing_requirements, `${row.boundary_class}: host preflight missing requirement drift`);
    assert.notEqual(row.runtime_requirements, "-", `${row.boundary_class}: host preflight lacks runtime requirements`);
    for (const gateRow of expectedRow.gateRows) {
      assert.equal(row.runtime_requirements, gateRow.runtime_requirements, `${row.boundary_class}: host preflight gate requirement drift`);
      assert.equal(row.missing_requirements, gateRow.missing_requirements, `${row.boundary_class}: host preflight gate missing requirement drift`);
      assert.equal(row.runtime_ready, gateRow.runtime_ready, `${row.boundary_class}: host preflight gate runtime readiness drift`);
      assert.equal(row.source_proof_ready, gateRow.source_proof_ready, `${row.boundary_class}: host preflight gate source readiness drift`);
    }
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: host preflight must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: host preflight must not allow promotion`);
    if (row.source_proof_ready !== "1") {
      assert.equal(row.preflight_status, "blocked_missing_source_proof", `${row.boundary_class}: source-blocked preflight drift`);
    } else if (row.runtime_ready === "1") {
      assert.equal(row.missing_requirements, "-", `${row.boundary_class}: ready preflight must not list missing requirements`);
      assert.equal(row.preflight_status, "ready_to_run_opt_in_native_probe", `${row.boundary_class}: ready preflight status drift`);
    } else {
      assert.notEqual(row.missing_requirements, "-", `${row.boundary_class}: blocked preflight lacks missing requirements`);
      assert.equal(row.preflight_status, "blocked_missing_host_runtime", `${row.boundary_class}: blocked preflight status drift`);
    }
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: host preflight note drift`);
  }

  return parsedRows;
}

function runtimeRequirementKind(requirement) {
  if (["python3", "tclsh", "halrun", "halcmd", "linuxcnc", "milltask"].includes(requirement)) {
    return "host_command";
  }
  if (requirement.endsWith(".cc") || requirement.endsWith(".py") || requirement.endsWith(".so")) {
    return "source_or_module";
  }
  return "runtime_input";
}

function runtimeBoundaryHostRequirementSummaryRows(preflightRows) {
  const byRequirement = new Map();

  for (const row of preflightRows) {
    for (const token of splitSummaryList(row.runtime_requirements)) {
      const separator = token.lastIndexOf(":");
      assert.notEqual(separator, -1, `${row.boundary_class}: malformed runtime requirement ${token}`);
      const requirement = token.slice(0, separator);
      const available = token.slice(separator + 1);
      const existing = byRequirement.get(requirement) ?? {
        requirement,
        available,
        requiredBy: [],
        missingFor: [],
        blockedFamilies: [],
        optInEnvs: [],
      };
      assert.equal(existing.available, available, `${requirement}: availability drift across preflight rows`);
      existing.requiredBy.push(row.boundary_class);
      existing.blockedFamilies.push(row.blocked);
      existing.optInEnvs.push(row.opt_in_env);
      if (splitSummaryList(row.missing_requirements).includes(requirement)) {
        existing.missingFor.push(row.boundary_class);
      }
      byRequirement.set(requirement, existing);
    }
  }

  return [...byRequirement.values()]
    .sort((left, right) => {
      const missingCompare = Number(right.missingFor.length > 0) - Number(left.missingFor.length > 0);
      if (missingCompare !== 0) {
        return missingCompare;
      }
      return left.requirement.localeCompare(right.requirement);
    })
    .map((row) => [
      row.requirement,
      runtimeRequirementKind(row.requirement),
      row.available,
      String(uniqueSorted(row.requiredBy).length),
      listValue(uniqueSorted(row.requiredBy)),
      listValue(uniqueSorted(row.missingFor)),
      listValue(uniqueSorted(row.blockedFamilies)),
      listValue(uniqueSorted(row.optInEnvs)),
      flagValue(row.missingFor.length > 0),
      "0",
      "0",
      "host_requirement_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t"));
}

function verifyRuntimeBoundaryHostRequirementSummaryRows(rows, preflightRows) {
  const expectedHeaders = [
    "requirement",
    "requirement_kind",
    "available",
    "required_by_count",
    "required_by",
    "missing_for",
    "blocked_families",
    "opt_in_envs",
    "missing_blocks_runtime",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRequirements = uniqueSorted(
    preflightRows.flatMap((row) =>
      splitSummaryList(row.runtime_requirements).map((token) => token.slice(0, token.lastIndexOf(":"))),
    ),
  );

  verifySamePathSet(
    "runtime_boundary_host_requirement_summary",
    expectedRequirements,
    parsedRows.map((row) => row.requirement).sort(),
  );

  const byRequirement = new Map(parsedRows.map((row) => [row.requirement, row]));
  for (const required of [
    ["linuxcnc", "0", "3", "L4-PYTHON-REMAP,L4-TOOL-DB,L4-USER-M-PROCESS"],
    ["halcmd", "0", "2", "L4-TOOL-DB,L4-USER-M-PROCESS"],
    ["milltask", "0", "1", "L4-TOOL-DB"],
    ["python3", "1", "2", "-"],
    ["tclsh", "1", "1", "-"],
  ]) {
    const [requirement, available, requiredByCount, missingFor] = required;
    const row = byRequirement.get(requirement);
    assert.ok(row, `host requirement summary missing ${requirement}`);
    assert.equal(row.available, available, `${requirement}: availability drift`);
    assert.equal(row.required_by_count, requiredByCount, `${requirement}: required-by count drift`);
    assert.equal(row.missing_for, missingFor, `${requirement}: missing-for drift`);
  }

  for (const row of parsedRows) {
    assert.ok(["host_command", "source_or_module", "runtime_input"].includes(row.requirement_kind), `${row.requirement}: invalid requirement kind`);
    assert.ok(["0", "1"].includes(row.available), `${row.requirement}: invalid availability`);
    assert.ok(/^[1-9][0-9]*$/.test(row.required_by_count), `${row.requirement}: invalid required-by count`);
    assert.notEqual(row.required_by, "-", `${row.requirement}: host requirement lacks required-by classes`);
    assert.notEqual(row.blocked_families, "-", `${row.requirement}: host requirement lacks blocked families`);
    assert.notEqual(row.opt_in_envs, "-", `${row.requirement}: host requirement lacks opt-in envs`);
    assert.equal(row.execution_enabled, "0", `${row.requirement}: host requirement summary must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.requirement}: host requirement summary must not allow promotion`);
    if (row.available === "0") {
      assert.notEqual(row.missing_for, "-", `${row.requirement}: unavailable requirement must list missing families`);
      assert.equal(row.missing_blocks_runtime, "1", `${row.requirement}: unavailable requirement must block runtime`);
    } else {
      assert.equal(row.missing_for, "-", `${row.requirement}: available requirement must not list missing families`);
      assert.equal(row.missing_blocks_runtime, "0", `${row.requirement}: available requirement must not block runtime`);
    }
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.requirement}: host requirement note drift`);
  }

  return parsedRows;
}

function runtimeBoundaryHostUnblockPlanRows({
  requirementSummaryRows,
  preflightRows,
}) {
  const preflightByClass = new Map(preflightRows.map((row) => [row.boundary_class, row]));

  return requirementSummaryRows
    .filter((row) => row.missing_blocks_runtime === "1")
    .map((row) => {
      const affectedClasses = splitSummaryList(row.missing_for);
      const affectedTargets = affectedClasses.map((boundaryClass) =>
        preflightByClass.get(boundaryClass)?.target ?? boundaryClass,
      );
      const affectedCommands = affectedClasses.map((boundaryClass) =>
        preflightByClass.get(boundaryClass)?.execution_command ?? "-",
      );
      const afterAvailableStillMissing = affectedClasses.flatMap((boundaryClass) =>
        splitSummaryList(preflightByClass.get(boundaryClass)?.missing_requirements ?? "-")
          .filter((requirement) => requirement !== row.requirement),
      );
      const unblocksWhenAvailable = afterAvailableStillMissing.length === 0
        ? "runtime_preflight_ready_for_affected_families"
        : "partial_unblock_other_requirements_remain";

      return [
        row.requirement,
        row.requirement_kind,
        row.available,
        row.missing_for,
        listValue(uniqueSorted(affectedTargets)),
        row.opt_in_envs,
        listValue(uniqueSorted(affectedCommands)),
        listValue(uniqueSorted(afterAvailableStillMissing)),
        unblocksWhenAvailable,
        "provide_missing_host_requirement",
        "0",
        "0",
        "host_unblock_plan_summary_only_no_runtime_execution_no_automatic_promotion",
      ].map(tsvValue).join("\t");
    });
}

function verifyRuntimeBoundaryHostUnblockPlanRows({
  rows,
  requirementSummaryRows,
  preflightRows,
}) {
  const expectedHeaders = [
    "requirement",
    "requirement_kind",
    "available",
    "missing_for",
    "affected_targets",
    "opt_in_envs",
    "affected_execution_commands",
    "remaining_missing_after_requirement",
    "unblocks_when_available",
    "next_action",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const blockingRequirements = requirementSummaryRows.filter((row) => row.missing_blocks_runtime === "1");
  const blockingRequirementNames = blockingRequirements.map((row) => row.requirement).sort();
  const summaryByRequirement = new Map(requirementSummaryRows.map((row) => [row.requirement, row]));
  const preflightByClass = new Map(preflightRows.map((row) => [row.boundary_class, row]));

  verifySamePathSet(
    "runtime_boundary_host_unblock_plan",
    blockingRequirementNames,
    parsedRows.map((row) => row.requirement).sort(),
  );

  const expected = new Map([
    ["linuxcnc", { missingFor: "L4-PYTHON-REMAP,L4-TOOL-DB,L4-USER-M-PROCESS", remaining: "halcmd,halrun,milltask" }],
    ["halcmd", { missingFor: "L4-TOOL-DB,L4-USER-M-PROCESS", remaining: "halrun,linuxcnc,milltask" }],
    ["halrun", { missingFor: "L4-USER-M-PROCESS", remaining: "halcmd,linuxcnc" }],
    ["milltask", { missingFor: "L4-TOOL-DB", remaining: "halcmd,linuxcnc" }],
  ]);

  for (const row of parsedRows) {
    const summary = summaryByRequirement.get(row.requirement);
    const expectedRow = expected.get(row.requirement);
    assert.ok(summary, `${row.requirement}: unblock plan lacks requirement summary`);
    assert.ok(expectedRow, `${row.requirement}: unexpected unblock requirement`);
    assert.equal(row.requirement_kind, summary.requirement_kind, `${row.requirement}: unblock kind drift`);
    assert.equal(row.available, "0", `${row.requirement}: unblock plan only covers unavailable requirements`);
    assert.equal(row.missing_for, expectedRow.missingFor, `${row.requirement}: unblock missing-for drift`);
    assert.equal(row.missing_for, summary.missing_for, `${row.requirement}: unblock summary missing-for drift`);
    assert.equal(row.remaining_missing_after_requirement, expectedRow.remaining, `${row.requirement}: unblock remaining requirement drift`);
    assert.notEqual(row.affected_targets, "-", `${row.requirement}: unblock plan lacks affected targets`);
    assert.notEqual(row.opt_in_envs, "-", `${row.requirement}: unblock plan lacks opt-in envs`);
    assert.notEqual(row.affected_execution_commands, "-", `${row.requirement}: unblock plan lacks commands`);
    for (const boundaryClass of splitSummaryList(row.missing_for)) {
      const preflight = preflightByClass.get(boundaryClass);
      assert.ok(preflight, `${row.requirement}: unblock plan lacks preflight for ${boundaryClass}`);
      assert.ok(row.affected_targets.includes(preflight.target), `${row.requirement}: unblock plan missing target ${preflight.target}`);
      assert.ok(row.affected_execution_commands.includes(preflight.execution_command), `${row.requirement}: unblock plan missing command for ${boundaryClass}`);
    }
    assert.equal(row.unblocks_when_available, "partial_unblock_other_requirements_remain", `${row.requirement}: current host should still require other missing runtime commands`);
    assert.equal(row.next_action, "provide_missing_host_requirement", `${row.requirement}: unblock next action drift`);
    assert.equal(row.execution_enabled, "0", `${row.requirement}: unblock plan must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.requirement}: unblock plan must not allow promotion`);
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.requirement}: unblock plan note drift`);
  }

  return parsedRows;
}

function runtimeBoundaryFamilyHostReadinessRows(preflightRows) {
  return preflightRows.map((row) => {
    const availableRequirements = splitSummaryList(row.runtime_requirements)
      .filter((token) => token.endsWith(":1"))
      .map((token) => token.slice(0, token.lastIndexOf(":")));
    const missingRequirements = splitSummaryList(row.missing_requirements);
    const familyHostStatus = missingRequirements.length === 0
      ? "host_ready_to_run_opt_in_probe"
      : "blocked_missing_host_requirements";

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.blocked,
      row.required_runtime,
      String(missingRequirements.length),
      listValue(missingRequirements),
      String(availableRequirements.length),
      listValue(availableRequirements),
      row.opt_in_env,
      row.execution_command,
      row.current_probe_status,
      row.preflight_status,
      familyHostStatus,
      "0",
      "0",
      "family_host_readiness_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryFamilyHostReadinessRows(rows, preflightRows) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "required_runtime",
    "missing_requirement_count",
    "missing_host_requirements",
    "available_requirement_count",
    "available_requirements",
    "opt_in_env",
    "execution_command",
    "current_probe_status",
    "preflight_status",
    "family_host_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const preflightByClass = new Map(preflightRows.map((row) => [row.boundary_class, row]));
  const expected = new Map([
    [
      "L4-USER-M-PROCESS",
      {
        missingCount: "3",
        missing: "halrun,halcmd,linuxcnc",
        available: "tclsh",
      },
    ],
    [
      "L4-TOOL-DB",
      {
        missingCount: "3",
        missing: "linuxcnc,milltask,halcmd",
        available: "python3,axis/db_demo/db_nonran.py,linuxcnc.so,tooldb.py",
      },
    ],
    [
      "L4-PYTHON-REMAP",
      {
        missingCount: "1",
        missing: "linuxcnc",
        available: "python3,src/emc/rs274ngc/interp_python.cc,src/emc/pythonplugin/python_plugin.cc,axis/remap/stop-lookahead/python/remap.py,axis/remap/stop-lookahead/python/toplevel.py",
      },
    ],
  ]);

  assert.equal(parsedRows.length, expected.size, "family host readiness row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    [...expected.keys()],
    "family host readiness order drift",
  );

  for (const row of parsedRows) {
    const preflight = preflightByClass.get(row.boundary_class);
    const expectedRow = expected.get(row.boundary_class);
    assert.ok(preflight, `${row.boundary_class}: family host readiness lacks preflight row`);
    assert.ok(expectedRow, `${row.boundary_class}: unexpected family host readiness row`);
    assert.equal(row.boundary_kind, preflight.boundary_kind, `${row.boundary_class}: family host readiness kind drift`);
    assert.equal(row.target, preflight.target, `${row.boundary_class}: family host readiness target drift`);
    assert.equal(row.blocked, preflight.blocked, `${row.boundary_class}: family host readiness blocked drift`);
    assert.equal(row.required_runtime, preflight.required_runtime, `${row.boundary_class}: family host readiness runtime drift`);
    assert.equal(row.opt_in_env, preflight.opt_in_env, `${row.boundary_class}: family host readiness opt-in drift`);
    assert.equal(row.execution_command, preflight.execution_command, `${row.boundary_class}: family host readiness command drift`);
    assert.equal(row.current_probe_status, preflight.current_probe_status, `${row.boundary_class}: family host readiness probe status drift`);
    assert.equal(row.preflight_status, preflight.preflight_status, `${row.boundary_class}: family host readiness preflight status drift`);
    assert.equal(row.missing_requirement_count, expectedRow.missingCount, `${row.boundary_class}: family host readiness missing count drift`);
    assert.equal(row.missing_host_requirements, expectedRow.missing, `${row.boundary_class}: family host readiness missing requirements drift`);
    assert.equal(row.available_requirements, expectedRow.available, `${row.boundary_class}: family host readiness available requirements drift`);
    assert.equal(row.available_requirement_count, String(splitSummaryList(expectedRow.available).length), `${row.boundary_class}: family host readiness available count drift`);
    assert.equal(row.family_host_status, "blocked_missing_host_requirements", `${row.boundary_class}: family host readiness should remain blocked on this host`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: family host readiness must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: family host readiness must not allow promotion`);
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: family host readiness note drift`);
  }

  return parsedRows;
}

function runtimeBoundaryHostReadinessRollupRows({
  familyHostReadinessRows,
  requirementSummaryRows,
}) {
  const readyFamilies = familyHostReadinessRows.filter((row) =>
    row.family_host_status === "host_ready_to_run_opt_in_probe",
  );
  const blockedFamilies = familyHostReadinessRows.filter((row) =>
    row.family_host_status !== "host_ready_to_run_opt_in_probe",
  );
  const missingHostRequirements = uniqueSorted(
    requirementSummaryRows
      .filter((row) => row.missing_blocks_runtime === "1")
      .map((row) => row.requirement),
  );
  const readyOptInCommands = readyFamilies.map((row) => row.execution_command);
  const blockedOptInCommands = blockedFamilies.map((row) => row.execution_command);
  const hostReadinessStatus = readyFamilies.length === familyHostReadinessRows.length
    ? "host_ready_for_all_opt_in_native_probes"
    : readyFamilies.length > 0
      ? "host_partially_ready_for_opt_in_native_probes"
      : "host_blocked_for_all_opt_in_native_probes";

  return [[
    "blocked_runtime_host_readiness",
    String(familyHostReadinessRows.length),
    String(readyFamilies.length),
    String(blockedFamilies.length),
    listValue(uniqueSorted(blockedFamilies.map((row) => row.boundary_class))),
    listValue(missingHostRequirements),
    String(missingHostRequirements.length),
    String(readyOptInCommands.length),
    listValue(uniqueSorted(readyOptInCommands)),
    listValue(uniqueSorted(blockedOptInCommands)),
    hostReadinessStatus,
    "0",
    "0",
    "host_readiness_rollup_summary_only_no_runtime_execution_no_automatic_promotion",
  ].map(tsvValue).join("\t")];
}

function verifyRuntimeBoundaryHostReadinessRollupRows({
  rows,
  familyHostReadinessRows,
  requirementSummaryRows,
}) {
  const expectedHeaders = [
    "scope",
    "family_count",
    "host_ready_family_count",
    "host_blocked_family_count",
    "blocked_families",
    "missing_host_requirements",
    "missing_host_requirement_count",
    "ready_opt_in_command_count",
    "ready_opt_in_commands",
    "blocked_opt_in_commands",
    "host_readiness_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const row = parsedRows[0];
  const expectedMissingRequirements = uniqueSorted(
    requirementSummaryRows
      .filter((requirement) => requirement.missing_blocks_runtime === "1")
      .map((requirement) => requirement.requirement),
  );

  assert.equal(parsedRows.length, 1, "host readiness rollup row count drift");
  assert.equal(row.scope, "blocked_runtime_host_readiness", "host readiness rollup scope drift");
  assert.equal(row.family_count, String(familyHostReadinessRows.length), "host readiness rollup family count drift");
  assert.equal(row.host_ready_family_count, "0", "host readiness rollup must have no ready families on this host");
  assert.equal(row.host_blocked_family_count, String(familyHostReadinessRows.length), "host readiness rollup blocked family count drift");
  assert.equal(row.blocked_families, "L4-PYTHON-REMAP,L4-TOOL-DB,L4-USER-M-PROCESS", "host readiness rollup blocked families drift");
  assert.equal(row.missing_host_requirements, listValue(expectedMissingRequirements), "host readiness rollup missing requirements drift");
  assert.equal(row.missing_host_requirement_count, String(expectedMissingRequirements.length), "host readiness rollup missing requirement count drift");
  assert.equal(row.ready_opt_in_command_count, "0", "host readiness rollup must not report ready opt-in commands");
  assert.equal(row.ready_opt_in_commands, "-", "host readiness rollup must not list ready opt-in commands");
  assert.notEqual(row.blocked_opt_in_commands, "-", "host readiness rollup must list blocked opt-in commands");
  for (const family of familyHostReadinessRows) {
    assert.ok(row.blocked_opt_in_commands.includes(family.execution_command), `${family.boundary_class}: host readiness rollup missing blocked command`);
  }
  assert.equal(row.host_readiness_status, "host_blocked_for_all_opt_in_native_probes", "host readiness rollup status drift");
  assert.equal(row.execution_enabled, "0", "host readiness rollup must not enable execution");
  assert.equal(row.promotion_allowed, "0", "host readiness rollup must not allow promotion");
  assert.ok(row.notes.includes("no_automatic_promotion"), "host readiness rollup note drift");

  return parsedRows;
}

function runtimeBoundaryOptInProbeDispatchPlanRows({
  familyHostReadinessRows,
  hostReadinessRollupRows,
}) {
  const rollup = hostReadinessRollupRows[0];

  return familyHostReadinessRows.map((row) => {
    const hostReady = row.family_host_status === "host_ready_to_run_opt_in_probe";
    const hostAction = hostReady
      ? "ready_for_manual_opt_in_native_probe"
      : "skip_missing_host_requirements";
    const nextAction = hostReady
      ? `manually_run_opt_in_probe:${row.execution_command}`
      : `provide_missing_host_requirements:${row.missing_host_requirements}`;

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.blocked,
      row.opt_in_env,
      row.execution_command,
      row.family_host_status,
      row.missing_host_requirements,
      rollup?.host_readiness_status ?? "-",
      hostAction,
      flagValue(hostReady),
      "0",
      "0",
      nextAction,
      "opt_in_probe_dispatch_plan_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryOptInProbeDispatchPlanRows({
  rows,
  familyHostReadinessRows,
  hostReadinessRollupRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "opt_in_env",
    "execution_command",
    "family_host_status",
    "missing_host_requirements",
    "host_readiness_status",
    "host_action",
    "dispatch_allowed",
    "execution_enabled",
    "promotion_allowed",
    "next_action",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const familyReadinessByClass = new Map(
    familyHostReadinessRows.map((row) => [row.boundary_class, row]),
  );
  const rollup = hostReadinessRollupRows[0];
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];

  assert.equal(parsedRows.length, expectedClasses.length, "opt-in probe dispatch plan row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    expectedClasses,
    "opt-in probe dispatch plan order drift",
  );
  assert.ok(rollup, "opt-in probe dispatch plan lacks host readiness rollup");

  for (const row of parsedRows) {
    const readiness = familyReadinessByClass.get(row.boundary_class);
    assert.ok(readiness, `${row.boundary_class}: dispatch plan lacks family readiness row`);
    assert.equal(row.boundary_kind, readiness.boundary_kind, `${row.boundary_class}: dispatch kind drift`);
    assert.equal(row.target, readiness.target, `${row.boundary_class}: dispatch target drift`);
    assert.equal(row.blocked, readiness.blocked, `${row.boundary_class}: dispatch blocked drift`);
    assert.equal(row.opt_in_env, readiness.opt_in_env, `${row.boundary_class}: dispatch opt-in drift`);
    assert.equal(row.execution_command, readiness.execution_command, `${row.boundary_class}: dispatch command drift`);
    assert.equal(row.family_host_status, readiness.family_host_status, `${row.boundary_class}: dispatch host status drift`);
    assert.equal(row.missing_host_requirements, readiness.missing_host_requirements, `${row.boundary_class}: dispatch missing requirement drift`);
    assert.equal(row.host_readiness_status, rollup.host_readiness_status, `${row.boundary_class}: dispatch rollup status drift`);
    assert.ok(row.execution_command.includes(row.opt_in_env), `${row.boundary_class}: dispatch command must include opt-in env`);
    assert.equal(row.family_host_status, "blocked_missing_host_requirements", `${row.boundary_class}: current host must remain blocked`);
    assert.notEqual(row.missing_host_requirements, "-", `${row.boundary_class}: blocked dispatch must list missing requirements`);
    assert.equal(row.host_readiness_status, "host_blocked_for_all_opt_in_native_probes", `${row.boundary_class}: dispatch host readiness status drift`);
    assert.equal(row.host_action, "skip_missing_host_requirements", `${row.boundary_class}: current host dispatch action drift`);
    assert.equal(row.dispatch_allowed, "0", `${row.boundary_class}: current host dispatch must not be allowed`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: dispatch plan must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: dispatch plan must not allow promotion`);
    assert.ok(row.next_action.includes(row.missing_host_requirements), `${row.boundary_class}: dispatch next action must name missing requirements`);
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: dispatch plan note drift`);
  }

  return parsedRows;
}

function runtimeBoundaryOptInProbeDispatchRollupRows(dispatchPlanRows) {
  const dispatchAllowedRows = dispatchPlanRows.filter((row) => row.dispatch_allowed === "1");
  const dispatchBlockedRows = dispatchPlanRows.filter((row) => row.dispatch_allowed !== "1");
  const dispatchActions = uniqueSorted(dispatchPlanRows.map((row) => row.host_action));
  const dispatchStatus = dispatchAllowedRows.length === dispatchPlanRows.length
    ? "dispatch_allowed_for_all_opt_in_native_probes"
    : dispatchAllowedRows.length > 0
      ? "dispatch_partially_allowed_for_opt_in_native_probes"
      : "dispatch_blocked_for_all_opt_in_native_probes";

  return [[
    "blocked_runtime_opt_in_probe_dispatch",
    String(dispatchPlanRows.length),
    String(dispatchAllowedRows.length),
    String(dispatchBlockedRows.length),
    listValue(uniqueSorted(dispatchBlockedRows.map((row) => row.boundary_class))),
    listValue(dispatchActions),
    listValue(uniqueSorted(dispatchAllowedRows.map((row) => row.execution_command))),
    listValue(uniqueSorted(dispatchBlockedRows.map((row) => row.execution_command))),
    listValue(uniqueSorted(dispatchBlockedRows.flatMap((row) =>
      splitSummaryList(row.missing_host_requirements),
    ))),
    dispatchStatus,
    "0",
    "0",
    "opt_in_probe_dispatch_rollup_summary_only_no_runtime_execution_no_automatic_promotion",
  ].map(tsvValue).join("\t")];
}

function verifyRuntimeBoundaryOptInProbeDispatchRollupRows({
  rows,
  dispatchPlanRows,
}) {
  const expectedHeaders = [
    "scope",
    "probe_count",
    "dispatch_allowed_count",
    "dispatch_blocked_count",
    "blocked_families",
    "dispatch_actions",
    "dispatch_allowed_commands",
    "dispatch_blocked_commands",
    "missing_host_requirements",
    "dispatch_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const row = parsedRows[0];
  const dispatchBlockedRows = dispatchPlanRows.filter((plan) => plan.dispatch_allowed !== "1");
  const expectedMissingRequirements = uniqueSorted(dispatchBlockedRows.flatMap((plan) =>
    splitSummaryList(plan.missing_host_requirements),
  ));

  assert.equal(parsedRows.length, 1, "opt-in probe dispatch rollup row count drift");
  assert.equal(row.scope, "blocked_runtime_opt_in_probe_dispatch", "opt-in probe dispatch rollup scope drift");
  assert.equal(row.probe_count, String(dispatchPlanRows.length), "opt-in probe dispatch rollup probe count drift");
  assert.equal(row.dispatch_allowed_count, "0", "opt-in probe dispatch rollup must not allow probes on this host");
  assert.equal(row.dispatch_blocked_count, String(dispatchPlanRows.length), "opt-in probe dispatch rollup blocked count drift");
  assert.equal(row.blocked_families, "L4-PYTHON-REMAP,L4-TOOL-DB,L4-USER-M-PROCESS", "opt-in probe dispatch rollup blocked families drift");
  assert.equal(row.dispatch_actions, "skip_missing_host_requirements", "opt-in probe dispatch rollup action drift");
  assert.equal(row.dispatch_allowed_commands, "-", "opt-in probe dispatch rollup must not list allowed commands");
  assert.notEqual(row.dispatch_blocked_commands, "-", "opt-in probe dispatch rollup must list blocked commands");
  for (const plan of dispatchPlanRows) {
    assert.ok(row.dispatch_blocked_commands.includes(plan.execution_command), `${plan.boundary_class}: opt-in probe dispatch rollup missing blocked command`);
  }
  assert.equal(row.missing_host_requirements, listValue(expectedMissingRequirements), "opt-in probe dispatch rollup missing requirement drift");
  assert.equal(row.dispatch_status, "dispatch_blocked_for_all_opt_in_native_probes", "opt-in probe dispatch rollup status drift");
  assert.equal(row.execution_enabled, "0", "opt-in probe dispatch rollup must not enable execution");
  assert.equal(row.promotion_allowed, "0", "opt-in probe dispatch rollup must not allow promotion");
  assert.ok(row.notes.includes("no_automatic_promotion"), "opt-in probe dispatch rollup note drift");

  return parsedRows;
}

function runtimeBoundaryOptInProbeSkipEvidenceContractRows({
  dispatchPlanRows,
  passEvidenceRows,
}) {
  const evidenceByClass = new Map(passEvidenceRows.map((row) => [row.boundary_class, row]));

  return dispatchPlanRows.map((row) => {
    const evidence = evidenceByClass.get(row.boundary_class);
    const skipReason = row.dispatch_allowed === "1" ? "-" : "missing_host_requirements";
    const skipEvidenceStatus = row.dispatch_allowed === "1"
      ? "skip_contract_not_applicable_dispatch_allowed"
      : "skip_valid_until_host_requirements_available";

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.blocked,
      evidence?.runtime_probe ?? "-",
      row.opt_in_env,
      row.execution_command,
      row.host_action,
      skipReason,
      row.missing_host_requirements,
      evidence?.current_probe_status ?? "-",
      evidence?.evidence_required_now ?? "0",
      evidence?.observed_evidence_ready ?? "0",
      evidence?.evidence_status ?? "-",
      skipEvidenceStatus,
      "0",
      "0",
      "opt_in_probe_skip_evidence_contract_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryOptInProbeSkipEvidenceContractRows({
  rows,
  dispatchPlanRows,
  passEvidenceRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "runtime_probe",
    "opt_in_env",
    "execution_command",
    "host_action",
    "skip_reason",
    "missing_host_requirements",
    "current_probe_status",
    "evidence_required_now",
    "observed_evidence_ready",
    "native_evidence_status",
    "skip_evidence_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const dispatchByClass = new Map(dispatchPlanRows.map((row) => [row.boundary_class, row]));
  const evidenceByClass = new Map(passEvidenceRows.map((row) => [row.boundary_class, row]));
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];

  assert.equal(parsedRows.length, expectedClasses.length, "opt-in probe skip evidence contract row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    expectedClasses,
    "opt-in probe skip evidence contract order drift",
  );

  for (const row of parsedRows) {
    const dispatch = dispatchByClass.get(row.boundary_class);
    const evidence = evidenceByClass.get(row.boundary_class);
    assert.ok(dispatch, `${row.boundary_class}: skip evidence contract lacks dispatch row`);
    assert.ok(evidence, `${row.boundary_class}: skip evidence contract lacks pass evidence row`);
    assert.equal(row.boundary_kind, dispatch.boundary_kind, `${row.boundary_class}: skip evidence kind drift`);
    assert.equal(row.target, dispatch.target, `${row.boundary_class}: skip evidence target drift`);
    assert.equal(row.blocked, dispatch.blocked, `${row.boundary_class}: skip evidence blocked drift`);
    assert.equal(row.runtime_probe, evidence.runtime_probe, `${row.boundary_class}: skip evidence runtime probe drift`);
    assert.equal(row.opt_in_env, dispatch.opt_in_env, `${row.boundary_class}: skip evidence opt-in drift`);
    assert.equal(row.execution_command, dispatch.execution_command, `${row.boundary_class}: skip evidence command drift`);
    assert.equal(row.host_action, "skip_missing_host_requirements", `${row.boundary_class}: current host skip action drift`);
    assert.equal(row.host_action, dispatch.host_action, `${row.boundary_class}: skip evidence host action drift`);
    assert.equal(row.skip_reason, "missing_host_requirements", `${row.boundary_class}: skip evidence reason drift`);
    assert.equal(row.missing_host_requirements, dispatch.missing_host_requirements, `${row.boundary_class}: skip evidence missing requirements drift`);
    assert.notEqual(row.missing_host_requirements, "-", `${row.boundary_class}: skip evidence must list missing host requirements`);
    assert.equal(row.current_probe_status, "skipped_missing_host_runtime", `${row.boundary_class}: skip evidence current probe status drift`);
    assert.equal(row.current_probe_status, evidence.current_probe_status, `${row.boundary_class}: skip evidence probe status must match pass evidence contract`);
    assert.equal(row.evidence_required_now, "0", `${row.boundary_class}: skipped probe must not require evidence now`);
    assert.equal(row.evidence_required_now, evidence.evidence_required_now, `${row.boundary_class}: skip evidence required-now drift`);
    assert.equal(row.observed_evidence_ready, "0", `${row.boundary_class}: skipped probe must not report evidence ready`);
    assert.equal(row.observed_evidence_ready, evidence.observed_evidence_ready, `${row.boundary_class}: skip evidence readiness drift`);
    assert.equal(row.native_evidence_status, "pending_until_native_pass", `${row.boundary_class}: skip evidence status drift`);
    assert.equal(row.native_evidence_status, evidence.evidence_status, `${row.boundary_class}: skip evidence native status drift`);
    assert.equal(row.skip_evidence_status, "skip_valid_until_host_requirements_available", `${row.boundary_class}: skip evidence contract status drift`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: skip evidence contract must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: skip evidence contract must not allow promotion`);
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: skip evidence contract note drift`);
  }

  return parsedRows;
}

function runtimeBoundaryOptInProbeSkipEvidenceRollupRows(skipEvidenceContractRows) {
  const skippedRows = skipEvidenceContractRows.filter((row) => row.skip_reason !== "-");
  const evidenceRequiredRows = skipEvidenceContractRows.filter((row) => row.evidence_required_now === "1");
  const evidenceReadyRows = skipEvidenceContractRows.filter((row) => row.observed_evidence_ready === "1");
  const missingHostRequirements = uniqueSorted(skippedRows.flatMap((row) =>
    splitSummaryList(row.missing_host_requirements),
  ));
  const evidenceRollupStatus = evidenceReadyRows.length > 0
    ? "native_pass_evidence_present"
    : "no_native_pass_evidence_accepted_while_host_blocked";

  return [[
    "blocked_runtime_opt_in_probe_skip_evidence",
    String(skipEvidenceContractRows.length),
    String(skippedRows.length),
    String(evidenceRequiredRows.length),
    String(evidenceReadyRows.length),
    listValue(uniqueSorted(skippedRows.map((row) => row.boundary_class))),
    listValue(uniqueSorted(skippedRows.map((row) => row.skip_reason))),
    listValue(missingHostRequirements),
    listValue(uniqueSorted(skipEvidenceContractRows.map((row) => row.current_probe_status))),
    listValue(uniqueSorted(skipEvidenceContractRows.map((row) => row.native_evidence_status))),
    listValue(uniqueSorted(skipEvidenceContractRows.map((row) => row.skip_evidence_status))),
    evidenceRollupStatus,
    "0",
    "0",
    "opt_in_probe_skip_evidence_rollup_summary_only_no_runtime_execution_no_automatic_promotion",
  ].map(tsvValue).join("\t")];
}

function verifyRuntimeBoundaryOptInProbeSkipEvidenceRollupRows({
  rows,
  skipEvidenceContractRows,
}) {
  const expectedHeaders = [
    "scope",
    "probe_count",
    "skip_count",
    "evidence_required_now_count",
    "observed_evidence_ready_count",
    "skipped_families",
    "skip_reasons",
    "missing_host_requirements",
    "current_probe_statuses",
    "native_evidence_statuses",
    "skip_evidence_statuses",
    "evidence_rollup_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const row = parsedRows[0];
  const expectedMissingRequirements = uniqueSorted(skipEvidenceContractRows.flatMap((contract) =>
    splitSummaryList(contract.missing_host_requirements),
  ));

  assert.equal(parsedRows.length, 1, "opt-in probe skip evidence rollup row count drift");
  assert.equal(row.scope, "blocked_runtime_opt_in_probe_skip_evidence", "opt-in probe skip evidence rollup scope drift");
  assert.equal(row.probe_count, String(skipEvidenceContractRows.length), "opt-in probe skip evidence rollup probe count drift");
  assert.equal(row.skip_count, String(skipEvidenceContractRows.length), "opt-in probe skip evidence rollup skip count drift");
  assert.equal(row.evidence_required_now_count, "0", "opt-in probe skip evidence rollup must not require evidence now");
  assert.equal(row.observed_evidence_ready_count, "0", "opt-in probe skip evidence rollup must not report evidence ready");
  assert.equal(row.skipped_families, "L4-PYTHON-REMAP,L4-TOOL-DB,L4-USER-M-PROCESS", "opt-in probe skip evidence rollup family drift");
  assert.equal(row.skip_reasons, "missing_host_requirements", "opt-in probe skip evidence rollup reason drift");
  assert.equal(row.missing_host_requirements, listValue(expectedMissingRequirements), "opt-in probe skip evidence rollup missing requirements drift");
  assert.equal(row.current_probe_statuses, "skipped_missing_host_runtime", "opt-in probe skip evidence rollup probe status drift");
  assert.equal(row.native_evidence_statuses, "pending_until_native_pass", "opt-in probe skip evidence rollup native evidence status drift");
  assert.equal(row.skip_evidence_statuses, "skip_valid_until_host_requirements_available", "opt-in probe skip evidence rollup skip evidence status drift");
  assert.equal(row.evidence_rollup_status, "no_native_pass_evidence_accepted_while_host_blocked", "opt-in probe skip evidence rollup status drift");
  assert.equal(row.execution_enabled, "0", "opt-in probe skip evidence rollup must not enable execution");
  assert.equal(row.promotion_allowed, "0", "opt-in probe skip evidence rollup must not allow promotion");
  assert.ok(row.notes.includes("no_automatic_promotion"), "opt-in probe skip evidence rollup note drift");

  return parsedRows;
}

function runtimeBoundaryNativeEvidenceAcceptanceGateRows({
  skipEvidenceContractRows,
  promotionReadinessRows,
  postNativePassGateRows,
}) {
  const readinessByClass = new Map(promotionReadinessRows.map((row) => [row.boundary_class, row]));
  const postNativeGateByClass = new Map(postNativePassGateRows.map((row) => [row.boundary_class, row]));

  return skipEvidenceContractRows.map((row) => {
    const readiness = readinessByClass.get(row.boundary_class);
    const postNativeGate = postNativeGateByClass.get(row.boundary_class);
    const evidenceGateOpen = row.observed_evidence_ready === "1" &&
      readiness?.native_pass_ready === "1" &&
      readiness?.native_evidence_ready === "1";
    const nativeEvidenceGate = evidenceGateOpen
      ? "native_pass_evidence_accepted"
      : row.skip_reason === "missing_host_requirements"
        ? "blocked_until_host_requirements_available"
        : "blocked_until_native_pass_evidence";

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.blocked,
      row.runtime_probe,
      row.current_probe_status,
      row.native_evidence_status,
      row.evidence_required_now,
      row.observed_evidence_ready,
      row.skip_evidence_status,
      readiness?.promotion_ready ?? "0",
      postNativeGate?.node_gate_status ?? "-",
      postNativeGate?.browser_gate_status ?? "-",
      nativeEvidenceGate,
      flagValue(evidenceGateOpen),
      row.skip_reason === "missing_host_requirements"
        ? `provide_missing_host_requirements:${row.missing_host_requirements}`
        : "run_opt_in_native_runtime_probe_and_collect_evidence",
      "0",
      "0",
      "native_evidence_acceptance_gate_summary_only_no_runtime_execution_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeBoundaryNativeEvidenceAcceptanceGateRows({
  rows,
  skipEvidenceContractRows,
  promotionReadinessRows,
  postNativePassGateRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "blocked",
    "runtime_probe",
    "current_probe_status",
    "native_evidence_status",
    "evidence_required_now",
    "observed_evidence_ready",
    "skip_evidence_status",
    "promotion_ready",
    "node_gate_status",
    "browser_gate_status",
    "native_evidence_gate",
    "evidence_acceptance_allowed",
    "next_action",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const skipByClass = new Map(skipEvidenceContractRows.map((row) => [row.boundary_class, row]));
  const readinessByClass = new Map(promotionReadinessRows.map((row) => [row.boundary_class, row]));
  const postNativeGateByClass = new Map(postNativePassGateRows.map((row) => [row.boundary_class, row]));
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];

  assert.equal(parsedRows.length, expectedClasses.length, "native evidence acceptance gate row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    expectedClasses,
    "native evidence acceptance gate order drift",
  );

  for (const row of parsedRows) {
    const skip = skipByClass.get(row.boundary_class);
    const readiness = readinessByClass.get(row.boundary_class);
    const postNativeGate = postNativeGateByClass.get(row.boundary_class);
    assert.ok(skip, `${row.boundary_class}: native evidence gate lacks skip evidence contract row`);
    assert.ok(readiness, `${row.boundary_class}: native evidence gate lacks promotion readiness row`);
    assert.ok(postNativeGate, `${row.boundary_class}: native evidence gate lacks post-native-pass gate row`);
    assert.equal(row.boundary_kind, skip.boundary_kind, `${row.boundary_class}: native evidence gate kind drift`);
    assert.equal(row.target, skip.target, `${row.boundary_class}: native evidence gate target drift`);
    assert.equal(row.blocked, skip.blocked, `${row.boundary_class}: native evidence gate blocked drift`);
    assert.equal(row.runtime_probe, skip.runtime_probe, `${row.boundary_class}: native evidence gate runtime probe drift`);
    assert.equal(row.current_probe_status, "skipped_missing_host_runtime", `${row.boundary_class}: native evidence gate probe status drift`);
    assert.equal(row.current_probe_status, skip.current_probe_status, `${row.boundary_class}: native evidence gate skip status drift`);
    assert.equal(row.native_evidence_status, "pending_until_native_pass", `${row.boundary_class}: native evidence gate evidence status drift`);
    assert.equal(row.native_evidence_status, skip.native_evidence_status, `${row.boundary_class}: native evidence gate native evidence status drift`);
    assert.equal(row.evidence_required_now, "0", `${row.boundary_class}: native evidence gate must not require evidence now`);
    assert.equal(row.evidence_required_now, skip.evidence_required_now, `${row.boundary_class}: native evidence gate required-now drift`);
    assert.equal(row.observed_evidence_ready, "0", `${row.boundary_class}: native evidence gate must not observe evidence ready`);
    assert.equal(row.observed_evidence_ready, skip.observed_evidence_ready, `${row.boundary_class}: native evidence gate readiness drift`);
    assert.equal(row.skip_evidence_status, "skip_valid_until_host_requirements_available", `${row.boundary_class}: native evidence gate skip status drift`);
    assert.equal(row.promotion_ready, "0", `${row.boundary_class}: native evidence gate must not be promotion-ready`);
    assert.equal(row.promotion_ready, readiness.promotion_ready, `${row.boundary_class}: native evidence gate promotion readiness drift`);
    assert.equal(row.node_gate_status, "blocked_until_native_pass_evidence", `${row.boundary_class}: native evidence gate Node status drift`);
    assert.equal(row.node_gate_status, postNativeGate.node_gate_status, `${row.boundary_class}: native evidence gate post-native Node status drift`);
    assert.equal(row.browser_gate_status, "blocked_until_node_gate_complete", `${row.boundary_class}: native evidence gate browser status drift`);
    assert.equal(row.browser_gate_status, postNativeGate.browser_gate_status, `${row.boundary_class}: native evidence gate post-native browser status drift`);
    assert.equal(row.native_evidence_gate, "blocked_until_host_requirements_available", `${row.boundary_class}: native evidence gate status drift`);
    assert.equal(row.evidence_acceptance_allowed, "0", `${row.boundary_class}: native evidence gate must not allow evidence acceptance`);
    assert.ok(row.next_action.includes(skip.missing_host_requirements), `${row.boundary_class}: native evidence gate next action must name missing requirements`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: native evidence gate must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: native evidence gate must not allow promotion`);
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: native evidence gate note drift`);
  }

  return parsedRows;
}

function verifyBlockedRuntimeOptInGateConsistency({
  recommendationRows,
  executionPlanRows,
  promotionReadinessRows,
  promotionBlockerRows,
  postNativePassGateRows,
  hostPreflightRows,
  familyHostReadinessRows,
  dispatchPlanRows,
  skipEvidenceContractRows,
  evidenceAcceptanceGateRows,
}) {
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];
  const classToKind = new Map([
    ["L4-USER-M-PROCESS", "external_user_m_process"],
    ["L4-TOOL-DB", "tool_database_process"],
    ["L4-PYTHON-REMAP", "python_runtime"],
  ]);
  const classToRecommendation = new Map(
    recommendationRows.map((row) => [row.blocked, row]),
  );
  const byClass = (rows) => new Map(rows.map((row) => [row.boundary_class, row]));
  const executionByClass = byClass(executionPlanRows);
  const readinessByClass = byClass(promotionReadinessRows);
  const blockerByClass = byClass(promotionBlockerRows);
  const postNativeByClass = byClass(postNativePassGateRows);
  const preflightByClass = byClass(hostPreflightRows);
  const familyReadinessByClass = byClass(familyHostReadinessRows);
  const dispatchByClass = byClass(dispatchPlanRows);
  const skipEvidenceByClass = byClass(skipEvidenceContractRows);
  const evidenceGateByClass = byClass(evidenceAcceptanceGateRows);

  for (const rowSet of [
    executionPlanRows,
    promotionReadinessRows,
    promotionBlockerRows,
    postNativePassGateRows,
    hostPreflightRows,
    familyHostReadinessRows,
    dispatchPlanRows,
    skipEvidenceContractRows,
    evidenceAcceptanceGateRows,
  ]) {
    assert.deepEqual(
      rowSet.map((row) => row.boundary_class),
      expectedClasses,
      "blocked runtime opt-in gate class order drift",
    );
  }

  for (const boundaryClass of expectedClasses) {
    const expectedKind = classToKind.get(boundaryClass);
    const recommendation = classToRecommendation.get(boundaryClass);
    const execution = executionByClass.get(boundaryClass);
    const readiness = readinessByClass.get(boundaryClass);
    const blocker = blockerByClass.get(boundaryClass);
    const postNative = postNativeByClass.get(boundaryClass);
    const preflight = preflightByClass.get(boundaryClass);
    const familyReadiness = familyReadinessByClass.get(boundaryClass);
    const dispatch = dispatchByClass.get(boundaryClass);
    const skipEvidence = skipEvidenceByClass.get(boundaryClass);
    const evidenceGate = evidenceGateByClass.get(boundaryClass);

    for (const [label, row] of [
      ["recommendation", recommendation],
      ["execution", execution],
      ["readiness", readiness],
      ["blocker", blocker],
      ["postNative", postNative],
      ["preflight", preflight],
      ["familyReadiness", familyReadiness],
      ["dispatch", dispatch],
      ["skipEvidence", skipEvidence],
      ["evidenceGate", evidenceGate],
    ]) {
      assert.ok(row, `${boundaryClass}: missing ${label} row for opt-in gate consistency`);
    }

    assert.equal(recommendation.boundary_kind, expectedKind, `${boundaryClass}: recommendation kind drift`);

    for (const row of [
      execution,
      readiness,
      blocker,
      postNative,
      preflight,
      familyReadiness,
      dispatch,
      skipEvidence,
      evidenceGate,
    ]) {
      assert.equal(row.boundary_kind, expectedKind, `${boundaryClass}: gate kind drift`);
      assert.equal(row.target, recommendation.target, `${boundaryClass}: gate target drift`);
      assert.equal(row.blocked ?? row.boundary_class, recommendation.blocked, `${boundaryClass}: gate blocked kind drift`);
      assert.equal(row.execution_enabled, "0", `${boundaryClass}: gate must not enable execution`);
      assert.equal(row.promotion_allowed, "0", `${boundaryClass}: gate must not allow promotion`);
    }

    assert.equal(execution.required_native_proof, recommendation.required_native_proof, `${boundaryClass}: native proof drift`);
    assert.equal(postNative.required_node_proof, recommendation.required_node_proof, `${boundaryClass}: Node proof drift`);
    assert.equal(postNative.required_browser_proof, recommendation.required_browser_proof, `${boundaryClass}: browser proof drift`);
    assert.equal(preflight.required_native_proof, execution.required_native_proof, `${boundaryClass}: preflight proof drift`);
    assert.equal(preflight.opt_in_env, execution.opt_in_env, `${boundaryClass}: preflight opt-in drift`);
    assert.equal(dispatch.opt_in_env, execution.opt_in_env, `${boundaryClass}: dispatch opt-in drift`);
    assert.equal(skipEvidence.opt_in_env, execution.opt_in_env, `${boundaryClass}: skip-evidence opt-in drift`);
    assert.equal(preflight.execution_command, execution.execution_command, `${boundaryClass}: preflight command drift`);
    assert.equal(dispatch.execution_command, execution.execution_command, `${boundaryClass}: dispatch command drift`);
    assert.equal(skipEvidence.execution_command, execution.execution_command, `${boundaryClass}: skip-evidence command drift`);
    assert.equal(preflight.current_probe_status, execution.current_probe_status, `${boundaryClass}: preflight probe status drift`);
    assert.equal(readiness.current_probe_status, execution.current_probe_status, `${boundaryClass}: readiness probe status drift`);
    assert.equal(postNative.current_probe_status, execution.current_probe_status, `${boundaryClass}: post-native probe status drift`);
    assert.equal(evidenceGate.current_probe_status, execution.current_probe_status, `${boundaryClass}: evidence gate probe status drift`);
    assert.equal(familyReadiness.current_probe_status, execution.current_probe_status, `${boundaryClass}: family readiness probe status drift`);
    assert.equal(preflight.missing_requirements, execution.missing_requirements, `${boundaryClass}: preflight missing requirements drift`);
    assert.equal(dispatch.missing_host_requirements, execution.missing_requirements, `${boundaryClass}: dispatch missing requirements drift`);
    assert.equal(skipEvidence.missing_host_requirements, execution.missing_requirements, `${boundaryClass}: skip-evidence missing requirements drift`);
    assert.equal(blocker.missing_runtime_requirements, execution.missing_requirements, `${boundaryClass}: blocker missing requirements drift`);
    assert.equal(evidenceGate.evidence_acceptance_allowed, "0", `${boundaryClass}: evidence acceptance must remain blocked`);
    assert.equal(dispatch.dispatch_allowed, "0", `${boundaryClass}: dispatch must remain blocked on this host`);
    assert.equal(readiness.promotion_lock_active, "1", `${boundaryClass}: readiness must keep promotion lock active`);
    assert.equal(postNative.promotion_lock_active, "1", `${boundaryClass}: post-native gate must keep promotion lock active`);
    assert.ok(blocker.blocker_keys.includes("promotion_lock_active"), `${boundaryClass}: blocker lacks promotion lock key`);
    assert.ok(blocker.blocker_keys.includes("manual_lock_update_required"), `${boundaryClass}: blocker lacks manual lock key`);
    assert.ok(blocker.blocker_keys.includes("host_runtime_requirements_missing"), `${boundaryClass}: blocker lacks host runtime key`);
    assert.ok(evidenceGate.native_evidence_gate.includes("blocked"), `${boundaryClass}: evidence gate must be blocked`);
  }
}

function verifyBlockedRuntimeProbeExecutionConsistency({
  executionPlanRows,
  passEvidenceRows,
  hostPreflightRows,
  dispatchPlanRows,
  skipEvidenceContractRows,
}) {
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];
  const byClass = (rows) => new Map(rows.map((row) => [row.boundary_class, row]));
  const passByClass = byClass(passEvidenceRows);
  const preflightByClass = byClass(hostPreflightRows);
  const dispatchByClass = byClass(dispatchPlanRows);
  const skipByClass = byClass(skipEvidenceContractRows);

  for (const rows of [
    executionPlanRows,
    passEvidenceRows,
    hostPreflightRows,
    dispatchPlanRows,
    skipEvidenceContractRows,
  ]) {
    assert.deepEqual(
      rows.map((row) => row.boundary_class),
      expectedClasses,
      "blocked runtime probe execution class order drift",
    );
  }

  for (const execution of executionPlanRows) {
    const pass = passByClass.get(execution.boundary_class);
    const preflight = preflightByClass.get(execution.boundary_class);
    const dispatch = dispatchByClass.get(execution.boundary_class);
    const skip = skipByClass.get(execution.boundary_class);

    assert.ok(pass, `${execution.boundary_class}: missing pass evidence contract row`);
    assert.ok(preflight, `${execution.boundary_class}: missing host preflight row`);
    assert.ok(dispatch, `${execution.boundary_class}: missing dispatch plan row`);
    assert.ok(skip, `${execution.boundary_class}: missing skip evidence contract row`);

    for (const row of [pass, preflight, dispatch, skip]) {
      assert.equal(row.boundary_kind, execution.boundary_kind, `${execution.boundary_class}: probe execution kind drift`);
      assert.equal(row.target, execution.target, `${execution.boundary_class}: probe execution target drift`);
    }
    assert.equal(preflight.blocked, execution.boundary_class, `${execution.boundary_class}: preflight blocked kind drift`);
    assert.equal(dispatch.blocked, execution.boundary_class, `${execution.boundary_class}: dispatch blocked kind drift`);
    assert.equal(skip.blocked, execution.boundary_class, `${execution.boundary_class}: skip evidence blocked kind drift`);

    assert.equal(pass.runtime_probe, execution.runtime_probe, `${execution.boundary_class}: pass evidence runtime probe drift`);
    assert.equal(skip.runtime_probe, execution.runtime_probe, `${execution.boundary_class}: skip evidence runtime probe drift`);
    assert.equal(pass.expected_pass_status, execution.expected_pass_status, `${execution.boundary_class}: expected pass status drift`);
    assert.equal(preflight.required_native_proof, execution.required_native_proof, `${execution.boundary_class}: required native proof drift`);
    assert.equal(preflight.opt_in_env, execution.opt_in_env, `${execution.boundary_class}: preflight opt-in env drift`);
    assert.equal(dispatch.opt_in_env, execution.opt_in_env, `${execution.boundary_class}: dispatch opt-in env drift`);
    assert.equal(skip.opt_in_env, execution.opt_in_env, `${execution.boundary_class}: skip evidence opt-in env drift`);
    assert.equal(preflight.execution_command, execution.execution_command, `${execution.boundary_class}: preflight execution command drift`);
    assert.equal(dispatch.execution_command, execution.execution_command, `${execution.boundary_class}: dispatch execution command drift`);
    assert.equal(skip.execution_command, execution.execution_command, `${execution.boundary_class}: skip evidence execution command drift`);
    assert.equal(pass.current_probe_status, execution.current_probe_status, `${execution.boundary_class}: pass evidence probe status drift`);
    assert.equal(preflight.current_probe_status, execution.current_probe_status, `${execution.boundary_class}: preflight probe status drift`);
    assert.equal(skip.current_probe_status, execution.current_probe_status, `${execution.boundary_class}: skip evidence probe status drift`);
    assert.equal(preflight.runtime_ready, execution.runtime_ready, `${execution.boundary_class}: preflight runtime readiness drift`);
    assert.equal(preflight.source_proof_ready, execution.source_proof_ready, `${execution.boundary_class}: preflight source proof readiness drift`);
    assert.equal(preflight.missing_requirements, execution.missing_requirements, `${execution.boundary_class}: preflight missing requirement drift`);
    assert.equal(dispatch.missing_host_requirements, execution.missing_requirements, `${execution.boundary_class}: dispatch missing requirement drift`);
    assert.equal(skip.missing_host_requirements, execution.missing_requirements, `${execution.boundary_class}: skip evidence missing requirement drift`);

    assert.equal(execution.runtime_ready, "0", `${execution.boundary_class}: current host must not be runtime-ready`);
    assert.equal(execution.source_proof_ready, "1", `${execution.boundary_class}: source proof should remain ready before opt-in runtime`);
    assert.equal(execution.current_probe_status, "skipped_missing_host_runtime", `${execution.boundary_class}: probe should remain skipped on this host`);
    assert.equal(execution.plan_status, "blocked_missing_host_runtime", `${execution.boundary_class}: execution plan must remain host-blocked`);
    assert.equal(preflight.preflight_status, "blocked_missing_host_runtime", `${execution.boundary_class}: preflight must remain host-blocked`);
    assert.equal(dispatch.host_readiness_status, "host_blocked_for_all_opt_in_native_probes", `${execution.boundary_class}: dispatch host readiness drift`);
    assert.equal(dispatch.host_action, "skip_missing_host_requirements", `${execution.boundary_class}: dispatch action must skip`);
    assert.equal(dispatch.dispatch_allowed, "0", `${execution.boundary_class}: dispatch must not be allowed`);
    assert.equal(skip.host_action, "skip_missing_host_requirements", `${execution.boundary_class}: skip evidence host action drift`);
    assert.equal(skip.skip_reason, "missing_host_requirements", `${execution.boundary_class}: skip reason drift`);
    assert.equal(pass.evidence_required_now, "0", `${execution.boundary_class}: pass evidence must not be required yet`);
    assert.equal(skip.evidence_required_now, "0", `${execution.boundary_class}: skip evidence must not be required yet`);
    assert.equal(pass.observed_evidence_ready, "0", `${execution.boundary_class}: pass evidence must not be ready yet`);
    assert.equal(skip.observed_evidence_ready, "0", `${execution.boundary_class}: skip evidence must not be ready yet`);
    assert.equal(pass.evidence_status, "pending_until_native_pass", `${execution.boundary_class}: pass evidence status drift`);
    assert.equal(skip.native_evidence_status, "pending_until_native_pass", `${execution.boundary_class}: skip evidence native status drift`);
    assert.equal(skip.skip_evidence_status, "skip_valid_until_host_requirements_available", `${execution.boundary_class}: skip evidence contract status drift`);

    for (const row of [execution, pass, preflight, dispatch, skip]) {
      assert.equal(row.execution_enabled, "0", `${execution.boundary_class}: probe execution row must not enable execution`);
      assert.equal(row.promotion_allowed, "0", `${execution.boundary_class}: probe execution row must not allow promotion`);
    }
  }

  return true;
}

function verifyBlockedRuntimeRollupConsistency({
  hostReadinessRollupRows,
  dispatchRollupRows,
  skipEvidenceRollupRows,
  familyHostReadinessRows,
  dispatchPlanRows,
  skipEvidenceContractRows,
}) {
  assert.equal(hostReadinessRollupRows.length, 1, "blocked runtime rollup consistency requires one host readiness rollup row");
  assert.equal(dispatchRollupRows.length, 1, "blocked runtime rollup consistency requires one dispatch rollup row");
  assert.equal(skipEvidenceRollupRows.length, 1, "blocked runtime rollup consistency requires one skip evidence rollup row");

  const host = hostReadinessRollupRows[0];
  const dispatch = dispatchRollupRows[0];
  const skipEvidence = skipEvidenceRollupRows[0];

  assert.equal(host.family_count, String(familyHostReadinessRows.length), "blocked runtime rollup family count drift");
  assert.equal(dispatch.probe_count, String(dispatchPlanRows.length), "blocked runtime rollup dispatch probe count drift");
  assert.equal(skipEvidence.probe_count, String(skipEvidenceContractRows.length), "blocked runtime rollup skip evidence probe count drift");
  assert.equal(host.family_count, dispatch.probe_count, "blocked runtime rollup host/dispatch count drift");
  assert.equal(dispatch.probe_count, skipEvidence.probe_count, "blocked runtime rollup dispatch/skip count drift");
  assert.equal(host.host_ready_family_count, dispatch.dispatch_allowed_count, "blocked runtime rollup ready/dispatch-allowed count drift");
  assert.equal(host.host_blocked_family_count, dispatch.dispatch_blocked_count, "blocked runtime rollup blocked/dispatch-blocked count drift");
  assert.equal(dispatch.dispatch_blocked_count, skipEvidence.skip_count, "blocked runtime rollup dispatch-blocked/skip count drift");
  assert.equal(skipEvidence.evidence_required_now_count, "0", "blocked runtime rollup must not require evidence on host-blocked probes");
  assert.equal(skipEvidence.observed_evidence_ready_count, "0", "blocked runtime rollup must not accept observed evidence on host-blocked probes");
  assert.equal(host.blocked_families, dispatch.blocked_families, "blocked runtime rollup blocked family drift");
  assert.equal(dispatch.blocked_families, skipEvidence.skipped_families, "blocked runtime rollup skipped family drift");
  assert.equal(host.missing_host_requirements, dispatch.missing_host_requirements, "blocked runtime rollup host/dispatch missing requirement drift");
  assert.equal(dispatch.missing_host_requirements, skipEvidence.missing_host_requirements, "blocked runtime rollup dispatch/skip missing requirement drift");
  assert.equal(host.ready_opt_in_commands, dispatch.dispatch_allowed_commands, "blocked runtime rollup allowed command drift");
  assert.equal(host.blocked_opt_in_commands, dispatch.dispatch_blocked_commands, "blocked runtime rollup blocked command drift");
  assert.equal(host.host_readiness_status, "host_blocked_for_all_opt_in_native_probes", "blocked runtime rollup host status drift");
  assert.equal(dispatch.dispatch_status, "dispatch_blocked_for_all_opt_in_native_probes", "blocked runtime rollup dispatch status drift");
  assert.equal(skipEvidence.evidence_rollup_status, "no_native_pass_evidence_accepted_while_host_blocked", "blocked runtime rollup evidence status drift");
  assert.equal(skipEvidence.current_probe_statuses, "skipped_missing_host_runtime", "blocked runtime rollup probe status drift");
  assert.equal(skipEvidence.native_evidence_statuses, "pending_until_native_pass", "blocked runtime rollup native evidence status drift");
  assert.equal(skipEvidence.skip_evidence_statuses, "skip_valid_until_host_requirements_available", "blocked runtime rollup skip evidence status drift");

  for (const [label, row] of [
    ["host readiness", host],
    ["dispatch", dispatch],
    ["skip evidence", skipEvidence],
  ]) {
    assert.equal(row.execution_enabled, "0", `blocked runtime ${label} rollup must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `blocked runtime ${label} rollup must not allow promotion`);
    assert.ok(row.notes.includes("no_automatic_promotion"), `blocked runtime ${label} rollup note drift`);
  }

  return true;
}

function verifyBlockedRuntimeHostRequirementConsistency({
  requirementSummaryRows,
  unblockPlanRows,
  familyHostReadinessRows,
}) {
  const requirementByName = new Map(
    requirementSummaryRows.map((row) => [row.requirement, row]),
  );
  const unblockByRequirement = new Map(
    unblockPlanRows.map((row) => [row.requirement, row]),
  );
  const familyByClass = new Map(
    familyHostReadinessRows.map((row) => [row.boundary_class, row]),
  );
  const blockingRequirements = requirementSummaryRows.filter((row) =>
    row.missing_blocks_runtime === "1",
  );

  assert.deepEqual(
    blockingRequirements.map((row) => row.requirement).sort(),
    unblockPlanRows.map((row) => row.requirement).sort(),
    "blocked runtime host requirement/unblock requirement drift",
  );

  for (const family of familyHostReadinessRows) {
    const expectedMissing = uniqueSorted(
      requirementSummaryRows
        .filter((row) => splitSummaryList(row.missing_for).includes(family.boundary_class))
        .map((row) => row.requirement),
    );
    const expectedAvailable = uniqueSorted(
      requirementSummaryRows
        .filter((row) =>
          row.available === "1" &&
            splitSummaryList(row.required_by).includes(family.boundary_class),
        )
        .map((row) => row.requirement),
    );

    assert.deepEqual(
      uniqueSorted(splitSummaryList(family.missing_host_requirements)),
      expectedMissing,
      `${family.boundary_class}: family missing requirements drift from requirement summary`,
    );
    assert.equal(
      family.missing_requirement_count,
      String(expectedMissing.length),
      `${family.boundary_class}: family missing requirement count drift from requirement summary`,
    );
    assert.deepEqual(
      uniqueSorted(splitSummaryList(family.available_requirements)),
      expectedAvailable,
      `${family.boundary_class}: family available requirements drift from requirement summary`,
    );
    assert.equal(
      family.available_requirement_count,
      String(expectedAvailable.length),
      `${family.boundary_class}: family available requirement count drift from requirement summary`,
    );
    assert.equal(family.execution_enabled, "0", `${family.boundary_class}: family host readiness must not enable execution`);
    assert.equal(family.promotion_allowed, "0", `${family.boundary_class}: family host readiness must not allow promotion`);
  }

  for (const requirement of blockingRequirements) {
    const unblock = unblockByRequirement.get(requirement.requirement);
    assert.ok(unblock, `${requirement.requirement}: missing unblock plan row`);
    assert.equal(unblock.requirement_kind, requirement.requirement_kind, `${requirement.requirement}: unblock kind drift`);
    assert.equal(unblock.available, "0", `${requirement.requirement}: unblock plan must only cover unavailable requirements`);
    assert.equal(unblock.missing_for, requirement.missing_for, `${requirement.requirement}: unblock missing-for drift`);
    assert.equal(unblock.opt_in_envs, requirement.opt_in_envs, `${requirement.requirement}: unblock opt-in env drift`);

    const affectedClasses = splitSummaryList(requirement.missing_for);
    const expectedTargets = uniqueSorted(affectedClasses.map((boundaryClass) =>
      familyByClass.get(boundaryClass)?.target ?? boundaryClass,
    ));
    const expectedCommands = uniqueSorted(affectedClasses.map((boundaryClass) =>
      familyByClass.get(boundaryClass)?.execution_command ?? "-",
    ));
    const expectedRemaining = uniqueSorted(affectedClasses.flatMap((boundaryClass) =>
      splitSummaryList(familyByClass.get(boundaryClass)?.missing_host_requirements ?? "-")
        .filter((missingRequirement) => missingRequirement !== requirement.requirement),
    ));

    assert.equal(unblock.affected_targets, listValue(expectedTargets), `${requirement.requirement}: unblock affected target drift`);
    assert.equal(unblock.affected_execution_commands, listValue(expectedCommands), `${requirement.requirement}: unblock affected command drift`);
    assert.equal(unblock.remaining_missing_after_requirement, listValue(expectedRemaining), `${requirement.requirement}: unblock remaining requirement drift`);
    assert.equal(unblock.unblocks_when_available, "partial_unblock_other_requirements_remain", `${requirement.requirement}: unblock readiness status drift`);
    assert.equal(unblock.next_action, "provide_missing_host_requirement", `${requirement.requirement}: unblock next action drift`);
    assert.equal(unblock.execution_enabled, "0", `${requirement.requirement}: unblock plan must not enable execution`);
    assert.equal(unblock.promotion_allowed, "0", `${requirement.requirement}: unblock plan must not allow promotion`);
  }

  for (const row of requirementSummaryRows) {
    assert.equal(row.execution_enabled, "0", `${row.requirement}: host requirement summary must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.requirement}: host requirement summary must not allow promotion`);
  }

  return true;
}

function verifyBlockedRuntimePromotionGateConsistency({
  promotionLockRows,
  promotionReadinessRows,
  promotionBlockerRows,
  postNativePassGateRows,
  nativeEvidenceAcceptanceGateRows,
  passEvidenceRows,
}) {
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];
  const lockByTarget = new Map(
    promotionLockRows.map((row) => [row.target, row]),
  );
  const readinessByClass = new Map(
    promotionReadinessRows.map((row) => [row.boundary_class, row]),
  );
  const blockerByClass = new Map(
    promotionBlockerRows.map((row) => [row.boundary_class, row]),
  );
  const postNativeByClass = new Map(
    postNativePassGateRows.map((row) => [row.boundary_class, row]),
  );
  const evidenceGateByClass = new Map(
    nativeEvidenceAcceptanceGateRows.map((row) => [row.boundary_class, row]),
  );
  const passEvidenceByClass = new Map(
    passEvidenceRows.map((row) => [row.boundary_class, row]),
  );

  for (const rows of [
    promotionReadinessRows,
    promotionBlockerRows,
    postNativePassGateRows,
    nativeEvidenceAcceptanceGateRows,
    passEvidenceRows,
  ]) {
    assert.deepEqual(
      rows.map((row) => row.boundary_class),
      expectedClasses,
      "blocked runtime promotion gate class order drift",
    );
  }

  for (const boundaryClass of expectedClasses) {
    const readiness = readinessByClass.get(boundaryClass);
    const blocker = blockerByClass.get(boundaryClass);
    const postNative = postNativeByClass.get(boundaryClass);
    const evidenceGate = evidenceGateByClass.get(boundaryClass);
    const passEvidence = passEvidenceByClass.get(boundaryClass);
    assert.ok(readiness, `${boundaryClass}: missing promotion readiness row`);
    assert.ok(blocker, `${boundaryClass}: missing promotion blocker row`);
    assert.ok(postNative, `${boundaryClass}: missing post-native-pass gate row`);
    assert.ok(evidenceGate, `${boundaryClass}: missing native evidence acceptance row`);
    assert.ok(passEvidence, `${boundaryClass}: missing pass evidence contract row`);

    const lock = lockByTarget.get(readiness.target);
    assert.ok(lock, `${boundaryClass}: missing promotion lock row for ${readiness.target}`);

    for (const row of [blocker, postNative, evidenceGate, passEvidence]) {
      assert.equal(row.boundary_kind, readiness.boundary_kind, `${boundaryClass}: promotion gate kind drift`);
      assert.equal(row.target, readiness.target, `${boundaryClass}: promotion gate target drift`);
    }
    for (const row of [blocker, postNative, evidenceGate]) {
      assert.equal(row.blocked, readiness.blocked, `${boundaryClass}: promotion gate blocked kind drift`);
    }

    assert.equal(readiness.current_probe_status, passEvidence.current_probe_status, `${boundaryClass}: readiness/pass probe status drift`);
    assert.equal(readiness.expected_pass_status, passEvidence.expected_pass_status, `${boundaryClass}: readiness/pass expected status drift`);
    assert.equal(readiness.native_evidence_status, passEvidence.evidence_status, `${boundaryClass}: readiness/pass evidence status drift`);
    assert.equal(readiness.native_evidence_ready, passEvidence.observed_evidence_ready, `${boundaryClass}: readiness/pass observed evidence drift`);
    assert.equal(readiness.promotion_lock_active, lock.lock_active, `${boundaryClass}: readiness/lock active drift`);
    assert.equal(readiness.promotion_ready, blocker.promotion_ready, `${boundaryClass}: readiness/blocker promotion flag drift`);
    assert.equal(readiness.promotion_ready, evidenceGate.promotion_ready, `${boundaryClass}: readiness/evidence promotion flag drift`);

    assert.equal(postNative.current_probe_status, readiness.current_probe_status, `${boundaryClass}: post-native probe status drift`);
    assert.equal(postNative.expected_pass_status, readiness.expected_pass_status, `${boundaryClass}: post-native expected status drift`);
    assert.equal(postNative.native_pass_ready, readiness.native_pass_ready, `${boundaryClass}: post-native native pass drift`);
    assert.equal(postNative.native_evidence_ready, readiness.native_evidence_ready, `${boundaryClass}: post-native native evidence drift`);
    assert.equal(postNative.manual_lock_update_required, readiness.manual_lock_update_required, `${boundaryClass}: post-native manual lock drift`);
    assert.equal(postNative.promotion_lock_active, readiness.promotion_lock_active, `${boundaryClass}: post-native promotion lock drift`);

    assert.equal(evidenceGate.current_probe_status, readiness.current_probe_status, `${boundaryClass}: evidence gate probe status drift`);
    assert.equal(evidenceGate.native_evidence_status, readiness.native_evidence_status, `${boundaryClass}: evidence gate status drift`);
    assert.equal(evidenceGate.evidence_required_now, passEvidence.evidence_required_now, `${boundaryClass}: evidence gate required-now drift`);
    assert.equal(evidenceGate.observed_evidence_ready, passEvidence.observed_evidence_ready, `${boundaryClass}: evidence gate observed evidence drift`);
    assert.equal(evidenceGate.node_gate_status, postNative.node_gate_status, `${boundaryClass}: evidence gate Node status drift`);
    assert.equal(evidenceGate.browser_gate_status, postNative.browser_gate_status, `${boundaryClass}: evidence gate browser status drift`);

    assert.equal(readiness.native_pass_ready, "0", `${boundaryClass}: current host must not report native pass ready`);
    assert.equal(readiness.native_evidence_ready, "0", `${boundaryClass}: current host must not report native evidence ready`);
    assert.equal(readiness.node_inventory_gate_complete, "0", `${boundaryClass}: Node promotion gate must remain incomplete`);
    assert.equal(readiness.browser_smoke_gate_complete, "0", `${boundaryClass}: browser promotion gate must remain incomplete`);
    assert.equal(readiness.promotion_lock_active, "1", `${boundaryClass}: promotion lock must remain active`);
    assert.equal(readiness.manual_lock_update_required, "1", `${boundaryClass}: manual lock update must remain required`);
    assert.equal(readiness.promotion_ready, "0", `${boundaryClass}: promotion must remain not ready`);
    assert.ok(blocker.blocker_keys.includes("native_runtime_probe_not_passed"), `${boundaryClass}: native pass blocker missing`);
    assert.ok(blocker.blocker_keys.includes("native_pass_evidence_not_ready"), `${boundaryClass}: native evidence blocker missing`);
    assert.ok(blocker.blocker_keys.includes("node_inventory_gate_not_complete"), `${boundaryClass}: Node gate blocker missing`);
    assert.ok(blocker.blocker_keys.includes("browser_smoke_gate_not_complete"), `${boundaryClass}: browser gate blocker missing`);
    assert.ok(blocker.blocker_keys.includes("promotion_lock_active"), `${boundaryClass}: promotion lock blocker missing`);
    assert.ok(blocker.blocker_keys.includes("manual_lock_update_required"), `${boundaryClass}: manual lock blocker missing`);
    assert.equal(postNative.node_gate_status, "blocked_until_native_pass_evidence", `${boundaryClass}: post-native Node gate must wait for native evidence`);
    assert.equal(postNative.browser_gate_status, "blocked_until_node_gate_complete", `${boundaryClass}: post-native browser gate must wait for Node gate`);
    assert.equal(postNative.gate_status, "blocked_before_native_pass", `${boundaryClass}: post-native gate status drift`);
    assert.equal(evidenceGate.native_evidence_gate, "blocked_until_host_requirements_available", `${boundaryClass}: native evidence gate must remain host-blocked`);
    assert.equal(evidenceGate.evidence_acceptance_allowed, "0", `${boundaryClass}: native evidence acceptance must remain blocked`);

    for (const row of [readiness, blocker, postNative, evidenceGate, passEvidence, lock]) {
      assert.equal(row.execution_enabled, "0", `${boundaryClass}: promotion consistency row must not enable execution`);
      assert.equal(row.promotion_allowed, "0", `${boundaryClass}: promotion consistency row must not allow promotion`);
    }
  }

  return true;
}

function verifyGeneratedArtifactDocumentationCoverage({
  artifactPaths,
  documentationPaths,
}) {
  const artifactNames = [...new Set(artifactPaths.map((artifactPath) => basename(artifactPath)))].sort();
  assert.equal(
    artifactNames.length,
    artifactPaths.length,
    "generated sim-config inventory artifact list contains duplicate paths",
  );
  assert.equal(
    artifactNames.length,
    54,
    "generated sim-config inventory artifact list count drift",
  );
  assert.deepEqual(
    artifactNames,
    [
      "blocked-dependency-summary.tsv",
      "blocked-runtime-promotion-lock.tsv",
      "boundary-phase-completion-summary.tsv",
      "boundary-proof-gates.tsv",
      "boundary-summary.tsv",
      "full-process-boundary-summary.tsv",
      "ini-boundary-summary.tsv",
      "native-proof-alignment-summary.tsv",
      "native-runtime-probe-execution-plan.tsv",
      "native-runtime-probe-pass-evidence-contract.tsv",
      "native-runtime-probe-summary.tsv",
      "next-boundary-recommendations.tsv",
      "next-boundary-worklist.tsv",
      "python-remap-boundary-summary.tsv",
      "python-remap-family-summary.tsv",
      "python-remap-native-runtime-alignment.tsv",
      "python-remap-native-runtime-fixture-plan.tsv",
      "python-remap-native-runtime-probe-gate.tsv",
      "python-remap-native-runtime-readiness.tsv",
      "python-remap-native-runtime-state-plan.tsv",
      "python-remap-runtime-contract.tsv",
      "python-remap-runtime-gates.tsv",
      "runtime-boundary-contract-summary.tsv",
      "runtime-boundary-family-host-readiness.tsv",
      "runtime-boundary-host-preflight.tsv",
      "runtime-boundary-host-readiness-rollup.tsv",
      "runtime-boundary-host-requirement-summary.tsv",
      "runtime-boundary-host-unblock-plan.tsv",
      "runtime-boundary-native-alignment-summary.tsv",
      "runtime-boundary-native-evidence-acceptance-gate.tsv",
      "runtime-boundary-opt-in-probe-dispatch-plan.tsv",
      "runtime-boundary-opt-in-probe-dispatch-rollup.tsv",
      "runtime-boundary-opt-in-probe-skip-evidence-contract.tsv",
      "runtime-boundary-opt-in-probe-skip-evidence-rollup.tsv",
      "runtime-boundary-post-native-pass-gates.tsv",
      "runtime-boundary-promotion-blockers.tsv",
      "runtime-boundary-promotion-readiness.tsv",
      "runtime-probe-gate-alignment.tsv",
      "skip-summary.tsv",
      "summary.tsv",
      "tool-db-process-boundary-summary.tsv",
      "tool-db-process-native-protocol-alignment.tsv",
      "tool-db-process-native-runtime-probe-gate.tsv",
      "tool-db-process-native-runtime-readiness.tsv",
      "tool-db-process-protocol-gates.tsv",
      "tool-db-process-transaction-plan.tsv",
      "user-m-process-boundary-summary.tsv",
      "user-m-process-native-runtime-probe-gate.tsv",
      "user-m-process-native-runtime-readiness.tsv",
      "user-m-process-native-runtime-state-plan.tsv",
      "user-m-process-native-state-alignment.tsv",
      "user-m-process-native-transition-alignment.tsv",
      "user-m-process-state-targets.tsv",
      "user-m-process-transition-plan.tsv",
    ],
    "generated sim-config inventory artifact list drift",
  );
  for (const artifactPath of artifactPaths) {
    assert.ok(existsSync(artifactPath), `${basename(artifactPath)}: generated sim-config inventory artifact missing`);
    const artifactText = readFileSync(artifactPath, "utf8");
    assert.ok(
      artifactText.includes("\t") && artifactText.trim().split("\n")[0].length > 0,
      `${basename(artifactPath)}: generated sim-config inventory artifact lacks TSV header`,
    );
  }

  const documentationText = documentationPaths
    .map((documentationPath) => readFileSync(documentationPath, "utf8"))
    .join("\n");
  const missingArtifactNames = artifactNames.filter((artifactName) =>
    !documentationText.includes(artifactName),
  );

  assert.deepEqual(
    missingArtifactNames,
    [],
    "generated sim-config inventory artifacts must be documented",
  );
  const browserSmokeText = readFileSync(browserInterpSmokePath, "utf8");
  const missingBrowserArtifactNames = artifactNames.filter((artifactName) =>
    !browserSmokeText.includes(artifactName),
  );
  assert.deepEqual(
    missingBrowserArtifactNames,
    [],
    "generated sim-config inventory artifacts must be listed in browser smoke",
  );
  assert.ok(
    browserSmokeText.includes("wasmArtifactNames.length !== 54"),
    "browser smoke must keep generated WASM artifact fixed-count guard",
  );
  assert.ok(
    browserSmokeText.includes("new Set(wasmArtifactNames).size !== wasmArtifactNames.length"),
    "browser smoke must keep generated WASM artifact duplicate-free guard",
  );
  assert.ok(
    browserSmokeText.includes("browser_generated_artifact_fetchability"),
    "browser smoke must keep generated WASM artifact fetchability guard",
  );
  assert.ok(
    browserSmokeText.includes("await fetchText(`../../build/wasm/sim-configs-inventory/${artifactName}`)"),
    "browser smoke must fetch each generated WASM artifact by artifact name",
  );
  assert.ok(
    browserSmokeText.includes("browser_generated_artifact_documentation_coverage: missing"),
    "browser smoke must keep generated WASM artifact documentation coverage guard",
  );
  assert.ok(
    browserSmokeText.includes(
      "for (const artifactName of wasmArtifactNames) {\n        if (!documentationText.includes(artifactName)) {",
    ),
    "browser smoke must check generated WASM artifact documentation coverage from joined documentation text",
  );
  for (const documentationToken of [
    "../../docs/compatibility-validation.md",
    "../../docs/sim-configs-coverage-matrix.md",
    "../../docs/full-process-boundary-design.md",
  ]) {
    assert.ok(
      browserSmokeText.includes(documentationToken),
      `browser smoke must fetch ${documentationToken} for artifact documentation coverage`,
    );
  }
  assert.ok(
    browserSmokeText.includes("const documentationText = ["),
    "browser smoke must collect fetched review docs for artifact documentation coverage",
  );
  assert.ok(
    browserSmokeText.includes(
      'const documentationText = [\n        await fetchText("../../docs/compatibility-validation.md"),\n        await fetchText("../../docs/sim-configs-coverage-matrix.md"),\n        await fetchText("../../docs/full-process-boundary-design.md"),\n      ].join("\\n");',
    ),
    "browser smoke must fetch and join the exact artifact documentation review source set",
  );
  assert.ok(
    browserSmokeText.includes("await verifyBrowserGeneratedArtifactDocumentationCoverage();"),
    "browser smoke must execute generated artifact documentation coverage helper",
  );
  assert.ok(
    browserSmokeText.includes('].join("\\n");'),
    "browser smoke must join fetched review docs before artifact documentation coverage checks",
  );
  assert.ok(
    browserSmokeText.includes('"wasm_inventory_artifact_documentation_coverage",\n            generatedArtifactDocumentationCoverage.wasmArtifactNames.length'),
    "browser smoke must keep generated WASM artifact completion count parity guard",
  );
  assert.ok(
    browserSmokeText.includes("verifyBrowserBoundaryPhaseCompletionCountParity(\n        boundaryPhaseCompletionRows,"),
    "browser smoke must call boundary phase completion count parity with generated completion rows",
  );
  assert.ok(
    browserSmokeText.includes(
      '[\n            "wasm_inventory_artifact_documentation_coverage",\n            generatedArtifactDocumentationCoverage.wasmArtifactNames.length,\n          ],\n          [\n            "native_artifact_documentation_coverage",\n            generatedArtifactDocumentationCoverage.nativeArtifactTokens.length,\n          ],',
    ),
    "browser smoke must bind artifact documentation completion counts to returned artifact arrays",
  );
  assert.ok(
    browserSmokeText.includes("verifyBrowserNextBoundaryRecommendationSourceArtifactCoverage({\n        recommendationRows: nextBoundaryRecommendationRows,\n        wasmArtifactNames: generatedArtifactDocumentationCoverage.wasmArtifactNames,"),
    "browser smoke must use generated artifact coverage names for recommendation source artifact coverage",
  );
  assert.ok(
    browserSmokeText.includes('row.evidence === "-" || row.evidence.length < 12'),
    "browser smoke must keep completion evidence reviewability guard",
  );
  assert.ok(
    browserSmokeText.includes("completion evidence is not reviewable"),
    "browser smoke must keep completion evidence reviewability error",
  );
}

function generatedTsvArtifactTokens(rootPath) {
  const artifacts = [];

  function walk(directory) {
    for (const entry of readdirSync(directory, { withFileTypes: true })) {
      const entryPath = resolve(directory, entry.name);
      if (entry.isDirectory()) {
        walk(entryPath);
        continue;
      }
      if (entry.isFile() && entry.name.endsWith(".tsv")) {
        artifacts.push(posix.relative(rootDir, entryPath.split("/").join(posix.sep)));
      }
    }
  }

  walk(rootPath);
  return artifacts.sort();
}

function verifyNativeGeneratedArtifactDocumentationCoverage(documentationPaths) {
  const nativeBuildDir = resolve(rootDir, "build/native");
  assert.ok(existsSync(nativeBuildDir), "native build artifact directory is required");

  const artifactTokens = generatedTsvArtifactTokens(nativeBuildDir);
  assert.ok(artifactTokens.length > 0, "native generated TSV artifact list is empty");
  assert.equal(new Set(artifactTokens).size, artifactTokens.length, "native generated TSV artifact list contains duplicate paths");
  assert.equal(artifactTokens.length, 8, "native generated TSV artifact list count drift");
  assert.deepEqual(
    artifactTokens,
    [
      "build/native/native-runtime-probe-summary.tsv",
      "build/native/native-source-proof-summary.tsv",
      "build/native/nc-files/summary.tsv",
      "build/native/sim-configs/class-summary.tsv",
      "build/native/sim-configs/path-matrix.tsv",
      "build/native/sim-configs/skipped.tsv",
      "build/native/sim-configs/summary.tsv",
      "build/native/source-probes.tsv",
    ],
    "native generated TSV artifact list drift",
  );
  const emptyNativeArtifactTokensAllowed = new Set([
    "build/native/sim-configs/skipped.tsv",
  ]);
  for (const artifactToken of artifactTokens) {
    const artifactPath = resolve(rootDir, artifactToken);
    assert.ok(existsSync(artifactPath), `${artifactToken}: generated native TSV artifact missing`);
    const artifactText = readFileSync(artifactPath, "utf8");
    if (artifactText.length === 0 && emptyNativeArtifactTokensAllowed.has(artifactToken)) {
      continue;
    }
    assert.ok(
      artifactText.includes("\t") && artifactText.trim().split("\n")[0].length > 0,
      `${artifactToken}: generated native TSV artifact lacks TSV header`,
    );
  }

  const documentationText = documentationPaths
    .map((documentationPath) => readFileSync(documentationPath, "utf8"))
    .join("\n");
  const missingArtifactTokens = artifactTokens.filter((artifactToken) =>
    !documentationText.includes(artifactToken),
  );

  assert.deepEqual(
    missingArtifactTokens,
    [],
    "generated native TSV artifacts must be documented",
  );
  const browserSmokeText = readFileSync(browserInterpSmokePath, "utf8");
  const missingBrowserArtifactTokens = artifactTokens.filter((artifactToken) =>
    !browserSmokeText.includes(artifactToken),
  );
  assert.deepEqual(
    missingBrowserArtifactTokens,
    [],
    "generated native TSV artifacts must be listed in browser smoke",
  );
  assert.ok(
    browserSmokeText.includes("nativeArtifactTokens.length !== 8"),
    "browser smoke must keep native artifact token fixed-count guard",
  );
  assert.ok(
    browserSmokeText.includes("new Set(nativeArtifactTokens).size !== nativeArtifactTokens.length"),
    "browser smoke must keep native artifact token duplicate-free guard",
  );
  assert.ok(
    browserSmokeText.includes("browser_native_artifact_fetchability"),
    "browser smoke must keep native artifact fetchability guard",
  );
  assert.ok(
    browserSmokeText.includes("await fetchText(`../../${artifactToken}`)"),
    "browser smoke must fetch each native artifact by relative artifact token",
  );
  assert.ok(
    browserSmokeText.includes("emptyNativeArtifactTokensAllowed.has(artifactToken)"),
    "browser smoke must keep native skipped artifact empty allowance",
  );
  assert.ok(
    browserSmokeText.includes("browser_native_artifact_documentation_coverage: missing"),
    "browser smoke must keep native artifact documentation coverage guard",
  );
  assert.ok(
    browserSmokeText.includes(
      "for (const artifactToken of nativeArtifactTokens) {\n        if (!documentationText.includes(artifactToken)) {",
    ),
    "browser smoke must check native artifact documentation coverage from joined documentation text",
  );
  assert.ok(
    browserSmokeText.includes('"native_artifact_documentation_coverage",\n            generatedArtifactDocumentationCoverage.nativeArtifactTokens.length'),
    "browser smoke must keep native artifact completion count parity guard",
  );
}

function nextBoundaryRecommendationRows({
  worklistRows,
  promotionLockRows,
  runtimeContractRows,
  userMRuntimeProbeGateRows,
  toolDbTransactionRows,
  toolDbRuntimeProbeGateRows,
  pythonFixturePlanRows,
}) {
  const lockByKind = new Map(promotionLockRows.map((row) => [row.boundary_kind, row]));
  const contractByKind = new Map(runtimeContractRows.map((row) => [row.boundary_kind, row]));
  const worklistByKind = new Map();
  for (const row of worklistRows) {
    const existing = worklistByKind.get(row.boundary_kind) ?? [];
    existing.push(row);
    worklistByKind.set(row.boundary_kind, existing);
  }

  const userMWork = worklistByKind.get("external_user_m_process")?.[0];
  const toolDbWork = worklistByKind.get("tool_database_process")?.[0];
  const pythonFixture = pythonFixturePlanRows[0];
  const pythonRows = worklistByKind.get("python_runtime") ?? [];
  const pythonContract = contractByKind.get("python_runtime");

  return [
    [
      "1",
      "external_user_m_process",
      userMWork?.target ?? "-",
      userMWork?.blocked ?? "L4-USER-M-PROCESS",
      "implement_native_m128_m129_state_probe",
      "user-m-process-native-runtime-probe-gate.tsv",
      String(userMRuntimeProbeGateRows.length),
      "native_runtime_state_probe_required",
      userMWork?.required_node_proof ?? "linuxcnc_owned_state_boundary_not_user_m_event_only",
      userMWork?.required_browser_proof ?? "browser_after_node_state_proof_no_full_process_claim",
      lockByKind.get("external_user_m_process")?.lock_active ?? "0",
      contractByKind.get("external_user_m_process")?.contract_ok ?? "0",
      "0",
      "0",
      "run LinuxCNC-owned millturn M128/M129 HAL/Tcl state probe after host runtime gate is ready",
      "next-boundary-worklist.tsv,blocked-runtime-promotion-lock.tsv,user-m-process-transition-plan.tsv,user-m-process-native-runtime-state-plan.tsv,user-m-process-native-runtime-probe-gate.tsv",
    ],
    [
      "2",
      "tool_database_process",
      toolDbWork?.target ?? "-",
      toolDbWork?.blocked ?? "L4-TOOL-DB",
      "implement_tooldata_db_protocol_probe",
      "tool-db-process-native-runtime-probe-gate.tsv",
      String(toolDbRuntimeProbeGateRows.length),
      "native_db_process_protocol_probe_required",
      toolDbWork?.required_node_proof ?? "linuxcnc_tooldata_db_protocol_not_tbl_fallback",
      toolDbWork?.required_browser_proof ?? "browser_after_node_protocol_proof_opfs_persistence_only",
      lockByKind.get("tool_database_process")?.lock_active ?? "0",
      contractByKind.get("tool_database_process")?.contract_ok ?? "0",
      "0",
      "0",
      "prove DB_PROGRAM v2.1/get/load/put/unload protocol after host runtime gate is ready; reject tbl fallback promotion",
      "next-boundary-worklist.tsv,blocked-runtime-promotion-lock.tsv,tool-db-process-transaction-plan.tsv,tool-db-process-native-runtime-readiness.tsv,tool-db-process-native-runtime-probe-gate.tsv",
    ],
    [
      "3",
      "python_runtime",
      pythonFixture?.family ?? "axis/remap/stop-lookahead/nc_files",
      "L4-PYTHON-REMAP",
      "implement_minimal_python_runtime_lifecycle_probe",
      "python-remap-native-runtime-fixture-plan.tsv",
      pythonContract?.contract_row_count ?? String(pythonRows.length),
      pythonFixture?.proof_kind ?? "linuxcnc_python_runtime_lifecycle_probe_required",
      "linuxcnc_python_runtime_boundary_not_js_semantics",
      "browser_after_node_python_boundary_no_full_process_claim",
      lockByKind.get("python_runtime")?.lock_active ?? "0",
      pythonContract?.contract_ok ?? "0",
      "0",
      "0",
      "start with stop-lookahead fixture; keep all Python-remap families inventory-only until runtime proof exists",
      "next-boundary-worklist.tsv,blocked-runtime-promotion-lock.tsv,python-remap-runtime-contract.tsv,python-remap-native-runtime-fixture-plan.tsv,python-remap-native-runtime-probe-gate.tsv",
    ],
  ].map((row) => row.map(tsvValue).join("\t"));
}

function verifyNextBoundaryRecommendationRows(rows) {
  const expectedHeaders = [
    "priority",
    "boundary_kind",
    "target",
    "blocked",
    "recommendation",
    "primary_artifact",
    "artifact_row_count",
    "required_native_proof",
    "required_node_proof",
    "required_browser_proof",
    "promotion_lock_active",
    "contract_ok",
    "execution_enabled",
    "promotion_allowed",
    "next_step",
    "source_artifacts",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  assert.deepEqual(
    parsedRows.map((row) => row.boundary_kind),
    ["external_user_m_process", "tool_database_process", "python_runtime"],
    "next boundary recommendations must stay ordered by current boundary priority",
  );
  const expectedSourceArtifacts = new Map([
    [
      "external_user_m_process",
      [
        "next-boundary-worklist.tsv",
        "blocked-runtime-promotion-lock.tsv",
        "user-m-process-transition-plan.tsv",
        "user-m-process-native-runtime-state-plan.tsv",
        "user-m-process-native-runtime-probe-gate.tsv",
      ],
    ],
    [
      "tool_database_process",
      [
        "next-boundary-worklist.tsv",
        "blocked-runtime-promotion-lock.tsv",
        "tool-db-process-transaction-plan.tsv",
        "tool-db-process-native-runtime-readiness.tsv",
        "tool-db-process-native-runtime-probe-gate.tsv",
      ],
    ],
    [
      "python_runtime",
      [
        "next-boundary-worklist.tsv",
        "blocked-runtime-promotion-lock.tsv",
        "python-remap-runtime-contract.tsv",
        "python-remap-native-runtime-fixture-plan.tsv",
        "python-remap-native-runtime-probe-gate.tsv",
      ],
    ],
  ]);

  for (const row of parsedRows) {
    const sourceArtifacts = row.source_artifacts === "-" ? [] : row.source_artifacts.split(",");
    const expectedSources = expectedSourceArtifacts.get(row.boundary_kind);
    assert.ok(expectedSources, `${row.target}: unexpected recommendation source artifact kind`);
    assert.deepEqual(sourceArtifacts, expectedSources, `${row.target}: recommendation source artifact set drift`);
    assert.equal(new Set(sourceArtifacts).size, sourceArtifacts.length, `${row.target}: duplicate recommendation source artifact`);
    assert.ok(sourceArtifacts.includes(row.primary_artifact), `${row.target}: recommendation primary artifact lacks source trace`);
    for (const artifactName of [row.primary_artifact, ...sourceArtifacts]) {
      assert.ok(
        existsSync(resolve(buildDir, artifactName)),
        `${row.target}: recommendation references missing generated artifact ${artifactName}`,
      );
    }
    assert.ok(/^[1-9][0-9]*$/.test(row.priority), `${row.target}: invalid recommendation priority`);
    assert.ok(/^[1-9][0-9]*$/.test(row.artifact_row_count), `${row.target}: invalid artifact row count`);
    assert.equal(row.promotion_lock_active, "1", `${row.target}: recommendation lacks active promotion lock`);
    assert.equal(row.contract_ok, "1", `${row.target}: recommendation lacks passing contract summary`);
    assert.equal(row.execution_enabled, "0", `${row.target}: recommendation must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.target}: recommendation must not allow promotion`);
    assert.notEqual(row.required_native_proof, "-", `${row.target}: recommendation lacks native proof`);
    assert.notEqual(row.required_node_proof, "-", `${row.target}: recommendation lacks Node proof`);
    assert.notEqual(row.required_browser_proof, "-", `${row.target}: recommendation lacks browser proof`);
    assert.notEqual(row.next_step, "-", `${row.target}: recommendation lacks next step`);
    assert.ok(
      row.source_artifacts.includes("next-boundary-worklist.tsv") &&
        row.source_artifacts.includes("blocked-runtime-promotion-lock.tsv"),
      `${row.target}: recommendation lacks source artifact trace`,
    );

    if (row.boundary_kind === "external_user_m_process") {
      assert.equal(row.target, "axis/vismach/millturn/example.ngc", "user-M recommendation target drift");
      assert.equal(row.blocked, "L4-USER-M-PROCESS", "user-M recommendation blocked kind drift");
      assert.equal(row.recommendation, "implement_native_m128_m129_state_probe", "user-M recommendation drift");
      assert.equal(row.primary_artifact, "user-m-process-native-runtime-probe-gate.tsv", "user-M artifact drift");
      assert.ok(row.required_node_proof.includes("not_user_m_event_only"), "user-M recommendation must reject event-only proof");
      assert.ok(row.next_step.includes("M128/M129"), "user-M recommendation lacks M128/M129 next step");
    } else if (row.boundary_kind === "tool_database_process") {
      assert.equal(row.target, "axis/db_demo/base.ngc", "tool DB recommendation target drift");
      assert.equal(row.blocked, "L4-TOOL-DB", "tool DB recommendation blocked kind drift");
      assert.equal(row.recommendation, "implement_tooldata_db_protocol_probe", "tool DB recommendation drift");
      assert.equal(row.primary_artifact, "tool-db-process-native-runtime-probe-gate.tsv", "tool DB artifact drift");
      assert.ok(row.required_native_proof.includes("native_db_process_protocol_probe"), "tool DB recommendation must require native DB process proof");
      assert.ok(row.next_step.includes("DB_PROGRAM"), "tool DB recommendation lacks DB_PROGRAM next step");
      assert.ok(row.next_step.includes("tbl fallback"), "tool DB recommendation must reject tbl fallback");
    } else if (row.boundary_kind === "python_runtime") {
      assert.equal(row.target, "axis/remap/stop-lookahead/nc_files", "Python recommendation target drift");
      assert.equal(row.blocked, "L4-PYTHON-REMAP", "Python recommendation blocked kind drift");
      assert.equal(row.recommendation, "implement_minimal_python_runtime_lifecycle_probe", "Python recommendation drift");
      assert.equal(row.primary_artifact, "python-remap-native-runtime-fixture-plan.tsv", "Python artifact drift");
      assert.ok(row.required_node_proof.includes("not_js_semantics"), "Python recommendation must reject JS semantics");
      assert.ok(row.next_step.includes("stop-lookahead"), "Python recommendation lacks fixture next step");
    } else {
      throw new Error(`${row.target}: unexpected recommendation boundary kind ${row.boundary_kind}`);
    }
  }

  return parsedRows;
}

function verifyBlockedRuntimeWorklistRecommendationConsistency({
  worklistRows,
  proofGateRows,
  promotionLockRows,
  runtimeContractRows,
  recommendationRows,
}) {
  const expectedKinds = [
    "external_user_m_process",
    "tool_database_process",
    "python_runtime",
  ];
  const worklistByTarget = new Map(worklistRows.map((row) => [row.target, row]));
  const lockByTarget = new Map(promotionLockRows.map((row) => [row.target, row]));
  const contractByKind = new Map(runtimeContractRows.map((row) => [row.boundary_kind, row]));
  const proofRowsByTarget = new Map();
  for (const row of proofGateRows) {
    const existing = proofRowsByTarget.get(row.target) ?? [];
    existing.push(row);
    proofRowsByTarget.set(row.target, existing);
  }

  assert.deepEqual(
    recommendationRows.map((row) => row.boundary_kind),
    expectedKinds,
    "blocked runtime recommendation kind order drift",
  );

  for (const recommendation of recommendationRows) {
    const worklist = worklistByTarget.get(recommendation.target);
    const lock = lockByTarget.get(recommendation.target);
    const contract = contractByKind.get(recommendation.boundary_kind);
    const proofRows = proofRowsByTarget.get(recommendation.target) ?? [];
    const proofByLayer = new Map(proofRows.map((row) => [row.proof_layer, row]));

    assert.ok(worklist, `${recommendation.target}: recommendation lacks worklist row`);
    assert.ok(lock, `${recommendation.target}: recommendation lacks promotion lock row`);
    assert.ok(contract, `${recommendation.target}: recommendation lacks runtime contract summary row`);
    assert.deepEqual(
      [...proofByLayer.keys()].sort(),
      ["browser", "native", "node"],
      `${recommendation.target}: recommendation proof gate layer drift`,
    );

    assert.equal(recommendation.boundary_kind, worklist.boundary_kind, `${recommendation.target}: recommendation/worklist kind drift`);
    assert.equal(recommendation.blocked, worklist.blocked, `${recommendation.target}: recommendation/worklist blocked drift`);
    assert.equal(recommendation.required_node_proof, worklist.required_node_proof, `${recommendation.target}: recommendation/worklist Node proof drift`);
    assert.equal(recommendation.required_browser_proof, worklist.required_browser_proof, `${recommendation.target}: recommendation/worklist browser proof drift`);
    assert.equal(recommendation.promotion_lock_active, lock.lock_active, `${recommendation.target}: recommendation/lock active drift`);
    assert.equal(recommendation.contract_ok, contract.contract_ok, `${recommendation.target}: recommendation/contract status drift`);
    assert.equal(lock.runtime_alignment_artifact, contract.runtime_alignment_artifact, `${recommendation.target}: lock/contract alignment artifact drift`);
    assert.equal(lock.runtime_alignment_row_count, contract.runtime_alignment_row_count, `${recommendation.target}: lock/contract alignment row count drift`);
    assert.equal(lock.runtime_alignment_ok, contract.runtime_alignment_ok, `${recommendation.target}: lock/contract alignment status drift`);

    for (const layer of ["native", "node", "browser"]) {
      const proof = proofByLayer.get(layer);
      assert.ok(proof, `${recommendation.target}: missing ${layer} proof gate`);
      assert.equal(proof.boundary_kind, recommendation.boundary_kind, `${recommendation.target}: ${layer} proof kind drift`);
      assert.equal(proof.blocked, recommendation.blocked, `${recommendation.target}: ${layer} proof blocked drift`);
      assert.equal(proof.proof_status, "pending", `${recommendation.target}: ${layer} proof gate must remain pending`);
      assert.equal(proof.execution_enabled, "0", `${recommendation.target}: ${layer} proof gate must not enable execution`);
      assert.equal(proof.promotion_allowed, "0", `${recommendation.target}: ${layer} proof gate must not allow promotion`);
    }
    assert.equal(proofByLayer.get("node").required_proof, recommendation.required_node_proof, `${recommendation.target}: Node proof/recommendation drift`);
    assert.equal(proofByLayer.get("browser").required_proof, recommendation.required_browser_proof, `${recommendation.target}: browser proof/recommendation drift`);

    assert.equal(recommendation.execution_enabled, "0", `${recommendation.target}: recommendation must not enable execution`);
    assert.equal(recommendation.promotion_allowed, "0", `${recommendation.target}: recommendation must not allow promotion`);
    assert.equal(lock.execution_enabled, "0", `${recommendation.target}: promotion lock must not enable execution`);
    assert.equal(lock.promotion_allowed, "0", `${recommendation.target}: promotion lock must not allow promotion`);
    assert.equal(lock.lock_active, "1", `${recommendation.target}: promotion lock must remain active`);
    assert.equal(contract.contract_ok, "1", `${recommendation.target}: runtime contract summary must remain OK`);
    assert.ok(recommendation.source_artifacts.includes("next-boundary-worklist.tsv"), `${recommendation.target}: recommendation source lacks worklist`);
    assert.ok(recommendation.source_artifacts.includes("blocked-runtime-promotion-lock.tsv"), `${recommendation.target}: recommendation source lacks promotion lock`);
  }

  return true;
}

function verifyRuntimeFamilyContractAlignmentConsistency({
  userMTransitionRows,
  userMRuntimeStatePlanRows,
  userMRuntimeReadinessRows,
  userMRuntimeProbeGateRows,
  toolDbTransactionRows,
  toolDbRuntimeReadinessRows,
  toolDbRuntimeProbeGateRows,
  pythonRuntimeContractRows,
  pythonRuntimeReadinessRows,
  pythonRuntimeStatePlanRows,
  pythonRuntimeFixturePlanRows,
  pythonRuntimeProbeGateRows,
  runtimeContractSummaryRows,
  runtimeNativeAlignmentRows,
}) {
  const contractByClass = new Map(
    runtimeContractSummaryRows.map((row) => [row.boundary_class, row]),
  );
  const nativeAlignmentByClass = new Map(
    runtimeNativeAlignmentRows.map((row) => [row.boundary_class, row]),
  );
  const requireDisabled = (row, label) => {
    assert.equal(row.proof_status, "pending", `${label}: proof status must remain pending`);
    assert.equal(row.execution_enabled, "0", `${label}: must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${label}: must not allow promotion`);
  };
  const missingRequirements = (rows) =>
    uniqueSorted(rows
      .filter((row) => row.available === "0")
      .map((row) => row.requirement));

  const userMContract = contractByClass.get("L4-USER-M-PROCESS");
  const userMNative = nativeAlignmentByClass.get("L4-USER-M-PROCESS");
  assert.ok(userMContract, "missing user-M runtime contract summary");
  assert.ok(userMNative, "missing user-M native alignment summary");
  assert.equal(userMContract.boundary_kind, "external_user_m_process", "user-M contract boundary kind drift");
  assert.equal(userMContract.contract_artifact, "user-m-process-transition-plan.tsv", "user-M contract artifact drift");
  assert.equal(userMContract.contract_row_count, String(userMTransitionRows.length), "user-M contract row count drift");
  assert.equal(userMContract.runtime_alignment_artifact, userMNative.artifact, "user-M contract/native alignment artifact drift");
  assert.equal(userMContract.runtime_alignment_row_count, userMNative.row_count, "user-M contract/native alignment count drift");
  assert.equal(userMContract.contract_ok, "1", "user-M contract summary must remain OK");
  assert.equal(userMNative.summary_ok, "1", "user-M native alignment summary must remain OK");

  const userMTransitionsByCode = new Map(userMTransitionRows.map((row) => [row.user_m_code, row]));
  const userMGateByCode = new Map(userMRuntimeProbeGateRows.map((row) => [row.user_m_code, row]));
  const userMMissingRequirements = missingRequirements(userMRuntimeReadinessRows);
  assert.equal(userMRuntimeStatePlanRows.length, userMTransitionRows.length, "user-M runtime state plan count drift");
  assert.equal(userMRuntimeProbeGateRows.length, userMTransitionRows.length, "user-M runtime probe gate count drift");
  for (const plan of userMRuntimeStatePlanRows) {
    const transition = userMTransitionsByCode.get(plan.user_m_code);
    const gate = userMGateByCode.get(plan.user_m_code);
    assert.ok(transition, `${plan.user_m_code}: missing user-M transition contract row`);
    assert.ok(gate, `${plan.user_m_code}: missing user-M probe gate row`);
    assert.equal(plan.path, transition.path, `${plan.user_m_code}: user-M path drift`);
    assert.equal(plan.ini, transition.ini, `${plan.user_m_code}: user-M INI drift`);
    assert.equal(plan.remap_code, transition.remap_code, `${plan.user_m_code}: user-M remap drift`);
    assert.equal(plan.switchkins_target, transition.switchkins_target, `${plan.user_m_code}: user-M switchkins drift`);
    assert.equal(plan.active_g5x, transition.active_g5x, `${plan.user_m_code}: user-M active G5x drift`);
    assert.equal(plan.work_offset_pocket, transition.work_offset_pocket, `${plan.user_m_code}: user-M work offset drift`);
    assert.equal(plan.expected_state_pins, transition.expected_state_pins, `${plan.user_m_code}: user-M state pin drift`);
    assert.equal(plan.source_alignment_ok, "1", `${plan.user_m_code}: user-M source alignment must be OK`);
    assert.ok(plan.source_alignment_artifacts.includes(userMContract.runtime_alignment_artifact), `${plan.user_m_code}: user-M plan lacks state alignment trace`);
    assert.ok(plan.source_alignment_artifacts.includes("user-m-process-native-transition-alignment.tsv"), `${plan.user_m_code}: user-M plan lacks transition alignment trace`);
    assert.equal(gate.required_runtime, plan.required_runtime, `${plan.user_m_code}: user-M gate runtime drift`);
    assert.equal(gate.required_native_proof, plan.proof_kind, `${plan.user_m_code}: user-M gate proof drift`);
    assert.equal(gate.source_proof_ready, "1", `${plan.user_m_code}: user-M source proof must be ready`);
    assert.deepEqual(
      uniqueSorted(splitSummaryList(gate.missing_requirements)),
      userMMissingRequirements,
      `${plan.user_m_code}: user-M gate missing requirements drift`,
    );
    requireDisabled(transition, `${plan.user_m_code}: user-M transition`);
    requireDisabled(plan, `${plan.user_m_code}: user-M runtime plan`);
    requireDisabled(gate, `${plan.user_m_code}: user-M probe gate`);
  }

  const toolDbContract = contractByClass.get("L4-TOOL-DB");
  const toolDbNative = nativeAlignmentByClass.get("L4-TOOL-DB");
  assert.ok(toolDbContract, "missing tool DB runtime contract summary");
  assert.ok(toolDbNative, "missing tool DB native alignment summary");
  assert.equal(toolDbContract.boundary_kind, "tool_database_process", "tool DB contract boundary kind drift");
  assert.equal(toolDbContract.contract_artifact, "tool-db-process-transaction-plan.tsv", "tool DB contract artifact drift");
  assert.equal(toolDbContract.contract_row_count, String(toolDbTransactionRows.length), "tool DB contract row count drift");
  assert.equal(toolDbContract.runtime_alignment_artifact, toolDbNative.artifact, "tool DB contract/native alignment artifact drift");
  assert.equal(toolDbContract.runtime_alignment_row_count, toolDbNative.row_count, "tool DB contract/native alignment count drift");
  assert.equal(toolDbContract.contract_ok, "1", "tool DB contract summary must remain OK");
  assert.equal(toolDbNative.summary_ok, "1", "tool DB native alignment summary must remain OK");
  assert.equal(toolDbRuntimeProbeGateRows.length, 1, "tool DB runtime probe gate count drift");
  const toolDbGate = toolDbRuntimeProbeGateRows[0];
  const toolDbMissingRequirements = missingRequirements(toolDbRuntimeReadinessRows);
  const expectedToolDbTransactions = toolDbTransactionRows.map((row) =>
    `${row.transaction_phase}:${row.protocol_message}`,
  );
  assert.deepEqual(
    uniqueSorted(splitSummaryList(toolDbGate.protocol_transactions)),
    uniqueSorted(expectedToolDbTransactions),
    "tool DB probe gate transaction set drift",
  );
  assert.deepEqual(
    uniqueSorted(splitSummaryList(toolDbGate.missing_requirements)),
    toolDbMissingRequirements,
    "tool DB probe gate missing requirements drift",
  );
  assert.equal(toolDbGate.required_native_proof, "native_db_process_protocol_probe_required", "tool DB native proof drift");
  assert.equal(toolDbGate.source_proof_ready, "1", "tool DB source proof must be ready");
  for (const row of toolDbTransactionRows) {
    assert.equal(row.db_program, toolDbGate.db_program, `${row.transaction_phase}: tool DB program drift`);
    requireDisabled(row, `${row.transaction_phase}: tool DB transaction`);
  }
  requireDisabled(toolDbGate, "tool DB probe gate");

  const pythonContract = contractByClass.get("L4-PYTHON-REMAP");
  const pythonNative = nativeAlignmentByClass.get("L4-PYTHON-REMAP");
  assert.ok(pythonContract, "missing Python runtime contract summary");
  assert.ok(pythonNative, "missing Python native alignment summary");
  assert.equal(pythonContract.boundary_kind, "python_runtime", "Python contract boundary kind drift");
  assert.equal(pythonContract.contract_artifact, "python-remap-runtime-contract.tsv", "Python contract artifact drift");
  assert.equal(pythonContract.contract_row_count, String(pythonRuntimeContractRows.length), "Python contract row count drift");
  assert.equal(pythonContract.runtime_alignment_artifact, pythonNative.artifact, "Python contract/native alignment artifact drift");
  assert.equal(pythonContract.runtime_alignment_row_count, pythonNative.row_count, "Python contract/native alignment count drift");
  assert.equal(pythonContract.contract_ok, "1", "Python contract summary must remain OK");
  assert.equal(pythonNative.summary_ok, "1", "Python native alignment summary must remain OK");
  assert.equal(pythonRuntimeStatePlanRows.length, pythonRuntimeContractRows.length, "Python runtime state plan count drift");
  assert.equal(pythonRuntimeFixturePlanRows.length, 1, "Python fixture plan count drift");
  assert.equal(pythonRuntimeProbeGateRows.length, 1, "Python probe gate count drift");

  const pythonContractByFamily = new Map(pythonRuntimeContractRows.map((row) => [row.family, row]));
  const pythonStatePlanByFamily = new Map(pythonRuntimeStatePlanRows.map((row) => [row.family, row]));
  for (const contract of pythonRuntimeContractRows) {
    const statePlan = pythonStatePlanByFamily.get(contract.family);
    assert.ok(statePlan, `${contract.family}: missing Python state plan row`);
    assert.equal(statePlan.runtime_phases, contract.runtime_phases, `${contract.family}: Python phase drift`);
    assert.equal(statePlan.python_modules, contract.python_modules, `${contract.family}: Python module drift`);
    assert.equal(statePlan.python_callables, contract.python_callables, `${contract.family}: Python callable drift`);
    assert.equal(statePlan.ngc_only_subpaths, contract.ngc_only_subpaths, `${contract.family}: Python NGC-only drift`);
    assert.equal(statePlan.process_assumptions, contract.process_assumptions, `${contract.family}: Python process assumption drift`);
    assert.equal(statePlan.source_alignment_ok, "1", `${contract.family}: Python source alignment must be OK`);
    assert.ok(statePlan.source_alignment_artifacts.includes(pythonContract.runtime_alignment_artifact), `${contract.family}: Python state plan lacks native alignment trace`);
    requireDisabled(contract, `${contract.family}: Python contract`);
    requireDisabled(statePlan, `${contract.family}: Python state plan`);
  }

  const pythonFixture = pythonRuntimeFixturePlanRows[0];
  const pythonGate = pythonRuntimeProbeGateRows[0];
  const pythonFixtureContract = pythonContractByFamily.get(pythonFixture.family);
  const pythonFixtureStatePlan = pythonStatePlanByFamily.get(pythonFixture.family);
  assert.ok(pythonFixtureContract, "Python fixture lacks contract row");
  assert.ok(pythonFixtureStatePlan, "Python fixture lacks state plan row");
  assert.equal(pythonGate.family, pythonFixture.family, "Python probe gate fixture family drift");
  assert.equal(pythonFixture.runtime_phases, pythonFixtureContract.runtime_phases, "Python fixture phase drift");
  assert.equal(pythonFixture.python_modules, pythonFixtureContract.python_modules, "Python fixture module drift");
  assert.equal(pythonFixture.process_assumptions, pythonFixtureContract.process_assumptions, "Python fixture process assumption drift");
  assert.equal(pythonFixture.source_alignment_ok, "1", "Python fixture source alignment must be OK");
  assert.equal(pythonGate.required_native_proof, pythonFixture.proof_kind, "Python probe gate proof drift");
  assert.equal(pythonGate.source_proof_ready, "1", "Python source proof must be ready");
  assert.deepEqual(
    uniqueSorted(splitSummaryList(pythonGate.missing_requirements)),
    missingRequirements(pythonRuntimeReadinessRows.filter((row) => row.family === pythonGate.family)),
    "Python probe gate missing requirements drift",
  );
  requireDisabled(pythonFixture, "Python fixture plan");
  requireDisabled(pythonGate, "Python probe gate");

  return true;
}

function nativeProofAlignmentRows(worklistRows, proofGateRows) {
  const expectedProofs = [
    {
      boundaryClass: "L4-USER-M-PROCESS",
      boundaryKind: "external_user_m_process",
      target: "axis/vismach/millturn/example.ngc",
      proofKey: "millturn_user_m_native_source_state_proof",
      requiredProofToken: "ini_xyz_hal_pin_state",
      note: "native_source_state_proof_consumed_by_boundary_worklist",
    },
    {
      boundaryClass: "L4-TOOL-DB",
      boundaryKind: "tool_database_process",
      target: "axis/db_demo/base.ngc",
      proofKey: "tool_db_native_source_protocol_proof",
      requiredProofToken: "v2_1_handshake",
      note: "native_source_protocol_proof_consumed_by_boundary_worklist",
    },
    {
      boundaryClass: "L4-PYTHON-REMAP",
      boundaryKind: "python_runtime",
      target: "*",
      proofKey: "python_remap_native_source_inventory_proof",
      requiredProofToken: "python_runtime_owner",
      note: "native_source_inventory_proof_consumed_by_python_family_worklist",
    },
  ];

  if (!existsSync(nativeSourceProofSummaryPath)) {
    return expectedProofs.map((expected) => [
      expected.boundaryClass,
      expected.boundaryKind,
      expected.target,
      expected.proofKey,
      "0",
      "-",
      "-",
      "-",
      "0",
      "0",
      "0",
      "native_source_proof_summary_unavailable",
    ].map(tsvValue).join("\t"));
  }

  const nativeProofRows = parseTsv(
    readFileSync(nativeSourceProofSummaryPath, "utf8"),
    [
      "boundary_class",
      "proof_key",
      "proof_value",
      "execution_enabled",
      "promotion_allowed",
      "stdout_log",
    ],
  );
  const nativeProofByClass = new Map(nativeProofRows.map((row) => [row.boundary_class, row]));

  return expectedProofs.map((expected) => {
    const nativeProof = nativeProofByClass.get(expected.boundaryClass);
    const matchingWorklistRows = worklistRows.filter((row) =>
      row.boundary_kind === expected.boundaryKind &&
        (expected.target === "*" || row.target === expected.target),
    );
    const matchingNativeGateRows = proofGateRows.filter((row) =>
      row.boundary_kind === expected.boundaryKind &&
        row.proof_layer === "native" &&
        row.required_proof.includes(expected.requiredProofToken) &&
        (expected.target === "*" || row.target === expected.target),
    );
    const alignmentOk = Boolean(nativeProof) &&
      nativeProof.proof_key === expected.proofKey &&
      nativeProof.proof_value === "1" &&
      nativeProof.execution_enabled === "0" &&
      nativeProof.promotion_allowed === "0" &&
      matchingWorklistRows.length > 0 &&
      matchingNativeGateRows.length > 0;

    return [
      expected.boundaryClass,
      expected.boundaryKind,
      expected.target,
      expected.proofKey,
      "1",
      nativeProof?.proof_value ?? "-",
      nativeProof?.execution_enabled ?? "-",
      nativeProof?.promotion_allowed ?? "-",
      String(matchingWorklistRows.length),
      String(matchingNativeGateRows.length),
      flagValue(alignmentOk),
      expected.note,
    ].map(tsvValue).join("\t");
  });
}

function verifyNativeProofAlignmentRows(rows) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "proof_key",
    "native_summary_available",
    "proof_value",
    "execution_enabled",
    "promotion_allowed",
    "matching_worklist_count",
    "matching_native_gate_count",
    "alignment_ok",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];

  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    expectedClasses,
    "native proof alignment class order drift",
  );

  for (const row of parsedRows) {
    assert.ok(["0", "1"].includes(row.native_summary_available), `${row.boundary_class}: invalid native availability`);
    assert.ok(["0", "1"].includes(row.alignment_ok), `${row.boundary_class}: invalid alignment flag`);
    assert.ok(/^[0-9]+$/.test(row.matching_worklist_count), `${row.boundary_class}: invalid worklist count`);
    assert.ok(/^[0-9]+$/.test(row.matching_native_gate_count), `${row.boundary_class}: invalid native gate count`);

    if (row.native_summary_available === "0") {
      assert.equal(row.alignment_ok, "0", `${row.boundary_class}: unavailable native proof cannot align`);
      assert.equal(row.notes, "native_source_proof_summary_unavailable", `${row.boundary_class}: missing unavailable note`);
      continue;
    }

    assert.equal(row.proof_value, "1", `${row.boundary_class}: native proof incomplete`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: native proof must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: native proof must not allow promotion`);
    assert.notEqual(row.matching_worklist_count, "0", `${row.boundary_class}: native proof lacks worklist consumer`);
    assert.notEqual(row.matching_native_gate_count, "0", `${row.boundary_class}: native proof lacks native gate consumer`);
    assert.equal(row.alignment_ok, "1", `${row.boundary_class}: native proof alignment failed`);
  }

  return parsedRows;
}

function nativeRuntimeProbeSummaryRows() {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "runtime_probe",
    "required_native_proof",
    "opt_in_env",
    "runtime_ready",
    "source_proof_ready",
    "probe_status",
    "execution_enabled",
    "promotion_allowed",
    "missing_requirements",
    "probe_note",
    "stdout_log",
  ];
  assert.ok(
    existsSync(nativeRuntimeProbeSummarySourcePath),
    "native runtime probe summary is required before WASM inventory generation",
  );
  const parsedRows = parseTsv(
    readFileSync(nativeRuntimeProbeSummarySourcePath, "utf8"),
    expectedHeaders,
  );
  const expectedRows = new Map([
    [
      "L4-USER-M-PROCESS",
      {
        boundaryKind: "external_user_m_process",
        target: "axis/vismach/millturn/example.ngc",
        runtimeProbe: "linuxcnc_millturn_user_m_runtime_probe",
        requiredNativeProof: "native_runtime_state_probe_required",
        optInEnv: "ENABLE_MILLTURN_USER_M_RUNTIME_PROBE=1",
      },
    ],
    [
      "L4-TOOL-DB",
      {
        boundaryKind: "tool_database_process",
        target: "axis/db_demo/base.ngc",
        runtimeProbe: "linuxcnc_tool_db_runtime_probe",
        requiredNativeProof: "native_db_process_protocol_probe_required",
        optInEnv: "ENABLE_TOOL_DB_RUNTIME_PROBE=1",
      },
    ],
    [
      "L4-PYTHON-REMAP",
      {
        boundaryKind: "python_runtime",
        target: "axis/remap/stop-lookahead/nc_files",
        runtimeProbe: "linuxcnc_python_remap_runtime_probe",
        requiredNativeProof: "linuxcnc_python_runtime_lifecycle_probe_required",
        optInEnv: "ENABLE_PYTHON_REMAP_RUNTIME_PROBE=1",
      },
    ],
  ]);
  const rowsByClass = new Map(parsedRows.map((row) => [row.boundary_class, row]));

  assert.equal(parsedRows.length, expectedRows.size, "native runtime probe summary row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    [...expectedRows.keys()],
    "native runtime probe summary class order drift",
  );

  for (const [boundaryClass, expected] of expectedRows) {
    const row = rowsByClass.get(boundaryClass);
    assert.ok(row, `${boundaryClass}: missing native runtime probe summary row`);
    assert.equal(row.boundary_kind, expected.boundaryKind, `${boundaryClass}: runtime probe boundary kind drift`);
    assert.equal(row.target, expected.target, `${boundaryClass}: runtime probe target drift`);
    assert.equal(row.runtime_probe, expected.runtimeProbe, `${boundaryClass}: runtime probe name drift`);
    assert.equal(row.required_native_proof, expected.requiredNativeProof, `${boundaryClass}: runtime probe native proof drift`);
    assert.equal(row.opt_in_env, expected.optInEnv, `${boundaryClass}: runtime probe opt-in env drift`);
    assert.ok(["0", "1"].includes(row.runtime_ready), `${boundaryClass}: invalid runtime_ready`);
    assert.equal(row.source_proof_ready, "1", `${boundaryClass}: source proof must be ready before runtime probe`);
    assert.ok(
      [
        "skipped_missing_host_runtime",
        "ready_disabled_by_default",
        "not_implemented_full_process_guard",
        "runtime_state_probe_passed",
        "runtime_protocol_probe_passed",
        "runtime_lifecycle_probe_passed",
      ].includes(row.probe_status),
      `${boundaryClass}: invalid runtime probe status`,
    );
    if (row.runtime_ready === "0") {
      assert.equal(row.probe_status, "skipped_missing_host_runtime", `${boundaryClass}: non-ready runtime must skip`);
      assert.notEqual(row.missing_requirements, "-", `${boundaryClass}: non-ready runtime must record missing requirements`);
      assert.ok(row.probe_note.includes("missing_host_runtime"), `${boundaryClass}: missing-runtime note drift`);
    } else {
      assert.equal(row.missing_requirements, "-", `${boundaryClass}: ready runtime must not record missing requirements`);
    }
    if (row.probe_status === "ready_disabled_by_default") {
      assert.ok(
        row.probe_note.includes(`set_${row.opt_in_env.split("=")[0]}`),
        `${boundaryClass}: ready-disabled opt-in note drift`,
      );
    }
    if (row.probe_status.startsWith("runtime_") && row.probe_status.endsWith("_passed")) {
      assert.ok(row.probe_note.includes("without_promotion"), `${boundaryClass}: passed probe note drift`);
    }
    assert.notEqual(row.probe_note, "-", `${boundaryClass}: runtime probe note is required`);
    assert.equal(row.execution_enabled, "0", `${boundaryClass}: native runtime probe must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${boundaryClass}: native runtime probe must not allow promotion`);
    assert.notEqual(row.stdout_log, "-", `${boundaryClass}: runtime probe must reference stdout log`);
    assert.ok(
      existsSync(resolve(dirname(nativeRuntimeProbeSummarySourcePath), row.stdout_log)),
      `${boundaryClass}: runtime probe stdout log is missing`,
    );
  }

  return parsedRows.map((row) => expectedHeaders.map((header) => row[header]).map(tsvValue).join("\t"));
}

function verifyNativeRuntimeProbeSummaryRows(rows) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "runtime_probe",
    "required_native_proof",
    "opt_in_env",
    "runtime_ready",
    "source_proof_ready",
    "probe_status",
    "execution_enabled",
    "promotion_allowed",
    "missing_requirements",
    "probe_note",
    "stdout_log",
  ];
  return parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
}

function runtimeProbeGateAlignmentRows({
  nativeRuntimeProbeRows,
  userMRuntimeProbeGateRows,
  toolDbRuntimeProbeGateRows,
  pythonRuntimeProbeGateRows,
}) {
  const nativeByClass = new Map(
    nativeRuntimeProbeRows.map((row) => [row.boundary_class, row]),
  );
  const groups = [
    {
      boundaryClass: "L4-USER-M-PROCESS",
      boundaryKind: "external_user_m_process",
      target: "axis/vismach/millturn/example.ngc",
      gateArtifact: "user-m-process-native-runtime-probe-gate.tsv",
      gateRow: userMRuntimeProbeGateRows[0],
    },
    {
      boundaryClass: "L4-TOOL-DB",
      boundaryKind: "tool_database_process",
      target: "axis/db_demo/base.ngc",
      gateArtifact: "tool-db-process-native-runtime-probe-gate.tsv",
      gateRow: toolDbRuntimeProbeGateRows[0],
    },
    {
      boundaryClass: "L4-PYTHON-REMAP",
      boundaryKind: "python_runtime",
      target: "axis/remap/stop-lookahead/nc_files",
      gateArtifact: "python-remap-native-runtime-probe-gate.tsv",
      gateRow: pythonRuntimeProbeGateRows[0],
    },
  ];

  return groups.map((group) => {
    const nativeRow = nativeByClass.get(group.boundaryClass);
    const gateRow = group.gateRow;
    const gateMissing = uniqueSorted(splitSummaryList(gateRow?.missing_requirements ?? "-"));
    const nativeMissing = uniqueSorted(splitSummaryList(nativeRow?.missing_requirements ?? "-"));
    const runtimeReadyMatch = gateRow?.runtime_ready === nativeRow?.runtime_ready;
    const sourceProofReadyMatch = gateRow?.source_proof_ready === nativeRow?.source_proof_ready;
    const missingRequirementsMatch = gateMissing.join(",") === nativeMissing.join(",");
    const requiredNativeProofMatch = gateRow?.required_native_proof === nativeRow?.required_native_proof;
    const executionDisabledMatch = (
      gateRow?.execution_enabled === "0" &&
      nativeRow?.execution_enabled === "0"
    );
    const promotionDisabledMatch = (
      gateRow?.promotion_allowed === "0" &&
      nativeRow?.promotion_allowed === "0"
    );
    const statusCompatible = (
      (gateRow?.runtime_ready === "0" &&
        gateRow?.gate_status === "blocked_missing_host_runtime" &&
        nativeRow?.probe_status === "skipped_missing_host_runtime") ||
      (gateRow?.runtime_ready === "1" &&
        gateRow?.gate_status?.startsWith("ready_to_implement_") &&
        nativeRow?.probe_status === "ready_disabled_by_default") ||
      (gateRow?.runtime_ready === "1" &&
        gateRow?.gate_status?.startsWith("ready_to_implement_") &&
        nativeRow?.probe_status?.startsWith("runtime_") &&
        nativeRow?.probe_status?.endsWith("_passed"))
    );
    const alignmentOk = (
      nativeRow &&
      gateRow &&
      nativeRow.boundary_kind === group.boundaryKind &&
      nativeRow.target === group.target &&
      runtimeReadyMatch &&
      sourceProofReadyMatch &&
      requiredNativeProofMatch &&
      missingRequirementsMatch &&
      executionDisabledMatch &&
      promotionDisabledMatch &&
      statusCompatible
    );

    return [
      group.boundaryClass,
      group.boundaryKind,
      group.target,
      group.gateArtifact,
      nativeRow?.runtime_probe ?? "-",
      gateRow?.required_native_proof ?? "-",
      nativeRow?.required_native_proof ?? "-",
      nativeRow?.opt_in_env ?? "-",
      gateRow?.runtime_ready ?? "-",
      nativeRow?.runtime_ready ?? "-",
      gateRow?.source_proof_ready ?? "-",
      nativeRow?.source_proof_ready ?? "-",
      gateRow?.gate_status ?? "-",
      nativeRow?.probe_status ?? "-",
      listValue(gateMissing),
      listValue(nativeMissing),
      flagValue(requiredNativeProofMatch),
      flagValue(missingRequirementsMatch),
      flagValue(executionDisabledMatch),
      flagValue(promotionDisabledMatch),
      flagValue(statusCompatible),
      flagValue(alignmentOk),
      "runtime_probe_gate_and_native_summary_must_agree_before_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyRuntimeProbeGateAlignmentRows(rows) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "gate_artifact",
    "native_runtime_probe",
    "gate_required_native_proof",
    "native_required_native_proof",
    "native_opt_in_env",
    "gate_runtime_ready",
    "native_runtime_ready",
    "gate_source_proof_ready",
    "native_source_proof_ready",
    "gate_status",
    "native_probe_status",
    "gate_missing_requirements",
    "native_missing_requirements",
    "required_native_proof_match",
    "missing_requirements_match",
    "execution_disabled_match",
    "promotion_disabled_match",
    "status_compatible",
    "alignment_ok",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expected = [
    ["L4-USER-M-PROCESS", "external_user_m_process", "axis/vismach/millturn/example.ngc"],
    ["L4-TOOL-DB", "tool_database_process", "axis/db_demo/base.ngc"],
    ["L4-PYTHON-REMAP", "python_runtime", "axis/remap/stop-lookahead/nc_files"],
  ];

  assert.equal(parsedRows.length, expected.length, "runtime probe gate alignment row count drift");
  assert.deepEqual(
    parsedRows.map((row) => [row.boundary_class, row.boundary_kind, row.target]),
    expected,
    "runtime probe gate alignment identity drift",
  );

  for (const row of parsedRows) {
    assert.ok(row.gate_artifact.endsWith(".tsv"), `${row.target}: missing gate artifact`);
    assert.notEqual(row.native_runtime_probe, "-", `${row.target}: missing native runtime probe`);
    assert.equal(row.required_native_proof_match, "1", `${row.target}: required native proof drift`);
    assert.notEqual(row.native_required_native_proof, "-", `${row.target}: missing native proof requirement`);
    assert.match(row.native_opt_in_env, /^ENABLE_[A-Z0-9_]+=1$/, `${row.target}: invalid native opt-in env`);
    assert.equal(row.gate_runtime_ready, row.native_runtime_ready, `${row.target}: runtime readiness drift`);
    assert.equal(row.gate_source_proof_ready, "1", `${row.target}: gate source proof must be ready`);
    assert.equal(row.native_source_proof_ready, "1", `${row.target}: native source proof must be ready`);
    assert.equal(row.missing_requirements_match, "1", `${row.target}: missing requirements drift`);
    assert.equal(row.execution_disabled_match, "1", `${row.target}: execution disabled drift`);
    assert.equal(row.promotion_disabled_match, "1", `${row.target}: promotion disabled drift`);
    assert.equal(row.status_compatible, "1", `${row.target}: native/gate status incompatibility`);
    assert.equal(row.alignment_ok, "1", `${row.target}: runtime probe gate alignment failed`);
    assert.ok(row.notes.includes("before_promotion"), `${row.target}: alignment notes drift`);
  }

  return parsedRows;
}

function verifyNativeSourceProofRuntimeProbeConsistency({
  nativeProofAlignmentRows,
  nativeRuntimeProbeRows,
  runtimeProbeGateAlignmentRows,
}) {
  const expectedClasses = [
    "L4-USER-M-PROCESS",
    "L4-TOOL-DB",
    "L4-PYTHON-REMAP",
  ];
  const proofByClass = new Map(nativeProofAlignmentRows.map((row) => [row.boundary_class, row]));
  const runtimeByClass = new Map(nativeRuntimeProbeRows.map((row) => [row.boundary_class, row]));
  const gateAlignmentByClass = new Map(runtimeProbeGateAlignmentRows.map((row) => [row.boundary_class, row]));

  assert.deepEqual(
    nativeProofAlignmentRows.map((row) => row.boundary_class),
    expectedClasses,
    "native source proof alignment class order drift",
  );
  assert.deepEqual(
    nativeRuntimeProbeRows.map((row) => row.boundary_class),
    expectedClasses,
    "native runtime probe source-proof class order drift",
  );
  assert.deepEqual(
    runtimeProbeGateAlignmentRows.map((row) => row.boundary_class),
    expectedClasses,
    "runtime probe gate source-proof class order drift",
  );

  for (const boundaryClass of expectedClasses) {
    const proof = proofByClass.get(boundaryClass);
    const runtime = runtimeByClass.get(boundaryClass);
    const gateAlignment = gateAlignmentByClass.get(boundaryClass);

    assert.ok(proof, `${boundaryClass}: missing native source proof alignment row`);
    assert.ok(runtime, `${boundaryClass}: missing native runtime probe row`);
    assert.ok(gateAlignment, `${boundaryClass}: missing runtime probe gate alignment row`);
    assert.equal(runtime.boundary_kind, proof.boundary_kind, `${boundaryClass}: native proof/runtime kind drift`);
    if (proof.target !== "*") {
      assert.equal(runtime.target, proof.target, `${boundaryClass}: native proof/runtime target drift`);
    }
    assert.equal(gateAlignment.boundary_kind, runtime.boundary_kind, `${boundaryClass}: gate/runtime kind drift`);
    assert.equal(gateAlignment.target, runtime.target, `${boundaryClass}: gate/runtime target drift`);
    assert.equal(proof.alignment_ok, "1", `${boundaryClass}: native source proof must align before runtime probe`);
    assert.equal(proof.execution_enabled, "0", `${boundaryClass}: native source proof must not enable execution`);
    assert.equal(proof.promotion_allowed, "0", `${boundaryClass}: native source proof must not allow promotion`);
    assert.equal(runtime.source_proof_ready, proof.alignment_ok, `${boundaryClass}: runtime source proof readiness drift`);
    assert.equal(gateAlignment.native_source_proof_ready, proof.alignment_ok, `${boundaryClass}: native gate source proof readiness drift`);
    assert.equal(gateAlignment.gate_source_proof_ready, proof.alignment_ok, `${boundaryClass}: generated gate source proof readiness drift`);
    assert.equal(runtime.execution_enabled, "0", `${boundaryClass}: native runtime probe must not enable execution`);
    assert.equal(runtime.promotion_allowed, "0", `${boundaryClass}: native runtime probe must not allow promotion`);
    assert.equal(gateAlignment.execution_disabled_match, "1", `${boundaryClass}: runtime gate execution-disabled alignment drift`);
    assert.equal(gateAlignment.promotion_disabled_match, "1", `${boundaryClass}: runtime gate promotion-disabled alignment drift`);
    assert.equal(gateAlignment.alignment_ok, "1", `${boundaryClass}: runtime probe gate alignment must pass`);
  }
}

function nativeRuntimeProbeExecutionPlanRows({
  nativeRuntimeProbeRows,
  runtimeProbeGateAlignmentRows,
}) {
  const alignmentByClass = new Map(
    runtimeProbeGateAlignmentRows.map((row) => [row.boundary_class, row]),
  );
  const scriptByProbe = new Map([
    [
      "linuxcnc_millturn_user_m_runtime_probe",
      "wasm-port/tests/native/probe_millturn_user_m_runtime.sh",
    ],
    [
      "linuxcnc_tool_db_runtime_probe",
      "wasm-port/tests/native/probe_tool_db_runtime.sh",
    ],
    [
      "linuxcnc_python_remap_runtime_probe",
      "wasm-port/tests/native/probe_python_remap_runtime.sh",
    ],
  ]);
  const expectedPassStatusByClass = new Map([
    ["L4-USER-M-PROCESS", "runtime_state_probe_passed"],
    ["L4-TOOL-DB", "runtime_protocol_probe_passed"],
    ["L4-PYTHON-REMAP", "runtime_lifecycle_probe_passed"],
  ]);

  return nativeRuntimeProbeRows.map((row) => {
    const alignment = alignmentByClass.get(row.boundary_class);
    const script = scriptByProbe.get(row.runtime_probe) ?? "-";
    const expectedPassStatus = expectedPassStatusByClass.get(row.boundary_class) ?? "-";
    const optInName = row.opt_in_env.split("=")[0] ?? row.opt_in_env;
    const planStatus = row.probe_status === expectedPassStatus
      ? "native_probe_passed_waiting_for_node_browser_promotion_proof"
      : row.runtime_ready === "1"
        ? "ready_to_run_opt_in_probe"
        : "blocked_missing_host_runtime";

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.runtime_probe,
      row.required_native_proof,
      row.opt_in_env,
      `${row.opt_in_env} bash ${script}`,
      row.runtime_ready,
      row.source_proof_ready,
      row.probe_status,
      expectedPassStatus,
      row.missing_requirements,
      alignment?.alignment_ok ?? "0",
      listValue([
        `native:${expectedPassStatus}`,
        "node:inventory_gate_alignment_after_native_pass",
        "browser:smoke_gate_alignment_after_node_pass",
        "manual:promotion_lock_update_required",
      ]),
      "0",
      "0",
      planStatus,
      `set_${optInName}_only_after_runtime_ready_no_automatic_promotion`,
    ].map(tsvValue).join("\t");
  });
}

function verifyNativeRuntimeProbeExecutionPlanRows({
  rows,
  nativeRuntimeProbeRows,
  runtimeProbeGateAlignmentRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "runtime_probe",
    "required_native_proof",
    "opt_in_env",
    "execution_command",
    "runtime_ready",
    "source_proof_ready",
    "current_probe_status",
    "expected_pass_status",
    "missing_requirements",
    "gate_alignment_ok",
    "promotion_requires",
    "execution_enabled",
    "promotion_allowed",
    "plan_status",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expected = new Map([
    [
      "L4-USER-M-PROCESS",
      {
        boundaryKind: "external_user_m_process",
        target: "axis/vismach/millturn/example.ngc",
        runtimeProbe: "linuxcnc_millturn_user_m_runtime_probe",
        requiredNativeProof: "native_runtime_state_probe_required",
        optInEnv: "ENABLE_MILLTURN_USER_M_RUNTIME_PROBE=1",
        script: "wasm-port/tests/native/probe_millturn_user_m_runtime.sh",
        expectedPassStatus: "runtime_state_probe_passed",
      },
    ],
    [
      "L4-TOOL-DB",
      {
        boundaryKind: "tool_database_process",
        target: "axis/db_demo/base.ngc",
        runtimeProbe: "linuxcnc_tool_db_runtime_probe",
        requiredNativeProof: "native_db_process_protocol_probe_required",
        optInEnv: "ENABLE_TOOL_DB_RUNTIME_PROBE=1",
        script: "wasm-port/tests/native/probe_tool_db_runtime.sh",
        expectedPassStatus: "runtime_protocol_probe_passed",
      },
    ],
    [
      "L4-PYTHON-REMAP",
      {
        boundaryKind: "python_runtime",
        target: "axis/remap/stop-lookahead/nc_files",
        runtimeProbe: "linuxcnc_python_remap_runtime_probe",
        requiredNativeProof: "linuxcnc_python_runtime_lifecycle_probe_required",
        optInEnv: "ENABLE_PYTHON_REMAP_RUNTIME_PROBE=1",
        script: "wasm-port/tests/native/probe_python_remap_runtime.sh",
        expectedPassStatus: "runtime_lifecycle_probe_passed",
      },
    ],
  ]);
  const nativeByClass = new Map(nativeRuntimeProbeRows.map((row) => [row.boundary_class, row]));
  const alignmentByClass = new Map(runtimeProbeGateAlignmentRows.map((row) => [row.boundary_class, row]));

  assert.equal(parsedRows.length, expected.size, "native runtime probe execution plan row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    [...expected.keys()],
    "native runtime probe execution plan order drift",
  );

  for (const row of parsedRows) {
    const expectedRow = expected.get(row.boundary_class);
    const nativeRow = nativeByClass.get(row.boundary_class);
    const alignmentRow = alignmentByClass.get(row.boundary_class);

    assert.ok(expectedRow, `${row.boundary_class}: unexpected execution plan row`);
    assert.ok(nativeRow, `${row.boundary_class}: execution plan lacks native summary row`);
    assert.ok(alignmentRow, `${row.boundary_class}: execution plan lacks gate alignment row`);
    assert.equal(row.boundary_kind, expectedRow.boundaryKind, `${row.boundary_class}: execution plan kind drift`);
    assert.equal(row.target, expectedRow.target, `${row.boundary_class}: execution plan target drift`);
    assert.equal(row.runtime_probe, expectedRow.runtimeProbe, `${row.boundary_class}: execution plan probe drift`);
    assert.equal(row.required_native_proof, expectedRow.requiredNativeProof, `${row.boundary_class}: execution plan proof drift`);
    assert.equal(row.opt_in_env, expectedRow.optInEnv, `${row.boundary_class}: execution plan opt-in drift`);
    assert.equal(row.expected_pass_status, expectedRow.expectedPassStatus, `${row.boundary_class}: expected pass status drift`);
    assert.equal(row.execution_command, `${expectedRow.optInEnv} bash ${expectedRow.script}`, `${row.boundary_class}: execution command drift`);
    assert.equal(row.runtime_ready, nativeRow.runtime_ready, `${row.boundary_class}: runtime readiness drift`);
    assert.equal(row.source_proof_ready, nativeRow.source_proof_ready, `${row.boundary_class}: source proof readiness drift`);
    assert.equal(row.current_probe_status, nativeRow.probe_status, `${row.boundary_class}: current probe status drift`);
    assert.equal(row.missing_requirements, nativeRow.missing_requirements, `${row.boundary_class}: missing requirements drift`);
    assert.equal(row.gate_alignment_ok, alignmentRow.alignment_ok, `${row.boundary_class}: gate alignment drift`);
    assert.equal(row.gate_alignment_ok, "1", `${row.boundary_class}: gate alignment must be ready before opt-in probe`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: execution plan must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: execution plan must not allow promotion`);
    for (const required of [
      `native:${expectedRow.expectedPassStatus}`,
      "node:inventory_gate_alignment_after_native_pass",
      "browser:smoke_gate_alignment_after_node_pass",
      "manual:promotion_lock_update_required",
    ]) {
      assert.ok(row.promotion_requires.includes(required), `${row.boundary_class}: promotion requirement ${required} missing`);
    }
    if (row.current_probe_status === row.expected_pass_status) {
      assert.equal(
        row.plan_status,
        "native_probe_passed_waiting_for_node_browser_promotion_proof",
        `${row.boundary_class}: passed probe plan status drift`,
      );
    } else if (row.runtime_ready === "1") {
      assert.equal(row.plan_status, "ready_to_run_opt_in_probe", `${row.boundary_class}: ready plan status drift`);
      assert.equal(row.missing_requirements, "-", `${row.boundary_class}: ready plan must not list missing requirements`);
    } else {
      assert.equal(row.plan_status, "blocked_missing_host_runtime", `${row.boundary_class}: missing-runtime plan status drift`);
      assert.notEqual(row.missing_requirements, "-", `${row.boundary_class}: missing-runtime plan must list requirements`);
    }
    assert.ok(row.notes.includes("no_automatic_promotion"), `${row.boundary_class}: execution plan note drift`);
  }

  return parsedRows;
}

function nativeRuntimeProbePassEvidenceContractRows({
  nativeRuntimeProbeRows,
  executionPlanRows,
}) {
  const planByClass = new Map(executionPlanRows.map((row) => [row.boundary_class, row]));
  const expectedEvidenceByClass = new Map([
    [
      "L4-USER-M-PROCESS",
      [
        "millturn_user_m_runtime_probe_status=runtime_state_probe_passed",
        "millturn_user_m_M128_switchkins_target_ready=1",
        "millturn_user_m_M128_runtime_state_ok=1",
        "millturn_user_m_M129_switchkins_target_ready=1",
        "millturn_user_m_M129_runtime_state_ok=1",
      ],
    ],
    [
      "L4-TOOL-DB",
      [
        "tool_db_runtime_probe_status=runtime_protocol_probe_passed",
        "tool_db_protocol_version=v2.1",
        "tool_db_get_all_count=10",
        "tool_db_get_all_fini=1",
        "tool_db_put_tool_update_state_ok=1",
        "tool_db_load_spindle_state_ok=1",
        "tool_db_unload_spindle_state_ok=1",
        "tool_db_persistence_state_ok=1",
        "tool_db_runtime_protocol_probe_ok=1",
      ],
    ],
    [
      "L4-PYTHON-REMAP",
      [
        "python_remap_runtime_probe_status=runtime_lifecycle_probe_passed",
        "python_remap_lifecycle_interpreter_sentinel_ok=1",
        "python_remap_lifecycle_toplevel_imported=1",
        "python_remap_lifecycle_remap_imported=1",
        "python_remap_lifecycle_callable_lookup_ok=1",
        "python_remap_lifecycle_generator_returned=1",
        "python_remap_lifecycle_generator_first_yield=2",
        "python_remap_lifecycle_generator_finish_ok=1",
        "python_remap_runtime_lifecycle_probe_ok=1",
      ],
    ],
  ]);

  return nativeRuntimeProbeRows.map((row) => {
    const plan = planByClass.get(row.boundary_class);
    const expectedEvidence = expectedEvidenceByClass.get(row.boundary_class) ?? [];
    const stdoutPath = resolve(dirname(nativeRuntimeProbeSummarySourcePath), row.stdout_log);
    const stdoutText = existsSync(stdoutPath) ? readFileSync(stdoutPath, "utf8") : "";
    const evidenceRequiredNow = row.probe_status === plan?.expected_pass_status;
    const missingEvidence = evidenceRequiredNow
      ? expectedEvidence.filter((evidence) => !stdoutText.includes(evidence))
      : [];
    const observedEvidenceReady = evidenceRequiredNow && missingEvidence.length === 0;
    const evidenceStatus = evidenceRequiredNow
      ? observedEvidenceReady
        ? "native_pass_evidence_observed"
        : "native_pass_evidence_missing"
      : "pending_until_native_pass";

    return [
      row.boundary_class,
      row.boundary_kind,
      row.target,
      row.runtime_probe,
      plan?.expected_pass_status ?? "-",
      row.stdout_log,
      listValue(expectedEvidence),
      row.probe_status,
      flagValue(evidenceRequiredNow),
      flagValue(observedEvidenceReady),
      listValue(missingEvidence),
      row.execution_enabled,
      row.promotion_allowed,
      evidenceStatus,
      evidenceRequiredNow
        ? "native_pass_stdout_evidence_required_before_node_browser_promotion"
        : "contract_only_not_evaluated_until_native_pass_no_automatic_promotion",
    ].map(tsvValue).join("\t");
  });
}

function verifyNativeRuntimeProbePassEvidenceContractRows({
  rows,
  nativeRuntimeProbeRows,
  executionPlanRows,
}) {
  const expectedHeaders = [
    "boundary_class",
    "boundary_kind",
    "target",
    "runtime_probe",
    "expected_pass_status",
    "stdout_log",
    "expected_evidence_keys",
    "current_probe_status",
    "evidence_required_now",
    "observed_evidence_ready",
    "missing_evidence_keys",
    "execution_enabled",
    "promotion_allowed",
    "evidence_status",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expected = new Map([
    [
      "L4-USER-M-PROCESS",
      {
        boundaryKind: "external_user_m_process",
        target: "axis/vismach/millturn/example.ngc",
        runtimeProbe: "linuxcnc_millturn_user_m_runtime_probe",
        expectedPassStatus: "runtime_state_probe_passed",
        evidence: [
          "millturn_user_m_runtime_probe_status=runtime_state_probe_passed",
          "millturn_user_m_M128_runtime_state_ok=1",
          "millturn_user_m_M129_runtime_state_ok=1",
        ],
      },
    ],
    [
      "L4-TOOL-DB",
      {
        boundaryKind: "tool_database_process",
        target: "axis/db_demo/base.ngc",
        runtimeProbe: "linuxcnc_tool_db_runtime_probe",
        expectedPassStatus: "runtime_protocol_probe_passed",
        evidence: [
          "tool_db_runtime_probe_status=runtime_protocol_probe_passed",
          "tool_db_protocol_version=v2.1",
          "tool_db_runtime_protocol_probe_ok=1",
          "tool_db_persistence_state_ok=1",
        ],
      },
    ],
    [
      "L4-PYTHON-REMAP",
      {
        boundaryKind: "python_runtime",
        target: "axis/remap/stop-lookahead/nc_files",
        runtimeProbe: "linuxcnc_python_remap_runtime_probe",
        expectedPassStatus: "runtime_lifecycle_probe_passed",
        evidence: [
          "python_remap_runtime_probe_status=runtime_lifecycle_probe_passed",
          "python_remap_lifecycle_generator_first_yield=2",
          "python_remap_runtime_lifecycle_probe_ok=1",
        ],
      },
    ],
  ]);
  const nativeByClass = new Map(nativeRuntimeProbeRows.map((row) => [row.boundary_class, row]));
  const planByClass = new Map(executionPlanRows.map((row) => [row.boundary_class, row]));

  assert.equal(parsedRows.length, expected.size, "native runtime pass evidence contract row count drift");
  assert.deepEqual(
    parsedRows.map((row) => row.boundary_class),
    [...expected.keys()],
    "native runtime pass evidence contract order drift",
  );

  for (const row of parsedRows) {
    const expectedRow = expected.get(row.boundary_class);
    const nativeRow = nativeByClass.get(row.boundary_class);
    const planRow = planByClass.get(row.boundary_class);
    assert.ok(expectedRow, `${row.boundary_class}: unexpected pass evidence contract row`);
    assert.ok(nativeRow, `${row.boundary_class}: pass evidence contract lacks native summary row`);
    assert.ok(planRow, `${row.boundary_class}: pass evidence contract lacks execution plan row`);
    assert.equal(row.boundary_kind, expectedRow.boundaryKind, `${row.boundary_class}: pass evidence kind drift`);
    assert.equal(row.target, expectedRow.target, `${row.boundary_class}: pass evidence target drift`);
    assert.equal(row.runtime_probe, expectedRow.runtimeProbe, `${row.boundary_class}: pass evidence probe drift`);
    assert.equal(row.expected_pass_status, expectedRow.expectedPassStatus, `${row.boundary_class}: pass evidence status drift`);
    assert.equal(row.expected_pass_status, planRow.expected_pass_status, `${row.boundary_class}: pass evidence execution plan drift`);
    assert.equal(row.stdout_log, nativeRow.stdout_log, `${row.boundary_class}: pass evidence stdout drift`);
    assert.equal(row.current_probe_status, nativeRow.probe_status, `${row.boundary_class}: pass evidence current status drift`);
    assert.equal(row.execution_enabled, "0", `${row.boundary_class}: pass evidence contract must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.boundary_class}: pass evidence contract must not allow promotion`);
    assert.notEqual(row.expected_evidence_keys, "-", `${row.boundary_class}: pass evidence contract lacks keys`);
    for (const evidence of expectedRow.evidence) {
      assert.ok(row.expected_evidence_keys.includes(evidence), `${row.boundary_class}: missing pass evidence ${evidence}`);
    }
    if (row.current_probe_status === row.expected_pass_status) {
      assert.equal(row.evidence_required_now, "1", `${row.boundary_class}: pass evidence should be required`);
      assert.equal(row.observed_evidence_ready, "1", `${row.boundary_class}: pass evidence must be observed after native pass`);
      assert.equal(row.missing_evidence_keys, "-", `${row.boundary_class}: pass evidence should have no missing keys`);
      assert.equal(row.evidence_status, "native_pass_evidence_observed", `${row.boundary_class}: pass evidence status drift`);
    } else {
      assert.equal(row.evidence_required_now, "0", `${row.boundary_class}: pass evidence must wait for native pass`);
      assert.equal(row.observed_evidence_ready, "0", `${row.boundary_class}: pending pass evidence must not be marked ready`);
      assert.equal(row.missing_evidence_keys, "-", `${row.boundary_class}: pending pass evidence must not report missing keys`);
      assert.equal(row.evidence_status, "pending_until_native_pass", `${row.boundary_class}: pending pass evidence status drift`);
    }
    assert.ok(
      row.notes.includes("no_automatic_promotion") || row.notes.includes("before_node_browser_promotion"),
      `${row.boundary_class}: pass evidence contract note drift`,
    );
  }

  return parsedRows;
}

function keyValuesFromText(text) {
  const values = new Map();
  for (const line of text.split("\n")) {
    const equals = line.indexOf("=");
    if (equals === -1) {
      continue;
    }
    values.set(line.slice(0, equals).trim(), line.slice(equals + 1).trim());
  }
  return values;
}

function userMNativeFieldForTarget(row) {
  const targetSuffix = row.target_pin.split(".").pop();
  if (targetSuffix === "min_velocity") {
    return "MAX_VELOCITY";
  }
  if (targetSuffix === "max_acceleration") {
    return "MAX_ACCELERATION";
  }
  if (targetSuffix === "min_limit") {
    return row.source_field === "MIN_LIMIT_TURN/MAX_LIMIT_TURN" ? "MIN_LIMIT_TURN" : "MIN_LIMIT";
  }
  if (targetSuffix === "max_limit") {
    return row.source_field === "MIN_LIMIT_TURN/MAX_LIMIT_TURN" ? "MAX_LIMIT_TURN" : "MAX_LIMIT";
  }
  return "";
}

function userMProcessNativeStateAlignmentRows(stateTargetRows) {
  const nativeProofUnavailableRows = () => stateTargetRows.map((row) => [
    row.path,
    row.ini,
    row.blocked,
    row.user_m_code,
    row.target_pin,
    row.source_section,
    row.source_field,
    row.expected_value,
    "0",
    "-",
    "-",
    "-",
    "-",
    "-",
    "-",
    "0",
    row.execution_enabled,
    row.promotion_allowed,
    "pending",
    "native_user_m_probe_stdout_unavailable",
  ].map(tsvValue).join("\t"));

  if (!existsSync(nativeSourceProofSummaryPath)) {
    return nativeProofUnavailableRows();
  }

  const nativeProofRows = parseTsv(
    readFileSync(nativeSourceProofSummaryPath, "utf8"),
    [
      "boundary_class",
      "proof_key",
      "proof_value",
      "execution_enabled",
      "promotion_allowed",
      "stdout_log",
    ],
  );
  const userMProof = nativeProofRows.find((row) => row.boundary_class === "L4-USER-M-PROCESS");
  if (!userMProof?.stdout_log) {
    return nativeProofUnavailableRows();
  }

  const stdoutPath = resolve(dirname(nativeSourceProofSummaryPath), userMProof.stdout_log);
  if (!existsSync(stdoutPath)) {
    return nativeProofUnavailableRows();
  }

  const stdoutValues = keyValuesFromText(readFileSync(stdoutPath, "utf8"));
  return stateTargetRows.map((row) => {
    const axis = row.source_section.slice("AXIS_".length);
    const nativeField = userMNativeFieldForTarget(row);
    const nativeValueKey = `${row.user_m_code}_${axis}_${row.source_section}.${nativeField}`;
    const nativeOkKey = `${nativeValueKey}_ok`;
    const sourceProofKey = `${row.user_m_code}_source_state_targets_from_linuxcnc`;
    const nativeValue = stdoutValues.get(nativeValueKey) ?? "-";
    const nativeOkValue = stdoutValues.get(nativeOkKey) ?? "-";
    const sourceProofValue = stdoutValues.get(sourceProofKey) ?? "-";
    const aligned = (
      userMProof.proof_key === "millturn_user_m_native_source_state_proof" &&
      userMProof.proof_value === "1" &&
      userMProof.execution_enabled === "0" &&
      userMProof.promotion_allowed === "0" &&
      nativeField !== "" &&
      nativeValue === row.expected_value &&
      nativeOkValue === "1" &&
      sourceProofValue === "1" &&
      row.execution_enabled === "0" &&
      row.promotion_allowed === "0"
    );

    return [
      row.path,
      row.ini,
      row.blocked,
      row.user_m_code,
      row.target_pin,
      row.source_section,
      row.source_field,
      row.expected_value,
      "1",
      nativeValueKey,
      nativeValue,
      nativeOkKey,
      nativeOkValue,
      sourceProofKey,
      sourceProofValue,
      flagValue(aligned),
      row.execution_enabled,
      row.promotion_allowed,
      "pending",
      "native_source_target_alignment_only_no_process_execution",
    ].map(tsvValue).join("\t");
  });
}

function verifyUserMProcessNativeStateAlignmentRows(rows, stateTargetRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "user_m_code",
    "target_pin",
    "source_section",
    "source_field",
    "expected_value",
    "native_stdout_available",
    "native_value_key",
    "native_value",
    "native_ok_key",
    "native_ok_value",
    "source_proof_key",
    "source_proof_value",
    "alignment_ok",
    "execution_enabled",
    "promotion_allowed",
    "proof_status",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_user_m_process_native_state_alignment",
    stateTargetRows.map((row) => `${row.path}:${row.user_m_code}:${row.target_pin}`).sort(),
    parsedRows.map((row) => `${row.path}:${row.user_m_code}:${row.target_pin}`).sort(),
  );
  assert.equal(parsedRows.length, 24, "user-M native state alignment must cover every generated state target");

  const stdoutAvailable = parsedRows.some((row) => row.native_stdout_available === "1");
  if (!stdoutAvailable) {
    for (const row of parsedRows) {
      assert.equal(row.native_stdout_available, "0", `${row.target_pin}: mixed native stdout availability`);
      assert.equal(row.alignment_ok, "0", `${row.target_pin}: unavailable native stdout cannot align`);
      assert.equal(row.execution_enabled, "0", `${row.target_pin}: alignment must not enable execution`);
      assert.equal(row.promotion_allowed, "0", `${row.target_pin}: alignment must not allow promotion`);
      assert.equal(row.proof_status, "pending", `${row.target_pin}: proof must remain pending`);
    }
    return parsedRows;
  }

  for (const row of parsedRows) {
    assert.equal(row.native_stdout_available, "1", `${row.target_pin}: native stdout must be available`);
    assert.ok(["M128", "M129"].includes(row.user_m_code), `${row.target_pin}: unexpected user-M code`);
    assert.ok(/^ini\.[xyz]\.(min_limit|max_limit|min_velocity|max_acceleration)$/.test(row.target_pin), `${row.target_pin}: invalid target pin`);
    assert.ok(row.native_value_key.startsWith(`${row.user_m_code}_`), `${row.target_pin}: native value key code drift`);
    assert.ok(row.native_ok_key.endsWith("_ok"), `${row.target_pin}: native ok key drift`);
    assert.equal(row.native_ok_value, "1", `${row.target_pin}: native ok value drift`);
    assert.equal(row.native_value, row.expected_value, `${row.target_pin}: native value does not match generated target`);
    assert.equal(row.source_proof_value, "1", `${row.target_pin}: source state proof missing`);
    assert.equal(row.alignment_ok, "1", `${row.target_pin}: native target alignment failed`);
    assert.equal(row.execution_enabled, "0", `${row.target_pin}: alignment must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.target_pin}: alignment must not allow promotion`);
    assert.equal(row.proof_status, "pending", `${row.target_pin}: proof must remain pending`);
    assert.ok(
      row.notes.includes("no_process_execution"),
      `${row.target_pin}: alignment row must remain non-executing`,
    );
  }

  return parsedRows;
}

function userMProcessNativeTransitionAlignmentRows(transitionRows) {
  const nativeProofUnavailableRows = () => transitionRows.map((row) => [
    row.path,
    row.ini,
    row.blocked,
    row.remap_code,
    row.user_m_code,
    row.switchkins_output_pin,
    row.switchkins_target,
    row.active_g5x,
    row.work_offset_pocket,
    "0",
    "-",
    "-",
    "-",
    "-",
    "-",
    "-",
    "-",
    "-",
    "0",
    row.execution_enabled,
    row.promotion_allowed,
    "pending",
    "native_user_m_probe_stdout_unavailable",
  ].map(tsvValue).join("\t"));

  if (!existsSync(nativeSourceProofSummaryPath)) {
    return nativeProofUnavailableRows();
  }

  const nativeProofRows = parseTsv(
    readFileSync(nativeSourceProofSummaryPath, "utf8"),
    [
      "boundary_class",
      "proof_key",
      "proof_value",
      "execution_enabled",
      "promotion_allowed",
      "stdout_log",
    ],
  );
  const userMProof = nativeProofRows.find((row) => row.boundary_class === "L4-USER-M-PROCESS");
  if (!userMProof?.stdout_log) {
    return nativeProofUnavailableRows();
  }

  const stdoutPath = resolve(dirname(nativeSourceProofSummaryPath), userMProof.stdout_log);
  if (!existsSync(stdoutPath)) {
    return nativeProofUnavailableRows();
  }

  const stdoutValues = keyValuesFromText(readFileSync(stdoutPath, "utf8"));
  return transitionRows.map((row) => {
    const callKey = `${row.remap_code}_calls_${row.user_m_code}`;
    const transitionKey = `${row.remap_code}_source_transition_from_linuxcnc`;
    const nativeOutputPin = stdoutValues.get(`${row.remap_code}_switchkins_output_pin`) ?? "-";
    const nativeTarget = stdoutValues.get(`${row.remap_code}_switchkins_target`) ?? "-";
    const nativeActiveG5x = stdoutValues.get(`${row.remap_code}_active_g5x`) ?? "-";
    const nativePocket = stdoutValues.get(`${row.remap_code}_work_offset_pocket`) ?? "-";
    const callValue = stdoutValues.get(callKey) ?? "-";
    const transitionValue = stdoutValues.get(transitionKey) ?? "-";
    const aligned = (
      userMProof.proof_key === "millturn_user_m_native_source_state_proof" &&
      userMProof.proof_value === "1" &&
      userMProof.execution_enabled === "0" &&
      userMProof.promotion_allowed === "0" &&
      nativeOutputPin === row.switchkins_output_pin &&
      nativeTarget === row.switchkins_target &&
      nativeActiveG5x === row.active_g5x &&
      nativePocket === row.work_offset_pocket &&
      callValue === "1" &&
      transitionValue === "1" &&
      row.execution_enabled === "0" &&
      row.promotion_allowed === "0"
    );

    return [
      row.path,
      row.ini,
      row.blocked,
      row.remap_code,
      row.user_m_code,
      row.switchkins_output_pin,
      row.switchkins_target,
      row.active_g5x,
      row.work_offset_pocket,
      "1",
      nativeOutputPin,
      nativeTarget,
      nativeActiveG5x,
      nativePocket,
      callKey,
      callValue,
      transitionKey,
      transitionValue,
      flagValue(aligned),
      row.execution_enabled,
      row.promotion_allowed,
      "pending",
      "native_source_transition_alignment_only_no_process_execution",
    ].map(tsvValue).join("\t");
  });
}

function verifyUserMProcessNativeTransitionAlignmentRows(rows, transitionRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "remap_code",
    "user_m_code",
    "switchkins_output_pin",
    "switchkins_target",
    "active_g5x",
    "work_offset_pocket",
    "native_stdout_available",
    "native_switchkins_output_pin",
    "native_switchkins_target",
    "native_active_g5x",
    "native_work_offset_pocket",
    "native_call_key",
    "native_call_value",
    "native_transition_key",
    "native_transition_value",
    "alignment_ok",
    "execution_enabled",
    "promotion_allowed",
    "proof_status",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_user_m_process_native_transition_alignment",
    transitionRows.map((row) => `${row.path}:${row.remap_code}:${row.user_m_code}`).sort(),
    parsedRows.map((row) => `${row.path}:${row.remap_code}:${row.user_m_code}`).sort(),
  );
  assert.equal(parsedRows.length, 2, "user-M native transition alignment must cover M428/M429");

  const expectedByRemap = new Map([
    ["M428", { userMCode: "M128", target: "0", g5x: "G59.1", pocket: "P7" }],
    ["M429", { userMCode: "M129", target: "1", g5x: "G59.2", pocket: "P8" }],
  ]);
  const stdoutAvailable = parsedRows.some((row) => row.native_stdout_available === "1");
  if (!stdoutAvailable) {
    for (const row of parsedRows) {
      assert.equal(row.native_stdout_available, "0", `${row.remap_code}: mixed native stdout availability`);
      assert.equal(row.alignment_ok, "0", `${row.remap_code}: unavailable native stdout cannot align`);
      assert.equal(row.execution_enabled, "0", `${row.remap_code}: transition alignment must not enable execution`);
      assert.equal(row.promotion_allowed, "0", `${row.remap_code}: transition alignment must not allow promotion`);
      assert.equal(row.proof_status, "pending", `${row.remap_code}: transition proof must remain pending`);
    }
    return parsedRows;
  }

  for (const row of parsedRows) {
    const expected = expectedByRemap.get(row.remap_code);
    assert.ok(expected, `${row.remap_code}: unexpected remap code`);
    assert.equal(row.native_stdout_available, "1", `${row.remap_code}: native stdout must be available`);
    assert.equal(row.user_m_code, expected.userMCode, `${row.remap_code}: user-M call drift`);
    assert.equal(row.switchkins_output_pin, "motion.analog-out-03", `${row.remap_code}: output pin drift`);
    assert.equal(row.switchkins_target, expected.target, `${row.remap_code}: target drift`);
    assert.equal(row.active_g5x, expected.g5x, `${row.remap_code}: G5x drift`);
    assert.equal(row.work_offset_pocket, expected.pocket, `${row.remap_code}: work offset pocket drift`);
    assert.equal(row.native_switchkins_output_pin, row.switchkins_output_pin, `${row.remap_code}: native output pin mismatch`);
    assert.equal(row.native_switchkins_target, row.switchkins_target, `${row.remap_code}: native target mismatch`);
    assert.equal(row.native_active_g5x, row.active_g5x, `${row.remap_code}: native G5x mismatch`);
    assert.equal(row.native_work_offset_pocket, row.work_offset_pocket, `${row.remap_code}: native pocket mismatch`);
    assert.equal(row.native_call_key, `${row.remap_code}_calls_${row.user_m_code}`, `${row.remap_code}: call key drift`);
    assert.equal(row.native_call_value, "1", `${row.remap_code}: call proof missing`);
    assert.equal(row.native_transition_key, `${row.remap_code}_source_transition_from_linuxcnc`, `${row.remap_code}: transition key drift`);
    assert.equal(row.native_transition_value, "1", `${row.remap_code}: transition proof missing`);
    assert.equal(row.alignment_ok, "1", `${row.remap_code}: transition alignment failed`);
    assert.equal(row.execution_enabled, "0", `${row.remap_code}: transition alignment must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.remap_code}: transition alignment must not allow promotion`);
    assert.equal(row.proof_status, "pending", `${row.remap_code}: transition proof must remain pending`);
    assert.ok(
      row.notes.includes("no_process_execution"),
      `${row.remap_code}: transition alignment row must remain non-executing`,
    );
  }

  return parsedRows;
}

function userMProcessNativeRuntimeStatePlanRows({
  transitionRows,
  stateTargetRows,
  transitionAlignmentRows,
}) {
  const stateTargetsByCode = new Map();
  for (const row of stateTargetRows) {
    const existing = stateTargetsByCode.get(row.user_m_code) ?? [];
    existing.push(row);
    stateTargetsByCode.set(row.user_m_code, existing);
  }
  const transitionAlignmentByRemap = new Map(
    transitionAlignmentRows.map((row) => [row.remap_code, row]),
  );

  return transitionRows.map((row) => {
    const targetRows = stateTargetsByCode.get(row.user_m_code) ?? [];
    const transitionAlignment = transitionAlignmentByRemap.get(row.remap_code);
    const expectedStateValues = uniqueSorted(targetRows.map((target) =>
      `${target.target_pin}=${target.expected_value}`,
    ));
    const sourceAlignmentOk = (
      transitionAlignment?.alignment_ok === "1" &&
      targetRows.length === Number(row.state_target_count)
    );

    return [
      row.path,
      row.ini,
      row.blocked,
      row.transition_step,
      row.remap_code,
      row.user_m_code,
      "linuxcnc_task_hal_tcl_user_m_process",
      "INI_FILE_NAME,motion.switchkins-type,kinstype.is-0,kinstype.is-1,ini.[xyz].*",
      row.switchkins_output_pin,
      row.switchkins_target,
      row.active_g5x,
      row.work_offset_pocket,
      row.guard_pin,
      row.state_mode,
      row.state_target_count,
      row.expected_state_pins,
      listValue(expectedStateValues),
      "user-m-process-native-transition-alignment.tsv,user-m-process-native-state-alignment.tsv",
      flagValue(sourceAlignmentOk),
      "pending_native_hal_tcl_process_probe",
      "native_runtime_state_probe_required",
      "pending",
      "0",
      "0",
      "native_runtime_not_executed_keep_millturn_blocked",
    ].map(tsvValue).join("\t");
  });
}

function verifyUserMProcessNativeRuntimeStatePlanRows(rows, transitionRows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "runtime_step",
    "remap_code",
    "user_m_code",
    "required_runtime",
    "required_environment",
    "switchkins_output_pin",
    "switchkins_target",
    "active_g5x",
    "work_offset_pocket",
    "guard_pin",
    "state_mode",
    "state_target_count",
    "expected_state_pins",
    "expected_state_values",
    "source_alignment_artifacts",
    "source_alignment_ok",
    "native_runtime_status",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_user_m_process_native_runtime_state_plan",
    transitionRows.map((row) => `${row.path}:${row.remap_code}:${row.user_m_code}`).sort(),
    parsedRows.map((row) => `${row.path}:${row.remap_code}:${row.user_m_code}`).sort(),
  );
  assert.equal(parsedRows.length, 2, "user-M native runtime state plan must cover M428/M429");

  const expectedByRemap = new Map([
    ["M428", { userMCode: "M128", target: "0", g5x: "G59.1", pocket: "P7", stateMode: "mill" }],
    ["M429", { userMCode: "M129", target: "1", g5x: "G59.2", pocket: "P8", stateMode: "turn" }],
  ]);

  for (const row of parsedRows) {
    const expected = expectedByRemap.get(row.remap_code);
    assert.ok(expected, `${row.remap_code}: unexpected runtime plan remap code`);
    assert.equal(row.path, "axis/vismach/millturn/example.ngc", `${row.remap_code}: path drift`);
    assert.equal(row.ini, "axis/vismach/millturn/millturn.ini", `${row.remap_code}: INI drift`);
    assert.equal(row.blocked, "L4-USER-M-PROCESS", `${row.remap_code}: blocked kind drift`);
    assert.equal(row.user_m_code, expected.userMCode, `${row.remap_code}: user-M code drift`);
    assert.equal(row.required_runtime, "linuxcnc_task_hal_tcl_user_m_process", `${row.remap_code}: runtime drift`);
    for (const token of ["INI_FILE_NAME", "motion.switchkins-type", "kinstype.is-0", "kinstype.is-1", "ini.[xyz].*"]) {
      assert.ok(row.required_environment.includes(token), `${row.remap_code}: missing runtime environment ${token}`);
    }
    assert.equal(row.switchkins_output_pin, "motion.analog-out-03", `${row.remap_code}: output pin drift`);
    assert.equal(row.switchkins_target, expected.target, `${row.remap_code}: target drift`);
    assert.equal(row.active_g5x, expected.g5x, `${row.remap_code}: G5x drift`);
    assert.equal(row.work_offset_pocket, expected.pocket, `${row.remap_code}: pocket drift`);
    assert.equal(row.state_mode, expected.stateMode, `${row.remap_code}: state mode drift`);
    assert.equal(row.state_target_count, "12", `${row.remap_code}: state target count drift`);
    for (const pin of ["ini.x.min_limit", "ini.y.min_velocity", "ini.z.max_acceleration"]) {
      assert.ok(row.expected_state_pins.includes(pin), `${row.remap_code}: missing expected pin ${pin}`);
    }
    assert.ok(row.expected_state_values.includes("ini.x.min_limit="), `${row.remap_code}: missing expected X limit value`);
    assert.ok(row.expected_state_values.includes("ini.z.max_acceleration=400.0"), `${row.remap_code}: missing expected Z acceleration`);
    assert.ok(
      row.source_alignment_artifacts.includes("user-m-process-native-transition-alignment.tsv") &&
        row.source_alignment_artifacts.includes("user-m-process-native-state-alignment.tsv"),
      `${row.remap_code}: missing source alignment artifact references`,
    );
    assert.equal(row.source_alignment_ok, "1", `${row.remap_code}: source alignment must be complete before runtime plan`);
    assert.equal(row.native_runtime_status, "pending_native_hal_tcl_process_probe", `${row.remap_code}: runtime status drift`);
    assert.equal(row.proof_kind, "native_runtime_state_probe_required", `${row.remap_code}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.remap_code}: runtime plan must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.remap_code}: runtime plan must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.remap_code}: runtime plan must not allow promotion`);
    assert.ok(row.notes.includes("keep_millturn_blocked"), `${row.remap_code}: runtime plan must keep millturn blocked`);
  }

  return parsedRows;
}

function commandPath(command) {
  for (const dir of (process.env.PATH ?? "").split(":").filter(Boolean)) {
    const candidate = resolve(dir, command);
    try {
      const stat = statSync(candidate);
      if (stat.isFile() && (stat.mode & 0o111) !== 0) {
        return candidate;
      }
    } catch {
      // Continue searching PATH.
    }
  }
  return "";
}

function userMProcessNativeRuntimeReadinessRows(runtimeStatePlanRows) {
  const first = runtimeStatePlanRows[0];
  if (!first) {
    return [];
  }

  const requirements = [
    ["host_command", "tclsh", "execute_config_user_m_tcl_scripts"],
    ["host_command", "halrun", "start_isolated_hal_runtime"],
    ["host_command", "halcmd", "create_and_read_hal_pins"],
    ["host_command", "linuxcnc", "run_linuxcnc_owned_task_hal_environment"],
  ];
  const commandAvailability = new Map(
    requirements.map(([, requirement]) => [requirement, commandPath(requirement)]),
  );
  const allAvailable = requirements.every(([, requirement]) =>
    commandAvailability.get(requirement),
  );
  const nativeRuntimeStatus = allAvailable
    ? "host_runtime_available_probe_not_implemented"
    : "blocked_missing_host_runtime";

  return requirements.map(([kind, requirement, purpose]) => {
    const path = commandAvailability.get(requirement) ?? "";
    return [
      first.path,
      first.ini,
      first.blocked,
      first.required_runtime,
      kind,
      requirement,
      purpose,
      flagValue(path !== ""),
      path || "-",
      nativeRuntimeStatus,
      "native_runtime_state_probe_required",
      "pending",
      "0",
      "0",
      allAvailable
        ? "runtime_commands_available_but_probe_still_not_implemented"
        : "missing_host_runtime_keep_millturn_blocked",
    ].map(tsvValue).join("\t");
  });
}

function verifyUserMProcessNativeRuntimeReadinessRows(rows) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "required_runtime",
    "requirement_kind",
    "requirement",
    "purpose",
    "available",
    "evidence",
    "native_runtime_status",
    "proof_kind",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedRequirements = ["tclsh", "halrun", "halcmd", "linuxcnc"];

  assert.deepEqual(
    parsedRows.map((row) => row.requirement),
    expectedRequirements,
    "user-M native runtime readiness requirements drift",
  );

  for (const row of parsedRows) {
    assert.equal(row.path, "axis/vismach/millturn/example.ngc", `${row.requirement}: path drift`);
    assert.equal(row.ini, "axis/vismach/millturn/millturn.ini", `${row.requirement}: INI drift`);
    assert.equal(row.blocked, "L4-USER-M-PROCESS", `${row.requirement}: blocked kind drift`);
    assert.equal(row.required_runtime, "linuxcnc_task_hal_tcl_user_m_process", `${row.requirement}: runtime drift`);
    assert.equal(row.requirement_kind, "host_command", `${row.requirement}: readiness kind drift`);
    assert.ok(["0", "1"].includes(row.available), `${row.requirement}: invalid availability`);
    assert.notEqual(row.purpose, "-", `${row.requirement}: missing purpose`);
    if (row.available === "1") {
      assert.notEqual(row.evidence, "-", `${row.requirement}: available command lacks evidence`);
    }
    assert.ok(
      ["blocked_missing_host_runtime", "host_runtime_available_probe_not_implemented"].includes(row.native_runtime_status),
      `${row.requirement}: invalid runtime status`,
    );
    assert.equal(row.proof_kind, "native_runtime_state_probe_required", `${row.requirement}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.requirement}: readiness proof must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.requirement}: readiness must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.requirement}: readiness must not allow promotion`);
    assert.ok(
      row.notes.includes("keep_millturn_blocked") ||
        row.notes.includes("probe_still_not_implemented"),
      `${row.requirement}: missing blocked/probe note`,
    );
  }

  assert.ok(
    parsedRows.some((row) => row.requirement === "tclsh" && row.available === "1"),
    "tclsh must be available for the Tcl user-M readiness check",
  );

  return parsedRows;
}

function userMProcessNativeRuntimeProbeGateRows({ runtimeStatePlanRows, runtimeReadinessRows }) {
  const readinessByRequirement = new Map(
    runtimeReadinessRows.map((row) => [row.requirement, row]),
  );

  return runtimeStatePlanRows.map((row) => {
    const missingRequirements = ["tclsh", "halrun", "halcmd", "linuxcnc"]
      .filter((requirement) => readinessByRequirement.get(requirement)?.available !== "1");
    const runtimeReady = missingRequirements.length === 0;
    const sourceProofReady = (
      row.source_alignment_ok === "1" &&
      row.execution_enabled === "0" &&
      row.promotion_allowed === "0"
    );
    const gateStatus = runtimeReady && sourceProofReady
      ? "ready_to_implement_probe"
      : "blocked_missing_host_runtime";

    return [
      row.path,
      row.ini,
      row.blocked,
      row.runtime_step,
      row.remap_code,
      row.user_m_code,
      row.required_runtime,
      listValue(["tclsh", "halrun", "halcmd", "linuxcnc"].map((requirement) =>
        `${requirement}:${readinessByRequirement.get(requirement)?.available ?? "0"}`,
      )),
      listValue(missingRequirements),
      flagValue(runtimeReady),
      flagValue(sourceProofReady),
      row.proof_kind,
      gateStatus,
      "pending",
      "0",
      "0",
      runtimeReady
        ? "host_runtime_available_write_native_hal_tcl_state_probe"
        : "missing_host_runtime_keep_millturn_blocked",
    ].map(tsvValue).join("\t");
  });
}

function verifyUserMProcessNativeRuntimeProbeGateRows({
  rows,
  runtimeStatePlanRows,
  runtimeReadinessRows,
}) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "runtime_step",
    "remap_code",
    "user_m_code",
    "required_runtime",
    "runtime_requirements",
    "missing_requirements",
    "runtime_ready",
    "source_proof_ready",
    "required_native_proof",
    "gate_status",
    "proof_status",
    "execution_enabled",
    "promotion_allowed",
    "notes",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_user_m_process_native_runtime_probe_gate",
    runtimeStatePlanRows.map((row) => `${row.remap_code}:${row.user_m_code}`).sort(),
    parsedRows.map((row) => `${row.remap_code}:${row.user_m_code}`).sort(),
  );

  const allRuntimeReady = runtimeReadinessRows.every((row) => row.available === "1");
  const expectedMissing = runtimeReadinessRows
    .filter((row) => row.available !== "1")
    .map((row) => row.requirement)
    .sort();

  for (const row of parsedRows) {
    assert.equal(row.path, "axis/vismach/millturn/example.ngc", `${row.user_m_code}: path drift`);
    assert.equal(row.ini, "axis/vismach/millturn/millturn.ini", `${row.user_m_code}: INI drift`);
    assert.equal(row.blocked, "L4-USER-M-PROCESS", `${row.user_m_code}: blocked kind drift`);
    assert.equal(row.required_runtime, "linuxcnc_task_hal_tcl_user_m_process", `${row.user_m_code}: runtime drift`);
    assert.ok(["M428", "M429"].includes(row.remap_code), `${row.user_m_code}: remap code drift`);
    assert.ok(["M128", "M129"].includes(row.user_m_code), `${row.user_m_code}: user-M code drift`);
    for (const requirement of ["tclsh", "halrun", "halcmd", "linuxcnc"]) {
      assert.ok(row.runtime_requirements.includes(`${requirement}:`), `${row.user_m_code}: missing runtime requirement ${requirement}`);
    }
    assert.equal(row.runtime_ready, flagValue(allRuntimeReady), `${row.user_m_code}: runtime readiness drift`);
    assert.equal(row.source_proof_ready, "1", `${row.user_m_code}: source proof must be ready before runtime probe`);
    assert.equal(row.required_native_proof, "native_runtime_state_probe_required", `${row.user_m_code}: proof kind drift`);
    assert.equal(row.proof_status, "pending", `${row.user_m_code}: probe gate must remain pending`);
    assert.equal(row.execution_enabled, "0", `${row.user_m_code}: probe gate must not enable execution`);
    assert.equal(row.promotion_allowed, "0", `${row.user_m_code}: probe gate must not allow promotion`);

    if (allRuntimeReady) {
      assert.equal(row.missing_requirements, "-", `${row.user_m_code}: ready runtime has missing requirements`);
      assert.equal(row.gate_status, "ready_to_implement_probe", `${row.user_m_code}: ready runtime gate status drift`);
      assert.ok(row.notes.includes("write_native_hal_tcl_state_probe"), `${row.user_m_code}: ready runtime note drift`);
    } else {
      assert.deepEqual(
        splitSummaryList(row.missing_requirements).sort(),
        expectedMissing,
        `${row.user_m_code}: missing runtime requirements drift`,
      );
      assert.equal(row.gate_status, "blocked_missing_host_runtime", `${row.user_m_code}: missing runtime gate status drift`);
      assert.ok(row.notes.includes("keep_millturn_blocked"), `${row.user_m_code}: missing runtime note drift`);
    }
  }

  return parsedRows;
}

function boundarySummaryRow(record, pathMatrixByPath) {
  const matrixBlocked = pathMatrixByPath.get(record.path)?.blocked ?? "-";
  const boundaryReport = runtimeBoundaryForRecord(record);

  if (!boundaryReport.available) {
    return [
      record.path,
      record.ini,
      matrixBlocked,
      "UNAVAILABLE",
      `missing_vendored_ini:${boundaryReport.missingVendoredRel}`,
      "-",
      "-",
      "0",
      "-",
      "0",
      "0",
      "0",
      "0",
      "0",
      "0",
    ].map(tsvValue).join("\t");
  }

  const boundary = boundaryReport.boundary;
  return [
    record.path,
    record.ini,
    matrixBlocked,
    boundary.recommendedBlockedKind,
    listValue(boundary.dependencies),
    listValue(boundary.userMRuntime.executionCodes),
    listValue(boundary.userMRuntime.unstagedExecutionCodes),
    boundary.userMRuntime.vendoredExecutableCount,
    boundary.toolDatabaseProgram || "-",
    flagValue(boundary.halRuntime.requiresProcess),
    flagValue(boundary.uiRuntime.requiresProcess),
    flagValue(boundary.haluiRuntime.requiresProcess),
    flagValue(boundary.pythonRuntime.requiresProcess),
    flagValue(boundary.pythonRuntime.uiReferences.length > 0),
    flagValue(boundary.pythonRuntime.remapReferences.length > 0),
  ].map(tsvValue).join("\t");
}

function verifyBoundarySummaryRows(rows, expectedPaths, trackedMatrixByPath) {
  const expectedHeaders = [
    "path",
    "ini",
    "blocked",
    "recommended_blocked",
    "dependencies",
    "user_m_execution_codes",
    "user_m_unstaged_execution_codes",
    "user_m_vendored_count",
    "db_program",
    "hal_process",
    "ui_process",
    "halui_mdi_process",
    "python_process",
    "python_ui_db_process",
    "python_remap_process",
  ];
  const hardBlockedKinds = new Set([
    "L4-TOOL-DB",
    "L4-USER-M-PROCESS",
    "L4-PYTHON-REMAP",
  ]);
  const allowedRecommendations = new Set(["-", "UNAVAILABLE", ...hardBlockedKinds]);
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );

  verifySamePathSet(
    "wasm_boundary_summary",
    expectedPaths,
    parsedRows.map((record) => record.path).sort(),
  );

  const requiredSafeProcessRepresentatives = new Map([
    [
      "axis/gladevcp/probe.ngc",
      {
        dependencies: "hal_process,python_runtime,ui_process",
        hal_process: "1",
        ui_process: "1",
        halui_mdi_process: "0",
        python_process: "1",
        python_ui_db_process: "1",
        python_remap_process: "0",
      },
    ],
    [
      "axis/vismach/melfa-sim/example.ngc",
      {
        dependencies: "hal_process,halui_mdi_process,ui_process",
        hal_process: "1",
        ui_process: "1",
        halui_mdi_process: "1",
        python_process: "0",
        python_ui_db_process: "0",
        python_remap_process: "0",
      },
    ],
    [
      "axis/vismach/puma/puma_cube.ngc",
      {
        dependencies: "hal_process,halui_mdi_process,ui_process",
        hal_process: "1",
        ui_process: "1",
        halui_mdi_process: "1",
        python_process: "0",
        python_ui_db_process: "0",
        python_remap_process: "0",
      },
    ],
    [
      "woodpecker/on_abort.ngc",
      {
        dependencies: "hal_process,ui_process",
        hal_process: "1",
        ui_process: "1",
        halui_mdi_process: "0",
        python_process: "0",
        python_ui_db_process: "0",
        python_remap_process: "0",
      },
    ],
  ]);
  const requiredDeterministicUserMRepresentatives = new Map([
    ["axis/geometry/xyzc.ngc", "M110"],
    ["axis/external_offsets/circles.ngc", "M111"],
    ["axis/external_offsets/dyn_demo.ngc", "M111"],
    ["axis/external_offsets/eoffsets.ngc", "M111"],
    ["axis/external_offsets/jwp_z.ngc", "M111"],
    ["axis/external_offsets/opa_demo.ngc", "M111"],
  ]);

  for (const row of parsedRows) {
    assert.ok(allowedRecommendations.has(row.recommended_blocked), `${row.path}: unknown recommended block ${row.recommended_blocked}`);
    assert.ok(/^[0-9]+$/.test(row.user_m_vendored_count), `${row.path}: invalid user-M count`);
    for (const field of [
      "hal_process",
      "ui_process",
      "halui_mdi_process",
      "python_process",
      "python_ui_db_process",
      "python_remap_process",
    ]) {
      assert.ok(["0", "1"].includes(row[field]), `${row.path}: invalid ${field} flag`);
    }
    if (vendoredConfigPathExists(`configs/sim/${row.ini}`)) {
      assert.notEqual(
        row.recommended_blocked,
        "UNAVAILABLE",
        `${row.path}: vendored INI lacks runtime-boundary report`,
      );
    }
    if (row.recommended_blocked === "UNAVAILABLE") {
      assert.ok(
        row.dependencies.startsWith("missing_vendored_ini:"),
        `${row.path}: unavailable boundary row lacks missing INI evidence`,
      );
    }

    if (
      hardBlockedKinds.has(row.blocked) &&
      row.recommended_blocked !== "UNAVAILABLE"
    ) {
      assert.equal(
        row.recommended_blocked,
        row.blocked,
        `${row.path}: boundary-summary hard blocked drift`,
      );
    }
    if (hardBlockedKinds.has(row.recommended_blocked) && row.blocked !== "ASSET-ONLY") {
      assert.equal(
        row.blocked,
        row.recommended_blocked,
        `${row.path}: classifier recommended hard block not reflected in matrix`,
      );
    }
    if (row.recommended_blocked === "L4-TOOL-DB") {
      assert.notEqual(row.db_program, "-", `${row.path}: tool DB block requires DB_PROGRAM`);
    }
    if (row.recommended_blocked === "L4-USER-M-PROCESS") {
      assert.notEqual(
        row.user_m_execution_codes,
        "-",
        `${row.path}: user-M process block requires execution codes`,
      );
      assert.notEqual(
        row.user_m_unstaged_execution_codes,
        "-",
        `${row.path}: user-M process block requires unstaged execution codes`,
      );
    }
    if (row.recommended_blocked === "L4-PYTHON-REMAP") {
      assert.equal(
        row.python_remap_process,
        "1",
        `${row.path}: Python remap block requires Python remap process evidence`,
      );
    }

    if (requiredSafeProcessRepresentatives.has(row.path)) {
      const expected = requiredSafeProcessRepresentatives.get(row.path);
      const tracked = trackedMatrixByPath.get(row.path);
      assert.ok(tracked, `${row.path}: safe process representative missing tracked row`);
      assert.equal(row.blocked, "-", `${row.path}: safe process representative must not be blocked`);
      assert.equal(
        row.recommended_blocked,
        "-",
        `${row.path}: safe process representative must not recommend hard block`,
      );
      assert.equal(
        tracked.layer4Node,
        "REP",
        `${row.path}: safe process representative must remain Node REP`,
      );
      assert.equal(
        tracked.layer4Browser,
        "REP",
        `${row.path}: safe process representative must remain browser REP`,
      );
      assert.notEqual(
        row.dependencies,
        "-",
        `${row.path}: safe process representative should declare its process dependencies`,
      );
      assert.equal(
        row.dependencies,
        expected.dependencies,
        `${row.path}: safe process representative dependency drift`,
      );
      for (const field of [
        "hal_process",
        "ui_process",
        "halui_mdi_process",
        "python_process",
        "python_ui_db_process",
        "python_remap_process",
      ]) {
        assert.equal(
          row[field],
          expected[field],
          `${row.path}: safe process representative ${field} drift`,
        );
      }
    }

    if (requiredDeterministicUserMRepresentatives.has(row.path)) {
      const expectedCode = requiredDeterministicUserMRepresentatives.get(row.path);
      assert.equal(row.blocked, "-", `${row.path}: deterministic user-M representative must not be blocked`);
      assert.equal(
        row.recommended_blocked,
        "-",
        `${row.path}: deterministic user-M representative must not recommend hard block`,
      );
      assert.equal(
        row.user_m_execution_codes,
        expectedCode,
        `${row.path}: deterministic user-M execution code drift`,
      );
      assert.equal(
        row.user_m_unstaged_execution_codes,
        "-",
        `${row.path}: deterministic user-M representative must not call unstaged user-M files`,
      );
      assert.notEqual(
        row.user_m_vendored_count,
        "0",
        `${row.path}: deterministic user-M representative lacks vendored user-M file`,
      );
    }
  }

  return parsedRows;
}

function iniBoundarySummaryRows(boundaryRows) {
  const byIni = new Map();
  for (const row of boundaryRows) {
    const entry = byIni.get(row.ini) ?? [];
    entry.push(row);
    byIni.set(row.ini, entry);
  }

  return [...byIni.entries()]
    .sort(([left], [right]) => left.localeCompare(right))
    .map(([ini, rows]) => {
      const vendored = vendoredConfigPathExists(`configs/sim/${ini}`);
      const recommendations = uniqueSorted(rows.map((row) => row.recommended_blocked));
      const hardRecommendations = recommendations.filter((value) =>
        ["L4-TOOL-DB", "L4-USER-M-PROCESS", "L4-PYTHON-REMAP"].includes(value),
      );
      const blockedKinds = uniqueSorted(rows.map((row) => row.blocked));
      return [
        ini,
        String(rows.length),
        flagValue(vendored),
        flagValue(vendored && rows.every((row) => row.recommended_blocked !== "UNAVAILABLE")),
        listValue(blockedKinds),
        listValue(recommendations),
        listValue(uniqueSorted(rows.flatMap((row) =>
          row.dependencies === "-" ? [] : row.dependencies.split(","),
        ))),
        listValue(uniqueSorted(rows.flatMap((row) =>
          row.user_m_execution_codes === "-" ? [] : row.user_m_execution_codes.split(","),
        ))),
        listValue(uniqueSorted(rows.flatMap((row) =>
          row.user_m_unstaged_execution_codes === "-" ? [] : row.user_m_unstaged_execution_codes.split(","),
        ))),
        String(Math.max(...rows.map((row) => Number(row.user_m_vendored_count)))),
        listValue(uniqueSorted(rows.map((row) => row.db_program).filter((value) => value !== "-"))),
        flagValue(rows.some((row) => row.hal_process === "1")),
        flagValue(rows.some((row) => row.ui_process === "1")),
        flagValue(rows.some((row) => row.halui_mdi_process === "1")),
        flagValue(rows.some((row) => row.python_process === "1")),
        flagValue(rows.some((row) => row.python_ui_db_process === "1")),
        flagValue(rows.some((row) => row.python_remap_process === "1")),
        flagValue(hardRecommendations.length === 0 || rows.some((row) => row.blocked === hardRecommendations[0])),
      ].map(tsvValue).join("\t");
    });
}

function verifyIniBoundarySummaryRows(rows, boundaryRows) {
  const expectedHeaders = [
    "ini",
    "path_count",
    "vendored",
    "report_available",
    "blocked",
    "recommended_blocked",
    "dependencies",
    "user_m_execution_codes",
    "user_m_unstaged_execution_codes",
    "user_m_vendored_count",
    "db_program",
    "hal_process",
    "ui_process",
    "halui_mdi_process",
    "python_process",
    "python_ui_db_process",
    "python_remap_process",
    "hard_block_policy_aligned",
  ];
  const parsedRows = parseTsv(
    `${expectedHeaders.join("\t")}\n${rows.join("\n")}\n`,
    expectedHeaders,
  );
  const expectedInis = uniqueSorted(boundaryRows.map((row) => row.ini));

  verifySamePathSet(
    "wasm_ini_boundary_summary",
    expectedInis,
    parsedRows.map((row) => row.ini).sort(),
  );

  for (const row of parsedRows) {
    assert.ok(/^[1-9][0-9]*$/.test(row.path_count), `${row.ini}: invalid path count`);
    for (const field of [
      "vendored",
      "report_available",
      "hal_process",
      "ui_process",
      "halui_mdi_process",
      "python_process",
      "python_ui_db_process",
      "python_remap_process",
      "hard_block_policy_aligned",
    ]) {
      assert.ok(["0", "1"].includes(row[field]), `${row.ini}: invalid ${field}`);
    }
    assert.ok(/^[0-9]+$/.test(row.user_m_vendored_count), `${row.ini}: invalid user-M count`);
    if (row.vendored === "1") {
      assert.equal(row.report_available, "1", `${row.ini}: vendored INI lacks classifier report`);
    }
    assert.equal(row.hard_block_policy_aligned, "1", `${row.ini}: hard block recommendation lacks matrix alignment`);
    if (row.recommended_blocked.split(",").includes("L4-TOOL-DB")) {
      assert.notEqual(row.db_program, "-", `${row.ini}: tool DB recommendation lacks DB_PROGRAM`);
    }
    if (row.recommended_blocked.split(",").includes("L4-USER-M-PROCESS")) {
      assert.notEqual(row.user_m_unstaged_execution_codes, "-", `${row.ini}: user-M recommendation lacks unstaged codes`);
    }
    if (row.recommended_blocked.split(",").includes("L4-PYTHON-REMAP")) {
      assert.equal(row.python_remap_process, "1", `${row.ini}: Python-remap recommendation lacks remap process flag`);
    }
  }

  return parsedRows;
}

function isRuntimeEdgeExpectedFail(record) {
  return [
    "ini-axis-mask-UV",
    "ini-axis-mask-W",
    "user-m-code-M110",
    "user-m-code-M111",
  ].includes(record.expected_failure);
}

function executionModeFor(record) {
  if (
    record.path === "axis/vismach/5axis/bridgemill/5axisgui.ngc" ||
    record.path.startsWith("axis/vismach/5axis/table-dual-rotary/") ||
    record.path.startsWith("axis/vismach/5axis/table-rotary-tilting/") ||
    record.path.startsWith("axis/vismach/melfa-sim/")
  ) {
    return "fiveAxisRemap";
  }
  return "fileWithIni";
}

function verifyInventoryCase(record, output, executionMode) {
  if (record.status === "PASS") {
    if (executionMode === "fiveAxisRemap") {
      verifyExpectedOutput(
        `inventory_${record.path}`,
        output,
        [
          "fiveaxis_ini_open=1",
          "fiveaxis_tool_table_load=0",
          "fiveaxis_file_open=0",
          "fiveaxis_file_reached_exit=1",
          "fiveaxis_linuxcnc_remap_file_execute=1",
        ].join("\n"),
      );
      return;
    }

    verifyExpectedOutput(
      `inventory_${record.path}`,
      output,
      [
        "file_open=0",
        "file_saw_error=0",
        "canon_event=PROGRAM_END",
        "absent=file_error_text=",
      ].join("\n"),
    );
    return;
  }

  if (record.path === "axis/foam/foam.ngc") {
    verifyExpectedOutput(
      "inventory_axis_foam",
      output,
      [
        "file_open=0",
        "file_saw_error=0",
        "canon_event=PROGRAM_END",
        "absent=Bad character 'u' used",
        "absent=Bad character 'v' used",
      ].join("\n"),
    );
    return;
  }

  if (record.path === "axis/geometry/xyzc.ngc") {
    verifyExpectedOutput(
      "inventory_axis_geometry_xyzc",
      output,
      [
        "file_open=0",
        "file_saw_error=0",
        "canon_event=USER_M_COMMAND code=M110",
        "canon_event=PROGRAM_END",
        "absent=Unknown m code used: M110",
      ].join("\n"),
    );
    return;
  }

  if (record.path.startsWith("axis/external_offsets/")) {
    verifyExpectedOutput(
      `inventory_${record.path}`,
      output,
      [
        "file_open=0",
        "file_saw_error=0",
        "canon_event=USER_M_COMMAND code=M111",
        "canon_event=PROGRAM_END",
        "absent=Unknown m code used: M111",
        "absent=Bad character",
        "absent=Cannot use axis values",
      ].join("\n"),
    );
    return;
  }

  if (record.path === "axis/vismach/5axis/bridgemill/5axisgui.ngc") {
    verifyExpectedOutput(
      "inventory_axis_bridgemill",
      output,
      [
        "fiveaxis_ini_open=1",
        "fiveaxis_tool_table_load=0",
        "fiveaxis_parse_remap_1=0",
        "fiveaxis_parse_remap_2=0",
        "fiveaxis_parse_remap_3=0",
        "fiveaxis_parsed_remap_count=3",
        "fiveaxis_remaps_ready=1",
        "fiveaxis_file_open=0",
        "fiveaxis_file_reached_exit=1",
        "fiveaxis_linuxcnc_remap_file_execute=1",
        "absent=Bad character 'w' used",
      ].join("\n"),
    );
    return;
  }

  throw new Error(`unexpected expected-fail inventory case: ${record.path}`);
}

const nativeRecords = parseTsv(readFileSync(nativeSummaryPath, "utf8"), [
  "path",
  "class",
  "status",
  "expected_failure",
  "exit_code",
  "seconds",
  "ini",
  "tbl",
  "output_lines",
  "stderr_summary",
]);
const classSummaryRecords = parseTsv(readFileSync(nativeClassSummaryPath, "utf8"), [
  "class",
  "status",
  "expected_failure",
  "count",
]);
const pathMatrixRecords = parseTsv(readFileSync(nativePathMatrixPath, "utf8"), [
  "path",
  "class",
  "status",
  "expected_failure",
  "ini",
  "tbl",
  "runtime_family",
  "blocked",
]);
const pathMatrixByPath = new Map(pathMatrixRecords.map((record) => [record.path, record]));
const nativePaths = sortedPaths(nativeRecords);
const trackedMatrixText = readFileSync(trackedMatrixPath, "utf8");
const trackedMatrixRecords = parseTrackedMatrix(trackedMatrixText);
const trackedMatrixByPath = new Map(trackedMatrixRecords.map((record) => [record.path, record]));
const trackedClassSummaryRows = parseTrackedSummaryTable(trackedMatrixText, "Summary", "class");
const trackedFamilySummaryRows = parseTrackedSummaryTable(
  trackedMatrixText,
  "Family Summary",
  "family",
);
verifyUniquePaths("native_summary", nativeRecords);
verifyUniquePaths("native_path_matrix", pathMatrixRecords);
verifyUniquePaths("tracked_sim_configs_coverage_matrix", trackedMatrixRecords);
verifySamePathSet(
  "native_path_matrix",
  nativePaths,
  sortedPaths(pathMatrixRecords),
);
verifySamePathSet(
  "tracked_sim_configs_coverage_matrix",
  nativePaths,
  trackedMatrixRecords.map((record) => record.path).sort(),
);
verifyClassesAndStatuses(nativeRecords);
verifyClassesAndStatuses(pathMatrixRecords);
verifyClassesAndStatuses(trackedMatrixRecords);
verifyNativeExpectedFailures(nativeRecords);
verifyMatrixExpectedFailures(pathMatrixRecords);
verifyMatrixExpectedFailures(trackedMatrixRecords);
verifyBlockedKinds(pathMatrixRecords);
verifyBlockedKinds(trackedMatrixRecords);
verifyLayerMarkers(trackedMatrixRecords);
verifyTrackedMatrixNotes(trackedMatrixRecords);
verifyTrackedSummaryTables(trackedMatrixRecords, trackedClassSummaryRows, trackedFamilySummaryRows);
verifyRequiredClassRepresentatives(trackedMatrixRecords);
verifyPathMatrixFields(nativeRecords, pathMatrixByPath);
verifyTrackedMatrixFields(trackedMatrixRecords, pathMatrixByPath);
verifyRuntimeBoundaryPolicy(nativeRecords, pathMatrixByPath);
verifyClassSummaryRows(classSummaryRecords);
assert.deepEqual(
  classSummaryRowsFromGenerated(classSummaryRecords),
  classSummaryRowsFromNativeRecords(nativeRecords),
  "native class-summary.tsv must match summary.tsv-derived counts",
);

const boundarySummaryRows = nativeRecords.map((record) =>
  boundarySummaryRow(record, pathMatrixByPath),
);
const boundarySummaryRecords = verifyBoundarySummaryRows(
  boundarySummaryRows,
  nativePaths,
  trackedMatrixByPath,
);
const iniBoundarySummaryRowsGenerated = iniBoundarySummaryRows(boundarySummaryRecords);
const iniBoundarySummaryRecords = verifyIniBoundarySummaryRows(
  iniBoundarySummaryRowsGenerated,
  boundarySummaryRecords,
);

const blockedDependencyRecords = nativeRecords.filter((record) =>
  ["L4-PYTHON-REMAP", "L4-TOOL-DB", "L4-USER-M-PROCESS"].includes(
    pathMatrixByPath.get(record.path)?.blocked ?? "-",
  ),
);
const blockedDependencySummaryRows = blockedDependencyRecords.map((record) =>
  blockedDependencySummaryRow(record, pathMatrixByPath),
);
const blockedDependencySummaryRecords = verifyBlockedDependencySummaryRows(
  blockedDependencySummaryRows,
  blockedDependencyRecords,
);
verifyFullProcessBoundaryDesign(
  readFileSync(fullProcessBoundaryDesignPath, "utf8"),
  blockedDependencySummaryRecords,
);
const fullProcessBoundarySummaryRows = blockedDependencySummaryRecords
  .map(fullProcessBoundarySummaryRow)
  .filter(Boolean);
const fullProcessBoundarySummaryRecords = verifyFullProcessBoundarySummaryRows(
  fullProcessBoundarySummaryRows,
  blockedDependencySummaryRecords,
);
const userMProcessBoundarySummaryRows = blockedDependencySummaryRecords
  .map(userMProcessBoundarySummaryRow)
  .filter(Boolean);
const userMProcessBoundarySummaryRecords = verifyUserMProcessBoundarySummaryRows(
  userMProcessBoundarySummaryRows,
  blockedDependencySummaryRecords,
);
const userMProcessStateTargetRowsGenerated = blockedDependencySummaryRecords
  .flatMap(userMProcessStateTargetRows);
const userMProcessStateTargetRecords = verifyUserMProcessStateTargetRows(
  userMProcessStateTargetRowsGenerated,
  blockedDependencySummaryRecords,
);
const userMProcessTransitionPlanRowsGenerated = userMProcessTransitionPlanRows(
  userMProcessStateTargetRecords,
);
const userMProcessTransitionPlanRecords = verifyUserMProcessTransitionPlanRows(
  userMProcessTransitionPlanRowsGenerated,
  userMProcessStateTargetRecords,
);
const userMProcessNativeStateAlignmentRowsGenerated =
  userMProcessNativeStateAlignmentRows(userMProcessStateTargetRecords);
const userMProcessNativeStateAlignmentRecords = verifyUserMProcessNativeStateAlignmentRows(
  userMProcessNativeStateAlignmentRowsGenerated,
  userMProcessStateTargetRecords,
);
const userMProcessNativeTransitionAlignmentRowsGenerated =
  userMProcessNativeTransitionAlignmentRows(userMProcessTransitionPlanRecords);
const userMProcessNativeTransitionAlignmentRecords = verifyUserMProcessNativeTransitionAlignmentRows(
  userMProcessNativeTransitionAlignmentRowsGenerated,
  userMProcessTransitionPlanRecords,
);
const userMProcessNativeRuntimeStatePlanRowsGenerated =
  userMProcessNativeRuntimeStatePlanRows({
    transitionRows: userMProcessTransitionPlanRecords,
    stateTargetRows: userMProcessStateTargetRecords,
    transitionAlignmentRows: userMProcessNativeTransitionAlignmentRecords,
  });
const userMProcessNativeRuntimeStatePlanRecords = verifyUserMProcessNativeRuntimeStatePlanRows(
  userMProcessNativeRuntimeStatePlanRowsGenerated,
  userMProcessTransitionPlanRecords,
);
const userMProcessNativeRuntimeReadinessRowsGenerated =
  userMProcessNativeRuntimeReadinessRows(userMProcessNativeRuntimeStatePlanRecords);
const userMProcessNativeRuntimeReadinessRecords = verifyUserMProcessNativeRuntimeReadinessRows(
  userMProcessNativeRuntimeReadinessRowsGenerated,
);
const userMProcessNativeRuntimeProbeGateRowsGenerated =
  userMProcessNativeRuntimeProbeGateRows({
    runtimeStatePlanRows: userMProcessNativeRuntimeStatePlanRecords,
    runtimeReadinessRows: userMProcessNativeRuntimeReadinessRecords,
  });
const userMProcessNativeRuntimeProbeGateRecords =
  verifyUserMProcessNativeRuntimeProbeGateRows({
    rows: userMProcessNativeRuntimeProbeGateRowsGenerated,
    runtimeStatePlanRows: userMProcessNativeRuntimeStatePlanRecords,
    runtimeReadinessRows: userMProcessNativeRuntimeReadinessRecords,
  });
const toolDbProcessBoundarySummaryRows = blockedDependencySummaryRecords
  .map(toolDbProcessBoundarySummaryRow)
  .filter(Boolean);
const toolDbProcessBoundarySummaryRecords = verifyToolDbProcessBoundarySummaryRows(
  toolDbProcessBoundarySummaryRows,
  blockedDependencySummaryRecords,
);
const toolDbProcessProtocolGateRowsGenerated = blockedDependencySummaryRecords
  .flatMap(toolDbProcessProtocolGateRows);
const toolDbProcessProtocolGateRecords = verifyToolDbProcessProtocolGateRows(
  toolDbProcessProtocolGateRowsGenerated,
  blockedDependencySummaryRecords,
);
const toolDbProcessTransactionPlanRowsGenerated = toolDbProcessTransactionPlanRows(
  toolDbProcessProtocolGateRecords,
);
const toolDbProcessTransactionPlanRecords = verifyToolDbProcessTransactionPlanRows(
  toolDbProcessTransactionPlanRowsGenerated,
  toolDbProcessProtocolGateRecords,
);
const toolDbProcessNativeProtocolAlignmentRowsGenerated =
  toolDbProcessNativeProtocolAlignmentRows(toolDbProcessProtocolGateRecords);
const toolDbProcessNativeProtocolAlignmentRecords = verifyToolDbProcessNativeProtocolAlignmentRows(
  toolDbProcessNativeProtocolAlignmentRowsGenerated,
  toolDbProcessProtocolGateRecords,
);
const toolDbProcessNativeRuntimeReadinessRowsGenerated =
  toolDbProcessNativeRuntimeReadinessRows(toolDbProcessTransactionPlanRecords);
const toolDbProcessNativeRuntimeReadinessRecords = verifyToolDbProcessNativeRuntimeReadinessRows(
  toolDbProcessNativeRuntimeReadinessRowsGenerated,
);
const toolDbProcessNativeRuntimeProbeGateRowsGenerated =
  toolDbProcessNativeRuntimeProbeGateRows({
    transactionRows: toolDbProcessTransactionPlanRecords,
    readinessRows: toolDbProcessNativeRuntimeReadinessRecords,
  });
const toolDbProcessNativeRuntimeProbeGateRecords = verifyToolDbProcessNativeRuntimeProbeGateRows({
  rows: toolDbProcessNativeRuntimeProbeGateRowsGenerated,
  transactionRows: toolDbProcessTransactionPlanRecords,
  readinessRows: toolDbProcessNativeRuntimeReadinessRecords,
});
const pythonRemapBoundarySummaryRows = blockedDependencySummaryRecords
  .map(pythonRemapBoundarySummaryRow)
  .filter(Boolean);
const pythonRemapBoundarySummaryRecords = verifyPythonRemapBoundarySummaryRows(
  pythonRemapBoundarySummaryRows,
  blockedDependencySummaryRecords,
);
const pythonRemapRuntimeGateRowsGenerated = pythonRemapBoundarySummaryRecords
  .flatMap(pythonRemapRuntimeGateRows);
const pythonRemapRuntimeGateRecords = verifyPythonRemapRuntimeGateRows(
  pythonRemapRuntimeGateRowsGenerated,
  pythonRemapBoundarySummaryRecords,
);
const pythonRemapNativeRuntimeAlignmentRowsGenerated =
  pythonRemapNativeRuntimeAlignmentRows(pythonRemapRuntimeGateRecords);
const pythonRemapNativeRuntimeAlignmentRecords = verifyPythonRemapNativeRuntimeAlignmentRows(
  pythonRemapNativeRuntimeAlignmentRowsGenerated,
  pythonRemapRuntimeGateRecords,
);
const pythonRemapFamilyRows = pythonRemapFamilySummaryRows(
  pythonRemapBoundarySummaryRecords,
);
const pythonRemapFamilyRecords = verifyPythonRemapFamilySummaryRows(
  pythonRemapFamilyRows,
  pythonRemapBoundarySummaryRecords,
);
const pythonRemapRuntimeContractRowsGenerated = pythonRemapRuntimeContractRows(
  pythonRemapFamilyRecords,
);
const pythonRemapRuntimeContractRecords = verifyPythonRemapRuntimeContractRows(
  pythonRemapRuntimeContractRowsGenerated,
  pythonRemapFamilyRecords,
);
const pythonRemapNativeRuntimeReadinessRowsGenerated =
  pythonRemapNativeRuntimeReadinessRows(pythonRemapRuntimeContractRecords);
const pythonRemapNativeRuntimeReadinessRecords = verifyPythonRemapNativeRuntimeReadinessRows(
  pythonRemapNativeRuntimeReadinessRowsGenerated,
  pythonRemapRuntimeContractRecords,
);
const pythonRemapNativeRuntimeStatePlanRowsGenerated =
  pythonRemapNativeRuntimeStatePlanRows({
    contractRows: pythonRemapRuntimeContractRecords,
    readinessRows: pythonRemapNativeRuntimeReadinessRecords,
    alignmentRows: pythonRemapNativeRuntimeAlignmentRecords,
  });
const pythonRemapNativeRuntimeStatePlanRecords = verifyPythonRemapNativeRuntimeStatePlanRows({
  rows: pythonRemapNativeRuntimeStatePlanRowsGenerated,
  contractRows: pythonRemapRuntimeContractRecords,
  readinessRows: pythonRemapNativeRuntimeReadinessRecords,
});
const pythonRemapNativeRuntimeFixturePlanRowsGenerated =
  pythonRemapNativeRuntimeFixturePlanRows(pythonRemapNativeRuntimeStatePlanRecords);
const pythonRemapNativeRuntimeFixturePlanRecords = verifyPythonRemapNativeRuntimeFixturePlanRows(
  pythonRemapNativeRuntimeFixturePlanRowsGenerated,
  pythonRemapNativeRuntimeStatePlanRecords,
);
const pythonRemapNativeRuntimeProbeGateRowsGenerated =
  pythonRemapNativeRuntimeProbeGateRows({
    fixturePlanRows: pythonRemapNativeRuntimeFixturePlanRecords,
    readinessRows: pythonRemapNativeRuntimeReadinessRecords,
  });
const pythonRemapNativeRuntimeProbeGateRecords = verifyPythonRemapNativeRuntimeProbeGateRows({
  rows: pythonRemapNativeRuntimeProbeGateRowsGenerated,
  fixturePlanRows: pythonRemapNativeRuntimeFixturePlanRecords,
  readinessRows: pythonRemapNativeRuntimeReadinessRecords,
});

const summaryRows = [];
const skipReasonCounts = new Map();
let executed = 0;
let passed = 0;
let skipped = 0;
let unexpectedFail = 0;

function recordSkip(reason) {
  skipped += 1;
  skipReasonCounts.set(reason, (skipReasonCounts.get(reason) ?? 0) + 1);
}

function skipReasonLogKey(reason) {
  return reason.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
}

function verifyInventorySummaryRows(rows, trackedMatrixByPath) {
  const allowedInventoryStatuses = new Set(["PASS", "SKIP", "FAIL"]);
  const allowedSkipReasons = new Set([
    "ASSET-ONLY",
    "L4-PYTHON-REMAP",
    "L4-TOOL-DB",
    "L4-USER-M-PROCESS",
    "NON_MAIN_CLASS",
    "UNMAPPED_EXPECTED_FAILURE",
    "UPSTREAM-DEMO",
  ]);

  for (const row of rows) {
    const [
      path,
      inventoryStatus,
      reason,
      className,
      nativeStatus,
      nativeExpectedFailure,
    ] = row.split("\t");
    assert.ok(path, "Node inventory summary row missing path");
    assert.ok(
      allowedInventoryStatuses.has(inventoryStatus),
      `${path}: unknown inventory status ${inventoryStatus}`,
    );
    verifyClassesAndStatuses([{ path, class: className, status: nativeStatus }]);
    verifyMatrixExpectedFailures([
      { path, status: nativeStatus, expected_failure: nativeExpectedFailure },
    ]);

    if (inventoryStatus === "PASS") {
      assert.equal(reason, "-", `${path}: PASS inventory row has reason ${reason}`);
      const tracked = trackedMatrixByPath.get(path);
      assert.ok(tracked, `${path}: PASS inventory row missing tracked matrix record`);
      assert.ok(
        ["REP", "INV"].includes(tracked.layer4Node),
        `${path}: PASS inventory row must be marked REP or INV in Layer 4 Node`,
      );
    } else if (inventoryStatus === "SKIP") {
      assert.ok(allowedSkipReasons.has(reason), `${path}: unknown skip reason ${reason}`);
    } else {
      assert.notEqual(reason, "-", `${path}: FAIL inventory row lacks reason`);
    }
  }
}

function verifySkipSummaryRows(rows, expectedSkipped, nativeRecords, pathMatrixByPath) {
  const allowedSkipReasons = new Set([
    "ASSET-ONLY",
    "L4-PYTHON-REMAP",
    "L4-TOOL-DB",
    "L4-USER-M-PROCESS",
    "NON_MAIN_CLASS",
    "UNMAPPED_EXPECTED_FAILURE",
    "UPSTREAM-DEMO",
  ]);
  let total = 0;

  const actualCounts = new Map();
  for (const row of rows) {
    const [reason, countText] = row.split("\t");
    assert.ok(allowedSkipReasons.has(reason), `unknown skip-summary reason ${reason}`);
    assert.ok(/^[1-9][0-9]*$/.test(countText), `${reason}: invalid skip count ${countText}`);
    const count = Number(countText);
    actualCounts.set(reason, count);
    total += count;
  }

  assert.equal(total, expectedSkipped, "skip-summary rows must add up to skipped count");

  const expectedCounts = new Map();
  for (const record of nativeRecords) {
    const reason = blockedKind(record, pathMatrixByPath);
    if (!reason) {
      continue;
    }
    expectedCounts.set(reason, (expectedCounts.get(reason) ?? 0) + 1);
  }

  assert.deepEqual(
    [...actualCounts.entries()].sort(),
    [...expectedCounts.entries()].sort(),
    "skip-summary rows must match matrix-derived blocked and class counts",
  );
}

function verifyHardBlockedInventorySkips(rows, pathMatrixByPath) {
  const hardBlockedKinds = new Set([
    "L4-PYTHON-REMAP",
    "L4-TOOL-DB",
    "L4-USER-M-PROCESS",
  ]);
  const byPath = new Map(rows.map((row) => {
    const [path, inventoryStatus, reason] = row.split("\t");
    return [path, { inventoryStatus, reason }];
  }));

  for (const [path, matrixRecord] of pathMatrixByPath) {
    const reason = matrixRecord.blocked;
    if (!hardBlockedKinds.has(reason)) {
      continue;
    }
    const row = byPath.get(path);
    assert.ok(row, `${path}: hard-blocked inventory row missing`);
    assert.equal(row.inventoryStatus, "SKIP", `${path}: blocked row must stay skipped`);
    assert.equal(row.reason, reason, `${path}: blocked row skip reason drift`);
  }
}

for (const record of nativeRecords) {
  const skipReason = blockedKind(record, pathMatrixByPath);
  if (skipReason) {
    recordSkip(skipReason);
    summaryRows.push(
      [
        record.path,
        "SKIP",
        skipReason,
        record.class,
        record.status,
        record.expected_failure || "-",
      ].join("\t"),
    );
    continue;
  }

  const missingVendoredRel = missingVendoredConfig(record);
  if (missingVendoredRel) {
    unexpectedFail += 1;
    summaryRows.push(
      [
        record.path,
        "FAIL",
        `MISSING_VENDORED_CONFIG:${missingVendoredRel}`,
        record.class,
        record.status,
        record.expected_failure || "-",
      ].join("\t"),
    );
    continue;
  }

  if (record.status !== "PASS" && !isRuntimeEdgeExpectedFail(record)) {
    recordSkip("UNMAPPED_EXPECTED_FAILURE");
    summaryRows.push(
      [
        record.path,
        "SKIP",
        "UNMAPPED_EXPECTED_FAILURE",
        record.class,
        record.status,
        record.expected_failure || "-",
      ].join("\t"),
    );
    continue;
  }

  const machineRel = posix.dirname(record.ini);
  const iniFile = basename(record.ini);
  const programFile = posix.relative(machineRel, record.path);
  const executionMode = executionModeFor(record);

  try {
    const machine = simMachine(machineRel, iniFile, programFile, record.tbl);
    const output = interp.runSimConfigProgram({
      files: machine.files,
      programPath: machine.programPath,
      iniPath: machine.iniPath,
      executionMode,
    });
    verifyInventoryCase(record, output, executionMode);
    executed += 1;
    passed += 1;
    summaryRows.push(
      [
        record.path,
        "PASS",
        "-",
        record.class,
        record.status,
        record.expected_failure || "-",
      ].join("\t"),
    );
  } catch (error) {
    executed += 1;
    unexpectedFail += 1;
    summaryRows.push(
      [
        record.path,
        "FAIL",
        error instanceof Error ? error.message.replace(/\s+/g, " ").trim() : String(error),
        record.class,
        record.status,
        record.expected_failure || "-",
      ].join("\t"),
    );
  }
}

assert.equal(
  summaryRows.length,
  nativeRecords.length,
  "Node inventory summary must contain exactly one row per native sim-config record",
);
assert.equal(
  executed + skipped,
  nativeRecords.length,
  "Node inventory executed plus skipped rows must cover every native sim-config record",
);
assert.equal(
  [...skipReasonCounts.values()].reduce((total, count) => total + count, 0),
  skipped,
  "Node inventory skip-summary counts must match skipped row count",
);
verifyInventorySummaryRows(summaryRows, trackedMatrixByPath);
verifyHardBlockedInventorySkips(summaryRows, pathMatrixByPath);
verifyTrackedBaselineText(
  trackedMatrixText,
  nativeRecords,
  { executed, passed, skipped, unexpectedFail },
  skipReasonCounts,
);

const nextBoundaryRows = nextBoundaryWorklistRows({
  fullProcessRows: fullProcessBoundarySummaryRecords,
  pythonFamilyRows: pythonRemapFamilyRecords,
});
const nextBoundaryRecords = verifyNextBoundaryWorklistRows(
  nextBoundaryRows,
  fullProcessBoundarySummaryRecords,
  pythonRemapFamilyRecords,
);
const boundaryProofGateRowsGenerated = boundaryProofGateRows(nextBoundaryRecords);
const boundaryProofGateRecords = verifyBoundaryProofGateRows(
  boundaryProofGateRowsGenerated,
  nextBoundaryRecords,
);
const nativeProofAlignmentRowsGenerated = nativeProofAlignmentRows(
  nextBoundaryRecords,
  boundaryProofGateRecords,
);
const nativeProofAlignmentRecords = verifyNativeProofAlignmentRows(
  nativeProofAlignmentRowsGenerated,
);
const nativeRuntimeProbeSummaryRowsGenerated = nativeRuntimeProbeSummaryRows();
const nativeRuntimeProbeSummaryRecords = verifyNativeRuntimeProbeSummaryRows(
  nativeRuntimeProbeSummaryRowsGenerated,
);
const runtimeProbeGateAlignmentRowsGenerated = runtimeProbeGateAlignmentRows({
  nativeRuntimeProbeRows: nativeRuntimeProbeSummaryRecords,
  userMRuntimeProbeGateRows: userMProcessNativeRuntimeProbeGateRecords,
  toolDbRuntimeProbeGateRows: toolDbProcessNativeRuntimeProbeGateRecords,
  pythonRuntimeProbeGateRows: pythonRemapNativeRuntimeProbeGateRecords,
});
const runtimeProbeGateAlignmentRecords = verifyRuntimeProbeGateAlignmentRows(
  runtimeProbeGateAlignmentRowsGenerated,
);
verifyNativeSourceProofRuntimeProbeConsistency({
  nativeProofAlignmentRows: nativeProofAlignmentRecords,
  nativeRuntimeProbeRows: nativeRuntimeProbeSummaryRecords,
  runtimeProbeGateAlignmentRows: runtimeProbeGateAlignmentRecords,
});
const nativeRuntimeProbeExecutionPlanRowsGenerated = nativeRuntimeProbeExecutionPlanRows({
  nativeRuntimeProbeRows: nativeRuntimeProbeSummaryRecords,
  runtimeProbeGateAlignmentRows: runtimeProbeGateAlignmentRecords,
});
const nativeRuntimeProbeExecutionPlanRecords = verifyNativeRuntimeProbeExecutionPlanRows({
  rows: nativeRuntimeProbeExecutionPlanRowsGenerated,
  nativeRuntimeProbeRows: nativeRuntimeProbeSummaryRecords,
  runtimeProbeGateAlignmentRows: runtimeProbeGateAlignmentRecords,
});
const nativeRuntimeProbePassEvidenceContractRowsGenerated =
  nativeRuntimeProbePassEvidenceContractRows({
    nativeRuntimeProbeRows: nativeRuntimeProbeSummaryRecords,
    executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
  });
const nativeRuntimeProbePassEvidenceContractRecords =
  verifyNativeRuntimeProbePassEvidenceContractRows({
    rows: nativeRuntimeProbePassEvidenceContractRowsGenerated,
    nativeRuntimeProbeRows: nativeRuntimeProbeSummaryRecords,
    executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
  });
const runtimeBoundaryNativeAlignmentSummaryRowsGenerated = runtimeBoundaryNativeAlignmentSummaryRows({
  userMRows: userMProcessNativeStateAlignmentRecords,
  toolDbRows: toolDbProcessNativeProtocolAlignmentRecords,
  pythonRows: pythonRemapNativeRuntimeAlignmentRecords,
});
const runtimeBoundaryNativeAlignmentSummaryRecords =
  verifyRuntimeBoundaryNativeAlignmentSummaryRows(
    runtimeBoundaryNativeAlignmentSummaryRowsGenerated,
  );
const runtimeBoundaryContractSummaryRowsGenerated = runtimeBoundaryContractSummaryRows({
  userMRows: userMProcessTransitionPlanRecords,
  toolDbRows: toolDbProcessTransactionPlanRecords,
  pythonRows: pythonRemapRuntimeContractRecords,
  runtimeNativeAlignmentRows: runtimeBoundaryNativeAlignmentSummaryRecords,
});
const runtimeBoundaryContractSummaryRecords = verifyRuntimeBoundaryContractSummaryRows(
  runtimeBoundaryContractSummaryRowsGenerated,
);
const runtimeFamilyContractAlignmentConsistencyOk =
  verifyRuntimeFamilyContractAlignmentConsistency({
    userMTransitionRows: userMProcessTransitionPlanRecords,
    userMRuntimeStatePlanRows: userMProcessNativeRuntimeStatePlanRecords,
    userMRuntimeReadinessRows: userMProcessNativeRuntimeReadinessRecords,
    userMRuntimeProbeGateRows: userMProcessNativeRuntimeProbeGateRecords,
    toolDbTransactionRows: toolDbProcessTransactionPlanRecords,
    toolDbRuntimeReadinessRows: toolDbProcessNativeRuntimeReadinessRecords,
    toolDbRuntimeProbeGateRows: toolDbProcessNativeRuntimeProbeGateRecords,
    pythonRuntimeContractRows: pythonRemapRuntimeContractRecords,
    pythonRuntimeReadinessRows: pythonRemapNativeRuntimeReadinessRecords,
    pythonRuntimeStatePlanRows: pythonRemapNativeRuntimeStatePlanRecords,
    pythonRuntimeFixturePlanRows: pythonRemapNativeRuntimeFixturePlanRecords,
    pythonRuntimeProbeGateRows: pythonRemapNativeRuntimeProbeGateRecords,
    runtimeContractSummaryRows: runtimeBoundaryContractSummaryRecords,
    runtimeNativeAlignmentRows: runtimeBoundaryNativeAlignmentSummaryRecords,
  });
const blockedRuntimePromotionLockRowsGenerated = blockedRuntimePromotionLockRows({
  worklistRows: nextBoundaryRecords,
  proofGateRows: boundaryProofGateRecords,
  runtimeNativeAlignmentRows: runtimeBoundaryNativeAlignmentSummaryRecords,
});
const blockedRuntimePromotionLockRecords = verifyBlockedRuntimePromotionLockRows(
  blockedRuntimePromotionLockRowsGenerated,
  nextBoundaryRecords,
);
const runtimeBoundaryPromotionReadinessRowsGenerated = runtimeBoundaryPromotionReadinessRows({
  executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
  passEvidenceRows: nativeRuntimeProbePassEvidenceContractRecords,
  promotionLockRows: blockedRuntimePromotionLockRecords,
});
const runtimeBoundaryPromotionReadinessRecords = verifyRuntimeBoundaryPromotionReadinessRows({
  rows: runtimeBoundaryPromotionReadinessRowsGenerated,
  executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
  passEvidenceRows: nativeRuntimeProbePassEvidenceContractRecords,
  promotionLockRows: blockedRuntimePromotionLockRecords,
});
const runtimeBoundaryPromotionBlockerRowsGenerated = runtimeBoundaryPromotionBlockerRows({
  promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
  executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
});
const runtimeBoundaryPromotionBlockerRecords = verifyRuntimeBoundaryPromotionBlockerRows({
  rows: runtimeBoundaryPromotionBlockerRowsGenerated,
  promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
  executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
});
const nextBoundaryRecommendationRowsGenerated = nextBoundaryRecommendationRows({
  worklistRows: nextBoundaryRecords,
  promotionLockRows: blockedRuntimePromotionLockRecords,
  runtimeContractRows: runtimeBoundaryContractSummaryRecords,
  userMRuntimeProbeGateRows: userMProcessNativeRuntimeProbeGateRecords,
  toolDbTransactionRows: toolDbProcessTransactionPlanRecords,
  toolDbRuntimeProbeGateRows: toolDbProcessNativeRuntimeProbeGateRecords,
  pythonFixturePlanRows: pythonRemapNativeRuntimeFixturePlanRecords,
});
const nextBoundaryRecommendationRecords =
  verifyNextBoundaryRecommendationRows(nextBoundaryRecommendationRowsGenerated);
const blockedRuntimeWorklistRecommendationConsistencyOk =
  verifyBlockedRuntimeWorklistRecommendationConsistency({
    worklistRows: nextBoundaryRecords,
    proofGateRows: boundaryProofGateRecords,
    promotionLockRows: blockedRuntimePromotionLockRecords,
    runtimeContractRows: runtimeBoundaryContractSummaryRecords,
    recommendationRows: nextBoundaryRecommendationRecords,
  });
const runtimeBoundaryPostNativePassGateRowsGenerated = runtimeBoundaryPostNativePassGateRows({
  promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
  recommendationRows: nextBoundaryRecommendationRecords,
});
const runtimeBoundaryPostNativePassGateRecords = verifyRuntimeBoundaryPostNativePassGateRows({
  rows: runtimeBoundaryPostNativePassGateRowsGenerated,
  promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
  recommendationRows: nextBoundaryRecommendationRecords,
});
const runtimeBoundaryHostPreflightRowsGenerated = runtimeBoundaryHostPreflightRows({
  userMRuntimeProbeGateRows: userMProcessNativeRuntimeProbeGateRecords,
  toolDbRuntimeProbeGateRows: toolDbProcessNativeRuntimeProbeGateRecords,
  pythonRuntimeProbeGateRows: pythonRemapNativeRuntimeProbeGateRecords,
  executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
});
const runtimeBoundaryHostPreflightRecords = verifyRuntimeBoundaryHostPreflightRows({
  rows: runtimeBoundaryHostPreflightRowsGenerated,
  userMRuntimeProbeGateRows: userMProcessNativeRuntimeProbeGateRecords,
  toolDbRuntimeProbeGateRows: toolDbProcessNativeRuntimeProbeGateRecords,
  pythonRuntimeProbeGateRows: pythonRemapNativeRuntimeProbeGateRecords,
  executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
});
const runtimeBoundaryHostRequirementSummaryRowsGenerated =
  runtimeBoundaryHostRequirementSummaryRows(runtimeBoundaryHostPreflightRecords);
const runtimeBoundaryHostRequirementSummaryRecords =
  verifyRuntimeBoundaryHostRequirementSummaryRows(
    runtimeBoundaryHostRequirementSummaryRowsGenerated,
    runtimeBoundaryHostPreflightRecords,
  );
const runtimeBoundaryHostUnblockPlanRowsGenerated = runtimeBoundaryHostUnblockPlanRows({
  requirementSummaryRows: runtimeBoundaryHostRequirementSummaryRecords,
  preflightRows: runtimeBoundaryHostPreflightRecords,
});
const runtimeBoundaryHostUnblockPlanRecords = verifyRuntimeBoundaryHostUnblockPlanRows({
  rows: runtimeBoundaryHostUnblockPlanRowsGenerated,
  requirementSummaryRows: runtimeBoundaryHostRequirementSummaryRecords,
  preflightRows: runtimeBoundaryHostPreflightRecords,
});
const runtimeBoundaryFamilyHostReadinessRowsGenerated =
  runtimeBoundaryFamilyHostReadinessRows(runtimeBoundaryHostPreflightRecords);
const runtimeBoundaryFamilyHostReadinessRecords =
  verifyRuntimeBoundaryFamilyHostReadinessRows(
    runtimeBoundaryFamilyHostReadinessRowsGenerated,
    runtimeBoundaryHostPreflightRecords,
  );
const blockedRuntimeHostRequirementConsistencyOk =
  verifyBlockedRuntimeHostRequirementConsistency({
    requirementSummaryRows: runtimeBoundaryHostRequirementSummaryRecords,
    unblockPlanRows: runtimeBoundaryHostUnblockPlanRecords,
    familyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
  });
const runtimeBoundaryHostReadinessRollupRowsGenerated = runtimeBoundaryHostReadinessRollupRows({
  familyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
  requirementSummaryRows: runtimeBoundaryHostRequirementSummaryRecords,
});
const runtimeBoundaryHostReadinessRollupRecords =
  verifyRuntimeBoundaryHostReadinessRollupRows({
    rows: runtimeBoundaryHostReadinessRollupRowsGenerated,
    familyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
    requirementSummaryRows: runtimeBoundaryHostRequirementSummaryRecords,
  });
const runtimeBoundaryOptInProbeDispatchPlanRowsGenerated =
  runtimeBoundaryOptInProbeDispatchPlanRows({
    familyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
    hostReadinessRollupRows: runtimeBoundaryHostReadinessRollupRecords,
  });
const runtimeBoundaryOptInProbeDispatchPlanRecords =
  verifyRuntimeBoundaryOptInProbeDispatchPlanRows({
    rows: runtimeBoundaryOptInProbeDispatchPlanRowsGenerated,
    familyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
    hostReadinessRollupRows: runtimeBoundaryHostReadinessRollupRecords,
  });
const runtimeBoundaryOptInProbeDispatchRollupRowsGenerated =
  runtimeBoundaryOptInProbeDispatchRollupRows(runtimeBoundaryOptInProbeDispatchPlanRecords);
const runtimeBoundaryOptInProbeDispatchRollupRecords =
  verifyRuntimeBoundaryOptInProbeDispatchRollupRows({
    rows: runtimeBoundaryOptInProbeDispatchRollupRowsGenerated,
    dispatchPlanRows: runtimeBoundaryOptInProbeDispatchPlanRecords,
  });
const runtimeBoundaryOptInProbeSkipEvidenceContractRowsGenerated =
  runtimeBoundaryOptInProbeSkipEvidenceContractRows({
    dispatchPlanRows: runtimeBoundaryOptInProbeDispatchPlanRecords,
    passEvidenceRows: nativeRuntimeProbePassEvidenceContractRecords,
  });
const runtimeBoundaryOptInProbeSkipEvidenceContractRecords =
  verifyRuntimeBoundaryOptInProbeSkipEvidenceContractRows({
    rows: runtimeBoundaryOptInProbeSkipEvidenceContractRowsGenerated,
    dispatchPlanRows: runtimeBoundaryOptInProbeDispatchPlanRecords,
    passEvidenceRows: nativeRuntimeProbePassEvidenceContractRecords,
  });
const blockedRuntimeProbeExecutionConsistencyOk =
  verifyBlockedRuntimeProbeExecutionConsistency({
    executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
    passEvidenceRows: nativeRuntimeProbePassEvidenceContractRecords,
    hostPreflightRows: runtimeBoundaryHostPreflightRecords,
    dispatchPlanRows: runtimeBoundaryOptInProbeDispatchPlanRecords,
    skipEvidenceContractRows: runtimeBoundaryOptInProbeSkipEvidenceContractRecords,
  });
const runtimeBoundaryOptInProbeSkipEvidenceRollupRowsGenerated =
  runtimeBoundaryOptInProbeSkipEvidenceRollupRows(runtimeBoundaryOptInProbeSkipEvidenceContractRecords);
const runtimeBoundaryOptInProbeSkipEvidenceRollupRecords =
  verifyRuntimeBoundaryOptInProbeSkipEvidenceRollupRows({
    rows: runtimeBoundaryOptInProbeSkipEvidenceRollupRowsGenerated,
    skipEvidenceContractRows: runtimeBoundaryOptInProbeSkipEvidenceContractRecords,
  });
const runtimeBoundaryNativeEvidenceAcceptanceGateRowsGenerated =
  runtimeBoundaryNativeEvidenceAcceptanceGateRows({
    skipEvidenceContractRows: runtimeBoundaryOptInProbeSkipEvidenceContractRecords,
    promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
    postNativePassGateRows: runtimeBoundaryPostNativePassGateRecords,
  });
const runtimeBoundaryNativeEvidenceAcceptanceGateRecords =
  verifyRuntimeBoundaryNativeEvidenceAcceptanceGateRows({
    rows: runtimeBoundaryNativeEvidenceAcceptanceGateRowsGenerated,
    skipEvidenceContractRows: runtimeBoundaryOptInProbeSkipEvidenceContractRecords,
    promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
    postNativePassGateRows: runtimeBoundaryPostNativePassGateRecords,
  });
const blockedRuntimePromotionGateConsistencyOk =
  verifyBlockedRuntimePromotionGateConsistency({
    promotionLockRows: blockedRuntimePromotionLockRecords,
    promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
    promotionBlockerRows: runtimeBoundaryPromotionBlockerRecords,
    postNativePassGateRows: runtimeBoundaryPostNativePassGateRecords,
    nativeEvidenceAcceptanceGateRows: runtimeBoundaryNativeEvidenceAcceptanceGateRecords,
    passEvidenceRows: nativeRuntimeProbePassEvidenceContractRecords,
  });
const blockedRuntimeRollupConsistencyOk = verifyBlockedRuntimeRollupConsistency({
  hostReadinessRollupRows: runtimeBoundaryHostReadinessRollupRecords,
  dispatchRollupRows: runtimeBoundaryOptInProbeDispatchRollupRecords,
  skipEvidenceRollupRows: runtimeBoundaryOptInProbeSkipEvidenceRollupRecords,
  familyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
  dispatchPlanRows: runtimeBoundaryOptInProbeDispatchPlanRecords,
  skipEvidenceContractRows: runtimeBoundaryOptInProbeSkipEvidenceContractRecords,
});
verifyBlockedRuntimeOptInGateConsistency({
  recommendationRows: nextBoundaryRecommendationRecords,
  executionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
  promotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
  promotionBlockerRows: runtimeBoundaryPromotionBlockerRecords,
  postNativePassGateRows: runtimeBoundaryPostNativePassGateRecords,
  hostPreflightRows: runtimeBoundaryHostPreflightRecords,
  familyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
  dispatchPlanRows: runtimeBoundaryOptInProbeDispatchPlanRecords,
  skipEvidenceContractRows: runtimeBoundaryOptInProbeSkipEvidenceContractRecords,
  evidenceAcceptanceGateRows: runtimeBoundaryNativeEvidenceAcceptanceGateRecords,
});
const boundaryPhaseCompletionRows = boundaryPhaseCompletionSummaryRows({
  generatedArtifactPaths: generatedSimConfigInventoryArtifactPaths,
  documentationPaths: [
    compatibilityValidationPath,
    trackedMatrixPath,
    fullProcessBoundaryDesignPath,
  ],
  boundaryRows: boundarySummaryRecords,
  iniBoundaryRows: iniBoundarySummaryRecords,
  blockedRows: blockedDependencySummaryRecords,
  fullProcessRows: fullProcessBoundarySummaryRecords,
  userMTransitionRows: userMProcessTransitionPlanRecords,
  userMRuntimeStatePlanRows: userMProcessNativeRuntimeStatePlanRecords,
  userMRuntimeReadinessRows: userMProcessNativeRuntimeReadinessRecords,
  userMRuntimeProbeGateRows: userMProcessNativeRuntimeProbeGateRecords,
  toolDbTransactionRows: toolDbProcessTransactionPlanRecords,
  toolDbRuntimeReadinessRows: toolDbProcessNativeRuntimeReadinessRecords,
  toolDbRuntimeProbeGateRows: toolDbProcessNativeRuntimeProbeGateRecords,
  pythonFamilyRows: pythonRemapFamilyRecords,
  pythonRuntimeContractRows: pythonRemapRuntimeContractRecords,
  pythonRuntimeReadinessRows: pythonRemapNativeRuntimeReadinessRecords,
  pythonRuntimeProbeGateRows: pythonRemapNativeRuntimeProbeGateRecords,
  pythonRuntimeStatePlanRows: pythonRemapNativeRuntimeStatePlanRecords,
  pythonRuntimeFixturePlanRows: pythonRemapNativeRuntimeFixturePlanRecords,
  runtimeContractSummaryRows: runtimeBoundaryContractSummaryRecords,
  runtimeFamilyContractAlignmentConsistencyOk,
  nativeProofAlignmentRows: nativeProofAlignmentRecords,
  nativeRuntimeProbeRows: nativeRuntimeProbeSummaryRecords,
  runtimeNativeAlignmentRows: runtimeBoundaryNativeAlignmentSummaryRecords,
  runtimeProbeGateAlignmentRows: runtimeProbeGateAlignmentRecords,
  blockedRuntimeWorklistRecommendationConsistencyOk,
  nativeRuntimeProbeExecutionPlanRows: nativeRuntimeProbeExecutionPlanRecords,
  nativeRuntimeProbePassEvidenceRows: nativeRuntimeProbePassEvidenceContractRecords,
  blockedRuntimeProbeExecutionConsistencyOk,
  runtimeBoundaryPromotionReadinessRows: runtimeBoundaryPromotionReadinessRecords,
  runtimeBoundaryPromotionBlockerRows: runtimeBoundaryPromotionBlockerRecords,
  runtimeBoundaryPostNativePassGateRows: runtimeBoundaryPostNativePassGateRecords,
  blockedRuntimePromotionGateConsistencyOk,
  runtimeBoundaryHostPreflightRows: runtimeBoundaryHostPreflightRecords,
  runtimeBoundaryHostRequirementSummaryRows: runtimeBoundaryHostRequirementSummaryRecords,
  runtimeBoundaryHostUnblockPlanRows: runtimeBoundaryHostUnblockPlanRecords,
  runtimeBoundaryFamilyHostReadinessRows: runtimeBoundaryFamilyHostReadinessRecords,
  runtimeBoundaryHostReadinessRollupRows: runtimeBoundaryHostReadinessRollupRecords,
  blockedRuntimeHostRequirementConsistencyOk,
  runtimeBoundaryOptInProbeDispatchPlanRows: runtimeBoundaryOptInProbeDispatchPlanRecords,
  runtimeBoundaryOptInProbeDispatchRollupRows: runtimeBoundaryOptInProbeDispatchRollupRecords,
  runtimeBoundaryOptInProbeSkipEvidenceContractRows: runtimeBoundaryOptInProbeSkipEvidenceContractRecords,
  runtimeBoundaryOptInProbeSkipEvidenceRollupRows: runtimeBoundaryOptInProbeSkipEvidenceRollupRecords,
  runtimeBoundaryNativeEvidenceAcceptanceGateRows: runtimeBoundaryNativeEvidenceAcceptanceGateRecords,
  nextBoundaryRecommendationRows: nextBoundaryRecommendationRecords,
  blockedRuntimeRollupConsistencyOk,
  trackedRows: trackedMatrixRecords,
  inventoryRows: summaryRows,
});
verifyBoundaryPhaseCompletionSummaryRows(boundaryPhaseCompletionRows);

writeFileSync(
  summaryPath,
  `${[
    "path\tinventory_status\tskip_or_fail_reason\tclass\tnative_status\tnative_expected_failure",
    ...summaryRows,
  ].join("\n")}\n`,
);

const skipSummaryRows = [...skipReasonCounts.entries()]
  .sort(([left], [right]) => left.localeCompare(right))
  .map(([reason, count]) => `${reason}\t${count}`);
verifySkipSummaryRows(skipSummaryRows, skipped, nativeRecords, pathMatrixByPath);
writeFileSync(
  skipSummaryPath,
  `${[
    "skip_or_block_reason\tcount",
    ...skipSummaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  boundarySummaryPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "recommended_blocked",
      "dependencies",
      "user_m_execution_codes",
      "user_m_unstaged_execution_codes",
      "user_m_vendored_count",
      "db_program",
      "hal_process",
      "ui_process",
      "halui_mdi_process",
      "python_process",
      "python_ui_db_process",
      "python_remap_process",
    ].join("\t"),
    ...boundarySummaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  iniBoundarySummaryPath,
  `${[
    [
      "ini",
      "path_count",
      "vendored",
      "report_available",
      "blocked",
      "recommended_blocked",
      "dependencies",
      "user_m_execution_codes",
      "user_m_unstaged_execution_codes",
      "user_m_vendored_count",
      "db_program",
      "hal_process",
      "ui_process",
      "halui_mdi_process",
      "python_process",
      "python_ui_db_process",
      "python_remap_process",
      "hard_block_policy_aligned",
    ].join("\t"),
    ...iniBoundarySummaryRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  blockedDependencySummaryPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "family",
      "source_available",
      "python_modules",
      "python_remap_functions",
      "prolog_functions",
      "epilog_functions",
      "remap_ngc_files",
      "ngc_only_subpaths",
      "hal_process",
      "ui_process",
      "halui_mdi_process",
      "db_program",
      "tool_db_protocol_evidence",
      "user_m_execution_codes",
      "user_m_process_files",
      "user_m_process_effects",
      "linuxcnc_owner",
      "notes",
    ].join("\t"),
    ...blockedDependencySummaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  fullProcessBoundarySummaryPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "design_status",
      "boundary_kind",
      "linuxcnc_owner",
      "runtime_owner_evidence",
      "required_native_proof",
      "required_node_proof",
      "required_browser_proof",
      "browser_policy",
      "execution_enabled",
      "notes",
    ].join("\t"),
    ...fullProcessBoundarySummaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessBoundarySummaryPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "design_status",
      "boundary_kind",
      "linuxcnc_owner",
      "user_m_execution_codes",
      "user_m_process_files",
      "remap_call_chain",
      "state_targets",
      "runtime_owner_evidence",
      "required_native_proof",
      "required_node_proof",
      "required_browser_proof",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...userMProcessBoundarySummaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessStateTargetsPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "user_m_code",
      "source_file",
      "remap_callers",
      "state_mode",
      "guard_pin",
      "target_pin",
      "source_section",
      "source_field",
      "expected_value",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
    ].join("\t"),
    ...userMProcessStateTargetRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessTransitionPlanPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "transition_step",
      "remap_code",
      "user_m_code",
      "remap_caller",
      "switchkins_output_pin",
      "switchkins_target",
      "active_g5x",
      "work_offset_pocket",
      "guard_pin",
      "state_mode",
      "state_target_count",
      "expected_state_pins",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...userMProcessTransitionPlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessNativeStateAlignmentPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "user_m_code",
      "target_pin",
      "source_section",
      "source_field",
      "expected_value",
      "native_stdout_available",
      "native_value_key",
      "native_value",
      "native_ok_key",
      "native_ok_value",
      "source_proof_key",
      "source_proof_value",
      "alignment_ok",
      "execution_enabled",
      "promotion_allowed",
      "proof_status",
      "notes",
    ].join("\t"),
    ...userMProcessNativeStateAlignmentRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessNativeTransitionAlignmentPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "remap_code",
      "user_m_code",
      "switchkins_output_pin",
      "switchkins_target",
      "active_g5x",
      "work_offset_pocket",
      "native_stdout_available",
      "native_switchkins_output_pin",
      "native_switchkins_target",
      "native_active_g5x",
      "native_work_offset_pocket",
      "native_call_key",
      "native_call_value",
      "native_transition_key",
      "native_transition_value",
      "alignment_ok",
      "execution_enabled",
      "promotion_allowed",
      "proof_status",
      "notes",
    ].join("\t"),
    ...userMProcessNativeTransitionAlignmentRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessNativeRuntimeStatePlanPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "runtime_step",
      "remap_code",
      "user_m_code",
      "required_runtime",
      "required_environment",
      "switchkins_output_pin",
      "switchkins_target",
      "active_g5x",
      "work_offset_pocket",
      "guard_pin",
      "state_mode",
      "state_target_count",
      "expected_state_pins",
      "expected_state_values",
      "source_alignment_artifacts",
      "source_alignment_ok",
      "native_runtime_status",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...userMProcessNativeRuntimeStatePlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessNativeRuntimeReadinessPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "required_runtime",
      "requirement_kind",
      "requirement",
      "purpose",
      "available",
      "evidence",
      "native_runtime_status",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...userMProcessNativeRuntimeReadinessRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  userMProcessNativeRuntimeProbeGatePath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "runtime_step",
      "remap_code",
      "user_m_code",
      "required_runtime",
      "runtime_requirements",
      "missing_requirements",
      "runtime_ready",
      "source_proof_ready",
      "required_native_proof",
      "gate_status",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...userMProcessNativeRuntimeProbeGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  toolDbProcessBoundarySummaryPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "design_status",
      "boundary_kind",
      "linuxcnc_owner",
      "db_program",
      "protocol_messages",
      "db_program_callbacks",
      "state_targets",
      "runtime_owner_evidence",
      "required_native_proof",
      "required_node_proof",
      "required_browser_proof",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...toolDbProcessBoundarySummaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  toolDbProcessProtocolGatesPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "gate_kind",
      "gate",
      "db_program",
      "linuxcnc_owner",
      "runtime_owner_evidence",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
    ].join("\t"),
    ...toolDbProcessProtocolGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  toolDbProcessTransactionPlanPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "transaction_step",
      "transaction_phase",
      "protocol_message",
      "db_program_callback",
      "state_targets",
      "db_program",
      "required_native_proof",
      "required_node_proof",
      "required_browser_proof",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...toolDbProcessTransactionPlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  toolDbProcessNativeProtocolAlignmentPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "gate_kind",
      "gate",
      "proof_kind",
      "native_stdout_available",
      "native_proof_key",
      "native_proof_value",
      "source_proof_key",
      "alignment_ok",
      "execution_enabled",
      "promotion_allowed",
      "proof_status",
      "notes",
    ].join("\t"),
    ...toolDbProcessNativeProtocolAlignmentRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  toolDbProcessNativeRuntimeReadinessPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "required_runtime",
      "requirement_kind",
      "requirement",
      "purpose",
      "available",
      "evidence",
      "db_program",
      "native_runtime_status",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...toolDbProcessNativeRuntimeReadinessRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  toolDbProcessNativeRuntimeProbeGatePath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "db_program",
      "required_runtime",
      "python3_available",
      "python3_sufficient",
      "tool_table_fallback_sufficient",
      "db_program_source_ready",
      "linuxcnc_python_modules_ready",
      "protocol_contract_ready",
      "protocol_transactions",
      "runtime_requirements",
      "missing_requirements",
      "runtime_ready",
      "source_proof_ready",
      "required_native_proof",
      "gate_status",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...toolDbProcessNativeRuntimeProbeGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapBoundarySummaryPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "design_status",
      "python_modules",
      "python_remap_functions",
      "prolog_functions",
      "epilog_functions",
      "remap_ngc_files",
      "ngc_only_subpaths",
      "hal_process",
      "ui_process",
      "halui_mdi_process",
      "linuxcnc_owner",
      "python_runtime_evidence",
      "required_boundary",
      "execution_enabled",
      "notes",
    ].join("\t"),
    ...pythonRemapBoundarySummaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapRuntimeGatesPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "gate_kind",
      "gate",
      "linuxcnc_owner",
      "runtime_owner_evidence",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...pythonRemapRuntimeGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapNativeRuntimeAlignmentPath,
  `${[
    [
      "path",
      "ini",
      "blocked",
      "gate_kind",
      "gate",
      "proof_kind",
      "native_stdout_available",
      "native_proof_key",
      "native_proof_value",
      "source_proof_key",
      "alignment_ok",
      "execution_enabled",
      "promotion_allowed",
      "proof_status",
      "notes",
    ].join("\t"),
    ...pythonRemapNativeRuntimeAlignmentRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapFamilySummaryPath,
  `${[
    [
      "family",
      "row_count",
      "ini_count",
      "python_modules",
      "python_remap_functions",
      "prolog_functions",
      "epilog_functions",
      "ngc_only_subpaths",
      "python_runtime_evidence",
      "hal_process",
      "ui_process",
      "halui_mdi_process",
      "execution_enabled",
      "notes",
    ].join("\t"),
    ...pythonRemapFamilyRows,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapRuntimeContractPath,
  `${[
    [
      "family",
      "blocked",
      "design_status",
      "row_count",
      "ini_count",
      "runtime_phases",
      "python_modules",
      "python_callables",
      "ngc_only_subpaths",
      "process_assumptions",
      "runtime_owner_evidence",
      "required_native_proof",
      "required_node_proof",
      "required_browser_proof",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...pythonRemapRuntimeContractRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapNativeRuntimeReadinessPath,
  `${[
    [
      "family",
      "blocked",
      "required_runtime",
      "requirement_kind",
      "requirement",
      "purpose",
      "available",
      "evidence",
      "native_runtime_status",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...pythonRemapNativeRuntimeReadinessRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapNativeRuntimeProbeGatePath,
  `${[
    [
      "family",
      "blocked",
      "fixture_id",
      "required_runtime",
      "python3_available",
      "python3_sufficient",
      "linuxcnc_available",
      "runtime_owner_sources_ready",
      "representative_module_imports",
      "representative_modules_ready",
      "runtime_requirements",
      "missing_requirements",
      "runtime_ready",
      "source_proof_ready",
      "required_native_proof",
      "gate_status",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...pythonRemapNativeRuntimeProbeGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapNativeRuntimeStatePlanPath,
  `${[
    [
      "family",
      "blocked",
      "required_runtime",
      "runtime_phases",
      "python_modules",
      "python_callables",
      "ngc_only_subpaths",
      "process_assumptions",
      "required_environment",
      "readiness_requirement_count",
      "readiness_available_count",
      "source_alignment_artifacts",
      "source_alignment_ok",
      "native_runtime_status",
      "required_state_probe",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...pythonRemapNativeRuntimeStatePlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  pythonRemapNativeRuntimeFixturePlanPath,
  `${[
    [
      "family",
      "blocked",
      "required_runtime",
      "selection_reason",
      "fixture_id",
      "fixture_scope",
      "runtime_phases",
      "python_modules",
      "process_assumptions",
      "required_environment",
      "readiness_requirement_count",
      "readiness_available_count",
      "source_alignment_artifacts",
      "source_alignment_ok",
      "expected_runtime_observations",
      "expected_module_inputs",
      "proof_kind",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...pythonRemapNativeRuntimeFixturePlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryContractSummaryPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "contract_artifact",
      "contract_scope",
      "contract_row_count",
      "pending_count",
      "execution_disabled_count",
      "promotion_disabled_count",
      "runtime_alignment_artifact",
      "runtime_alignment_row_count",
      "runtime_alignment_ok",
      "contract_ok",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryContractSummaryRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  boundaryPhaseCompletionSummaryPath,
  `${[
    [
      "criterion",
      "passed",
      "count",
      "evidence",
    ].join("\t"),
    ...boundaryPhaseCompletionRows,
  ].join("\n")}\n`,
);

writeFileSync(
  nextBoundaryWorklistPath,
  `${[
    [
      "priority",
      "boundary_kind",
      "target",
      "blocked",
      "design_status",
      "linuxcnc_owner",
      "runtime_owner_evidence",
      "required_native_proof",
      "required_node_proof",
      "required_browser_proof",
      "execution_enabled",
      "promotion_allowed",
      "next_action",
      "notes",
    ].join("\t"),
    ...nextBoundaryRows,
  ].join("\n")}\n`,
);

writeFileSync(
  boundaryProofGatesPath,
  `${[
    [
      "priority",
      "boundary_kind",
      "target",
      "proof_layer",
      "blocked",
      "design_status",
      "linuxcnc_owner",
      "runtime_owner_evidence",
      "required_proof",
      "proof_status",
      "execution_enabled",
      "promotion_allowed",
      "next_action",
      "notes",
    ].join("\t"),
    ...boundaryProofGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  nativeProofAlignmentSummaryPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "proof_key",
      "native_summary_available",
      "proof_value",
      "execution_enabled",
      "promotion_allowed",
      "matching_worklist_count",
      "matching_native_gate_count",
      "alignment_ok",
      "notes",
    ].join("\t"),
    ...nativeProofAlignmentRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  nativeRuntimeProbeSummaryPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "runtime_probe",
      "required_native_proof",
      "opt_in_env",
      "runtime_ready",
      "source_proof_ready",
      "probe_status",
      "execution_enabled",
      "promotion_allowed",
      "missing_requirements",
      "probe_note",
      "stdout_log",
    ].join("\t"),
    ...nativeRuntimeProbeSummaryRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeProbeGateAlignmentPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "gate_artifact",
      "native_runtime_probe",
      "gate_required_native_proof",
      "native_required_native_proof",
      "native_opt_in_env",
      "gate_runtime_ready",
      "native_runtime_ready",
      "gate_source_proof_ready",
      "native_source_proof_ready",
      "gate_status",
      "native_probe_status",
      "gate_missing_requirements",
      "native_missing_requirements",
      "required_native_proof_match",
      "missing_requirements_match",
      "execution_disabled_match",
      "promotion_disabled_match",
      "status_compatible",
      "alignment_ok",
      "notes",
    ].join("\t"),
    ...runtimeProbeGateAlignmentRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  nativeRuntimeProbeExecutionPlanPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "runtime_probe",
      "required_native_proof",
      "opt_in_env",
      "execution_command",
      "runtime_ready",
      "source_proof_ready",
      "current_probe_status",
      "expected_pass_status",
      "missing_requirements",
      "gate_alignment_ok",
      "promotion_requires",
      "execution_enabled",
      "promotion_allowed",
      "plan_status",
      "notes",
    ].join("\t"),
    ...nativeRuntimeProbeExecutionPlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  nativeRuntimeProbePassEvidenceContractPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "runtime_probe",
      "expected_pass_status",
      "stdout_log",
      "expected_evidence_keys",
      "current_probe_status",
      "evidence_required_now",
      "observed_evidence_ready",
      "missing_evidence_keys",
      "execution_enabled",
      "promotion_allowed",
      "evidence_status",
      "notes",
    ].join("\t"),
    ...nativeRuntimeProbePassEvidenceContractRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryNativeAlignmentSummaryPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "row_count",
      "native_stdout_available_count",
      "alignment_ok_count",
      "pending_count",
      "execution_disabled_count",
      "promotion_disabled_count",
      "artifact",
      "summary_ok",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryNativeAlignmentSummaryRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  blockedRuntimePromotionLockPath,
  `${[
    [
      "priority",
      "boundary_kind",
      "target",
      "blocked",
      "design_status",
      "execution_enabled",
      "promotion_allowed",
      "native_gate_pending",
      "node_gate_pending",
      "browser_gate_pending",
      "runtime_alignment_artifact",
      "runtime_alignment_row_count",
      "runtime_alignment_ok",
      "next_action",
      "lock_active",
      "notes",
    ].join("\t"),
    ...blockedRuntimePromotionLockRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryPromotionReadinessPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "current_probe_status",
      "expected_pass_status",
      "native_pass_ready",
      "native_evidence_status",
      "native_evidence_ready",
      "node_inventory_gate_complete",
      "browser_smoke_gate_complete",
      "promotion_lock_active",
      "manual_lock_update_required",
      "promotion_ready",
      "execution_enabled",
      "promotion_allowed",
      "blocking_reason",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryPromotionReadinessRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryPromotionBlockersPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "promotion_ready",
      "blocker_count",
      "blocker_keys",
      "missing_runtime_requirements",
      "next_unblock_action",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryPromotionBlockerRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryPostNativePassGatesPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "current_probe_status",
      "expected_pass_status",
      "native_pass_ready",
      "native_evidence_ready",
      "required_node_proof",
      "required_browser_proof",
      "node_gate_status",
      "browser_gate_status",
      "manual_lock_update_required",
      "promotion_lock_active",
      "execution_enabled",
      "promotion_allowed",
      "gate_status",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryPostNativePassGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryHostPreflightPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "required_runtime",
      "runtime_requirements",
      "missing_requirements",
      "runtime_ready",
      "source_proof_ready",
      "required_native_proof",
      "opt_in_env",
      "execution_command",
      "current_probe_status",
      "preflight_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryHostPreflightRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryHostRequirementSummaryPath,
  `${[
    [
      "requirement",
      "requirement_kind",
      "available",
      "required_by_count",
      "required_by",
      "missing_for",
      "blocked_families",
      "opt_in_envs",
      "missing_blocks_runtime",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryHostRequirementSummaryRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryHostUnblockPlanPath,
  `${[
    [
      "requirement",
      "requirement_kind",
      "available",
      "missing_for",
      "affected_targets",
      "opt_in_envs",
      "affected_execution_commands",
      "remaining_missing_after_requirement",
      "unblocks_when_available",
      "next_action",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryHostUnblockPlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryFamilyHostReadinessPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "required_runtime",
      "missing_requirement_count",
      "missing_host_requirements",
      "available_requirement_count",
      "available_requirements",
      "opt_in_env",
      "execution_command",
      "current_probe_status",
      "preflight_status",
      "family_host_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryFamilyHostReadinessRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryHostReadinessRollupPath,
  `${[
    [
      "scope",
      "family_count",
      "host_ready_family_count",
      "host_blocked_family_count",
      "blocked_families",
      "missing_host_requirements",
      "missing_host_requirement_count",
      "ready_opt_in_command_count",
      "ready_opt_in_commands",
      "blocked_opt_in_commands",
      "host_readiness_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryHostReadinessRollupRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryOptInProbeDispatchPlanPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "opt_in_env",
      "execution_command",
      "family_host_status",
      "missing_host_requirements",
      "host_readiness_status",
      "host_action",
      "dispatch_allowed",
      "execution_enabled",
      "promotion_allowed",
      "next_action",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryOptInProbeDispatchPlanRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryOptInProbeDispatchRollupPath,
  `${[
    [
      "scope",
      "probe_count",
      "dispatch_allowed_count",
      "dispatch_blocked_count",
      "blocked_families",
      "dispatch_actions",
      "dispatch_allowed_commands",
      "dispatch_blocked_commands",
      "missing_host_requirements",
      "dispatch_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryOptInProbeDispatchRollupRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryOptInProbeSkipEvidenceContractPath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "runtime_probe",
      "opt_in_env",
      "execution_command",
      "host_action",
      "skip_reason",
      "missing_host_requirements",
      "current_probe_status",
      "evidence_required_now",
      "observed_evidence_ready",
      "native_evidence_status",
      "skip_evidence_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryOptInProbeSkipEvidenceContractRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryOptInProbeSkipEvidenceRollupPath,
  `${[
    [
      "scope",
      "probe_count",
      "skip_count",
      "evidence_required_now_count",
      "observed_evidence_ready_count",
      "skipped_families",
      "skip_reasons",
      "missing_host_requirements",
      "current_probe_statuses",
      "native_evidence_statuses",
      "skip_evidence_statuses",
      "evidence_rollup_status",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryOptInProbeSkipEvidenceRollupRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  runtimeBoundaryNativeEvidenceAcceptanceGatePath,
  `${[
    [
      "boundary_class",
      "boundary_kind",
      "target",
      "blocked",
      "runtime_probe",
      "current_probe_status",
      "native_evidence_status",
      "evidence_required_now",
      "observed_evidence_ready",
      "skip_evidence_status",
      "promotion_ready",
      "node_gate_status",
      "browser_gate_status",
      "native_evidence_gate",
      "evidence_acceptance_allowed",
      "next_action",
      "execution_enabled",
      "promotion_allowed",
      "notes",
    ].join("\t"),
    ...runtimeBoundaryNativeEvidenceAcceptanceGateRowsGenerated,
  ].join("\n")}\n`,
);

writeFileSync(
  nextBoundaryRecommendationsPath,
  `${[
    [
      "priority",
      "boundary_kind",
      "target",
      "blocked",
      "recommendation",
      "primary_artifact",
      "artifact_row_count",
      "required_native_proof",
      "required_node_proof",
      "required_browser_proof",
      "promotion_lock_active",
      "contract_ok",
      "execution_enabled",
      "promotion_allowed",
      "next_step",
      "source_artifacts",
    ].join("\t"),
    ...nextBoundaryRecommendationRowsGenerated,
  ].join("\n")}\n`,
);

verifyGeneratedArtifactDocumentationCoverage({
  artifactPaths: generatedSimConfigInventoryArtifactPaths,
  documentationPaths: [
    compatibilityValidationPath,
    trackedMatrixPath,
    fullProcessBoundaryDesignPath,
  ],
});
verifyNativeGeneratedArtifactDocumentationCoverage([
  compatibilityValidationPath,
  trackedMatrixPath,
  fullProcessBoundaryDesignPath,
]);

console.log(`sim_configs_wasm_node_inventory_executed=${executed}`);
console.log(`sim_configs_wasm_node_inventory_passed=${passed}`);
console.log(`sim_configs_wasm_node_inventory_skipped=${skipped}`);
console.log(`sim_configs_wasm_node_inventory_unexpected_fail=${unexpectedFail}`);
const skipReasonLogCounts = new Map();
for (const [reason, count] of skipReasonCounts) {
  const key = skipReasonLogKey(reason);
  skipReasonLogCounts.set(key, (skipReasonLogCounts.get(key) ?? 0) + count);
}
for (const [reason, count] of [...skipReasonLogCounts.entries()].sort(([left], [right]) =>
  left.localeCompare(right)
)) {
  console.log(`sim_configs_wasm_node_inventory_skip_${reason}=${count}`);
}

if (unexpectedFail !== 0) {
  throw new Error(`sim_configs inventory unexpected failures: ${unexpectedFail}`);
}

console.log("sim_configs_wasm_node_inventory=ok");
