File size: 108,284 Bytes
57e5bea bdd8da5 57e5bea 84110a3 57e5bea 84110a3 57e5bea 84110a3 57e5bea bdd8da5 57e5bea 84110a3 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea 84110a3 57e5bea 84110a3 57e5bea 84110a3 57e5bea 84110a3 57e5bea 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 57e5bea 84110a3 57e5bea 84110a3 57e5bea bdd8da5 57e5bea 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 bdd8da5 57e5bea bdd8da5 57e5bea 84110a3 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea bdd8da5 57e5bea 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 57e5bea 84110a3 bdd8da5 84110a3 bdd8da5 84110a3 57e5bea bdd8da5 57e5bea 84110a3 57e5bea | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 | #!/usr/bin/env node
/**
* Deterministic, read-only integrity and semantic audit for the v0.4.0 CSV release.
*
* Usage:
* node scripts/audit-v03.mjs [data-directory]
*
* The script writes nothing. It prints one stable JSON report and exits 1 only
* when blocking errors exist. Warnings never change the exit status.
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const packageRoot = path.resolve(here, "..");
const dataDir = path.resolve(process.argv[2] || path.join(packageRoot, "data"));
const EXPECTED_TABLES = Object.freeze([
"cases", "claims", "sources", "events", "case_sources", "watchlist", "candidates",
"official_elections", "official_turnout", "official_results", "official_data_sources",
"official_election_metrics", "research_view", "case_catalog", "case_actors",
"technology_uses", "content_items", "pathways", "observations", "model_evaluations",
"claim_evidence", "analytic_record_claims", "case_elections", "election_sources",
"sampling_frame", "coverage_summary"
]);
const blocking = [];
const advisory = [];
const loaded = new Map();
function issue(severity, test, code, table, rowId, message) {
const item = {
layer: test.startsWith("T00_") ? "integrity" : "semantic",
test,
code,
table: table || null,
row_id: rowId || null,
message
};
(severity === "error" ? blocking : advisory).push(item);
}
const error = (...args) => issue("error", ...args);
const warn = (...args) => issue("warning", ...args);
const datapackagePath = path.join(dataDir, "datapackage.json");
let datapackage = null;
if (!fs.existsSync(datapackagePath)) {
error("T00_DATAPACKAGE", "DATAPACKAGE_MISSING", "datapackage", null, "data/datapackage.json is missing");
} else {
try {
datapackage = JSON.parse(fs.readFileSync(datapackagePath, "utf8"));
} catch (caught) {
error("T00_DATAPACKAGE", "DATAPACKAGE_INVALID_JSON", "datapackage", null, `Invalid JSON: ${caught.message}`);
}
}
const resourceByName = new Map();
if (datapackage && !Array.isArray(datapackage.resources)) {
error("T00_DATAPACKAGE", "RESOURCES_NOT_ARRAY", "datapackage", null, "resources must be an array");
} else {
for (const [position, resource] of (datapackage?.resources || []).entries()) {
const name = String(resource?.name || "").trim();
if (!name) {
error("T00_DATAPACKAGE", "RESOURCE_NAME_MISSING", "datapackage", `resource:${position}`, "Resource name is blank");
continue;
}
if (resourceByName.has(name)) {
error("T00_DATAPACKAGE", "RESOURCE_DUPLICATE", "datapackage", name, `Duplicate resource: ${name}`);
continue;
}
resourceByName.set(name, resource);
}
}
for (const name of EXPECTED_TABLES) {
if (datapackage && !resourceByName.has(name)) {
error("T00_DATAPACKAGE", "RESOURCE_MISSING", "datapackage", name, `Expected resource is not declared: ${name}`);
}
}
for (const name of [...resourceByName.keys()].sort()) {
if (!EXPECTED_TABLES.includes(name)) {
error("T00_DATAPACKAGE", "RESOURCE_UNEXPECTED", "datapackage", name, `Unexpected tabular resource: ${name}`);
}
}
function parseCsv(text, filename) {
const input = text.replace(/^\uFEFF/, "");
const records = [];
let record = [];
let field = "";
let quoted = false;
for (let i = 0; i < input.length; i += 1) {
const char = input[i];
if (quoted) {
if (char === '"') {
if (input[i + 1] === '"') {
field += '"';
i += 1;
} else {
quoted = false;
}
} else {
field += char;
}
continue;
}
if (char === '"' && field === "") {
quoted = true;
} else if (char === ",") {
record.push(field);
field = "";
} else if (char === "\n") {
record.push(field);
records.push(record);
record = [];
field = "";
} else if (char !== "\r") {
field += char;
}
}
if (quoted) {
error("T00_SCHEMA", "CSV_UNCLOSED_QUOTE", filename, null, "CSV ends inside a quoted field");
}
if (field !== "" || record.length > 0) {
record.push(field);
records.push(record);
}
while (records.length && records.at(-1).every((value) => value === "")) records.pop();
if (!records.length) {
error("T00_SCHEMA", "CSV_EMPTY", filename, null, "CSV has no header row");
return { headers: [], rows: [] };
}
const headers = records[0].map((value) => value.trim());
const duplicateHeaders = headers.filter((value, index) => headers.indexOf(value) !== index);
for (const header of [...new Set(duplicateHeaders)].sort()) {
error("T00_SCHEMA", "DUPLICATE_HEADER", filename, null, `Duplicate header: ${header}`);
}
const rows = [];
for (let i = 1; i < records.length; i += 1) {
const values = records[i];
if (values.every((value) => value === "")) continue;
if (values.length !== headers.length) {
error(
"T00_SCHEMA",
"CSV_WIDTH",
filename,
`line:${i + 1}`,
`Expected ${headers.length} cells; found ${values.length}`
);
}
const row = { __line: i + 1 };
headers.forEach((header, index) => {
row[header] = values[index] ?? "";
});
rows.push(row);
}
return { headers, rows };
}
function loadTable(name, requiredHeaders, required = true) {
const filename = `${name}.csv`;
const filepath = path.join(dataDir, filename);
if (!fs.existsSync(filepath)) {
(required ? error : warn)(
"T00_SCHEMA",
required ? "REQUIRED_TABLE_MISSING" : "OPTIONAL_TABLE_MISSING",
name,
null,
`${filename} is missing`
);
const empty = { headers: [], rows: [], exists: false };
loaded.set(name, empty);
return empty;
}
const parsed = parseCsv(fs.readFileSync(filepath, "utf8"), name);
const headerSet = new Set(parsed.headers);
for (const header of requiredHeaders) {
if (!headerSet.has(header)) {
error("T00_SCHEMA", "REQUIRED_COLUMN_MISSING", name, null, `Required column is missing: ${header}`);
}
}
const table = { ...parsed, exists: true };
loaded.set(name, table);
return table;
}
const requiredColumns = {
cases: [
"case_id", "case_family_id", "title", "country", "region", "election_date_start",
"case_status", "as_of_date", "record_type", "manipulation_assessment", "last_verified"
],
claims: [
"claim_id", "case_id", "claim_type", "evidence_label", "claim_status",
"evidence_basis", "evidence_scope", "source_ids"
],
sources: ["source_id", "source_type", "publication_date", "retrieved_at"],
events: ["event_id", "case_id", "event_date", "event_type", "description", "claim_ids", "source_ids", "event_status"],
case_sources: ["case_id", "source_id", "source_role", "supports_claim_types", "notes"],
watchlist: [
"watch_id", "case_id", "jurisdiction", "election_date", "monitoring_window", "signal_category",
"observable_indicator", "defensive_data_source", "assessment_rule", "status", "last_checked", "notes"
],
candidates: ["candidate_id", "region", "research_status"],
case_catalog: [
"catalog_id", "record_layer", "record_type", "manipulation_assessment",
"incident_count_eligible", "research_status"
],
case_actors: [
"case_actor_id", "case_id", "actor_name", "actor_role", "actor_type",
"attribution_status", "control_dimension", "source_claim_ids"
],
technology_uses: [
"tech_use_id", "case_id", "provider", "product_or_model", "version", "access_type",
"technology_role", "use_status", "provenance_status", "evidence_label", "source_claim_ids", "notes"
],
content_items: ["content_item_id", "case_id", "source_claim_ids"],
pathways: [
"pathway_id", "case_id", "agency_dimension", "hypothesized_control_shift_from",
"hypothesized_control_shift_to", "mechanism", "hypothesized_power_recipient",
"potential_harm_pathway", "capability_status", "control_mechanism_status",
"attempted_transfer_status", "agency_change_status", "agency_preservation_status",
"maximum_conclusion", "falsification_condition", "comparator", "observed_evidence",
"researcher_inference", "assessment_label", "source_claim_ids"
],
observations: [
"observation_id", "case_id", "pathway_id", "claim_id", "metric_family", "metric_name",
"value_low", "value_best", "value_high", "unit", "denominator", "unique_entity_status",
"platform", "geographic_scope", "measurement_window", "measurement_method", "causal_status",
"source_id", "as_of_date", "limitations"
],
model_evaluations: [
"evaluation_id", "title", "country", "evaluation_window", "election_or_context",
"systems_tested", "versions_known", "interface", "languages", "sample_unit", "sample_size",
"design", "primary_metrics", "headline_results", "causal_scope", "source_id",
"data_availability", "notes"
],
claim_evidence: ["claim_evidence_id", "claim_id", "source_id", "relation", "evidence_scope", "directness", "locator", "locator_coverage", "locator_note"],
case_elections: ["case_election_id", "case_id", "election_id", "relation"],
sampling_frame: [
"frame_id", "region", "selection_basis", "search_status", "search_languages", "source_channels",
"included_case_count", "candidate_count", "negative_search_recorded", "known_gap", "last_searched"
],
coverage_summary: ["region", "included_case_count", "candidate_count", "model_evaluation_count", "coverage_note"],
research_view: [
"pathway_id", "case_id", "record_type", "manipulation_assessment", "system_or_model",
"controller", "influence_vector", "target", "agency_dimension", "capability_status",
"control_mechanism_status", "attempted_transfer_status", "agency_change_status",
"agency_preservation_status", "maximum_conclusion", "hypothesized_power_recipient",
"reach_summary", "behavioural_effect", "electoral_effect", "case_evidence_summary"
],
official_data_sources: ["official_source_id", "case_family_id", "data_status", "retrieved_at"],
official_elections: [
"election_id", "case_family_id", "linked_case_ids", "election_date", "election_status",
"legal_result_status", "official_source_ids", "as_of_date"
],
official_turnout: [
"turnout_id", "election_id", "geographic_unit_type", "geographic_unit_code", "data_status",
"electorate_measure", "participation_measure", "registered_voters", "ballots_cast", "valid_votes",
"invalid_votes", "turnout_rate", "reporting_units_total", "reporting_units_counted",
"official_source_id", "as_of_date", "notes"
],
official_results: [
"result_id", "election_id", "geographic_unit_type", "geographic_unit_code", "contest_name",
"candidate_or_option", "votes", "valid_vote_share", "rank", "result_status", "coverage_status",
"official_source_id", "as_of_date", "notes"
],
official_election_metrics: [
"metric_id", "election_id", "geographic_unit_type", "geographic_unit_code", "metric_code", "value",
"source_field_code", "source_label_original", "numerator_metric", "denominator_metric",
"authority_reported_rate", "computed_rate", "legal_role", "data_status", "official_source_id",
"as_of_date", "notes"
],
analytic_record_claims: ["record_claim_id", "record_type", "record_id", "case_id", "claim_id", "relation"],
election_sources: ["election_source_id", "election_id", "official_source_id", "source_role"]
};
const csvFiles = fs.existsSync(dataDir)
? fs.readdirSync(dataDir).filter((filename) => filename.endsWith(".csv")).map((filename) => filename.slice(0, -4)).sort()
: [];
for (const name of csvFiles) {
if (!EXPECTED_TABLES.includes(name)) {
error("T00_SCHEMA", "CSV_TABLE_UNEXPECTED", name, null, `${name}.csv is not one of the 26 release tables`);
}
}
for (const name of EXPECTED_TABLES) {
const schemaFields = resourceByName.get(name)?.schema?.fields;
const declaredHeaders = Array.isArray(schemaFields)
? schemaFields.map((field) => String(field?.name || "").trim()).filter(Boolean)
: [];
loadTable(name, [...new Set([...(requiredColumns[name] || []), ...declaredHeaders])]);
}
const rows = (name) => loaded.get(name)?.rows || [];
const ids = (value) => String(value || "").split("|").map((part) => part.trim()).filter(Boolean);
const clean = (value) => String(value ?? "").trim();
const lower = (value) => clean(value).toLowerCase();
const isBlank = (value) => clean(value) === "";
function isIsoDate(value) {
const text = clean(value);
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
if (!match) return false;
const parsed = new Date(`${text}T00:00:00.000Z`);
return !Number.isNaN(parsed.valueOf()) &&
parsed.getUTCFullYear() === Number(match[1]) &&
parsed.getUTCMonth() + 1 === Number(match[2]) &&
parsed.getUTCDate() === Number(match[3]);
}
function rowId(row, table) {
const likely = [
`${table.replace(/s$/, "")}_id`, "case_actor_id", "tech_use_id", "content_item_id",
"claim_evidence_id", "record_claim_id", "case_election_id", "election_source_id", "watch_id",
"metric_id", "event_id", "case_id", "pathway_id", "observation_id", "evaluation_id", "frame_id",
"catalog_id", "result_id", "turnout_id", "election_id", "official_source_id", "source_id", "claim_id"
];
for (const field of likely) if (!isBlank(row[field])) return clean(row[field]);
return `line:${row.__line}`;
}
function requireNonBlank(row, fields, test, table, id) {
for (const field of fields) {
if (isBlank(row[field])) error(test, "REQUIRED_VALUE_MISSING", table, id, `Required value is blank: ${field}`);
}
}
const EXPECTED_PRIMARY_KEYS = Object.freeze({
cases: "case_id", claims: "claim_id", sources: "source_id", events: "event_id", watchlist: "watch_id",
case_sources: ["case_id", "source_id"],
candidates: "candidate_id", official_elections: "election_id", official_turnout: "turnout_id",
official_results: "result_id", official_data_sources: "official_source_id",
official_election_metrics: "metric_id", case_catalog: "catalog_id", case_actors: "case_actor_id",
technology_uses: "tech_use_id", content_items: "content_item_id", pathways: "pathway_id",
observations: "observation_id", model_evaluations: "evaluation_id", claim_evidence: "claim_evidence_id",
analytic_record_claims: "record_claim_id", case_elections: "case_election_id",
election_sources: "election_source_id", sampling_frame: "frame_id", research_view: "pathway_id",
coverage_summary: "region"
});
function normalizedFields(value) {
if (typeof value === "string") return value.trim() ? [value.trim()] : [];
if (Array.isArray(value)) return value.map((field) => String(field || "").trim()).filter(Boolean);
return [];
}
function typedValue(value, type) {
const text = clean(value);
if (type === "string") return { valid: true, value: String(value ?? "") };
if (type === "integer") {
if (!/^[+-]?\d+$/.test(text)) return { valid: false, value: null };
const number = Number(text);
return { valid: Number.isSafeInteger(number), value: number };
}
if (type === "number") {
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text)) return { valid: false, value: null };
const number = Number(text);
return { valid: Number.isFinite(number), value: number };
}
if (type === "boolean") {
if (!/^(true|false)$/i.test(text)) return { valid: false, value: null };
return { valid: true, value: lower(text) === "true" };
}
if (type === "date") return { valid: isIsoDate(text), value: text };
return { valid: false, value: null, unsupported: true };
}
// T00 — datapackage.json is the executable integrity contract for all 26 tables.
for (const name of EXPECTED_TABLES) {
const resource = resourceByName.get(name);
if (!resource) continue;
if (clean(resource.path) !== `${name}.csv`) {
error("T00_DATAPACKAGE", "RESOURCE_PATH_MISMATCH", "datapackage", name, `Expected path ${name}.csv; found ${clean(resource.path) || "blank"}`);
}
if (!resource.schema || !Array.isArray(resource.schema.fields)) {
error("T00_DATAPACKAGE", "SCHEMA_FIELDS_MISSING", "datapackage", name, "Resource schema.fields must be an array");
continue;
}
const fieldNames = [];
const fieldByName = new Map();
for (const [position, field] of resource.schema.fields.entries()) {
const fieldName = clean(field?.name);
if (!fieldName) {
error("T00_DATAPACKAGE", "FIELD_NAME_MISSING", "datapackage", `${name}:${position}`, "Schema field name is blank");
continue;
}
if (fieldByName.has(fieldName)) {
error("T00_DATAPACKAGE", "FIELD_DUPLICATE", "datapackage", `${name}:${fieldName}`, `Duplicate schema field: ${fieldName}`);
}
fieldNames.push(fieldName);
fieldByName.set(fieldName, field);
}
const table = loaded.get(name);
if (table?.exists && (
table.headers.length !== fieldNames.length ||
table.headers.some((header, position) => header !== fieldNames[position])
)) {
error(
"T00_DATAPACKAGE", "HEADER_SCHEMA_MISMATCH", name, null,
`CSV header/order differs from datapackage schema (CSV ${table.headers.length} fields; schema ${fieldNames.length})`
);
}
const expectedPrimaryKey = EXPECTED_PRIMARY_KEYS[name];
const declaredPrimaryKey = normalizedFields(resource.schema.primaryKey);
const expectedPrimaryKeyFields = normalizedFields(expectedPrimaryKey);
if (expectedPrimaryKey && (
declaredPrimaryKey.length !== expectedPrimaryKeyFields.length ||
declaredPrimaryKey.some((field, index) => field !== expectedPrimaryKeyFields[index])
)) {
error(
"T00_DATAPACKAGE", "PRIMARY_KEY_DECLARATION_MISMATCH", "datapackage", name,
`Expected primaryKey=${expectedPrimaryKeyFields.join("|")}; found ${declaredPrimaryKey.join("|") || "none"}`
);
}
if (!expectedPrimaryKey && declaredPrimaryKey.length) {
error("T00_DATAPACKAGE", "PRIMARY_KEY_UNEXPECTED", "datapackage", name, `Unexpected primary key declaration: ${declaredPrimaryKey.join("|")}`);
}
for (const fieldName of declaredPrimaryKey) {
if (!fieldByName.has(fieldName)) {
error("T00_DATAPACKAGE", "PRIMARY_KEY_FIELD_UNKNOWN", "datapackage", name, `primaryKey references undeclared field: ${fieldName}`);
}
}
for (const [fieldName, field] of fieldByName) {
const type = clean(field.type);
if (!["string", "integer", "number", "boolean", "date"].includes(type)) {
error("T00_DATAPACKAGE", "FIELD_TYPE_UNSUPPORTED", "datapackage", `${name}:${fieldName}`, `Unsupported or blank field type: ${type || "blank"}`);
continue;
}
const constraints = field.constraints && typeof field.constraints === "object" ? field.constraints : {};
const seenUnique = new Set();
for (const row of table?.rows || []) {
const id = rowId(row, name);
const raw = row[fieldName];
if (isBlank(raw)) {
if (constraints.required === true) {
error("T00_TYPES", "REQUIRED_CONSTRAINT_VIOLATION", name, id, `${fieldName} is required by datapackage.json`);
}
continue;
}
const parsed = typedValue(raw, type);
if (!parsed.valid) {
error(
"T00_TYPES", type === "date" ? "DATE_TYPE_INVALID" : "FIELD_TYPE_INVALID", name, id,
`${fieldName}=${JSON.stringify(clean(raw))} is not a valid ${type}`
);
continue;
}
if (Array.isArray(constraints.enum) && !constraints.enum.map(String).includes(String(parsed.value))) {
error("T00_TYPES", "ENUM_CONSTRAINT_VIOLATION", name, id, `${fieldName} is outside the datapackage enum constraint`);
}
if (typeof constraints.pattern === "string") {
try {
if (!new RegExp(constraints.pattern).test(clean(raw))) {
error("T00_TYPES", "PATTERN_CONSTRAINT_VIOLATION", name, id, `${fieldName} does not match its datapackage pattern`);
}
} catch {
error("T00_DATAPACKAGE", "PATTERN_CONSTRAINT_INVALID", "datapackage", `${name}:${fieldName}`, "Invalid regular expression in field constraint");
}
}
if (typeof parsed.value === "number") {
if (Number.isFinite(constraints.minimum) && parsed.value < constraints.minimum) {
error("T00_TYPES", "MINIMUM_CONSTRAINT_VIOLATION", name, id, `${fieldName} is below ${constraints.minimum}`);
}
if (Number.isFinite(constraints.maximum) && parsed.value > constraints.maximum) {
error("T00_TYPES", "MAXIMUM_CONSTRAINT_VIOLATION", name, id, `${fieldName} exceeds ${constraints.maximum}`);
}
}
if (constraints.unique === true) {
const key = String(parsed.value);
if (seenUnique.has(key)) error("T00_TYPES", "UNIQUE_CONSTRAINT_VIOLATION", name, id, `${fieldName} duplicates ${key}`);
seenUnique.add(key);
}
}
}
}
// Validate every foreign key declared in the datapackage, rather than a hand-picked subset.
for (const name of EXPECTED_TABLES) {
const resource = resourceByName.get(name);
const foreignKeys = resource?.schema?.foreignKeys;
if (foreignKeys !== undefined && !Array.isArray(foreignKeys)) {
error("T00_FOREIGN_KEYS", "FOREIGN_KEYS_NOT_ARRAY", "datapackage", name, "schema.foreignKeys must be an array");
continue;
}
for (const [position, foreignKey] of (foreignKeys || []).entries()) {
const localFields = normalizedFields(foreignKey?.fields);
const targetName = clean(foreignKey?.reference?.resource);
const targetFields = normalizedFields(foreignKey?.reference?.fields);
const declarationId = `${name}:foreignKey:${position}`;
if (!localFields.length || localFields.length !== targetFields.length || !targetName) {
error("T00_FOREIGN_KEYS", "FOREIGN_KEY_DECLARATION_INVALID", "datapackage", declarationId, "Foreign key needs equally sized local/reference fields and a target resource");
continue;
}
const localHeaders = new Set(loaded.get(name)?.headers || []);
const targetTable = loaded.get(targetName);
const targetHeaders = new Set(targetTable?.headers || []);
for (const fieldName of localFields) {
if (!localHeaders.has(fieldName)) error("T00_FOREIGN_KEYS", "FOREIGN_KEY_LOCAL_FIELD_UNKNOWN", "datapackage", declarationId, `Unknown local field: ${fieldName}`);
}
if (!resourceByName.has(targetName) || !targetTable?.exists) {
error("T00_FOREIGN_KEYS", "FOREIGN_KEY_RESOURCE_UNKNOWN", "datapackage", declarationId, `Unknown target resource: ${targetName}`);
continue;
}
for (const fieldName of targetFields) {
if (!targetHeaders.has(fieldName)) error("T00_FOREIGN_KEYS", "FOREIGN_KEY_TARGET_FIELD_UNKNOWN", "datapackage", declarationId, `Unknown target field: ${targetName}.${fieldName}`);
}
if (localFields.some((field) => !localHeaders.has(field)) || targetFields.some((field) => !targetHeaders.has(field))) continue;
const targetKeys = new Set(targetTable.rows.map((row) => targetFields.map((field) => clean(row[field])).join("\u001f")));
for (const row of rows(name)) {
const values = localFields.map((field) => clean(row[field]));
if (values.every((value) => !value)) continue;
if (values.some((value) => !value)) {
error("T00_FOREIGN_KEYS", "FOREIGN_KEY_PARTIAL", name, rowId(row, name), `Partially blank foreign key: ${localFields.join("|")}`);
} else if (!targetKeys.has(values.join("\u001f"))) {
error(
"T00_FOREIGN_KEYS", "FOREIGN_KEY_UNKNOWN", name, rowId(row, name),
`${localFields.join("|")} references unknown ${targetName}.${targetFields.join("|")}: ${values.join("|")}`
);
}
}
}
}
function uniqueIndex(table, field) {
const index = new Map();
for (const row of rows(table)) {
const id = clean(row[field]);
const ref = rowId(row, table);
if (!id) {
error("T00_RELATIONAL_INTEGRITY", "PRIMARY_KEY_MISSING", table, ref, `Primary key is blank: ${field}`);
} else if (index.has(id)) {
error("T00_RELATIONAL_INTEGRITY", "PRIMARY_KEY_DUPLICATE", table, id, `Duplicate ${field}: ${id}`);
} else {
index.set(id, row);
}
}
return index;
}
const primaryKeys = Object.fromEntries(Object.entries(EXPECTED_PRIMARY_KEYS).filter(([, field]) => typeof field === "string"));
const index = Object.fromEntries(Object.entries(primaryKeys).map(([table, field]) => [table, uniqueIndex(table, field)]));
function requireFk(test, table, row, field, targetTable, targetIndex = index[targetTable], allowBlank = false) {
const values = ids(row[field]);
const id = rowId(row, table);
if (!values.length && !allowBlank) {
error(test, "FOREIGN_KEY_MISSING", table, id, `${field} is blank; expected ${targetTable}`);
return;
}
for (const value of values) {
if (!targetIndex?.has(value)) {
error(test, "FOREIGN_KEY_UNKNOWN", table, id, `${field} references unknown ${targetTable}: ${value}`);
}
}
}
const caseFamilyIds = new Set(rows("cases").map((row) => clean(row.case_family_id)).filter(Boolean));
const cutoffCandidates = rows("cases").map((row) => clean(row.as_of_date)).filter(isIsoDate).sort();
const cutoff = cutoffCandidates.at(-1) || null;
const DOCUMENTED_ENUMS = Object.freeze({
"cases.case_status": ["retrospective", "ongoing", "prospective_monitoring"],
"cases.record_type": ["election_wide_case", "observed_network", "observed_incident", "observed_campaign_set", "preparedness_file"],
"cases.manipulation_assessment": [
"manipulation_confirmed", "manipulation_probable", "mixed_documented_manipulation",
"transparent_contested_use", "manipulation_not_established", "no_manipulation_observed",
"preparedness_not_incident", "not_an_incident", "not_yet_claim_coded"
],
"cases.ai_role": ["core_generation", "material_amplification", "supporting_tool", "detection_response", "none_established", "mixed"],
"cases.generative_ai_status": ["confirmed", "probable", "alleged", "not_established", "not_applicable"],
"cases.occurrence_status": ["confirmed", "partly_confirmed", "alleged", "not_observed"],
"cases.behavioural_effect_status": ["measured", "indicated", "not_detected", "unknown"],
"cases.electoral_effect_status": ["measured", "institutionally_asserted", "not_detected", "unknown"],
"case_catalog.record_layer": ["claim_coded_core", "screening_register", "empirical_model_study"],
"case_catalog.record_type": [
"election_wide_case", "observed_network", "observed_incident", "observed_campaign_set",
"preparedness_file", "candidate_lead", "model_evaluation_or_experiment"
],
"case_catalog.manipulation_assessment": [
"manipulation_confirmed", "manipulation_probable", "mixed_documented_manipulation",
"transparent_contested_use", "manipulation_not_established", "no_manipulation_observed",
"preparedness_not_incident", "not_an_incident", "not_yet_claim_coded"
],
"claims.claim_type": [
"occurrence", "mechanism", "ai_role", "reach", "attribution", "intent", "behavioural_effect",
"electoral_effect", "institutional_outcome", "response", "legal_status", "counterevidence", "control_shift_hypothesis"
],
"claims.evidence_label": [
"established_evidence", "established_as_campaign_report", "strong_inference",
"researcher_hypothesis", "not_identified_in_declared_review", "open_question"
],
"claims.claim_status": [
"supported_as_worded", "supported_as_attributed_measurement", "partly_supported",
"not_identified_in_declared_review", "hypothesis_not_tested", "unresolved"
],
"claims.evidence_basis": [
"supported_as_worded", "attributed_measurement_only", "inferential_synthesis",
"review_bounded_absence", "not_tested", "none"
],
"claims.evidence_scope": [
"underlying_fact", "assertion_was_made", "institutional_action", "measurement",
"researcher_inference", "review_scope_statement"
],
"claim_evidence.relation": ["supports", "premise", "counterevidence"],
"claim_evidence.evidence_scope": [
"underlying_fact", "assertion_was_made", "institutional_action", "measurement",
"researcher_inference", "review_scope_statement"
],
"claim_evidence.directness": ["firsthand_artifact_or_measurement", "official_record_or_allegation", "independent_secondary_reporting"],
"claim_evidence.locator_coverage": ["full_claim", "partial_claim", "not_verified"],
"sources.source_quality": ["A", "B", "C", "D"],
"sources.source_independence": ["independent_or_official", "independent_secondary", "interested_or_mixed", "unknown"],
"sources.method_transparency": [
"sufficiently_described_or_reproducible", "not_applicable_official_record",
"limited_to_published_account", "opaque"
],
"case_actors.attribution_status": [
"admitted", "adjudicated", "officially_attributed", "platform_attributed",
"credibly_reported", "alleged", "unknown", "mixed"
],
"pathways.capability_status": ["observed", "not_observed", "not_assessed", "not_applicable"],
"pathways.control_mechanism_status": ["observed", "not_observed", "not_assessed", "not_applicable"],
"pathways.attempted_transfer_status": ["observed", "not_observed", "insufficient_evidence", "not_applicable"],
"pathways.agency_change_status": ["observed", "not_observed", "insufficient_evidence", "not_applicable"],
"pathways.agency_preservation_status": ["observed", "not_observed", "insufficient_evidence", "not_applicable"],
"pathways.maximum_conclusion": [
"control_mechanism_observed", "attempted_transfer_observed", "agency_change_observed",
"agency_preserved_or_extended", "insufficient_evidence", "not_an_incident"
],
"pathways.assessment_label": [
"observed_mechanism", "observed_attempt_with_unmeasured_agency", "boundary_case", "not_applicable"
],
"observations.causal_status": [
"descriptive_only", "association_only", "experimental_causal_estimate",
"quasi_experimental_causal_estimate", "causal_estimate", "not_applicable"
],
"sampling_frame.search_status": ["complete", "systematic", "substantial", "partial", "ongoing", "not_started"],
"official_elections.election_status": ["completed", "scheduled", "conditional"],
"official_results.coverage_status": ["complete_national_contest", "complete", "partial"]
});
for (const [qualifiedField, allowedValues] of Object.entries(DOCUMENTED_ENUMS)) {
const separator = qualifiedField.indexOf(".");
const table = qualifiedField.slice(0, separator);
const field = qualifiedField.slice(separator + 1);
const allowed = new Set(allowedValues);
for (const row of rows(table)) {
const value = clean(row[field]);
if (!value) {
error("T13_DOCUMENTED_ENUMS", "DOCUMENTED_ENUM_BLANK", table, rowId(row, table), `${field} must use a documented value`);
} else if (!allowed.has(value)) {
error(
"T13_DOCUMENTED_ENUMS", "DOCUMENTED_ENUM_INVALID", table, rowId(row, table),
`${field}=${JSON.stringify(value)} is not in the documented vocabulary`
);
}
}
}
const CLAIM_SEMANTICS = Object.freeze({
established_evidence: ["supported_as_worded", "supported_as_worded"],
established_as_campaign_report: ["supported_as_attributed_measurement", "attributed_measurement_only"],
strong_inference: ["partly_supported", "inferential_synthesis"],
researcher_hypothesis: ["hypothesis_not_tested", "not_tested"],
not_identified_in_declared_review: ["not_identified_in_declared_review", "review_bounded_absence"],
open_question: ["unresolved", "none"]
});
for (const claim of rows("claims")) {
const id = rowId(claim, "claims");
const expected = CLAIM_SEMANTICS[clean(claim.evidence_label)];
if (expected && (clean(claim.claim_status) !== expected[0] || clean(claim.evidence_basis) !== expected[1])) {
error(
"T13_DOCUMENTED_ENUMS", "CLAIM_SEMANTICS_MISMATCH", "claims", id,
`evidence_label=${clean(claim.evidence_label)} requires claim_status=${expected[0]} and evidence_basis=${expected[1]}`
);
}
if (clean(claim.claim_type) === "control_shift_hypothesis" && clean(claim.evidence_label) !== "researcher_hypothesis") {
error(
"T13_DOCUMENTED_ENUMS", "CONTROL_SHIFT_NOT_HYPOTHESIS", "claims", id,
"control_shift_hypothesis claims must use evidence_label=researcher_hypothesis"
);
}
if (["strong_inference", "researcher_hypothesis"].includes(clean(claim.evidence_label)) && clean(claim.evidence_scope) !== "researcher_inference") {
error("T13_DOCUMENTED_ENUMS", "INFERENCE_SCOPE_MISMATCH", "claims", id, "Inferential claims must use evidence_scope=researcher_inference");
}
if (clean(claim.evidence_label) === "not_identified_in_declared_review" && clean(claim.evidence_scope) !== "review_scope_statement") {
error("T13_DOCUMENTED_ENUMS", "REVIEW_SCOPE_MISMATCH", "claims", id, "Review-bounded absence must use evidence_scope=review_scope_statement");
}
}
// T01 — every included case has an explicit, controlled record classification.
const validRecordTypes = new Set([
"observed_incident", "observed_network", "observed_campaign_set", "election_wide_case",
"preparedness_file", "observational_null_case", "negative_case"
]);
const validManipulationAssessments = new Set([
"manipulation_confirmed", "manipulation_probable", "mixed_documented_manipulation",
"transparent_contested_use", "manipulation_not_established", "no_manipulation_observed",
"preparedness_not_incident", "not_applicable"
]);
for (const row of rows("cases")) {
const id = rowId(row, "cases");
requireNonBlank(row, ["record_type", "manipulation_assessment"], "T01_RECORD_CLASSIFICATION", "cases", id);
if (!validRecordTypes.has(clean(row.record_type))) {
error("T01_RECORD_CLASSIFICATION", "RECORD_TYPE_INVALID", "cases", id, `Unknown record_type: ${clean(row.record_type)}`);
}
if (!validManipulationAssessments.has(clean(row.manipulation_assessment))) {
error(
"T01_RECORD_CLASSIFICATION", "MANIPULATION_ASSESSMENT_INVALID", "cases", id,
`Unknown manipulation_assessment: ${clean(row.manipulation_assessment)}`
);
}
if (!isIsoDate(row.as_of_date) || !isIsoDate(row.last_verified)) {
error("T01_RECORD_CLASSIFICATION", "CASE_DATE_INVALID", "cases", id, "as_of_date and last_verified must be ISO dates");
} else if (clean(row.last_verified) > clean(row.as_of_date)) {
error("T01_RECORD_CLASSIFICATION", "VERIFIED_AFTER_AS_OF", "cases", id, "last_verified is after as_of_date");
}
if (/^(manipulation_confirmed|manipulation_probable|mixed_documented_manipulation)$/.test(clean(row.manipulation_assessment))) {
const processClaims = rows("claims").filter(
(claim) => clean(claim.case_id) === clean(row.case_id) &&
["occurrence", "mechanism", "attribution", "intent"].includes(clean(claim.claim_type)) &&
["established_evidence", "strong_inference"].includes(clean(claim.evidence_label)) &&
ids(claim.source_ids).length > 0
);
if (!processClaims.length) {
error(
"T01_RECORD_CLASSIFICATION", "MANIPULATION_WITHOUT_PROCESS_EVIDENCE", "cases", id,
"Confirmed/probable/mixed manipulation requires an evidence-backed process claim"
);
}
}
}
// T02 — preparedness and model-evaluation records can never inflate incident counts.
const trueValues = new Set(["true"]);
const falseValues = new Set(["false"]);
for (const row of rows("cases")) {
const id = rowId(row, "cases");
const isPreparedness = clean(row.record_type) === "preparedness_file";
if (isPreparedness && clean(row.manipulation_assessment) !== "preparedness_not_incident") {
error(
"T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_ASSESSMENT", "cases", id,
"preparedness_file must use manipulation_assessment=preparedness_not_incident"
);
}
if (!isPreparedness && clean(row.manipulation_assessment) === "preparedness_not_incident") {
error(
"T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_TYPE_MISMATCH", "cases", id,
"preparedness_not_incident is only valid for record_type=preparedness_file"
);
}
}
for (const row of rows("case_catalog")) {
const id = rowId(row, "case_catalog");
const eligibility = lower(row.incident_count_eligible);
if (!trueValues.has(eligibility) && !falseValues.has(eligibility)) {
error(
"T02_INCIDENT_DENOMINATOR", "INCIDENT_ELIGIBILITY_INVALID", "case_catalog", id,
"incident_count_eligible must be an explicit boolean"
);
}
if (
clean(row.record_type) === "preparedness_file" ||
/model.?evaluation/i.test(clean(row.record_layer)) ||
/model.?evaluation/i.test(clean(row.research_status))
) {
if (!falseValues.has(eligibility)) {
error(
"T02_INCIDENT_DENOMINATOR", "NON_INCIDENT_COUNTED", "case_catalog", id,
"Preparedness and model-evaluation records must have incident_count_eligible=false"
);
}
}
}
const preparednessCatalogCount = rows("case_catalog").filter((row) => clean(row.record_type) === "preparedness_file").length;
const preparednessCaseCount = rows("cases").filter((row) => clean(row.record_type) === "preparedness_file").length;
if (rows("case_catalog").length && preparednessCatalogCount !== preparednessCaseCount) {
error(
"T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_CATALOG_COUNT_MISMATCH", "case_catalog", null,
`case_catalog has ${preparednessCatalogCount} preparedness rows; cases.csv has ${preparednessCaseCount}`
);
}
const modelCatalogCount = rows("case_catalog").filter((row) => clean(row.record_layer) === "empirical_model_study").length;
if (rows("case_catalog").length && modelCatalogCount !== rows("model_evaluations").length) {
error(
"T02_INCIDENT_DENOMINATOR", "MODEL_EVALUATION_CATALOG_COUNT_MISMATCH", "case_catalog", null,
`case_catalog has ${modelCatalogCount} model-evaluation rows; model_evaluations.csv has ${rows("model_evaluations").length}`
);
}
for (const row of rows("pathways")) {
const parent = index.cases.get(clean(row.case_id));
if (parent?.record_type === "preparedness_file") {
if (clean(row.maximum_conclusion) !== "not_an_incident") {
error(
"T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_PATHWAY_STATUS", "pathways", rowId(row, "pathways"),
"A preparedness pathway must use maximum_conclusion=not_an_incident"
);
}
for (const field of ["attempted_transfer_status", "agency_change_status", "agency_preservation_status"]) {
if (clean(row[field]) !== "not_applicable") {
error(
"T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_DIMENSION_NOT_APPLICABLE", "pathways", rowId(row, "pathways"),
`A preparedness pathway must use ${field}=not_applicable`
);
}
}
}
}
// T03 — relational integrity across the research and official-election layers.
for (const row of rows("claims")) requireFk("T03_FOREIGN_KEYS", "claims", row, "case_id", "cases");
for (const table of ["case_actors", "technology_uses", "content_items", "pathways", "observations", "case_elections"]) {
for (const row of rows(table)) requireFk("T03_FOREIGN_KEYS", table, row, "case_id", "cases");
}
for (const table of ["case_actors", "technology_uses", "content_items", "pathways"]) {
for (const row of rows(table)) {
requireFk("T03_FOREIGN_KEYS", table, row, "source_claim_ids", "claims");
for (const claimId of ids(row.source_claim_ids)) {
const claim = index.claims.get(claimId);
if (claim && clean(claim.case_id) !== clean(row.case_id)) {
error(
"T03_FOREIGN_KEYS", "CROSS_CASE_SOURCE_CLAIM", table, rowId(row, table),
`source_claim_ids references a claim from another case: ${claimId}`
);
}
}
}
}
for (const row of rows("observations")) {
requireFk("T03_FOREIGN_KEYS", "observations", row, "pathway_id", "pathways");
requireFk("T03_FOREIGN_KEYS", "observations", row, "claim_id", "claims");
requireFk("T03_FOREIGN_KEYS", "observations", row, "source_id", "sources");
const caseId = clean(row.case_id);
const pathway = index.pathways.get(clean(row.pathway_id));
const claim = index.claims.get(clean(row.claim_id));
if (pathway && clean(pathway.case_id) !== caseId) {
error("T03_FOREIGN_KEYS", "CROSS_CASE_PATHWAY", "observations", rowId(row, "observations"), "pathway_id belongs to another case");
}
if (claim && clean(claim.case_id) !== caseId) {
error("T03_FOREIGN_KEYS", "CROSS_CASE_CLAIM", "observations", rowId(row, "observations"), "claim_id belongs to another case");
}
}
for (const row of rows("model_evaluations")) requireFk("T03_FOREIGN_KEYS", "model_evaluations", row, "source_id", "sources");
for (const row of rows("claim_evidence")) {
requireFk("T03_FOREIGN_KEYS", "claim_evidence", row, "claim_id", "claims");
requireFk("T03_FOREIGN_KEYS", "claim_evidence", row, "source_id", "sources");
}
for (const row of rows("case_elections")) requireFk("T03_FOREIGN_KEYS", "case_elections", row, "election_id", "official_elections");
for (const row of rows("official_elections")) {
requireFk("T03_FOREIGN_KEYS", "official_elections", row, "linked_case_ids", "cases");
requireFk("T03_FOREIGN_KEYS", "official_elections", row, "official_source_ids", "official_data_sources");
if (!caseFamilyIds.has(clean(row.case_family_id))) {
error("T03_FOREIGN_KEYS", "CASE_FAMILY_UNKNOWN", "official_elections", rowId(row, "official_elections"), `Unknown case_family_id: ${clean(row.case_family_id)}`);
}
}
for (const table of ["official_turnout", "official_results", "official_election_metrics"]) {
for (const row of rows(table)) {
requireFk("T03_FOREIGN_KEYS", table, row, "election_id", "official_elections");
requireFk("T03_FOREIGN_KEYS", table, row, "official_source_id", "official_data_sources");
const election = index.official_elections.get(clean(row.election_id));
const source = index.official_data_sources.get(clean(row.official_source_id));
if (election && source && clean(election.case_family_id) !== clean(source.case_family_id)) {
error("T03_FOREIGN_KEYS", "OFFICIAL_SOURCE_FAMILY_MISMATCH", table, rowId(row, table), "Official source and election belong to different case families");
}
}
}
for (const row of rows("official_data_sources")) {
if (!caseFamilyIds.has(clean(row.case_family_id))) {
error("T03_FOREIGN_KEYS", "CASE_FAMILY_UNKNOWN", "official_data_sources", rowId(row, "official_data_sources"), `Unknown case_family_id: ${clean(row.case_family_id)}`);
}
}
for (const row of rows("research_view")) {
requireFk("T03_FOREIGN_KEYS", "research_view", row, "case_id", "cases");
requireFk("T03_FOREIGN_KEYS", "research_view", row, "pathway_id", "pathways");
const pathway = index.pathways.get(clean(row.pathway_id));
if (pathway && clean(pathway.case_id) !== clean(row.case_id)) {
error("T03_FOREIGN_KEYS", "RESEARCH_VIEW_PATHWAY_CASE_MISMATCH", "research_view", rowId(row, "research_view"), "Research-view pathway belongs to another case");
}
}
// T04 — each control-shift pathway separates observation, inference and the
// strongest conclusion the evidence permits. It must also state how the
// proposition could be challenged and which comparison would test it.
const pathwayEnums = Object.freeze({
capability_status: new Set(["observed", "not_observed", "not_assessed", "not_applicable"]),
control_mechanism_status: new Set(["observed", "not_observed", "not_assessed", "not_applicable"]),
attempted_transfer_status: new Set(["observed", "not_observed", "insufficient_evidence", "not_applicable"]),
agency_change_status: new Set(["observed", "not_observed", "insufficient_evidence", "not_applicable"]),
agency_preservation_status: new Set(["observed", "not_observed", "insufficient_evidence", "not_applicable"]),
maximum_conclusion: new Set([
"control_mechanism_observed", "attempted_transfer_observed", "agency_change_observed",
"agency_preserved_or_extended", "insufficient_evidence", "not_an_incident"
]),
assessment_label: new Set(["observed_mechanism", "observed_attempt_with_unmeasured_agency", "boundary_case", "not_applicable"])
});
const pathwaysByCase = new Map();
for (const row of rows("pathways")) {
const id = rowId(row, "pathways");
requireNonBlank(
row,
[
"case_id", "agency_dimension", "hypothesized_control_shift_from", "hypothesized_control_shift_to",
"mechanism", "hypothesized_power_recipient", "potential_harm_pathway",
"capability_status", "control_mechanism_status", "attempted_transfer_status",
"agency_change_status", "agency_preservation_status", "maximum_conclusion",
"falsification_condition", "comparator", "observed_evidence",
"assessment_label", "source_claim_ids"
],
"T04_PATHWAY", "pathways", id
);
for (const [field, allowed] of Object.entries(pathwayEnums)) {
if (!allowed.has(clean(row[field]))) {
error("T04_PATHWAY", "PATHWAY_STATUS_INVALID", "pathways", id, `Unknown ${field}: ${clean(row[field])}`);
}
}
const conclusion = clean(row.maximum_conclusion);
const parent = index.cases.get(clean(row.case_id));
const controlShiftClaims = rows("claims").filter(
(claim) => clean(claim.case_id) === clean(row.case_id) && clean(claim.claim_type) === "control_shift_hypothesis"
);
if (parent?.record_type !== "preparedness_file") {
if (controlShiftClaims.length !== 1) {
error(
"T04_PATHWAY", "CONTROL_SHIFT_CLAIM_COUNT", "pathways", id,
`Each incident pathway requires exactly one explicit control_shift_hypothesis claim; found ${controlShiftClaims.length}`
);
} else if (!ids(row.source_claim_ids).includes(clean(controlShiftClaims[0].claim_id))) {
error(
"T04_PATHWAY", "CONTROL_SHIFT_CLAIM_NOT_LINKED", "pathways", id,
`source_claim_ids must include ${clean(controlShiftClaims[0].claim_id)}`
);
}
} else if (controlShiftClaims.length) {
error("T04_PATHWAY", "PREPAREDNESS_CONTROL_SHIFT_CLAIM", "pathways", id, "Preparedness records must not contain an incident-level control-shift claim");
}
if (parent?.record_type !== "preparedness_file" && isBlank(row.researcher_inference)) {
error("T04_PATHWAY", "RESEARCHER_INFERENCE_MISSING", "pathways", id, "Incident pathways must separate and state the researcher inference");
}
if (conclusion === "not_an_incident" && parent?.record_type !== "preparedness_file") {
warn("T04_PATHWAY", "NON_PREPAREDNESS_NOT_INCIDENT", "pathways", id, "not_an_incident is attached to a non-preparedness case; verify deliberate negative-case coding");
}
if (conclusion === "control_mechanism_observed" && clean(row.control_mechanism_status) !== "observed") {
error("T04_PATHWAY", "CONCLUSION_EXCEEDS_CONTROL_EVIDENCE", "pathways", id, "control_mechanism_observed requires control_mechanism_status=observed");
}
if (conclusion === "attempted_transfer_observed" && clean(row.attempted_transfer_status) !== "observed") {
error("T04_PATHWAY", "CONCLUSION_EXCEEDS_ATTEMPT_EVIDENCE", "pathways", id, "attempted_transfer_observed requires attempted_transfer_status=observed");
}
if (conclusion === "agency_change_observed" && clean(row.agency_change_status) !== "observed") {
error("T04_PATHWAY", "CONCLUSION_EXCEEDS_AGENCY_EVIDENCE", "pathways", id, "agency_change_observed requires agency_change_status=observed");
}
if (conclusion === "agency_preserved_or_extended" && clean(row.agency_preservation_status) !== "observed") {
error("T04_PATHWAY", "CONCLUSION_EXCEEDS_PRESERVATION_EVIDENCE", "pathways", id, "agency_preserved_or_extended requires agency_preservation_status=observed");
}
if (clean(row.agency_change_status) === "observed" && conclusion !== "agency_change_observed") {
error("T04_PATHWAY", "OBSERVED_AGENCY_CHANGE_UNREFLECTED", "pathways", id, "Observed agency change must be the declared maximum conclusion");
}
const text = [row.mechanism, row.potential_harm_pathway, row.observed_outcome].join(" ").toLowerCase();
if (/(defen[cs]e|mitigat|monitoring|safeguard|enforcement)/.test(text) && /(manipulat|impersonat|decept|amplif|influence)/.test(text)) {
warn("T04_PATHWAY", "OFFENSE_DEFENSE_CONFLATED", "pathways", id, "Pathway text appears to combine offensive influence and defensive response; split if they are distinct mechanisms");
}
const caseId = clean(row.case_id);
if (!pathwaysByCase.has(caseId)) pathwaysByCase.set(caseId, []);
pathwaysByCase.get(caseId).push(row);
}
const expectedMaximumConclusions = Object.freeze({
control_mechanism_observed: 4,
attempted_transfer_observed: 2,
insufficient_evidence: 2,
not_an_incident: 2,
agency_change_observed: 0,
agency_preserved_or_extended: 0
});
for (const [value, expected] of Object.entries(expectedMaximumConclusions)) {
const actual = rows("pathways").filter((row) => clean(row.maximum_conclusion) === value).length;
if (actual !== expected) {
error("T04_PATHWAY", "RELEASE_CONCLUSION_COUNT_MISMATCH", "pathways", value, `Expected ${expected} ${value} rows in v0.4.0; found ${actual}`);
}
}
const nonPreparednessPathways = rows("pathways").filter(
(row) => index.cases.get(clean(row.case_id))?.record_type !== "preparedness_file"
);
if (nonPreparednessPathways.length !== 8 || nonPreparednessPathways.some((row) => clean(row.agency_change_status) !== "not_observed")) {
error(
"T04_PATHWAY", "AGENCY_CHANGE_BOUNDARY_MISMATCH", "pathways", null,
"v0.4.0 must contain eight incident-eligible pathways and must not code observed agency change"
);
}
for (const row of rows("cases")) {
if (!pathwaysByCase.has(clean(row.case_id))) {
error("T04_PATHWAY", "CASE_WITHOUT_PATHWAY", "cases", rowId(row, "cases"), "Every case must have at least one pathway assessment");
}
}
for (const row of rows("case_actors")) {
requireNonBlank(row, ["actor_name", "actor_role", "actor_type", "attribution_status", "control_dimension"], "T04_PATHWAY", "case_actors", rowId(row, "case_actors"));
}
for (const row of rows("technology_uses")) {
const id = rowId(row, "technology_uses");
requireNonBlank(row, ["provider", "product_or_model", "technology_role", "use_status", "provenance_status", "evidence_label"], "T04_PATHWAY", "technology_uses", id);
if (isBlank(row.version) && !/(not established|not identified|unknown|not disclosed|unavailable)/i.test(clean(row.notes))) {
error("T04_PATHWAY", "MODEL_VERSION_BLANK_UNEXPLAINED", "technology_uses", id, "A blank version requires an explicit limitation in notes");
}
if (
lower(row.version) === "unknown" &&
!/(unknown|not disclosed|not identified|unavailable|does not identify|does not establish which service|not product-level|exact model|exact producer|exact models|provider identification|public record|predominantly non-ai|do not infer|exact model, api)/i.test(clean(row.notes))
) {
error("T04_PATHWAY", "UNKNOWN_MODEL_VERSION_UNEXPLAINED", "technology_uses", id, "version=unknown requires an explicit limitation in notes");
}
}
const actorCaseIds = new Set(rows("case_actors").map((row) => clean(row.case_id)));
const technologyCaseIds = new Set(rows("technology_uses").map((row) => clean(row.case_id)));
for (const row of rows("cases")) {
const id = rowId(row, "cases");
if (clean(row.record_type) !== "preparedness_file" && !actorCaseIds.has(clean(row.case_id))) {
error("T04_PATHWAY", "CASE_WITHOUT_ACTOR", "case_actors", id, "Every case must identify at least one actor or explicitly coded unknown actor");
}
if (
clean(row.record_type) !== "preparedness_file" &&
/^(confirmed|probable|mixed)$/.test(clean(row.generative_ai_status)) &&
!technologyCaseIds.has(clean(row.case_id))
) {
error("T04_PATHWAY", "AI_CASE_WITHOUT_TECHNOLOGY", "technology_uses", id, "A case with material generative AI must have at least one technology-use row");
}
}
// T05 — all quantitative observations retain numeric values, denominators and causal status.
function parseNumber(value) {
if (isBlank(value)) return null;
const number = Number(value);
return Number.isFinite(number) ? number : Number.NaN;
}
function isCountMetric(row) {
return /(count|reach|engagement|volume|audience|network|views?|impressions?|accounts?|followers?|posts?|likes?|shares?|comments?|calls?|questions?|votes?|ballots?)/i.test(
[row.metric_family, row.metric_name, row.unit].join(" ")
);
}
const causalValues = new Set([
"descriptive_only", "descriptive_non_causal", "non_causal", "no", "unknown", "not_applicable", "association_only",
"experimental_causal_estimate", "quasi_experimental_causal_estimate", "causal_estimate", "causal_estimate_limited"
]);
for (const row of rows("observations")) {
const id = rowId(row, "observations");
requireNonBlank(
row,
[
"case_id", "pathway_id", "claim_id", "metric_family", "metric_name", "unit", "denominator",
"unique_entity_status", "platform", "geographic_scope", "measurement_window", "measurement_method",
"causal_status", "source_id", "as_of_date", "limitations"
],
"T05_OBSERVATIONS", "observations", id
);
const values = ["value_low", "value_best", "value_high"].map((field) => [field, parseNumber(row[field])]);
if (values.every(([, value]) => value === null)) {
error("T05_OBSERVATIONS", "NUMERIC_VALUE_MISSING", "observations", id, "At least one of value_low, value_best or value_high is required");
}
for (const [field, value] of values) {
if (Number.isNaN(value)) error("T05_OBSERVATIONS", "NUMERIC_VALUE_INVALID", "observations", id, `${field} is not a finite number`);
if (value !== null && isCountMetric(row) && value < 0) error("T05_OBSERVATIONS", "COUNT_NEGATIVE", "observations", id, `${field} is negative for a count/reach metric`);
}
const lowValue = parseNumber(row.value_low);
const bestValue = parseNumber(row.value_best);
const highValue = parseNumber(row.value_high);
if (lowValue !== null && bestValue !== null && lowValue > bestValue) {
error("T05_OBSERVATIONS", "INTERVAL_ORDER", "observations", id, "value_low exceeds value_best");
}
if (bestValue !== null && highValue !== null && bestValue > highValue) {
error("T05_OBSERVATIONS", "INTERVAL_ORDER", "observations", id, "value_best exceeds value_high");
}
if (lowValue !== null && highValue !== null && lowValue > highValue) {
error("T05_OBSERVATIONS", "INTERVAL_ORDER", "observations", id, "value_low exceeds value_high");
}
const causalStatus = clean(row.causal_status);
if (!causalValues.has(causalStatus)) {
error("T05_OBSERVATIONS", "CAUSAL_STATUS_INVALID", "observations", id, `Unknown causal_status: ${causalStatus}`);
}
if (/causal_estimate/.test(causalStatus)) {
const claim = index.claims.get(clean(row.claim_id));
if (!claim || !["behavioural_effect", "electoral_effect"].includes(clean(claim.claim_type))) {
error("T05_OBSERVATIONS", "CAUSAL_CLAIM_TYPE", "observations", id, "A causal estimate must link to a behavioural_effect or electoral_effect claim");
}
if (lowValue === null || bestValue === null || highValue === null) {
error("T05_OBSERVATIONS", "CAUSAL_UNCERTAINTY_MISSING", "observations", id, "A causal estimate requires low, best and high values");
}
if (/(official.?result|turnout|administrative total)/i.test(clean(row.measurement_method))) {
error("T05_OBSERVATIONS", "OFFICIAL_OUTCOME_AS_CAUSAL_DESIGN", "observations", id, "Official results or turnout alone cannot identify a causal effect");
}
}
const metricUnitText = [row.metric_family, row.metric_name, row.unit].join(" ");
if (/(^|[_ -])(rate|share|percent|percentage|proportion)([_ -]|$)/i.test(metricUnitText)) {
if (/^(unknown|not_applicable|n\/a)$/i.test(clean(row.denominator))) {
error("T05_OBSERVATIONS", "RATE_DENOMINATOR_UNKNOWN", "observations", id, "A rate/share/percentage requires an identified denominator");
}
const ceiling = /percent|percentage|%/i.test(clean(row.unit)) ? 100 : 1;
for (const [field, value] of values) {
if (value !== null && Number.isFinite(value) && (value < 0 || value > ceiling)) {
error("T05_OBSERVATIONS", "RATE_OUT_OF_RANGE", "observations", id, `${field} is outside 0-${ceiling} for the stated unit`);
}
}
}
if (!isIsoDate(row.as_of_date)) error("T05_OBSERVATIONS", "OBSERVATION_DATE_INVALID", "observations", id, "as_of_date must be an ISO date");
}
// T06 — platform activity and delivery proxies are never relabelled as unique people or voters.
const proxyMetric = /(views?|impressions?|accounts?|followers?|posts?|likes?|shares?|comments?|call_attempts?|completed_calls?|submitted_questions?|interactions?|engagements?)/i;
const uniquePerson = /(unique[_ -]?(person|people|human|user|voter)|deduplicated[_ -]?(person|people|human|user|voter)|^people$|^voters?$)/i;
for (const row of rows("observations")) {
const id = rowId(row, "observations");
const metricText = [row.metric_family, row.metric_name, row.unit].join(" ");
if (proxyMetric.test(metricText) && uniquePerson.test(clean(row.unique_entity_status))) {
error("T06_REACH_UNIQUENESS", "PROXY_AS_UNIQUE_PERSON", "observations", id, "A platform/delivery proxy is coded as unique people or voters");
}
if (
proxyMetric.test(metricText) &&
/\b(?:represents?|counts?|measures?|equals?|is|are)\s+(?:an?\s+)?(?:estimate of\s+)?unique\s+(?:people|persons|users|voters)\b/i.test(clean(row.limitations)) &&
!/\b(?:not|non-)\s*unique\s+(?:people|persons|users|voters)\b/i.test(clean(row.limitations))
) {
error("T06_REACH_UNIQUENESS", "PROXY_LIMITATION_CONTRADICTION", "observations", id, "Limitations text affirmatively promotes a non-unique proxy to unique-person reach");
}
}
for (const row of rows("research_view")) {
const id = rowId(row, "research_view");
const caseObservations = rows("observations").filter((item) => clean(item.case_id) === clean(row.case_id));
const hasVerifiedUniquePeople = caseObservations.some((item) => uniquePerson.test(clean(item.unique_entity_status)) && !proxyMetric.test([item.metric_family, item.metric_name, item.unit].join(" ")));
if (/\b\d[\d,.+]*\s+(people|persons|users|voters)\b|\b(reached|exposed)\s+\d[\d,.+]*\s+(people|persons|users|voters)\b/i.test(clean(row.reach_summary)) && !hasVerifiedUniquePeople) {
error("T06_REACH_UNIQUENESS", "RESEARCH_VIEW_UNIQUE_REACH_UNSUPPORTED", "research_view", id, "Unique-person reach appears in the simple view without a qualifying observation");
}
}
// T07 — model tests retain their tested system, version, interface and causal scope.
for (const row of rows("model_evaluations")) {
const id = rowId(row, "model_evaluations");
requireNonBlank(
row,
[
"evaluation_window", "election_or_context", "systems_tested", "versions_known", "interface",
"languages", "sample_unit", "design", "primary_metrics", "headline_results",
"causal_scope", "source_id", "data_availability", "notes"
],
"T07_MODEL_EVALUATIONS", "model_evaluations", id
);
const sampleSize = parseNumber(row.sample_size);
if (isBlank(row.sample_size)) {
if (!/(sample|participant|question|prompt|benchmark|row count|output|denominator|experiment|not (?:reported|available|coded)|consult)/i.test([row.design, row.notes, row.data_availability].join(" "))) {
error("T07_MODEL_EVALUATIONS", "SAMPLE_SIZE_MISSING_UNEXPLAINED", "model_evaluations", id, "Blank sample_size requires a scoped sample/denominator explanation");
} else {
warn("T07_MODEL_EVALUATIONS", "SAMPLE_SIZE_NOT_STRUCTURED", "model_evaluations", id, "Sample size is not available as a structured integer; retain study-specific denominators before quantitative synthesis");
}
} else if (!Number.isInteger(sampleSize) || sampleSize <= 0) {
error("T07_MODEL_EVALUATIONS", "SAMPLE_SIZE_INVALID", "model_evaluations", id, "sample_size must be a positive integer for the stated sample unit");
}
if (/unknown/i.test(clean(row.versions_known)) && !/(unknown|not visible|not disclosed|unavailable|consumer|version)/i.test([row.notes, row.versions_known, row.causal_scope].join(" "))) {
error("T07_MODEL_EVALUATIONS", "UNKNOWN_VERSION_SCOPE_UNEXPLAINED", "model_evaluations", id, "Unknown versions must be explained in notes");
}
if (!/(not |no |point-in-time|capability|scope|limited|cannot|does not|may differ|laboratory|audit)/i.test(clean(row.causal_scope))) {
warn("T07_MODEL_EVALUATIONS", "CAUSAL_SCOPE_TOO_VAGUE", "model_evaluations", id, "causal_scope does not contain an explicit non-generalisation or design limitation");
}
if (/\b(changed|caused|determined|swung)\b.*\b(actual ballots?|observed votes?|turnout|aggregate election (?:result|outcome)|seats won)\b/i.test(clean(row.headline_results))) {
error("T07_MODEL_EVALUATIONS", "HEADLINE_CAUSAL_OVERCLAIM", "model_evaluations", id, "Headline results make an election-effect claim that a model evaluation cannot establish on its own");
}
const source = index.sources.get(clean(row.source_id));
if (source && !/(model_evaluation|research|scholarly|methodology|report|peer_reviewed|experiment|benchmark|audit)/i.test(clean(source.source_type))) {
warn("T07_MODEL_EVALUATIONS", "SOURCE_TYPE_UNEXPECTED", "model_evaluations", id, `Source type does not identify an evaluation or research record: ${clean(source.source_type)}`);
}
}
// T08 — the denominator of searched elections/regions is explicit and internally counted.
const framesByRegion = new Map();
const validSearchStatuses = new Set([
"complete", "systematic", "substantial", "partial", "partial_search_recorded", "ongoing", "not_started", "gap"
]);
const regionParent = (region) => {
if (["East Asia", "South Asia", "Southeast Asia", "Central Asia", "West Asia"].includes(region)) return "Asia";
if (["East Africa", "West Africa", "Southern Africa", "North Africa", "Central Africa"].includes(region)) return "Africa";
return region;
};
for (const row of rows("sampling_frame")) {
const id = rowId(row, "sampling_frame");
requireNonBlank(
row,
[
"region", "selection_basis", "search_status", "search_languages", "source_channels",
"included_case_count", "candidate_count", "negative_search_recorded", "known_gap", "last_searched"
],
"T08_SAMPLING_FRAME", "sampling_frame", id
);
const region = clean(row.region);
if (framesByRegion.has(region)) {
error("T08_SAMPLING_FRAME", "REGION_DUPLICATE", "sampling_frame", id, `Duplicate sampling-frame region: ${region}`);
}
framesByRegion.set(region, row);
if (!validSearchStatuses.has(clean(row.search_status))) {
error("T08_SAMPLING_FRAME", "SEARCH_STATUS_INVALID", "sampling_frame", id, `Unknown search_status: ${clean(row.search_status)}`);
}
for (const field of ["included_case_count", "candidate_count"]) {
const number = parseNumber(row[field]);
if (!Number.isInteger(number) || number < 0) {
error("T08_SAMPLING_FRAME", "FRAME_COUNT_INVALID", "sampling_frame", id, `${field} must be a non-negative integer`);
}
}
if (!trueValues.has(lower(row.negative_search_recorded)) && !falseValues.has(lower(row.negative_search_recorded))) {
error("T08_SAMPLING_FRAME", "NEGATIVE_SEARCH_FLAG_INVALID", "sampling_frame", id, "negative_search_recorded must be an explicit boolean");
} else if (falseValues.has(lower(row.negative_search_recorded))) {
warn("T08_SAMPLING_FRAME", "NEGATIVE_SEARCH_NOT_RECORDED", "sampling_frame", id, "No negative/null search was recorded for this frame; prevalence inference is unsafe");
}
if (!isIsoDate(row.last_searched)) {
error("T08_SAMPLING_FRAME", "LAST_SEARCHED_INVALID", "sampling_frame", id, "last_searched must be an ISO date");
} else if (cutoff && clean(row.last_searched) > cutoff) {
error("T08_SAMPLING_FRAME", "LAST_SEARCHED_AFTER_CUTOFF", "sampling_frame", id, `last_searched is after dataset cutoff ${cutoff}`);
}
const actualCases = rows("cases").filter((item) => regionParent(clean(item.region)) === region).length;
const actualCandidates = rows("candidates").filter((item) => regionParent(clean(item.region)) === region).length;
if (parseNumber(row.included_case_count) !== actualCases) {
error("T08_SAMPLING_FRAME", "INCLUDED_COUNT_MISMATCH", "sampling_frame", id, `included_case_count=${clean(row.included_case_count)} but cases.csv has ${actualCases} for ${region}`);
}
if (parseNumber(row.candidate_count) !== actualCandidates) {
error("T08_SAMPLING_FRAME", "CANDIDATE_COUNT_MISMATCH", "sampling_frame", id, `candidate_count=${clean(row.candidate_count)} but candidates.csv has ${actualCandidates} for ${region}`);
}
}
for (const region of [...new Set([...rows("cases"), ...rows("candidates")].map((row) => regionParent(clean(row.region))).filter(Boolean))].sort()) {
if (!framesByRegion.has(region)) error("T08_SAMPLING_FRAME", "REGION_UNCOVERED", "sampling_frame", region, "Cases or candidates exist without a sampling-frame row");
}
if (rows("sampling_frame").length && !rows("sampling_frame").some((row) => trueValues.has(lower(row.negative_search_recorded)))) {
warn("T08_SAMPLING_FRAME", "NO_NEGATIVE_SEARCH_ANYWHERE", "sampling_frame", null, "The release records no systematic negative/null search in any sampling frame; incident prevalence claims remain unsupported");
}
// T09 — official election status is coherent with the release cutoff.
const validElectionStatuses = new Set(["completed", "scheduled", "conditional"]);
const officialDataStatuses = new Set(["current", "final", "pre_election", "scheduled", "not_yet_available"]);
for (const row of rows("official_data_sources")) {
const id = rowId(row, "official_data_sources");
if (!officialDataStatuses.has(clean(row.data_status))) {
error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_SOURCE_STATUS_INVALID", "official_data_sources", id, `Unknown data_status: ${clean(row.data_status)}`);
}
if (!isIsoDate(row.retrieved_at)) {
error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_SOURCE_DATE_INVALID", "official_data_sources", id, "retrieved_at must be an ISO date");
} else if (cutoff && clean(row.retrieved_at) > cutoff) {
error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_SOURCE_AFTER_CUTOFF", "official_data_sources", id, `retrieved_at is after dataset cutoff ${cutoff}`);
}
}
for (const row of rows("official_elections")) {
const id = rowId(row, "official_elections");
if (!isIsoDate(row.election_date) || !isIsoDate(row.as_of_date)) {
error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_DATE_INVALID", "official_elections", id, "election_date and as_of_date must be ISO dates");
}
if (!validElectionStatuses.has(clean(row.election_status))) {
error("T09_OFFICIAL_ELECTION_STATUS", "ELECTION_STATUS_INVALID", "official_elections", id, `Unknown election_status: ${clean(row.election_status)}`);
}
const legalStatus = clean(row.legal_result_status);
if (!/^(not_yet_available|annulled|certified|final)$|(?:validated|confirmed|certified|final|void|annul|mandate|law_adopted)/i.test(legalStatus)) {
error("T09_OFFICIAL_ELECTION_STATUS", "LEGAL_STATUS_INVALID", "official_elections", id, `legal_result_status does not encode a recognized official chronology: ${legalStatus}`);
}
if (cutoff && clean(row.election_date) > cutoff && clean(row.election_status) === "completed") {
error("T09_OFFICIAL_ELECTION_STATUS", "FUTURE_ELECTION_COMPLETED", "official_elections", id, `Election is after dataset cutoff ${cutoff} but marked completed`);
}
if (cutoff && clean(row.election_date) <= cutoff && clean(row.election_status) !== "completed") {
warn("T09_OFFICIAL_ELECTION_STATUS", "PAST_ELECTION_NOT_COMPLETED", "official_elections", id, `Election is on/before dataset cutoff ${cutoff} but not marked completed`);
}
}
// T10 — turnout figures are numeric and arithmetically reconcilable.
function optionalNonNegative(row, field, table, test) {
if (isBlank(row[field])) return null;
const value = parseNumber(row[field]);
if (!Number.isFinite(value) || value < 0) {
error(test, "NON_NEGATIVE_NUMBER_INVALID", table, rowId(row, table), `${field} must be a non-negative number when present`);
return null;
}
return value;
}
const turnoutByElection = new Map();
for (const row of rows("official_turnout")) {
const id = rowId(row, "official_turnout");
requireNonBlank(row, ["electorate_measure", "participation_measure", "data_status", "official_source_id", "as_of_date"], "T10_TURNOUT", "official_turnout", id);
if (!officialDataStatuses.has(clean(row.data_status))) {
error("T10_TURNOUT", "TURNOUT_STATUS_INVALID", "official_turnout", id, `Unknown data_status: ${clean(row.data_status)}`);
}
const values = {};
for (const field of ["registered_voters", "ballots_cast", "valid_votes", "invalid_votes", "reporting_units_total", "reporting_units_counted"]) {
values[field] = optionalNonNegative(row, field, "official_turnout", "T10_TURNOUT");
}
if (loaded.get("official_turnout")?.headers.includes("turnout_numerator")) {
values.turnout_numerator = optionalNonNegative(row, "turnout_numerator", "official_turnout", "T10_TURNOUT");
}
if (values.reporting_units_total !== null && values.reporting_units_counted !== null && values.reporting_units_counted > values.reporting_units_total) {
error("T10_TURNOUT", "REPORTING_UNITS_EXCEED_TOTAL", "official_turnout", id, "reporting_units_counted exceeds reporting_units_total");
}
if (!isBlank(row.turnout_rate)) {
const rate = parseNumber(row.turnout_rate);
if (!Number.isFinite(rate) || rate < 0 || rate > 1) {
error("T10_TURNOUT", "TURNOUT_RATE_INVALID", "official_turnout", id, "turnout_rate must be between 0 and 1");
} else if (values.registered_voters > 0 && (values.turnout_numerator ?? values.ballots_cast) !== null) {
const numerator = values.turnout_numerator ?? values.ballots_cast;
const derived = numerator / values.registered_voters;
if (Math.abs(rate - derived) > 0.0001) {
error("T10_TURNOUT", "TURNOUT_RATE_DENOMINATOR_MISMATCH", "official_turnout", id, `turnout_rate=${rate} but stated turnout numerator/registered_voters=${derived}`);
}
}
}
if (values.ballots_cast !== null && values.valid_votes !== null && values.invalid_votes !== null) {
const derived = values.valid_votes + values.invalid_votes;
if (values.ballots_cast !== derived && !/(differ|reconcil|special ballot|blank vote)/i.test(clean(row.notes))) {
error("T10_TURNOUT", "BALLOT_ARITHMETIC", "official_turnout", id, `ballots_cast=${values.ballots_cast} but valid_votes+invalid_votes=${derived}; no reconciliation note`);
}
}
const election = index.official_elections.get(clean(row.election_id));
if (cutoff && election && clean(election.election_date) > cutoff && clean(row.data_status) === "final") {
error("T10_TURNOUT", "FUTURE_FINAL_TURNOUT", "official_turnout", id, "Future election has final turnout data");
}
if (!turnoutByElection.has(clean(row.election_id))) turnoutByElection.set(clean(row.election_id), []);
turnoutByElection.get(clean(row.election_id)).push(row);
}
// T11 — official result shares, totals and temporal status are coherent.
const coverageStatuses = new Set(["complete", "complete_national_contest", "partial"]);
const completeGroups = new Map();
for (const row of rows("official_results")) {
const id = rowId(row, "official_results");
requireNonBlank(
row,
["votes", "valid_vote_share", "result_status", "coverage_status", "official_source_id", "as_of_date"],
"T11_OFFICIAL_RESULTS", "official_results", id
);
const resultStatus = clean(row.result_status);
if (!/^(final|certified|annulled)$|(?:final|validat|confirm|certif|void|annul)/i.test(resultStatus)) {
error("T11_OFFICIAL_RESULTS", "RESULT_STATUS_INVALID", "official_results", id, `result_status does not encode a recognized official chronology: ${resultStatus}`);
}
if (!coverageStatuses.has(clean(row.coverage_status))) {
error("T11_OFFICIAL_RESULTS", "COVERAGE_STATUS_INVALID", "official_results", id, `Unknown coverage_status: ${clean(row.coverage_status)}`);
}
const votes = optionalNonNegative(row, "votes", "official_results", "T11_OFFICIAL_RESULTS");
const share = parseNumber(row.valid_vote_share);
if (!Number.isFinite(share) || share < 0 || share > 1) {
error("T11_OFFICIAL_RESULTS", "VOTE_SHARE_INVALID", "official_results", id, "valid_vote_share must be between 0 and 1");
}
const rank = parseNumber(row.rank);
if (!isBlank(row.rank) && (!Number.isInteger(rank) || rank <= 0)) {
error("T11_OFFICIAL_RESULTS", "RANK_INVALID", "official_results", id, "rank must be a positive integer when present");
}
if (isBlank(row.rank) && !/excluded|invalidated|withdrawn|not_ranked/i.test(clean(row.outcome))) {
error("T11_OFFICIAL_RESULTS", "RANK_MISSING", "official_results", id, "rank may be blank only for an explicitly excluded, invalidated, withdrawn or unranked option");
}
const election = index.official_elections.get(clean(row.election_id));
if (cutoff && election && clean(election.election_date) > cutoff) {
error("T11_OFFICIAL_RESULTS", "FUTURE_RESULT_ROW", "official_results", id, "Future election has an official result row");
}
if (["complete", "complete_national_contest"].includes(clean(row.coverage_status))) {
const key = [row.election_id, row.geographic_unit_type, row.geographic_unit_code, row.contest_name].map(clean).join("::");
if (!completeGroups.has(key)) completeGroups.set(key, []);
completeGroups.get(key).push({ row, votes, share });
}
}
const nationalCompleteGroupsByElection = new Map();
for (const [key, group] of completeGroups) {
const shares = group.map((item) => item.share);
if (shares.every(Number.isFinite)) {
const total = shares.reduce((sum, value) => sum + value, 0);
if (Math.abs(total - 1) > 0.001) error("T11_OFFICIAL_RESULTS", "COMPLETE_SHARES_NOT_ONE", "official_results", key, `Complete-group shares sum to ${total}, not 1`);
}
if (clean(group[0].row.geographic_unit_type) === "national") {
const electionId = clean(group[0].row.election_id);
if (!nationalCompleteGroupsByElection.has(electionId)) nationalCompleteGroupsByElection.set(electionId, []);
nationalCompleteGroupsByElection.get(electionId).push(group);
}
}
for (const [electionId, groups] of nationalCompleteGroupsByElection) {
const nationalTurnouts = (turnoutByElection.get(electionId) || []).filter((row) => clean(row.geographic_unit_type) === "national" && !isBlank(row.valid_votes));
if (groups.length === 1 && nationalTurnouts.length === 1) {
const voteTotal = groups[0].reduce((sum, item) => sum + (item.votes ?? 0), 0);
const validVotes = parseNumber(nationalTurnouts[0].valid_votes);
if (Number.isFinite(validVotes) && voteTotal !== validVotes) {
error("T11_OFFICIAL_RESULTS", "RESULT_TURNOUT_TOTAL_MISMATCH", "official_results", electionId, `Complete national results total ${voteTotal}; official_turnout valid_votes=${validVotes}`);
}
} else if (groups.length > 1 && nationalTurnouts.length) {
warn("T11_OFFICIAL_RESULTS", "MULTIPLE_NATIONAL_CONTESTS", "official_results", electionId, "Multiple complete national contests prevent an automatic result-to-turnout total match");
}
}
// T12 — simple researcher view and coverage summaries reproduce the underlying rows.
const researchViewKeys = new Set();
for (const row of rows("research_view")) {
const id = rowId(row, "research_view");
requireNonBlank(
row,
[
"case_id", "pathway_id", "record_type", "manipulation_assessment", "controller",
"influence_vector", "target", "agency_dimension", "capability_status",
"control_mechanism_status", "attempted_transfer_status", "agency_change_status",
"agency_preservation_status", "maximum_conclusion", "hypothesized_power_recipient",
"case_evidence_summary"
],
"T12_DERIVED_VIEWS", "research_view", id
);
const key = `${clean(row.case_id)}::${clean(row.pathway_id)}`;
if (researchViewKeys.has(key)) error("T12_DERIVED_VIEWS", "RESEARCH_VIEW_DUPLICATE", "research_view", id, `Duplicate case/pathway row: ${key}`);
researchViewKeys.add(key);
const parent = index.cases.get(clean(row.case_id));
const pathway = index.pathways.get(clean(row.pathway_id));
if (parent && clean(parent.record_type) !== clean(row.record_type)) {
error("T12_DERIVED_VIEWS", "VIEW_RECORD_TYPE_MISMATCH", "research_view", id, "record_type differs from cases.csv");
}
if (parent && clean(parent.manipulation_assessment) !== clean(row.manipulation_assessment)) {
error("T12_DERIVED_VIEWS", "VIEW_MANIPULATION_MISMATCH", "research_view", id, "manipulation_assessment differs from cases.csv");
}
for (const field of [
"agency_dimension", "capability_status", "control_mechanism_status", "attempted_transfer_status",
"agency_change_status", "agency_preservation_status", "maximum_conclusion", "hypothesized_power_recipient"
]) {
if (pathway && clean(pathway[field]) !== clean(row[field])) {
error("T12_DERIVED_VIEWS", "VIEW_PATHWAY_FIELD_MISMATCH", "research_view", id, `${field} differs from pathways.csv`);
}
}
}
for (const row of rows("pathways")) {
const key = `${clean(row.case_id)}::${clean(row.pathway_id)}`;
if (!researchViewKeys.has(key)) error("T12_DERIVED_VIEWS", "PATHWAY_MISSING_FROM_VIEW", "research_view", clean(row.pathway_id), "Every pathway must appear once in research_view.csv");
}
const coverageRegions = new Set();
for (const row of rows("coverage_summary")) {
const region = clean(row.region);
if (coverageRegions.has(region)) error("T12_DERIVED_VIEWS", "COVERAGE_REGION_DUPLICATE", "coverage_summary", region, "Duplicate coverage-summary region");
coverageRegions.add(region);
const actualCases = rows("cases").filter((item) => regionParent(clean(item.region)) === region).length;
const actualCandidates = rows("candidates").filter((item) => regionParent(clean(item.region)) === region).length;
const actualEvaluations = rows("case_catalog").filter(
(item) => clean(item.record_layer) === "empirical_model_study" && clean(item.region) === region
).length;
if (parseNumber(row.included_case_count) !== actualCases) {
error("T12_DERIVED_VIEWS", "COVERAGE_CASE_COUNT_MISMATCH", "coverage_summary", region, `included_case_count differs from cases.csv (${actualCases})`);
}
if (parseNumber(row.candidate_count) !== actualCandidates) {
error("T12_DERIVED_VIEWS", "COVERAGE_CANDIDATE_COUNT_MISMATCH", "coverage_summary", region, `candidate_count differs from candidates.csv (${actualCandidates})`);
}
// model_evaluations stores country rather than region; only enforce a numeric count here.
const statedEvaluations = parseNumber(row.model_evaluation_count);
if (!Number.isInteger(statedEvaluations) || statedEvaluations < 0) {
error("T12_DERIVED_VIEWS", "COVERAGE_EVALUATION_COUNT_INVALID", "coverage_summary", region, "model_evaluation_count must be a non-negative integer");
} else if (statedEvaluations !== actualEvaluations) {
error("T12_DERIVED_VIEWS", "COVERAGE_EVALUATION_COUNT_MISMATCH", "coverage_summary", region, `model_evaluation_count differs from empirical-model rows in case_catalog.csv (${actualEvaluations})`);
}
}
// Normalized v0.4.0 joins must cover legacy pipe lists; this catches silent evidence loss.
const evidencePairs = new Set(rows("claim_evidence").map((row) => `${clean(row.claim_id)}::${clean(row.source_id)}::${clean(row.relation)}`));
const evidenceRelationsByClaimSource = new Map();
for (const row of rows("claim_evidence")) {
const key = `${clean(row.claim_id)}::${clean(row.source_id)}`;
if (!evidenceRelationsByClaimSource.has(key)) evidenceRelationsByClaimSource.set(key, new Set());
evidenceRelationsByClaimSource.get(key).add(clean(row.relation));
const claim = index.claims.get(clean(row.claim_id));
if (claim && clean(row.evidence_scope) !== clean(claim.evidence_scope)) {
error(
"T03_FOREIGN_KEYS", "CLAIM_EVIDENCE_SCOPE_MISMATCH", "claim_evidence", rowId(row, "claim_evidence"),
`evidence_scope differs from claims.csv (${clean(claim.evidence_scope)})`
);
}
if (clean(row.relation) === "premise" && clean(row.evidence_scope) !== "researcher_inference") {
error("T14_TABLE_SEMANTICS", "PREMISE_SCOPE_INVALID", "claim_evidence", rowId(row, "claim_evidence"), "premise relations are reserved for researcher_inference claims");
}
if (clean(row.relation) === "supports" && clean(row.evidence_scope) === "researcher_inference") {
error("T14_TABLE_SEMANTICS", "INFERENCE_DIRECT_SUPPORT_AMBIGUOUS", "claim_evidence", rowId(row, "claim_evidence"), "Researcher inferences must link factual sources as premise, not supports");
}
const locator = clean(row.locator);
const locatorCoverage = clean(row.locator_coverage);
if (locatorCoverage === "not_verified" && locator) {
error("T14_TABLE_SEMANTICS", "UNVERIFIED_LOCATOR_NONBLANK", "claim_evidence", rowId(row, "claim_evidence"), "locator must be blank when locator_coverage=not_verified");
}
if (locatorCoverage === "not_verified" && isBlank(row.locator_note)) {
error("T14_TABLE_SEMANTICS", "UNVERIFIED_LOCATOR_REASON_MISSING", "claim_evidence", rowId(row, "claim_evidence"), "not_verified relations require a concise locator_note reason");
}
if (["full_claim", "partial_claim"].includes(locatorCoverage) && !locator) {
error("T14_TABLE_SEMANTICS", "VERIFIED_LOCATOR_MISSING", "claim_evidence", rowId(row, "claim_evidence"), "A verified locator coverage label requires a nonblank pinpoint");
}
}
const expectedLocatorCoverage = Object.freeze({ full_claim: 57, partial_claim: 47, not_verified: 20 });
for (const [coverage, expected] of Object.entries(expectedLocatorCoverage)) {
const actual = rows("claim_evidence").filter((row) => clean(row.locator_coverage) === coverage).length;
if (actual !== expected) {
error("T14_TABLE_SEMANTICS", "RELEASE_LOCATOR_COVERAGE_MISMATCH", "claim_evidence", coverage, `Expected ${expected} ${coverage} relations in v0.4.0; found ${actual}`);
}
}
for (const claim of rows("claims")) {
for (const sourceId of ids(claim.source_ids)) {
const prefix = `${clean(claim.claim_id)}::${sourceId}::`;
if (![...evidencePairs].some((pair) => pair.startsWith(prefix))) {
error("T03_FOREIGN_KEYS", "CLAIM_EVIDENCE_JOIN_MISSING", "claim_evidence", clean(claim.claim_id), `Supporting source is absent from normalized join: ${sourceId}`);
}
}
for (const sourceId of ids(claim.counter_source_ids)) {
const relations = evidenceRelationsByClaimSource.get(`${clean(claim.claim_id)}::${sourceId}`) || new Set();
if (![...relations].some((relation) => /counter|qualif/i.test(relation))) {
error("T03_FOREIGN_KEYS", "COUNTEREVIDENCE_JOIN_MISSING", "claim_evidence", clean(claim.claim_id), `Counter-source is absent or not labelled counterevidence: ${sourceId}`);
}
}
}
// Reciprocity between the normalized case-election join and the legacy official link list.
const normalizedCaseElections = new Set(rows("case_elections").map((row) => `${clean(row.case_id)}::${clean(row.election_id)}`));
for (const election of rows("official_elections")) {
for (const caseId of ids(election.linked_case_ids)) {
const pair = `${caseId}::${clean(election.election_id)}`;
if (!normalizedCaseElections.has(pair)) {
error("T03_FOREIGN_KEYS", "CASE_ELECTION_JOIN_MISSING", "case_elections", pair, "Official linked_case_ids entry is absent from case_elections.csv");
}
}
}
for (const row of rows("case_elections")) {
const election = index.official_elections.get(clean(row.election_id));
if (election && !ids(election.linked_case_ids).includes(clean(row.case_id))) {
error("T03_FOREIGN_KEYS", "CASE_ELECTION_NOT_RECIPROCAL", "case_elections", rowId(row, "case_elections"), "Normalized join is absent from official_elections.linked_case_ids");
}
}
for (const caseRow of rows("cases")) {
if (![...normalizedCaseElections].some((pair) => pair.startsWith(`${clean(caseRow.case_id)}::`))) {
error("T03_FOREIGN_KEYS", "CASE_WITHOUT_ELECTION", "case_elections", clean(caseRow.case_id), "Every case must link to at least one official election/context row");
}
}
// T14 — explicit semantics for the six tables that earlier auditors loaded incompletely or not at all.
function uniqueComposite(table, fields, test = "T14_TABLE_SEMANTICS") {
const seen = new Set();
for (const row of rows(table)) {
const values = fields.map((field) => clean(row[field]));
if (values.some((value) => !value)) continue;
const key = values.join("::");
if (seen.has(key)) {
error(test, "COMPOSITE_KEY_DUPLICATE", table, rowId(row, table), `Duplicate ${fields.join("+")}: ${key}`);
}
seen.add(key);
}
return seen;
}
const documentedClaimTypes = new Set(DOCUMENTED_ENUMS["claims.claim_type"]);
const caseSourceRoles = new Set(["primary_record", "corroboration", "counterevidence", "context", "methodology", "ongoing_monitoring"]);
const caseSourcePairs = uniqueComposite("case_sources", ["case_id", "source_id"]);
for (const row of rows("case_sources")) {
const id = rowId(row, "case_sources");
requireNonBlank(row, ["case_id", "source_id", "source_role"], "T14_TABLE_SEMANTICS", "case_sources", id);
if (!caseSourceRoles.has(clean(row.source_role))) {
error("T14_TABLE_SEMANTICS", "CASE_SOURCE_ROLE_INVALID", "case_sources", id, `Unknown source_role: ${clean(row.source_role)}`);
}
const caseClaimTypes = new Set(rows("claims").filter((claim) => clean(claim.case_id) === clean(row.case_id)).map((claim) => clean(claim.claim_type)));
for (const claimType of ids(row.supports_claim_types)) {
if (!documentedClaimTypes.has(claimType)) {
error("T14_TABLE_SEMANTICS", "CASE_SOURCE_CLAIM_TYPE_INVALID", "case_sources", id, `Unknown supports_claim_types token: ${claimType}`);
} else if (!caseClaimTypes.has(claimType)) {
warn("T14_TABLE_SEMANTICS", "CASE_SOURCE_CLAIM_TYPE_ORPHAN", "case_sources", id, `No ${claimType} claim exists for this case; verify or narrow supports_claim_types`);
}
}
}
for (const claim of rows("claims")) {
requireFk("T03_FOREIGN_KEYS", "claims", claim, "source_ids", "sources", index.sources, true);
requireFk("T03_FOREIGN_KEYS", "claims", claim, "counter_source_ids", "sources", index.sources, true);
const sourceOptionalLabels = new Set(["open_question", "researcher_hypothesis", "not_identified_in_declared_review"]);
if (
!ids(claim.source_ids).length && !ids(claim.counter_source_ids).length &&
!sourceOptionalLabels.has(clean(claim.evidence_label))
) {
error(
"T14_TABLE_SEMANTICS", "CLAIM_WITHOUT_EVIDENCE_LINK", "claims", clean(claim.claim_id),
"Only an open question, researcher hypothesis, or declared-review absence may lack a source link"
);
}
for (const sourceId of [...ids(claim.source_ids), ...ids(claim.counter_source_ids)]) {
const pair = `${clean(claim.case_id)}::${sourceId}`;
if (!caseSourcePairs.has(pair)) {
error("T14_TABLE_SEMANTICS", "CLAIM_CASE_SOURCE_JOIN_MISSING", "case_sources", clean(claim.claim_id), `Claim source is absent from case_sources.csv: ${sourceId}`);
}
}
}
const eventStatuses = new Set(["observed", "contested", "prospective"]);
for (const row of rows("events")) {
const id = rowId(row, "events");
requireNonBlank(row, ["case_id", "event_date", "event_type", "description", "source_ids", "event_status"], "T14_TABLE_SEMANTICS", "events", id);
requireFk("T03_FOREIGN_KEYS", "events", row, "claim_ids", "claims", index.claims, true);
requireFk("T03_FOREIGN_KEYS", "events", row, "source_ids", "sources");
if (!eventStatuses.has(clean(row.event_status))) {
error("T14_TABLE_SEMANTICS", "EVENT_STATUS_INVALID", "events", id, `Unknown event_status: ${clean(row.event_status)}`);
}
for (const claimId of ids(row.claim_ids)) {
const claim = index.claims.get(claimId);
if (claim && clean(claim.case_id) !== clean(row.case_id)) {
error("T14_TABLE_SEMANTICS", "EVENT_CROSS_CASE_CLAIM", "events", id, `claim_ids references another case: ${claimId}`);
}
}
for (const sourceId of ids(row.source_ids)) {
if (!caseSourcePairs.has(`${clean(row.case_id)}::${sourceId}`)) {
error("T14_TABLE_SEMANTICS", "EVENT_CASE_SOURCE_JOIN_MISSING", "events", id, `Event source is absent from case_sources.csv: ${sourceId}`);
}
}
if (cutoff && isIsoDate(row.event_date) && clean(row.event_date) > cutoff && clean(row.event_status) !== "prospective") {
error("T14_TABLE_SEMANTICS", "FUTURE_EVENT_NOT_PROSPECTIVE", "events", id, `Event after cutoff ${cutoff} must be prospective`);
}
}
const watchStatuses = new Set(["active", "prospective_monitoring"]);
for (const row of rows("watchlist")) {
const id = rowId(row, "watchlist");
requireNonBlank(
row,
[
"case_id", "jurisdiction", "election_date", "monitoring_window", "signal_category",
"observable_indicator", "defensive_data_source", "assessment_rule", "status", "last_checked"
],
"T14_TABLE_SEMANTICS", "watchlist", id
);
if (!watchStatuses.has(clean(row.status))) {
error("T14_TABLE_SEMANTICS", "WATCH_STATUS_INVALID", "watchlist", id, `Unknown status: ${clean(row.status)}`);
}
if (cutoff && isIsoDate(row.last_checked) && clean(row.last_checked) > cutoff) {
error("T14_TABLE_SEMANTICS", "WATCH_CHECK_AFTER_CUTOFF", "watchlist", id, `last_checked is after dataset cutoff ${cutoff}`);
}
const linkedElectionDates = rows("case_elections")
.filter((join) => clean(join.case_id) === clean(row.case_id))
.map((join) => clean(index.official_elections.get(clean(join.election_id))?.election_date))
.filter(Boolean);
if (!linkedElectionDates.includes(clean(row.election_date))) {
error("T14_TABLE_SEMANTICS", "WATCH_ELECTION_DATE_UNLINKED", "watchlist", id, "election_date does not match an official election linked to the case");
}
}
const analyticTargets = Object.freeze({
case_actor: ["case_actors", "case_actor_id", "source_claim_ids"],
technology_use: ["technology_uses", "tech_use_id", "source_claim_ids"],
content_item: ["content_items", "content_item_id", "source_claim_ids"],
pathway: ["pathways", "pathway_id", "source_claim_ids"],
event: ["events", "event_id", "claim_ids"]
});
const analyticPairs = uniqueComposite("analytic_record_claims", ["record_type", "record_id", "claim_id"]);
for (const row of rows("analytic_record_claims")) {
const id = rowId(row, "analytic_record_claims");
requireNonBlank(row, ["record_type", "record_id", "case_id", "claim_id", "relation"], "T14_TABLE_SEMANTICS", "analytic_record_claims", id);
const target = analyticTargets[clean(row.record_type)];
if (!target) {
error("T14_TABLE_SEMANTICS", "ANALYTIC_RECORD_TYPE_INVALID", "analytic_record_claims", id, `Unknown record_type: ${clean(row.record_type)}`);
continue;
}
if (clean(row.relation) !== "supports_coding") {
error("T14_TABLE_SEMANTICS", "ANALYTIC_RELATION_INVALID", "analytic_record_claims", id, `Unknown relation: ${clean(row.relation)}`);
}
const targetRow = index[target[0]]?.get(clean(row.record_id));
if (!targetRow) {
error("T14_TABLE_SEMANTICS", "ANALYTIC_RECORD_UNKNOWN", "analytic_record_claims", id, `${row.record_type} references unknown ${target[0]} row: ${clean(row.record_id)}`);
} else if (clean(targetRow.case_id) !== clean(row.case_id)) {
error("T14_TABLE_SEMANTICS", "ANALYTIC_RECORD_CASE_MISMATCH", "analytic_record_claims", id, "record_id belongs to another case");
}
const claim = index.claims.get(clean(row.claim_id));
if (claim && clean(claim.case_id) !== clean(row.case_id)) {
error("T14_TABLE_SEMANTICS", "ANALYTIC_CLAIM_CASE_MISMATCH", "analytic_record_claims", id, "claim_id belongs to another case");
}
}
for (const [recordType, [table, idField, claimField]] of Object.entries(analyticTargets)) {
for (const row of rows(table)) {
for (const claimId of ids(row[claimField])) {
const key = `${recordType}::${clean(row[idField])}::${claimId}`;
if (!analyticPairs.has(key)) {
error("T14_TABLE_SEMANTICS", "ANALYTIC_CLAIM_JOIN_MISSING", "analytic_record_claims", clean(row[idField]), `Legacy ${claimField} entry is absent from normalized join: ${claimId}`);
}
}
}
}
const caseElectionRelations = new Set(["primary_or_institutional_context", "future_or_campaign_context"]);
uniqueComposite("case_elections", ["case_id", "election_id"]);
for (const row of rows("case_elections")) {
if (!caseElectionRelations.has(clean(row.relation))) {
error("T14_TABLE_SEMANTICS", "CASE_ELECTION_RELATION_INVALID", "case_elections", rowId(row, "case_elections"), `Unknown relation: ${clean(row.relation)}`);
}
}
const electionSourcePairs = uniqueComposite("election_sources", ["election_id", "official_source_id"]);
const electionSourceRoles = new Set([
"supports_election_context_or_status", "election_definition", "turnout", "results", "metrics", "legal_status"
]);
for (const row of rows("election_sources")) {
const id = rowId(row, "election_sources");
requireNonBlank(row, ["election_id", "official_source_id", "source_role"], "T14_TABLE_SEMANTICS", "election_sources", id);
if (!electionSourceRoles.has(clean(row.source_role))) {
error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_ROLE_INVALID", "election_sources", id, `Unknown source_role: ${clean(row.source_role)}`);
}
const election = index.official_elections.get(clean(row.election_id));
const source = index.official_data_sources.get(clean(row.official_source_id));
if (election && source && clean(election.case_family_id) !== clean(source.case_family_id)) {
error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_FAMILY_MISMATCH", "election_sources", id, "Election and official source belong to different case families");
}
if (election && !ids(election.official_source_ids).includes(clean(row.official_source_id))) {
error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_NOT_RECIPROCAL", "election_sources", id, "Normalized link is absent from official_elections.official_source_ids");
}
}
for (const election of rows("official_elections")) {
for (const sourceId of ids(election.official_source_ids)) {
const pair = `${clean(election.election_id)}::${sourceId}`;
if (!electionSourcePairs.has(pair)) {
error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_JOIN_MISSING", "election_sources", pair, "Legacy official_source_ids entry is absent from election_sources.csv");
}
}
}
for (const table of ["official_turnout", "official_results", "official_election_metrics"]) {
for (const row of rows(table)) {
const pair = `${clean(row.election_id)}::${clean(row.official_source_id)}`;
if (!electionSourcePairs.has(pair)) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_ROW_SOURCE_JOIN_MISSING", "election_sources", rowId(row, table), `${table} source/election pair is absent from election_sources.csv`);
}
}
}
const metricLookup = new Map();
for (const row of rows("official_election_metrics")) {
const id = rowId(row, "official_election_metrics");
requireNonBlank(
row,
["election_id", "geographic_unit_type", "metric_code", "value", "source_label_original", "legal_role", "data_status", "official_source_id", "as_of_date"],
"T14_TABLE_SEMANTICS", "official_election_metrics", id
);
const key = [row.election_id, row.geographic_unit_type, row.geographic_unit_code, row.metric_code].map(clean).join("::");
if (metricLookup.has(key)) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_DUPLICATE", "official_election_metrics", id, `Duplicate election/geography/metric_code: ${key}`);
}
metricLookup.set(key, row);
const value = parseNumber(row.value);
if (!Number.isFinite(value) || value < 0) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_VALUE_INVALID", "official_election_metrics", id, "value must be a non-negative finite number");
}
if (/rate|share/i.test(clean(row.metric_code)) && Number.isFinite(value) && value > 1) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_RATE_RANGE", "official_election_metrics", id, "Rate/share metric value must be between 0 and 1");
}
for (const field of ["authority_reported_rate", "computed_rate"]) {
if (!isBlank(row[field])) {
const rate = parseNumber(row[field]);
if (!Number.isFinite(rate) || rate < 0 || rate > 1) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_RATE_INVALID", "official_election_metrics", id, `${field} must be between 0 and 1`);
}
}
}
if (isBlank(row.numerator_metric) !== isBlank(row.denominator_metric)) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_COMPONENT_PARTIAL", "official_election_metrics", id, "numerator_metric and denominator_metric must be present together");
}
if (!officialDataStatuses.has(clean(row.data_status))) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_STATUS_INVALID", "official_election_metrics", id, `Unknown data_status: ${clean(row.data_status)}`);
}
if (cutoff && isIsoDate(row.as_of_date) && clean(row.as_of_date) > cutoff) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_AFTER_CUTOFF", "official_election_metrics", id, `as_of_date is after dataset cutoff ${cutoff}`);
}
const election = index.official_elections.get(clean(row.election_id));
if (cutoff && election && clean(election.election_date) > cutoff && clean(row.data_status) === "final") {
error("T14_TABLE_SEMANTICS", "FUTURE_FINAL_OFFICIAL_METRIC", "official_election_metrics", id, "Future election has final metric data");
}
}
function metricReferenceKey(row, metricCode) {
const normalizedCode = clean(metricCode) === "A+B" ? "A_plus_B" : clean(metricCode);
return [row.election_id, row.geographic_unit_type, row.geographic_unit_code, normalizedCode].map(clean).join("::");
}
function resolveMetricComponent(row, metricCode) {
const longMetric = metricLookup.get(metricReferenceKey(row, metricCode));
if (longMetric) return { value: longMetric.value, origin: "official_election_metrics" };
const field = clean(metricCode);
if (!loaded.get("official_turnout")?.headers.includes(field)) return null;
const matches = rows("official_turnout").filter(
(turnout) => clean(turnout.election_id) === clean(row.election_id) &&
clean(turnout.geographic_unit_type) === clean(row.geographic_unit_type) &&
clean(turnout.geographic_unit_code) === clean(row.geographic_unit_code) &&
!isBlank(turnout[field])
);
return matches.length === 1 ? { value: matches[0][field], origin: "official_turnout" } : null;
}
for (const row of rows("official_election_metrics")) {
if (isBlank(row.numerator_metric) && isBlank(row.denominator_metric)) continue;
const id = rowId(row, "official_election_metrics");
const numerator = resolveMetricComponent(row, row.numerator_metric);
const denominator = resolveMetricComponent(row, row.denominator_metric);
if (!numerator) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_NUMERATOR_UNKNOWN", "official_election_metrics", id, `Unknown numerator metric in the same election/geography: ${clean(row.numerator_metric)}`);
}
if (!denominator) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_DENOMINATOR_UNKNOWN", "official_election_metrics", id, `Unknown denominator metric in the same election/geography: ${clean(row.denominator_metric)}`);
}
if (!numerator || !denominator) continue;
const denominatorValue = parseNumber(denominator.value);
const expectedRate = denominatorValue > 0 ? parseNumber(numerator.value) / denominatorValue : Number.NaN;
const computedRate = parseNumber(row.computed_rate);
if (!Number.isFinite(computedRate)) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_COMPUTED_RATE_MISSING", "official_election_metrics", id, "Rate components require computed_rate");
} else if (!Number.isFinite(expectedRate) || Math.abs(computedRate - expectedRate) > 1e-12) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_RECOMPUTATION_MISMATCH", "official_election_metrics", id, `computed_rate=${computedRate}; numerator/denominator=${expectedRate}`);
}
const value = parseNumber(row.value);
if (Number.isFinite(computedRate) && Number.isFinite(value) && Math.abs(value - computedRate) > 1e-12) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_VALUE_RATE_MISMATCH", "official_election_metrics", id, "Rate metric value differs from computed_rate");
}
const authorityRate = parseNumber(row.authority_reported_rate);
if (authorityRate !== null && Number.isFinite(authorityRate) && Number.isFinite(computedRate) && Math.abs(authorityRate - computedRate) > 0.0001) {
error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_AUTHORITY_RATE_MISMATCH", "official_election_metrics", id, "authority_reported_rate differs from computed_rate by more than rounding tolerance");
}
}
const catalogById = index.case_catalog;
const catalogLayers = Object.freeze({
claim_coded_core: ["cases", "case_id"],
screening_register: ["candidates", "candidate_id"],
empirical_model_study: ["model_evaluations", "evaluation_id"]
});
for (const row of rows("case_catalog")) {
const id = rowId(row, "case_catalog");
const target = catalogLayers[clean(row.record_layer)];
const targetRow = target ? index[target[0]]?.get(clean(row.catalog_id)) : null;
if (target && !targetRow) {
error("T14_TABLE_SEMANTICS", "CATALOG_TARGET_UNKNOWN", "case_catalog", id, `${row.record_layer} does not resolve to ${target[0]}.${target[1]}`);
}
let expectedSourceCount = null;
if (clean(row.record_layer) === "claim_coded_core") {
expectedSourceCount = rows("case_sources").filter((item) => clean(item.case_id) === clean(row.catalog_id)).length;
if (targetRow && clean(row.record_type) !== clean(targetRow.record_type)) {
error("T14_TABLE_SEMANTICS", "CATALOG_RECORD_TYPE_MISMATCH", "case_catalog", id, "record_type differs from cases.csv");
}
if (targetRow && clean(row.manipulation_assessment) !== clean(targetRow.manipulation_assessment)) {
error("T14_TABLE_SEMANTICS", "CATALOG_MANIPULATION_MISMATCH", "case_catalog", id, "manipulation_assessment differs from cases.csv");
}
} else if (clean(row.record_layer) === "screening_register") {
expectedSourceCount = ids(targetRow?.source_urls).length;
if (clean(row.record_type) !== "candidate_lead") {
error("T14_TABLE_SEMANTICS", "CATALOG_CANDIDATE_TYPE_INVALID", "case_catalog", id, "screening_register must use record_type=candidate_lead");
}
} else if (clean(row.record_layer) === "empirical_model_study") {
expectedSourceCount = ids(targetRow?.source_id).length;
if (clean(row.record_type) !== "model_evaluation_or_experiment") {
error("T14_TABLE_SEMANTICS", "CATALOG_MODEL_TYPE_INVALID", "case_catalog", id, "empirical_model_study must use record_type=model_evaluation_or_experiment");
}
}
if (expectedSourceCount !== null && parseNumber(row.source_count_or_links) !== expectedSourceCount) {
error("T14_TABLE_SEMANTICS", "CATALOG_SOURCE_COUNT_MISMATCH", "case_catalog", id, `source_count_or_links differs from normalized/source links (${expectedSourceCount})`);
}
}
for (const [layer, [table, idField]] of Object.entries(catalogLayers)) {
for (const row of rows(table)) {
const id = clean(row[idField]);
const catalog = catalogById.get(id);
if (!catalog) {
error("T14_TABLE_SEMANTICS", "SOURCE_RECORD_MISSING_FROM_CATALOG", "case_catalog", id, `${table}.${idField} is absent from case_catalog.csv`);
} else if (clean(catalog.record_layer) !== layer) {
error("T14_TABLE_SEMANTICS", "CATALOG_LAYER_MISMATCH", "case_catalog", id, `Expected record_layer=${layer}; found ${clean(catalog.record_layer)}`);
}
}
}
function stableIssueOrder(a, b) {
return (
a.test.localeCompare(b.test) ||
a.code.localeCompare(b.code) ||
String(a.table).localeCompare(String(b.table)) ||
String(a.row_id).localeCompare(String(b.row_id)) ||
a.message.localeCompare(b.message)
);
}
blocking.sort(stableIssueOrder);
advisory.sort(stableIssueOrder);
const tableCounts = Object.fromEntries([...loaded.entries()].map(([name, table]) => [name, table.rows.length]));
const integrityErrors = blocking.filter((item) => item.layer === "integrity");
const integrityWarnings = advisory.filter((item) => item.layer === "integrity");
const semanticErrors = blocking.filter((item) => item.layer === "semantic");
const semanticWarnings = advisory.filter((item) => item.layer === "semantic");
const semanticChecksByTable = Object.freeze({
cases: ["classification", "incident denominator", "case-family and election links", "pathway/actor/technology coverage"],
claims: ["documented enums", "case/source links", "normalized evidence and case-source reciprocity"],
sources: ["documented enums", "claim/event/case-source referential use"],
events: ["status/date chronology", "case-scoped claim links", "case-source reciprocity", "analytic join reciprocity"],
case_sources: ["unique case/source pair", "role and claim-type vocabulary", "claim/event reciprocity"],
watchlist: ["required monitoring fields", "status/cutoff chronology", "linked election date"],
candidates: ["sampling counts", "catalog membership and layer"],
official_elections: ["status chronology", "case/source links", "normalized join reciprocity"],
official_turnout: ["numeric ranges", "turnout and ballot arithmetic", "source/election chronology"],
official_results: ["coverage/status", "share/rank arithmetic", "turnout reconciliation"],
official_data_sources: ["family link", "status and retrieval chronology", "election-source use"],
official_election_metrics: ["numeric/rate ranges", "rate-component resolution", "rate recomputation", "source/election chronology"],
research_view: ["unique pathway projection", "case/pathway field parity", "complete pathway coverage"],
case_catalog: ["documented enums", "layer/record resolution", "incident denominator", "source-link counts"],
case_actors: ["documented attribution enum", "case-scoped claim links", "case and analytic coverage"],
technology_uses: ["provenance/version limitations", "case-scoped claim links", "AI-case and analytic coverage"],
content_items: ["case-scoped claim links", "analytic join reciprocity"],
pathways: ["dimensioned control-shift enums", "falsification/comparator fields", "case/view/hypothesis-claim coverage"],
observations: ["numeric intervals and denominators", "causal-status requirements", "case/pathway/claim/source scope"],
model_evaluations: ["sample/design fields", "source link", "catalog membership and layer"],
claim_evidence: ["documented enums", "claim/source links", "legacy evidence reciprocity", "locator/coverage/reason consistency"],
analytic_record_claims: ["record-type resolution", "case-scoped claims", "legacy analytic-link reciprocity"],
case_elections: ["unique pair and relation", "case/election links", "legacy link reciprocity"],
election_sources: ["unique pair and role", "family consistency", "legacy and official-row reciprocity"],
sampling_frame: ["documented status", "counts/flags/dates", "region coverage"],
coverage_summary: ["unique region", "case/candidate/model counts"]
});
const report = {
auditor: "agency-transfer-election-cases-v0.4.0/audit-v04",
cutoff,
status: blocking.length ? "fail" : "pass",
integrity: {
status: integrityErrors.length ? "fail" : "pass",
expected_table_count: EXPECTED_TABLES.length,
loaded_table_count: EXPECTED_TABLES.filter((name) => loaded.get(name)?.exists).length,
datapackage_resource_count: resourceByName.size,
declared_field_count: [...resourceByName.values()].reduce((sum, resource) => sum + (resource.schema?.fields?.length || 0), 0),
declared_foreign_key_count: [...resourceByName.values()].reduce((sum, resource) => sum + (resource.schema?.foreignKeys?.length || 0), 0),
error_count: integrityErrors.length,
warning_count: integrityWarnings.length
},
semantic_audit: {
status: semanticErrors.length ? "fail" : "pass",
audited_table_count: Object.keys(semanticChecksByTable).length,
audited_tables: Object.keys(semanticChecksByTable),
checks_by_table: semanticChecksByTable,
error_count: semanticErrors.length,
warning_count: semanticWarnings.length
},
summary: {
error_count: blocking.length,
warning_count: advisory.length,
table_row_counts: tableCounts
},
errors: blocking,
warnings: advisory
};
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
if (blocking.length) process.exitCode = 1;
|