apol commited on
Commit
84110a3
·
verified ·
1 Parent(s): 3818c69

Publish strict v0.3.1 builders and 26-table validation

Browse files

Deterministic audit now validates 26 tables, 382 fields, 23 primary keys, 29 foreign keys, controlled vocabularies and electoral arithmetic.

scripts/audit-v03.mjs CHANGED
@@ -1,7 +1,7 @@
1
  #!/usr/bin/env node
2
 
3
  /**
4
- * Deterministic, read-only acceptance audit for the v0.3 CSV release.
5
  *
6
  * Usage:
7
  * node scripts/audit-v03.mjs [data-directory]
@@ -18,12 +18,22 @@ const here = path.dirname(fileURLToPath(import.meta.url));
18
  const packageRoot = path.resolve(here, "..");
19
  const dataDir = path.resolve(process.argv[2] || path.join(packageRoot, "data"));
20
 
 
 
 
 
 
 
 
 
 
21
  const blocking = [];
22
  const advisory = [];
23
  const loaded = new Map();
24
 
25
  function issue(severity, test, code, table, rowId, message) {
26
  const item = {
 
27
  test,
28
  code,
29
  table: table || null,
@@ -36,6 +46,46 @@ function issue(severity, test, code, table, rowId, message) {
36
  const error = (...args) => issue("error", ...args);
37
  const warn = (...args) => issue("warning", ...args);
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  function parseCsv(text, filename) {
40
  const input = text.replace(/^\uFEFF/, "");
41
  const records = [];
@@ -148,6 +198,12 @@ const requiredColumns = {
148
  ],
149
  claims: ["claim_id", "case_id", "claim_type", "evidence_label", "source_ids"],
150
  sources: ["source_id", "source_type", "publication_date", "retrieved_at"],
 
 
 
 
 
 
151
  candidates: ["candidate_id", "region", "research_status"],
152
  case_catalog: [
153
  "catalog_id", "record_layer", "record_type", "manipulation_assessment",
@@ -206,23 +262,55 @@ const requiredColumns = {
206
  "result_id", "election_id", "geographic_unit_type", "geographic_unit_code", "contest_name",
207
  "candidate_or_option", "votes", "valid_vote_share", "rank", "result_status", "coverage_status",
208
  "official_source_id", "as_of_date", "notes"
209
- ]
 
 
 
 
 
 
 
 
210
  };
211
 
212
- for (const [name, headers] of Object.entries(requiredColumns)) loadTable(name, headers);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
  const rows = (name) => loaded.get(name)?.rows || [];
215
  const ids = (value) => String(value || "").split("|").map((part) => part.trim()).filter(Boolean);
216
  const clean = (value) => String(value ?? "").trim();
217
  const lower = (value) => clean(value).toLowerCase();
218
  const isBlank = (value) => clean(value) === "";
219
- const isIsoDate = (value) => /^\d{4}-\d{2}-\d{2}$/.test(clean(value));
 
 
 
 
 
 
 
 
 
220
 
221
  function rowId(row, table) {
222
  const likely = [
223
  `${table.replace(/s$/, "")}_id`, "case_actor_id", "tech_use_id", "content_item_id",
224
- "claim_evidence_id", "case_election_id", "case_id", "pathway_id", "observation_id", "evaluation_id",
225
- "frame_id", "catalog_id", "result_id", "turnout_id", "election_id", "source_id", "claim_id"
 
226
  ];
227
  for (const field of likely) if (!isBlank(row[field])) return clean(row[field]);
228
  return `line:${row.__line}`;
@@ -234,15 +322,209 @@ function requireNonBlank(row, fields, test, table, id) {
234
  }
235
  }
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  function uniqueIndex(table, field) {
238
  const index = new Map();
239
  for (const row of rows(table)) {
240
  const id = clean(row[field]);
241
  const ref = rowId(row, table);
242
  if (!id) {
243
- error("T03_FOREIGN_KEYS", "PRIMARY_KEY_MISSING", table, ref, `Primary key is blank: ${field}`);
244
  } else if (index.has(id)) {
245
- error("T03_FOREIGN_KEYS", "PRIMARY_KEY_DUPLICATE", table, id, `Duplicate ${field}: ${id}`);
246
  } else {
247
  index.set(id, row);
248
  }
@@ -250,15 +532,7 @@ function uniqueIndex(table, field) {
250
  return index;
251
  }
252
 
253
- const primaryKeys = {
254
- cases: "case_id", claims: "claim_id", sources: "source_id", candidates: "candidate_id",
255
- case_catalog: "catalog_id", case_actors: "case_actor_id", technology_uses: "tech_use_id",
256
- content_items: "content_item_id", pathways: "pathway_id", observations: "observation_id",
257
- model_evaluations: "evaluation_id", claim_evidence: "claim_evidence_id",
258
- case_elections: "case_election_id", sampling_frame: "frame_id",
259
- official_data_sources: "official_source_id", official_elections: "election_id",
260
- official_turnout: "turnout_id", official_results: "result_id"
261
- };
262
  const index = Object.fromEntries(Object.entries(primaryKeys).map(([table, field]) => [table, uniqueIndex(table, field)]));
263
 
264
  function requireFk(test, table, row, field, targetTable, targetIndex = index[targetTable], allowBlank = false) {
@@ -279,6 +553,84 @@ const caseFamilyIds = new Set(rows("cases").map((row) => clean(row.case_family_i
279
  const cutoffCandidates = rows("cases").map((row) => clean(row.as_of_date)).filter(isIsoDate).sort();
280
  const cutoff = cutoffCandidates.at(-1) || null;
281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  // T01 — every included case has an explicit, controlled record classification.
283
  const validRecordTypes = new Set([
284
  "observed_incident", "observed_network", "observed_campaign_set", "election_wide_case",
@@ -434,7 +786,7 @@ for (const row of rows("official_elections")) {
434
  error("T03_FOREIGN_KEYS", "CASE_FAMILY_UNKNOWN", "official_elections", rowId(row, "official_elections"), `Unknown case_family_id: ${clean(row.case_family_id)}`);
435
  }
436
  }
437
- for (const table of ["official_turnout", "official_results"]) {
438
  for (const row of rows(table)) {
439
  requireFk("T03_FOREIGN_KEYS", table, row, "election_id", "official_elections");
440
  requireFk("T03_FOREIGN_KEYS", table, row, "official_source_id", "official_data_sources");
@@ -943,7 +1295,7 @@ for (const row of rows("coverage_summary")) {
943
  }
944
  }
945
 
946
- // Normalized v0.3 joins must cover legacy pipe lists; this catches silent evidence loss.
947
  const evidencePairs = new Set(rows("claim_evidence").map((row) => `${clean(row.claim_id)}::${clean(row.source_id)}::${clean(row.relation)}`));
948
  const evidenceRelationsByClaimSource = new Map();
949
  for (const row of rows("claim_evidence")) {
@@ -988,6 +1340,330 @@ for (const caseRow of rows("cases")) {
988
  }
989
  }
990
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991
  function stableIssueOrder(a, b) {
992
  return (
993
  a.test.localeCompare(b.test) ||
@@ -1001,10 +1677,60 @@ blocking.sort(stableIssueOrder);
1001
  advisory.sort(stableIssueOrder);
1002
 
1003
  const tableCounts = Object.fromEntries([...loaded.entries()].map(([name, table]) => [name, table.rows.length]));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1004
  const report = {
1005
- auditor: "agency-transfer-election-cases-v0.3.0/audit-v03",
1006
  cutoff,
1007
  status: blocking.length ? "fail" : "pass",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1008
  summary: {
1009
  error_count: blocking.length,
1010
  warning_count: advisory.length,
 
1
  #!/usr/bin/env node
2
 
3
  /**
4
+ * Deterministic, read-only integrity and semantic audit for the v0.3.1 CSV release.
5
  *
6
  * Usage:
7
  * node scripts/audit-v03.mjs [data-directory]
 
18
  const packageRoot = path.resolve(here, "..");
19
  const dataDir = path.resolve(process.argv[2] || path.join(packageRoot, "data"));
20
 
21
+ const EXPECTED_TABLES = Object.freeze([
22
+ "cases", "claims", "sources", "events", "case_sources", "watchlist", "candidates",
23
+ "official_elections", "official_turnout", "official_results", "official_data_sources",
24
+ "official_election_metrics", "research_view", "case_catalog", "case_actors",
25
+ "technology_uses", "content_items", "pathways", "observations", "model_evaluations",
26
+ "claim_evidence", "analytic_record_claims", "case_elections", "election_sources",
27
+ "sampling_frame", "coverage_summary"
28
+ ]);
29
+
30
  const blocking = [];
31
  const advisory = [];
32
  const loaded = new Map();
33
 
34
  function issue(severity, test, code, table, rowId, message) {
35
  const item = {
36
+ layer: test.startsWith("T00_") ? "integrity" : "semantic",
37
  test,
38
  code,
39
  table: table || null,
 
46
  const error = (...args) => issue("error", ...args);
47
  const warn = (...args) => issue("warning", ...args);
48
 
49
+ const datapackagePath = path.join(dataDir, "datapackage.json");
50
+ let datapackage = null;
51
+ if (!fs.existsSync(datapackagePath)) {
52
+ error("T00_DATAPACKAGE", "DATAPACKAGE_MISSING", "datapackage", null, "data/datapackage.json is missing");
53
+ } else {
54
+ try {
55
+ datapackage = JSON.parse(fs.readFileSync(datapackagePath, "utf8"));
56
+ } catch (caught) {
57
+ error("T00_DATAPACKAGE", "DATAPACKAGE_INVALID_JSON", "datapackage", null, `Invalid JSON: ${caught.message}`);
58
+ }
59
+ }
60
+
61
+ const resourceByName = new Map();
62
+ if (datapackage && !Array.isArray(datapackage.resources)) {
63
+ error("T00_DATAPACKAGE", "RESOURCES_NOT_ARRAY", "datapackage", null, "resources must be an array");
64
+ } else {
65
+ for (const [position, resource] of (datapackage?.resources || []).entries()) {
66
+ const name = String(resource?.name || "").trim();
67
+ if (!name) {
68
+ error("T00_DATAPACKAGE", "RESOURCE_NAME_MISSING", "datapackage", `resource:${position}`, "Resource name is blank");
69
+ continue;
70
+ }
71
+ if (resourceByName.has(name)) {
72
+ error("T00_DATAPACKAGE", "RESOURCE_DUPLICATE", "datapackage", name, `Duplicate resource: ${name}`);
73
+ continue;
74
+ }
75
+ resourceByName.set(name, resource);
76
+ }
77
+ }
78
+ for (const name of EXPECTED_TABLES) {
79
+ if (datapackage && !resourceByName.has(name)) {
80
+ error("T00_DATAPACKAGE", "RESOURCE_MISSING", "datapackage", name, `Expected resource is not declared: ${name}`);
81
+ }
82
+ }
83
+ for (const name of [...resourceByName.keys()].sort()) {
84
+ if (!EXPECTED_TABLES.includes(name)) {
85
+ error("T00_DATAPACKAGE", "RESOURCE_UNEXPECTED", "datapackage", name, `Unexpected tabular resource: ${name}`);
86
+ }
87
+ }
88
+
89
  function parseCsv(text, filename) {
90
  const input = text.replace(/^\uFEFF/, "");
91
  const records = [];
 
198
  ],
199
  claims: ["claim_id", "case_id", "claim_type", "evidence_label", "source_ids"],
200
  sources: ["source_id", "source_type", "publication_date", "retrieved_at"],
201
+ events: ["event_id", "case_id", "event_date", "event_type", "description", "claim_ids", "source_ids", "event_status"],
202
+ case_sources: ["case_id", "source_id", "source_role", "supports_claim_types", "notes"],
203
+ watchlist: [
204
+ "watch_id", "case_id", "jurisdiction", "election_date", "monitoring_window", "signal_category",
205
+ "observable_indicator", "defensive_data_source", "assessment_rule", "status", "last_checked", "notes"
206
+ ],
207
  candidates: ["candidate_id", "region", "research_status"],
208
  case_catalog: [
209
  "catalog_id", "record_layer", "record_type", "manipulation_assessment",
 
262
  "result_id", "election_id", "geographic_unit_type", "geographic_unit_code", "contest_name",
263
  "candidate_or_option", "votes", "valid_vote_share", "rank", "result_status", "coverage_status",
264
  "official_source_id", "as_of_date", "notes"
265
+ ],
266
+ official_election_metrics: [
267
+ "metric_id", "election_id", "geographic_unit_type", "geographic_unit_code", "metric_code", "value",
268
+ "source_field_code", "source_label_original", "numerator_metric", "denominator_metric",
269
+ "authority_reported_rate", "computed_rate", "legal_role", "data_status", "official_source_id",
270
+ "as_of_date", "notes"
271
+ ],
272
+ analytic_record_claims: ["record_claim_id", "record_type", "record_id", "case_id", "claim_id", "relation"],
273
+ election_sources: ["election_source_id", "election_id", "official_source_id", "source_role"]
274
  };
275
 
276
+ const csvFiles = fs.existsSync(dataDir)
277
+ ? fs.readdirSync(dataDir).filter((filename) => filename.endsWith(".csv")).map((filename) => filename.slice(0, -4)).sort()
278
+ : [];
279
+ for (const name of csvFiles) {
280
+ if (!EXPECTED_TABLES.includes(name)) {
281
+ error("T00_SCHEMA", "CSV_TABLE_UNEXPECTED", name, null, `${name}.csv is not one of the 26 release tables`);
282
+ }
283
+ }
284
+ for (const name of EXPECTED_TABLES) {
285
+ const schemaFields = resourceByName.get(name)?.schema?.fields;
286
+ const declaredHeaders = Array.isArray(schemaFields)
287
+ ? schemaFields.map((field) => String(field?.name || "").trim()).filter(Boolean)
288
+ : [];
289
+ loadTable(name, [...new Set([...(requiredColumns[name] || []), ...declaredHeaders])]);
290
+ }
291
 
292
  const rows = (name) => loaded.get(name)?.rows || [];
293
  const ids = (value) => String(value || "").split("|").map((part) => part.trim()).filter(Boolean);
294
  const clean = (value) => String(value ?? "").trim();
295
  const lower = (value) => clean(value).toLowerCase();
296
  const isBlank = (value) => clean(value) === "";
297
+ function isIsoDate(value) {
298
+ const text = clean(value);
299
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
300
+ if (!match) return false;
301
+ const parsed = new Date(`${text}T00:00:00.000Z`);
302
+ return !Number.isNaN(parsed.valueOf()) &&
303
+ parsed.getUTCFullYear() === Number(match[1]) &&
304
+ parsed.getUTCMonth() + 1 === Number(match[2]) &&
305
+ parsed.getUTCDate() === Number(match[3]);
306
+ }
307
 
308
  function rowId(row, table) {
309
  const likely = [
310
  `${table.replace(/s$/, "")}_id`, "case_actor_id", "tech_use_id", "content_item_id",
311
+ "claim_evidence_id", "record_claim_id", "case_election_id", "election_source_id", "watch_id",
312
+ "metric_id", "event_id", "case_id", "pathway_id", "observation_id", "evaluation_id", "frame_id",
313
+ "catalog_id", "result_id", "turnout_id", "election_id", "official_source_id", "source_id", "claim_id"
314
  ];
315
  for (const field of likely) if (!isBlank(row[field])) return clean(row[field]);
316
  return `line:${row.__line}`;
 
322
  }
323
  }
324
 
325
+ const EXPECTED_PRIMARY_KEYS = Object.freeze({
326
+ cases: "case_id", claims: "claim_id", sources: "source_id", events: "event_id", watchlist: "watch_id",
327
+ candidates: "candidate_id", official_elections: "election_id", official_turnout: "turnout_id",
328
+ official_results: "result_id", official_data_sources: "official_source_id",
329
+ official_election_metrics: "metric_id", case_catalog: "catalog_id", case_actors: "case_actor_id",
330
+ technology_uses: "tech_use_id", content_items: "content_item_id", pathways: "pathway_id",
331
+ observations: "observation_id", model_evaluations: "evaluation_id", claim_evidence: "claim_evidence_id",
332
+ analytic_record_claims: "record_claim_id", case_elections: "case_election_id",
333
+ election_sources: "election_source_id", sampling_frame: "frame_id"
334
+ });
335
+
336
+ function normalizedFields(value) {
337
+ if (typeof value === "string") return value.trim() ? [value.trim()] : [];
338
+ if (Array.isArray(value)) return value.map((field) => String(field || "").trim()).filter(Boolean);
339
+ return [];
340
+ }
341
+
342
+ function typedValue(value, type) {
343
+ const text = clean(value);
344
+ if (type === "string") return { valid: true, value: String(value ?? "") };
345
+ if (type === "integer") {
346
+ if (!/^[+-]?\d+$/.test(text)) return { valid: false, value: null };
347
+ const number = Number(text);
348
+ return { valid: Number.isSafeInteger(number), value: number };
349
+ }
350
+ if (type === "number") {
351
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text)) return { valid: false, value: null };
352
+ const number = Number(text);
353
+ return { valid: Number.isFinite(number), value: number };
354
+ }
355
+ if (type === "boolean") {
356
+ if (!/^(true|false)$/i.test(text)) return { valid: false, value: null };
357
+ return { valid: true, value: lower(text) === "true" };
358
+ }
359
+ if (type === "date") return { valid: isIsoDate(text), value: text };
360
+ return { valid: false, value: null, unsupported: true };
361
+ }
362
+
363
+ // T00 — datapackage.json is the executable integrity contract for all 26 tables.
364
+ for (const name of EXPECTED_TABLES) {
365
+ const resource = resourceByName.get(name);
366
+ if (!resource) continue;
367
+ if (clean(resource.path) !== `${name}.csv`) {
368
+ error("T00_DATAPACKAGE", "RESOURCE_PATH_MISMATCH", "datapackage", name, `Expected path ${name}.csv; found ${clean(resource.path) || "blank"}`);
369
+ }
370
+ if (!resource.schema || !Array.isArray(resource.schema.fields)) {
371
+ error("T00_DATAPACKAGE", "SCHEMA_FIELDS_MISSING", "datapackage", name, "Resource schema.fields must be an array");
372
+ continue;
373
+ }
374
+
375
+ const fieldNames = [];
376
+ const fieldByName = new Map();
377
+ for (const [position, field] of resource.schema.fields.entries()) {
378
+ const fieldName = clean(field?.name);
379
+ if (!fieldName) {
380
+ error("T00_DATAPACKAGE", "FIELD_NAME_MISSING", "datapackage", `${name}:${position}`, "Schema field name is blank");
381
+ continue;
382
+ }
383
+ if (fieldByName.has(fieldName)) {
384
+ error("T00_DATAPACKAGE", "FIELD_DUPLICATE", "datapackage", `${name}:${fieldName}`, `Duplicate schema field: ${fieldName}`);
385
+ }
386
+ fieldNames.push(fieldName);
387
+ fieldByName.set(fieldName, field);
388
+ }
389
+
390
+ const table = loaded.get(name);
391
+ if (table?.exists && (
392
+ table.headers.length !== fieldNames.length ||
393
+ table.headers.some((header, position) => header !== fieldNames[position])
394
+ )) {
395
+ error(
396
+ "T00_DATAPACKAGE", "HEADER_SCHEMA_MISMATCH", name, null,
397
+ `CSV header/order differs from datapackage schema (CSV ${table.headers.length} fields; schema ${fieldNames.length})`
398
+ );
399
+ }
400
+
401
+ const expectedPrimaryKey = EXPECTED_PRIMARY_KEYS[name];
402
+ const declaredPrimaryKey = normalizedFields(resource.schema.primaryKey);
403
+ if (expectedPrimaryKey && (declaredPrimaryKey.length !== 1 || declaredPrimaryKey[0] !== expectedPrimaryKey)) {
404
+ error(
405
+ "T00_DATAPACKAGE", "PRIMARY_KEY_DECLARATION_MISMATCH", "datapackage", name,
406
+ `Expected primaryKey=${expectedPrimaryKey}; found ${declaredPrimaryKey.join("|") || "none"}`
407
+ );
408
+ }
409
+ if (!expectedPrimaryKey && declaredPrimaryKey.length) {
410
+ error("T00_DATAPACKAGE", "PRIMARY_KEY_UNEXPECTED", "datapackage", name, `Unexpected primary key declaration: ${declaredPrimaryKey.join("|")}`);
411
+ }
412
+ for (const fieldName of declaredPrimaryKey) {
413
+ if (!fieldByName.has(fieldName)) {
414
+ error("T00_DATAPACKAGE", "PRIMARY_KEY_FIELD_UNKNOWN", "datapackage", name, `primaryKey references undeclared field: ${fieldName}`);
415
+ }
416
+ }
417
+
418
+ for (const [fieldName, field] of fieldByName) {
419
+ const type = clean(field.type);
420
+ if (!["string", "integer", "number", "boolean", "date"].includes(type)) {
421
+ error("T00_DATAPACKAGE", "FIELD_TYPE_UNSUPPORTED", "datapackage", `${name}:${fieldName}`, `Unsupported or blank field type: ${type || "blank"}`);
422
+ continue;
423
+ }
424
+ const constraints = field.constraints && typeof field.constraints === "object" ? field.constraints : {};
425
+ const seenUnique = new Set();
426
+ for (const row of table?.rows || []) {
427
+ const id = rowId(row, name);
428
+ const raw = row[fieldName];
429
+ if (isBlank(raw)) {
430
+ if (constraints.required === true) {
431
+ error("T00_TYPES", "REQUIRED_CONSTRAINT_VIOLATION", name, id, `${fieldName} is required by datapackage.json`);
432
+ }
433
+ continue;
434
+ }
435
+ const parsed = typedValue(raw, type);
436
+ if (!parsed.valid) {
437
+ error(
438
+ "T00_TYPES", type === "date" ? "DATE_TYPE_INVALID" : "FIELD_TYPE_INVALID", name, id,
439
+ `${fieldName}=${JSON.stringify(clean(raw))} is not a valid ${type}`
440
+ );
441
+ continue;
442
+ }
443
+ if (Array.isArray(constraints.enum) && !constraints.enum.map(String).includes(String(parsed.value))) {
444
+ error("T00_TYPES", "ENUM_CONSTRAINT_VIOLATION", name, id, `${fieldName} is outside the datapackage enum constraint`);
445
+ }
446
+ if (typeof constraints.pattern === "string") {
447
+ try {
448
+ if (!new RegExp(constraints.pattern).test(clean(raw))) {
449
+ error("T00_TYPES", "PATTERN_CONSTRAINT_VIOLATION", name, id, `${fieldName} does not match its datapackage pattern`);
450
+ }
451
+ } catch {
452
+ error("T00_DATAPACKAGE", "PATTERN_CONSTRAINT_INVALID", "datapackage", `${name}:${fieldName}`, "Invalid regular expression in field constraint");
453
+ }
454
+ }
455
+ if (typeof parsed.value === "number") {
456
+ if (Number.isFinite(constraints.minimum) && parsed.value < constraints.minimum) {
457
+ error("T00_TYPES", "MINIMUM_CONSTRAINT_VIOLATION", name, id, `${fieldName} is below ${constraints.minimum}`);
458
+ }
459
+ if (Number.isFinite(constraints.maximum) && parsed.value > constraints.maximum) {
460
+ error("T00_TYPES", "MAXIMUM_CONSTRAINT_VIOLATION", name, id, `${fieldName} exceeds ${constraints.maximum}`);
461
+ }
462
+ }
463
+ if (constraints.unique === true) {
464
+ const key = String(parsed.value);
465
+ if (seenUnique.has(key)) error("T00_TYPES", "UNIQUE_CONSTRAINT_VIOLATION", name, id, `${fieldName} duplicates ${key}`);
466
+ seenUnique.add(key);
467
+ }
468
+ }
469
+ }
470
+ }
471
+
472
+ // Validate every foreign key declared in the datapackage, rather than a hand-picked subset.
473
+ for (const name of EXPECTED_TABLES) {
474
+ const resource = resourceByName.get(name);
475
+ const foreignKeys = resource?.schema?.foreignKeys;
476
+ if (foreignKeys !== undefined && !Array.isArray(foreignKeys)) {
477
+ error("T00_FOREIGN_KEYS", "FOREIGN_KEYS_NOT_ARRAY", "datapackage", name, "schema.foreignKeys must be an array");
478
+ continue;
479
+ }
480
+ for (const [position, foreignKey] of (foreignKeys || []).entries()) {
481
+ const localFields = normalizedFields(foreignKey?.fields);
482
+ const targetName = clean(foreignKey?.reference?.resource);
483
+ const targetFields = normalizedFields(foreignKey?.reference?.fields);
484
+ const declarationId = `${name}:foreignKey:${position}`;
485
+ if (!localFields.length || localFields.length !== targetFields.length || !targetName) {
486
+ error("T00_FOREIGN_KEYS", "FOREIGN_KEY_DECLARATION_INVALID", "datapackage", declarationId, "Foreign key needs equally sized local/reference fields and a target resource");
487
+ continue;
488
+ }
489
+ const localHeaders = new Set(loaded.get(name)?.headers || []);
490
+ const targetTable = loaded.get(targetName);
491
+ const targetHeaders = new Set(targetTable?.headers || []);
492
+ for (const fieldName of localFields) {
493
+ if (!localHeaders.has(fieldName)) error("T00_FOREIGN_KEYS", "FOREIGN_KEY_LOCAL_FIELD_UNKNOWN", "datapackage", declarationId, `Unknown local field: ${fieldName}`);
494
+ }
495
+ if (!resourceByName.has(targetName) || !targetTable?.exists) {
496
+ error("T00_FOREIGN_KEYS", "FOREIGN_KEY_RESOURCE_UNKNOWN", "datapackage", declarationId, `Unknown target resource: ${targetName}`);
497
+ continue;
498
+ }
499
+ for (const fieldName of targetFields) {
500
+ if (!targetHeaders.has(fieldName)) error("T00_FOREIGN_KEYS", "FOREIGN_KEY_TARGET_FIELD_UNKNOWN", "datapackage", declarationId, `Unknown target field: ${targetName}.${fieldName}`);
501
+ }
502
+ if (localFields.some((field) => !localHeaders.has(field)) || targetFields.some((field) => !targetHeaders.has(field))) continue;
503
+ const targetKeys = new Set(targetTable.rows.map((row) => targetFields.map((field) => clean(row[field])).join("\u001f")));
504
+ for (const row of rows(name)) {
505
+ const values = localFields.map((field) => clean(row[field]));
506
+ if (values.every((value) => !value)) continue;
507
+ if (values.some((value) => !value)) {
508
+ error("T00_FOREIGN_KEYS", "FOREIGN_KEY_PARTIAL", name, rowId(row, name), `Partially blank foreign key: ${localFields.join("|")}`);
509
+ } else if (!targetKeys.has(values.join("\u001f"))) {
510
+ error(
511
+ "T00_FOREIGN_KEYS", "FOREIGN_KEY_UNKNOWN", name, rowId(row, name),
512
+ `${localFields.join("|")} references unknown ${targetName}.${targetFields.join("|")}: ${values.join("|")}`
513
+ );
514
+ }
515
+ }
516
+ }
517
+ }
518
+
519
  function uniqueIndex(table, field) {
520
  const index = new Map();
521
  for (const row of rows(table)) {
522
  const id = clean(row[field]);
523
  const ref = rowId(row, table);
524
  if (!id) {
525
+ error("T00_RELATIONAL_INTEGRITY", "PRIMARY_KEY_MISSING", table, ref, `Primary key is blank: ${field}`);
526
  } else if (index.has(id)) {
527
+ error("T00_RELATIONAL_INTEGRITY", "PRIMARY_KEY_DUPLICATE", table, id, `Duplicate ${field}: ${id}`);
528
  } else {
529
  index.set(id, row);
530
  }
 
532
  return index;
533
  }
534
 
535
+ const primaryKeys = { ...EXPECTED_PRIMARY_KEYS };
 
 
 
 
 
 
 
 
536
  const index = Object.fromEntries(Object.entries(primaryKeys).map(([table, field]) => [table, uniqueIndex(table, field)]));
537
 
538
  function requireFk(test, table, row, field, targetTable, targetIndex = index[targetTable], allowBlank = false) {
 
553
  const cutoffCandidates = rows("cases").map((row) => clean(row.as_of_date)).filter(isIsoDate).sort();
554
  const cutoff = cutoffCandidates.at(-1) || null;
555
 
556
+ const DOCUMENTED_ENUMS = Object.freeze({
557
+ "cases.case_status": ["retrospective", "ongoing", "prospective_monitoring"],
558
+ "cases.record_type": ["election_wide_case", "observed_network", "observed_incident", "observed_campaign_set", "preparedness_file"],
559
+ "cases.manipulation_assessment": [
560
+ "manipulation_confirmed", "manipulation_probable", "mixed_documented_manipulation",
561
+ "transparent_contested_use", "manipulation_not_established", "no_manipulation_observed",
562
+ "preparedness_not_incident", "not_an_incident", "not_yet_claim_coded"
563
+ ],
564
+ "cases.ai_role": ["core_generation", "material_amplification", "supporting_tool", "detection_response", "none_established", "mixed"],
565
+ "cases.generative_ai_status": ["confirmed", "probable", "alleged", "not_established", "not_applicable"],
566
+ "cases.occurrence_status": ["confirmed", "partly_confirmed", "alleged", "not_observed"],
567
+ "cases.behavioural_effect_status": ["measured", "indicated", "not_detected", "unknown"],
568
+ "cases.electoral_effect_status": ["measured", "institutionally_asserted", "not_detected", "unknown"],
569
+ "case_catalog.record_layer": ["claim_coded_core", "screening_register", "empirical_model_study"],
570
+ "case_catalog.record_type": [
571
+ "election_wide_case", "observed_network", "observed_incident", "observed_campaign_set",
572
+ "preparedness_file", "candidate_lead", "model_evaluation_or_experiment"
573
+ ],
574
+ "case_catalog.manipulation_assessment": [
575
+ "manipulation_confirmed", "manipulation_probable", "mixed_documented_manipulation",
576
+ "transparent_contested_use", "manipulation_not_established", "no_manipulation_observed",
577
+ "preparedness_not_incident", "not_an_incident", "not_yet_claim_coded"
578
+ ],
579
+ "claims.claim_type": [
580
+ "occurrence", "mechanism", "ai_role", "reach", "attribution", "intent", "behavioural_effect",
581
+ "electoral_effect", "institutional_outcome", "response", "legal_status", "counterevidence", "agency_transfer"
582
+ ],
583
+ "claims.evidence_label": ["established_evidence", "established_as_campaign_report", "strong_inference", "open_question"],
584
+ "claims.claim_status": ["supported", "supported_as_attributed_measurement", "partly_supported", "unresolved"],
585
+ "claims.evidence_strength": ["high", "moderate", "low", "none"],
586
+ "claim_evidence.relation": ["supports", "counterevidence", "qualifies"],
587
+ "claim_evidence.evidence_scope": ["underlying_fact", "assertion_was_made", "institutional_action", "measurement", "researcher_inference"],
588
+ "claim_evidence.directness": ["firsthand_artifact_or_measurement", "official_record_or_allegation", "independent_secondary_reporting"],
589
+ "sources.source_quality": ["A", "B", "C", "D"],
590
+ "sources.source_independence": ["independent_or_official", "independent_secondary", "interested_or_mixed", "unknown"],
591
+ "sources.method_transparency": [
592
+ "sufficiently_described_or_reproducible", "not_applicable_official_record",
593
+ "limited_to_published_account", "opaque"
594
+ ],
595
+ "case_actors.attribution_status": [
596
+ "admitted", "adjudicated", "officially_attributed", "platform_attributed",
597
+ "credibly_reported", "alleged", "unknown", "mixed"
598
+ ],
599
+ "pathways.agency_transfer_status": [
600
+ "full_chain_observed", "partial_chain_observed", "mechanism_observed_effect_unknown",
601
+ "mechanism_inferred", "plausible_hypothesis", "no_transfer_observed", "insufficient_evidence", "not_an_incident"
602
+ ],
603
+ "pathways.assessment_label": [
604
+ "established_evidence", "strong_inference", "plausible_hypothesis",
605
+ "speculative_scenario", "open_question", "not_applicable"
606
+ ],
607
+ "observations.causal_status": [
608
+ "descriptive_only", "association_only", "experimental_causal_estimate",
609
+ "quasi_experimental_causal_estimate", "causal_estimate", "not_applicable"
610
+ ],
611
+ "sampling_frame.search_status": ["complete", "systematic", "substantial", "partial", "ongoing", "not_started"],
612
+ "official_elections.election_status": ["completed", "scheduled", "conditional"],
613
+ "official_results.coverage_status": ["complete_national_contest", "complete", "partial"]
614
+ });
615
+
616
+ for (const [qualifiedField, allowedValues] of Object.entries(DOCUMENTED_ENUMS)) {
617
+ const separator = qualifiedField.indexOf(".");
618
+ const table = qualifiedField.slice(0, separator);
619
+ const field = qualifiedField.slice(separator + 1);
620
+ const allowed = new Set(allowedValues);
621
+ for (const row of rows(table)) {
622
+ const value = clean(row[field]);
623
+ if (!value) {
624
+ error("T13_DOCUMENTED_ENUMS", "DOCUMENTED_ENUM_BLANK", table, rowId(row, table), `${field} must use a documented value`);
625
+ } else if (!allowed.has(value)) {
626
+ error(
627
+ "T13_DOCUMENTED_ENUMS", "DOCUMENTED_ENUM_INVALID", table, rowId(row, table),
628
+ `${field}=${JSON.stringify(value)} is not in the documented vocabulary`
629
+ );
630
+ }
631
+ }
632
+ }
633
+
634
  // T01 — every included case has an explicit, controlled record classification.
635
  const validRecordTypes = new Set([
636
  "observed_incident", "observed_network", "observed_campaign_set", "election_wide_case",
 
786
  error("T03_FOREIGN_KEYS", "CASE_FAMILY_UNKNOWN", "official_elections", rowId(row, "official_elections"), `Unknown case_family_id: ${clean(row.case_family_id)}`);
787
  }
788
  }
789
+ for (const table of ["official_turnout", "official_results", "official_election_metrics"]) {
790
  for (const row of rows(table)) {
791
  requireFk("T03_FOREIGN_KEYS", table, row, "election_id", "official_elections");
792
  requireFk("T03_FOREIGN_KEYS", table, row, "official_source_id", "official_data_sources");
 
1295
  }
1296
  }
1297
 
1298
+ // Normalized v0.3.1 joins must cover legacy pipe lists; this catches silent evidence loss.
1299
  const evidencePairs = new Set(rows("claim_evidence").map((row) => `${clean(row.claim_id)}::${clean(row.source_id)}::${clean(row.relation)}`));
1300
  const evidenceRelationsByClaimSource = new Map();
1301
  for (const row of rows("claim_evidence")) {
 
1340
  }
1341
  }
1342
 
1343
+ // T14 — explicit semantics for the six tables that earlier auditors loaded incompletely or not at all.
1344
+ function uniqueComposite(table, fields, test = "T14_TABLE_SEMANTICS") {
1345
+ const seen = new Set();
1346
+ for (const row of rows(table)) {
1347
+ const values = fields.map((field) => clean(row[field]));
1348
+ if (values.some((value) => !value)) continue;
1349
+ const key = values.join("::");
1350
+ if (seen.has(key)) {
1351
+ error(test, "COMPOSITE_KEY_DUPLICATE", table, rowId(row, table), `Duplicate ${fields.join("+")}: ${key}`);
1352
+ }
1353
+ seen.add(key);
1354
+ }
1355
+ return seen;
1356
+ }
1357
+
1358
+ const documentedClaimTypes = new Set(DOCUMENTED_ENUMS["claims.claim_type"]);
1359
+ const caseSourceRoles = new Set(["primary_record", "corroboration", "counterevidence", "context", "methodology", "ongoing_monitoring"]);
1360
+ const caseSourcePairs = uniqueComposite("case_sources", ["case_id", "source_id"]);
1361
+ for (const row of rows("case_sources")) {
1362
+ const id = rowId(row, "case_sources");
1363
+ requireNonBlank(row, ["case_id", "source_id", "source_role"], "T14_TABLE_SEMANTICS", "case_sources", id);
1364
+ if (!caseSourceRoles.has(clean(row.source_role))) {
1365
+ error("T14_TABLE_SEMANTICS", "CASE_SOURCE_ROLE_INVALID", "case_sources", id, `Unknown source_role: ${clean(row.source_role)}`);
1366
+ }
1367
+ const caseClaimTypes = new Set(rows("claims").filter((claim) => clean(claim.case_id) === clean(row.case_id)).map((claim) => clean(claim.claim_type)));
1368
+ for (const claimType of ids(row.supports_claim_types)) {
1369
+ if (!documentedClaimTypes.has(claimType)) {
1370
+ error("T14_TABLE_SEMANTICS", "CASE_SOURCE_CLAIM_TYPE_INVALID", "case_sources", id, `Unknown supports_claim_types token: ${claimType}`);
1371
+ } else if (!caseClaimTypes.has(claimType)) {
1372
+ 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`);
1373
+ }
1374
+ }
1375
+ }
1376
+ for (const claim of rows("claims")) {
1377
+ requireFk("T03_FOREIGN_KEYS", "claims", claim, "source_ids", "sources", index.sources, true);
1378
+ requireFk("T03_FOREIGN_KEYS", "claims", claim, "counter_source_ids", "sources", index.sources, true);
1379
+ if (
1380
+ !ids(claim.source_ids).length && !ids(claim.counter_source_ids).length &&
1381
+ !(clean(claim.evidence_label) === "open_question" && clean(claim.evidence_strength) === "none" && clean(claim.claim_status) === "unresolved")
1382
+ ) {
1383
+ error("T14_TABLE_SEMANTICS", "CLAIM_WITHOUT_EVIDENCE_LINK", "claims", clean(claim.claim_id), "A claim without source or counter-source links must be an unresolved open question with evidence_strength=none");
1384
+ }
1385
+ for (const sourceId of [...ids(claim.source_ids), ...ids(claim.counter_source_ids)]) {
1386
+ const pair = `${clean(claim.case_id)}::${sourceId}`;
1387
+ if (!caseSourcePairs.has(pair)) {
1388
+ error("T14_TABLE_SEMANTICS", "CLAIM_CASE_SOURCE_JOIN_MISSING", "case_sources", clean(claim.claim_id), `Claim source is absent from case_sources.csv: ${sourceId}`);
1389
+ }
1390
+ }
1391
+ }
1392
+
1393
+ const eventStatuses = new Set(["observed", "contested", "prospective"]);
1394
+ for (const row of rows("events")) {
1395
+ const id = rowId(row, "events");
1396
+ requireNonBlank(row, ["case_id", "event_date", "event_type", "description", "source_ids", "event_status"], "T14_TABLE_SEMANTICS", "events", id);
1397
+ requireFk("T03_FOREIGN_KEYS", "events", row, "claim_ids", "claims", index.claims, true);
1398
+ requireFk("T03_FOREIGN_KEYS", "events", row, "source_ids", "sources");
1399
+ if (!eventStatuses.has(clean(row.event_status))) {
1400
+ error("T14_TABLE_SEMANTICS", "EVENT_STATUS_INVALID", "events", id, `Unknown event_status: ${clean(row.event_status)}`);
1401
+ }
1402
+ for (const claimId of ids(row.claim_ids)) {
1403
+ const claim = index.claims.get(claimId);
1404
+ if (claim && clean(claim.case_id) !== clean(row.case_id)) {
1405
+ error("T14_TABLE_SEMANTICS", "EVENT_CROSS_CASE_CLAIM", "events", id, `claim_ids references another case: ${claimId}`);
1406
+ }
1407
+ }
1408
+ for (const sourceId of ids(row.source_ids)) {
1409
+ if (!caseSourcePairs.has(`${clean(row.case_id)}::${sourceId}`)) {
1410
+ error("T14_TABLE_SEMANTICS", "EVENT_CASE_SOURCE_JOIN_MISSING", "events", id, `Event source is absent from case_sources.csv: ${sourceId}`);
1411
+ }
1412
+ }
1413
+ if (cutoff && isIsoDate(row.event_date) && clean(row.event_date) > cutoff && clean(row.event_status) !== "prospective") {
1414
+ error("T14_TABLE_SEMANTICS", "FUTURE_EVENT_NOT_PROSPECTIVE", "events", id, `Event after cutoff ${cutoff} must be prospective`);
1415
+ }
1416
+ }
1417
+
1418
+ const watchStatuses = new Set(["active", "prospective_monitoring"]);
1419
+ for (const row of rows("watchlist")) {
1420
+ const id = rowId(row, "watchlist");
1421
+ requireNonBlank(
1422
+ row,
1423
+ [
1424
+ "case_id", "jurisdiction", "election_date", "monitoring_window", "signal_category",
1425
+ "observable_indicator", "defensive_data_source", "assessment_rule", "status", "last_checked"
1426
+ ],
1427
+ "T14_TABLE_SEMANTICS", "watchlist", id
1428
+ );
1429
+ if (!watchStatuses.has(clean(row.status))) {
1430
+ error("T14_TABLE_SEMANTICS", "WATCH_STATUS_INVALID", "watchlist", id, `Unknown status: ${clean(row.status)}`);
1431
+ }
1432
+ if (cutoff && isIsoDate(row.last_checked) && clean(row.last_checked) > cutoff) {
1433
+ error("T14_TABLE_SEMANTICS", "WATCH_CHECK_AFTER_CUTOFF", "watchlist", id, `last_checked is after dataset cutoff ${cutoff}`);
1434
+ }
1435
+ const linkedElectionDates = rows("case_elections")
1436
+ .filter((join) => clean(join.case_id) === clean(row.case_id))
1437
+ .map((join) => clean(index.official_elections.get(clean(join.election_id))?.election_date))
1438
+ .filter(Boolean);
1439
+ if (!linkedElectionDates.includes(clean(row.election_date))) {
1440
+ error("T14_TABLE_SEMANTICS", "WATCH_ELECTION_DATE_UNLINKED", "watchlist", id, "election_date does not match an official election linked to the case");
1441
+ }
1442
+ }
1443
+
1444
+ const analyticTargets = Object.freeze({
1445
+ case_actor: ["case_actors", "case_actor_id", "source_claim_ids"],
1446
+ technology_use: ["technology_uses", "tech_use_id", "source_claim_ids"],
1447
+ content_item: ["content_items", "content_item_id", "source_claim_ids"],
1448
+ pathway: ["pathways", "pathway_id", "source_claim_ids"],
1449
+ event: ["events", "event_id", "claim_ids"]
1450
+ });
1451
+ const analyticPairs = uniqueComposite("analytic_record_claims", ["record_type", "record_id", "claim_id"]);
1452
+ for (const row of rows("analytic_record_claims")) {
1453
+ const id = rowId(row, "analytic_record_claims");
1454
+ requireNonBlank(row, ["record_type", "record_id", "case_id", "claim_id", "relation"], "T14_TABLE_SEMANTICS", "analytic_record_claims", id);
1455
+ const target = analyticTargets[clean(row.record_type)];
1456
+ if (!target) {
1457
+ error("T14_TABLE_SEMANTICS", "ANALYTIC_RECORD_TYPE_INVALID", "analytic_record_claims", id, `Unknown record_type: ${clean(row.record_type)}`);
1458
+ continue;
1459
+ }
1460
+ if (clean(row.relation) !== "supports_coding") {
1461
+ error("T14_TABLE_SEMANTICS", "ANALYTIC_RELATION_INVALID", "analytic_record_claims", id, `Unknown relation: ${clean(row.relation)}`);
1462
+ }
1463
+ const targetRow = index[target[0]]?.get(clean(row.record_id));
1464
+ if (!targetRow) {
1465
+ error("T14_TABLE_SEMANTICS", "ANALYTIC_RECORD_UNKNOWN", "analytic_record_claims", id, `${row.record_type} references unknown ${target[0]} row: ${clean(row.record_id)}`);
1466
+ } else if (clean(targetRow.case_id) !== clean(row.case_id)) {
1467
+ error("T14_TABLE_SEMANTICS", "ANALYTIC_RECORD_CASE_MISMATCH", "analytic_record_claims", id, "record_id belongs to another case");
1468
+ }
1469
+ const claim = index.claims.get(clean(row.claim_id));
1470
+ if (claim && clean(claim.case_id) !== clean(row.case_id)) {
1471
+ error("T14_TABLE_SEMANTICS", "ANALYTIC_CLAIM_CASE_MISMATCH", "analytic_record_claims", id, "claim_id belongs to another case");
1472
+ }
1473
+ }
1474
+ for (const [recordType, [table, idField, claimField]] of Object.entries(analyticTargets)) {
1475
+ for (const row of rows(table)) {
1476
+ for (const claimId of ids(row[claimField])) {
1477
+ const key = `${recordType}::${clean(row[idField])}::${claimId}`;
1478
+ if (!analyticPairs.has(key)) {
1479
+ error("T14_TABLE_SEMANTICS", "ANALYTIC_CLAIM_JOIN_MISSING", "analytic_record_claims", clean(row[idField]), `Legacy ${claimField} entry is absent from normalized join: ${claimId}`);
1480
+ }
1481
+ }
1482
+ }
1483
+ }
1484
+
1485
+ const caseElectionRelations = new Set(["primary_or_institutional_context", "future_or_campaign_context"]);
1486
+ uniqueComposite("case_elections", ["case_id", "election_id"]);
1487
+ for (const row of rows("case_elections")) {
1488
+ if (!caseElectionRelations.has(clean(row.relation))) {
1489
+ error("T14_TABLE_SEMANTICS", "CASE_ELECTION_RELATION_INVALID", "case_elections", rowId(row, "case_elections"), `Unknown relation: ${clean(row.relation)}`);
1490
+ }
1491
+ }
1492
+
1493
+ const electionSourcePairs = uniqueComposite("election_sources", ["election_id", "official_source_id"]);
1494
+ const electionSourceRoles = new Set([
1495
+ "supports_election_context_or_status", "election_definition", "turnout", "results", "metrics", "legal_status"
1496
+ ]);
1497
+ for (const row of rows("election_sources")) {
1498
+ const id = rowId(row, "election_sources");
1499
+ requireNonBlank(row, ["election_id", "official_source_id", "source_role"], "T14_TABLE_SEMANTICS", "election_sources", id);
1500
+ if (!electionSourceRoles.has(clean(row.source_role))) {
1501
+ error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_ROLE_INVALID", "election_sources", id, `Unknown source_role: ${clean(row.source_role)}`);
1502
+ }
1503
+ const election = index.official_elections.get(clean(row.election_id));
1504
+ const source = index.official_data_sources.get(clean(row.official_source_id));
1505
+ if (election && source && clean(election.case_family_id) !== clean(source.case_family_id)) {
1506
+ error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_FAMILY_MISMATCH", "election_sources", id, "Election and official source belong to different case families");
1507
+ }
1508
+ if (election && !ids(election.official_source_ids).includes(clean(row.official_source_id))) {
1509
+ error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_NOT_RECIPROCAL", "election_sources", id, "Normalized link is absent from official_elections.official_source_ids");
1510
+ }
1511
+ }
1512
+ for (const election of rows("official_elections")) {
1513
+ for (const sourceId of ids(election.official_source_ids)) {
1514
+ const pair = `${clean(election.election_id)}::${sourceId}`;
1515
+ if (!electionSourcePairs.has(pair)) {
1516
+ error("T14_TABLE_SEMANTICS", "ELECTION_SOURCE_JOIN_MISSING", "election_sources", pair, "Legacy official_source_ids entry is absent from election_sources.csv");
1517
+ }
1518
+ }
1519
+ }
1520
+ for (const table of ["official_turnout", "official_results", "official_election_metrics"]) {
1521
+ for (const row of rows(table)) {
1522
+ const pair = `${clean(row.election_id)}::${clean(row.official_source_id)}`;
1523
+ if (!electionSourcePairs.has(pair)) {
1524
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_ROW_SOURCE_JOIN_MISSING", "election_sources", rowId(row, table), `${table} source/election pair is absent from election_sources.csv`);
1525
+ }
1526
+ }
1527
+ }
1528
+
1529
+ const metricLookup = new Map();
1530
+ for (const row of rows("official_election_metrics")) {
1531
+ const id = rowId(row, "official_election_metrics");
1532
+ requireNonBlank(
1533
+ row,
1534
+ ["election_id", "geographic_unit_type", "metric_code", "value", "source_label_original", "legal_role", "data_status", "official_source_id", "as_of_date"],
1535
+ "T14_TABLE_SEMANTICS", "official_election_metrics", id
1536
+ );
1537
+ const key = [row.election_id, row.geographic_unit_type, row.geographic_unit_code, row.metric_code].map(clean).join("::");
1538
+ if (metricLookup.has(key)) {
1539
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_DUPLICATE", "official_election_metrics", id, `Duplicate election/geography/metric_code: ${key}`);
1540
+ }
1541
+ metricLookup.set(key, row);
1542
+ const value = parseNumber(row.value);
1543
+ if (!Number.isFinite(value) || value < 0) {
1544
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_VALUE_INVALID", "official_election_metrics", id, "value must be a non-negative finite number");
1545
+ }
1546
+ if (/rate|share/i.test(clean(row.metric_code)) && Number.isFinite(value) && value > 1) {
1547
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_RATE_RANGE", "official_election_metrics", id, "Rate/share metric value must be between 0 and 1");
1548
+ }
1549
+ for (const field of ["authority_reported_rate", "computed_rate"]) {
1550
+ if (!isBlank(row[field])) {
1551
+ const rate = parseNumber(row[field]);
1552
+ if (!Number.isFinite(rate) || rate < 0 || rate > 1) {
1553
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_RATE_INVALID", "official_election_metrics", id, `${field} must be between 0 and 1`);
1554
+ }
1555
+ }
1556
+ }
1557
+ if (isBlank(row.numerator_metric) !== isBlank(row.denominator_metric)) {
1558
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_COMPONENT_PARTIAL", "official_election_metrics", id, "numerator_metric and denominator_metric must be present together");
1559
+ }
1560
+ if (!officialDataStatuses.has(clean(row.data_status))) {
1561
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_STATUS_INVALID", "official_election_metrics", id, `Unknown data_status: ${clean(row.data_status)}`);
1562
+ }
1563
+ if (cutoff && isIsoDate(row.as_of_date) && clean(row.as_of_date) > cutoff) {
1564
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_AFTER_CUTOFF", "official_election_metrics", id, `as_of_date is after dataset cutoff ${cutoff}`);
1565
+ }
1566
+ const election = index.official_elections.get(clean(row.election_id));
1567
+ if (cutoff && election && clean(election.election_date) > cutoff && clean(row.data_status) === "final") {
1568
+ error("T14_TABLE_SEMANTICS", "FUTURE_FINAL_OFFICIAL_METRIC", "official_election_metrics", id, "Future election has final metric data");
1569
+ }
1570
+ }
1571
+ function metricReferenceKey(row, metricCode) {
1572
+ const normalizedCode = clean(metricCode) === "A+B" ? "A_plus_B" : clean(metricCode);
1573
+ return [row.election_id, row.geographic_unit_type, row.geographic_unit_code, normalizedCode].map(clean).join("::");
1574
+ }
1575
+ function resolveMetricComponent(row, metricCode) {
1576
+ const longMetric = metricLookup.get(metricReferenceKey(row, metricCode));
1577
+ if (longMetric) return { value: longMetric.value, origin: "official_election_metrics" };
1578
+ const field = clean(metricCode);
1579
+ if (!loaded.get("official_turnout")?.headers.includes(field)) return null;
1580
+ const matches = rows("official_turnout").filter(
1581
+ (turnout) => clean(turnout.election_id) === clean(row.election_id) &&
1582
+ clean(turnout.geographic_unit_type) === clean(row.geographic_unit_type) &&
1583
+ clean(turnout.geographic_unit_code) === clean(row.geographic_unit_code) &&
1584
+ !isBlank(turnout[field])
1585
+ );
1586
+ return matches.length === 1 ? { value: matches[0][field], origin: "official_turnout" } : null;
1587
+ }
1588
+ for (const row of rows("official_election_metrics")) {
1589
+ if (isBlank(row.numerator_metric) && isBlank(row.denominator_metric)) continue;
1590
+ const id = rowId(row, "official_election_metrics");
1591
+ const numerator = resolveMetricComponent(row, row.numerator_metric);
1592
+ const denominator = resolveMetricComponent(row, row.denominator_metric);
1593
+ if (!numerator) {
1594
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_NUMERATOR_UNKNOWN", "official_election_metrics", id, `Unknown numerator metric in the same election/geography: ${clean(row.numerator_metric)}`);
1595
+ }
1596
+ if (!denominator) {
1597
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_DENOMINATOR_UNKNOWN", "official_election_metrics", id, `Unknown denominator metric in the same election/geography: ${clean(row.denominator_metric)}`);
1598
+ }
1599
+ if (!numerator || !denominator) continue;
1600
+ const denominatorValue = parseNumber(denominator.value);
1601
+ const expectedRate = denominatorValue > 0 ? parseNumber(numerator.value) / denominatorValue : Number.NaN;
1602
+ const computedRate = parseNumber(row.computed_rate);
1603
+ if (!Number.isFinite(computedRate)) {
1604
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_COMPUTED_RATE_MISSING", "official_election_metrics", id, "Rate components require computed_rate");
1605
+ } else if (!Number.isFinite(expectedRate) || Math.abs(computedRate - expectedRate) > 1e-12) {
1606
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_RECOMPUTATION_MISMATCH", "official_election_metrics", id, `computed_rate=${computedRate}; numerator/denominator=${expectedRate}`);
1607
+ }
1608
+ const value = parseNumber(row.value);
1609
+ if (Number.isFinite(computedRate) && Number.isFinite(value) && Math.abs(value - computedRate) > 1e-12) {
1610
+ error("T14_TABLE_SEMANTICS", "OFFICIAL_METRIC_VALUE_RATE_MISMATCH", "official_election_metrics", id, "Rate metric value differs from computed_rate");
1611
+ }
1612
+ const authorityRate = parseNumber(row.authority_reported_rate);
1613
+ if (authorityRate !== null && Number.isFinite(authorityRate) && Number.isFinite(computedRate) && Math.abs(authorityRate - computedRate) > 0.0001) {
1614
+ 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");
1615
+ }
1616
+ }
1617
+
1618
+ const catalogById = index.case_catalog;
1619
+ const catalogLayers = Object.freeze({
1620
+ claim_coded_core: ["cases", "case_id"],
1621
+ screening_register: ["candidates", "candidate_id"],
1622
+ empirical_model_study: ["model_evaluations", "evaluation_id"]
1623
+ });
1624
+ for (const row of rows("case_catalog")) {
1625
+ const id = rowId(row, "case_catalog");
1626
+ const target = catalogLayers[clean(row.record_layer)];
1627
+ const targetRow = target ? index[target[0]]?.get(clean(row.catalog_id)) : null;
1628
+ if (target && !targetRow) {
1629
+ error("T14_TABLE_SEMANTICS", "CATALOG_TARGET_UNKNOWN", "case_catalog", id, `${row.record_layer} does not resolve to ${target[0]}.${target[1]}`);
1630
+ }
1631
+ let expectedSourceCount = null;
1632
+ if (clean(row.record_layer) === "claim_coded_core") {
1633
+ expectedSourceCount = rows("case_sources").filter((item) => clean(item.case_id) === clean(row.catalog_id)).length;
1634
+ if (targetRow && clean(row.record_type) !== clean(targetRow.record_type)) {
1635
+ error("T14_TABLE_SEMANTICS", "CATALOG_RECORD_TYPE_MISMATCH", "case_catalog", id, "record_type differs from cases.csv");
1636
+ }
1637
+ if (targetRow && clean(row.manipulation_assessment) !== clean(targetRow.manipulation_assessment)) {
1638
+ error("T14_TABLE_SEMANTICS", "CATALOG_MANIPULATION_MISMATCH", "case_catalog", id, "manipulation_assessment differs from cases.csv");
1639
+ }
1640
+ } else if (clean(row.record_layer) === "screening_register") {
1641
+ expectedSourceCount = ids(targetRow?.source_urls).length;
1642
+ if (clean(row.record_type) !== "candidate_lead") {
1643
+ error("T14_TABLE_SEMANTICS", "CATALOG_CANDIDATE_TYPE_INVALID", "case_catalog", id, "screening_register must use record_type=candidate_lead");
1644
+ }
1645
+ } else if (clean(row.record_layer) === "empirical_model_study") {
1646
+ expectedSourceCount = ids(targetRow?.source_id).length;
1647
+ if (clean(row.record_type) !== "model_evaluation_or_experiment") {
1648
+ error("T14_TABLE_SEMANTICS", "CATALOG_MODEL_TYPE_INVALID", "case_catalog", id, "empirical_model_study must use record_type=model_evaluation_or_experiment");
1649
+ }
1650
+ }
1651
+ if (expectedSourceCount !== null && parseNumber(row.source_count_or_links) !== expectedSourceCount) {
1652
+ error("T14_TABLE_SEMANTICS", "CATALOG_SOURCE_COUNT_MISMATCH", "case_catalog", id, `source_count_or_links differs from normalized/source links (${expectedSourceCount})`);
1653
+ }
1654
+ }
1655
+ for (const [layer, [table, idField]] of Object.entries(catalogLayers)) {
1656
+ for (const row of rows(table)) {
1657
+ const id = clean(row[idField]);
1658
+ const catalog = catalogById.get(id);
1659
+ if (!catalog) {
1660
+ error("T14_TABLE_SEMANTICS", "SOURCE_RECORD_MISSING_FROM_CATALOG", "case_catalog", id, `${table}.${idField} is absent from case_catalog.csv`);
1661
+ } else if (clean(catalog.record_layer) !== layer) {
1662
+ error("T14_TABLE_SEMANTICS", "CATALOG_LAYER_MISMATCH", "case_catalog", id, `Expected record_layer=${layer}; found ${clean(catalog.record_layer)}`);
1663
+ }
1664
+ }
1665
+ }
1666
+
1667
  function stableIssueOrder(a, b) {
1668
  return (
1669
  a.test.localeCompare(b.test) ||
 
1677
  advisory.sort(stableIssueOrder);
1678
 
1679
  const tableCounts = Object.fromEntries([...loaded.entries()].map(([name, table]) => [name, table.rows.length]));
1680
+ const integrityErrors = blocking.filter((item) => item.layer === "integrity");
1681
+ const integrityWarnings = advisory.filter((item) => item.layer === "integrity");
1682
+ const semanticErrors = blocking.filter((item) => item.layer === "semantic");
1683
+ const semanticWarnings = advisory.filter((item) => item.layer === "semantic");
1684
+ const semanticChecksByTable = Object.freeze({
1685
+ cases: ["classification", "incident denominator", "case-family and election links", "pathway/actor/technology coverage"],
1686
+ claims: ["documented enums", "case/source links", "normalized evidence and case-source reciprocity"],
1687
+ sources: ["documented enums", "claim/event/case-source referential use"],
1688
+ events: ["status/date chronology", "case-scoped claim links", "case-source reciprocity", "analytic join reciprocity"],
1689
+ case_sources: ["unique case/source pair", "role and claim-type vocabulary", "claim/event reciprocity"],
1690
+ watchlist: ["required monitoring fields", "status/cutoff chronology", "linked election date"],
1691
+ candidates: ["sampling counts", "catalog membership and layer"],
1692
+ official_elections: ["status chronology", "case/source links", "normalized join reciprocity"],
1693
+ official_turnout: ["numeric ranges", "turnout and ballot arithmetic", "source/election chronology"],
1694
+ official_results: ["coverage/status", "share/rank arithmetic", "turnout reconciliation"],
1695
+ official_data_sources: ["family link", "status and retrieval chronology", "election-source use"],
1696
+ official_election_metrics: ["numeric/rate ranges", "rate-component resolution", "rate recomputation", "source/election chronology"],
1697
+ research_view: ["unique pathway projection", "case/pathway field parity", "complete pathway coverage"],
1698
+ case_catalog: ["documented enums", "layer/record resolution", "incident denominator", "source-link counts"],
1699
+ case_actors: ["documented attribution enum", "case-scoped claim links", "case and analytic coverage"],
1700
+ technology_uses: ["provenance/version limitations", "case-scoped claim links", "AI-case and analytic coverage"],
1701
+ content_items: ["case-scoped claim links", "analytic join reciprocity"],
1702
+ pathways: ["documented transfer/assessment enums", "required proposition fields", "case/view/claim coverage"],
1703
+ observations: ["numeric intervals and denominators", "causal-status requirements", "case/pathway/claim/source scope"],
1704
+ model_evaluations: ["sample/design fields", "source link", "catalog membership and layer"],
1705
+ claim_evidence: ["documented enums", "claim/source links", "legacy evidence reciprocity"],
1706
+ analytic_record_claims: ["record-type resolution", "case-scoped claims", "legacy analytic-link reciprocity"],
1707
+ case_elections: ["unique pair and relation", "case/election links", "legacy link reciprocity"],
1708
+ election_sources: ["unique pair and role", "family consistency", "legacy and official-row reciprocity"],
1709
+ sampling_frame: ["documented status", "counts/flags/dates", "region coverage"],
1710
+ coverage_summary: ["unique region", "case/candidate/model counts"]
1711
+ });
1712
  const report = {
1713
+ auditor: "agency-transfer-election-cases-v0.3.1/audit-v03",
1714
  cutoff,
1715
  status: blocking.length ? "fail" : "pass",
1716
+ integrity: {
1717
+ status: integrityErrors.length ? "fail" : "pass",
1718
+ expected_table_count: EXPECTED_TABLES.length,
1719
+ loaded_table_count: EXPECTED_TABLES.filter((name) => loaded.get(name)?.exists).length,
1720
+ datapackage_resource_count: resourceByName.size,
1721
+ declared_field_count: [...resourceByName.values()].reduce((sum, resource) => sum + (resource.schema?.fields?.length || 0), 0),
1722
+ declared_foreign_key_count: [...resourceByName.values()].reduce((sum, resource) => sum + (resource.schema?.foreignKeys?.length || 0), 0),
1723
+ error_count: integrityErrors.length,
1724
+ warning_count: integrityWarnings.length
1725
+ },
1726
+ semantic_audit: {
1727
+ status: semanticErrors.length ? "fail" : "pass",
1728
+ audited_table_count: Object.keys(semanticChecksByTable).length,
1729
+ audited_tables: Object.keys(semanticChecksByTable),
1730
+ checks_by_table: semanticChecksByTable,
1731
+ error_count: semanticErrors.length,
1732
+ warning_count: semanticWarnings.length
1733
+ },
1734
  summary: {
1735
  error_count: blocking.length,
1736
  warning_count: advisory.length,
scripts/build-data.mjs CHANGED
@@ -11,6 +11,7 @@ const europeCandidatesPath = path.join(root, "research", "europe_candidates.json
11
  const officialElectoralDataPath = path.join(root, "research", "official_electoral_data.json");
12
  const extensionsPath = path.join(root, "research", "v0.3_extensions.json");
13
  const outDir = path.join(root, "data");
 
14
  const seed = JSON.parse(fs.readFileSync(seedPath, "utf8"));
15
  const officialElectoralData = JSON.parse(fs.readFileSync(officialElectoralDataPath, "utf8"));
16
  const extensions = JSON.parse(fs.readFileSync(extensionsPath, "utf8"));
@@ -221,17 +222,18 @@ const additionalOfficialSources = [
221
  ["off-md-2025-cc-h12", "moldova-elections-2024-2025", "Moldova", "Constitutional Court of Moldova", "Decision 12 of 16 October 2025 confirming legality and validating 101 mandates", "https://constcourt.md/ccdocview.php?docid=882&l=ro&tip=hotariri", "legal_validation_and_mandates", "final", "HTML legal record", "national", "landing page", "finalized election record", "official legal record", "2026-08-12", "Confirms the election and validates 101 mandates."],
222
  ["off-br-2026-contests", "brazil-general-2026", "Brazil", "Superior Electoral Court", "Resolution 23.751/2026 on offices contested and voting rules", "https://www.tse.jus.br/legislacao/compilada/res/2026/resolucao-no-23-751-de-26-de-fevereiro-de-2026", "contest_definition", "current", "HTML legal record", "national and state", "landing page", "election cycle", "official legal record", "2026-08-12", "Second round applies only to president and governors when required."],
223
  ["off-us-congress-election-law", "us-midterms-2026", "United States", "United States Congress", "2 U.S.C. sections 1 and 7: congressional election timing", "https://uscode.house.gov/view.xhtml?edition=prelim&num=0&req=granuleid%3AUSC-prelim-title2-section7", "contest_timing_context", "current", "HTML legal code", "federal and state/district", "landing page", "statutory", "public law", "2026-08-12", "The national date bundles separate House, Senate and special contests administered and certified by states."],
224
- ["off-nh-2024-primary-law", "new-hampshire-biden-robocall-2024", "New Hampshire", "New Hampshire General Court", "RSA 659:73 and RSA 654:34 primary counting and undeclared-voter context", "https://gc.nh.gov/rsa/html/LXIII/659/659-73.htm", "denominator_and_counting_context", "current", "HTML legal code", "state", "landing page", "statutory", "public law", "2026-08-12", "Explains why the all-party checklist is not a Democratic-primary turnout denominator."]
 
225
  ].map((values) => {
226
  const oldColumns = ["official_source_id", "case_family_id", "jurisdiction", "electoral_institution", "title", "url", "dataset_role", "data_status", "format", "geographic_granularity", "access_method", "update_frequency", "license_or_terms", "retrieved_at", "notes"];
227
  const row = Object.fromEntries(oldColumns.map((column, index) => [column, values[index] ?? ""]));
228
- return { ...row, landing_url: row.url, download_url: /direct download/i.test(row.access_method) ? row.url : "", published_or_updated_at: "", content_sha256: "", content_bytes: "", source_schema_version: "", snapshot_cutoff: "2026-08-12" };
229
  });
230
  seed.official_data_sources.push(...additionalOfficialSources);
231
  seed.official_data_sources = seed.official_data_sources.map((row) => ({
232
  ...row,
233
  landing_url: row.landing_url || row.url,
234
- download_url: row.download_url || (/direct download/i.test(row.access_method || "") ? row.url : ""),
235
  published_or_updated_at: row.published_or_updated_at || "",
236
  content_sha256: row.content_sha256 || "",
237
  content_bytes: row.content_bytes || "",
@@ -293,6 +295,10 @@ for (const election of seed.official_elections) {
293
  election.official_source_ids = appendPipe(election.official_source_ids, "off-us-congress-election-law");
294
  election.notes = "Not one national contest: 435 House districts, Senate Class II and special/delegate contests are administered and certified by states; some jurisdictions can hold later runoffs. FEC files are calendar/finance snapshots, not ballot-access or result certification.";
295
  }
 
 
 
 
296
  }
297
 
298
  const mdTurnout = {
@@ -362,6 +368,11 @@ for (const row of seed.official_results) {
362
  if (row.election_id.startsWith("elec-md-")) row.result_status = "CEC_final_and_Constitutional_Court_confirmed";
363
  if (row.result_id === "result-md24r1-maia-sandu") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PAS"; }
364
  if (row.result_id === "result-md24r1-alexandr-stoianoglo") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PSRM"; }
 
 
 
 
 
365
  }
366
 
367
  const extraResults = [];
@@ -408,6 +419,25 @@ seed.claims = seed.claims.map((claim) => {
408
  return { ...claim, coder_confidence_in_label: claim.confidence, claim_status: claimStatus, evidence_strength: evidenceStrength };
409
  });
410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  seed.sources = seed.sources.map((source) => {
412
  const interestedTypes = /campaign|platform|provider|party/.test(source.source_type);
413
  const reproducibleTypes = /model_evaluation|peer_reviewed|dataset|methodology/.test(source.source_type);
@@ -426,6 +456,11 @@ seed.technology_uses = rowsFromArrays(extensions.technology_uses, schemas.techno
426
  seed.content_items = rowsFromArrays(extensions.content_items, schemas.content_items);
427
  seed.pathways = rowsFromArrays(extensions.agency_transfer_assessments, schemas.pathways);
428
  seed.model_evaluations = rowsFromArrays(extensions.model_evaluations, schemas.model_evaluations);
 
 
 
 
 
429
 
430
  const pathwayByCase = new Map(seed.pathways.map((row) => [row.case_id, row.pathway_id]));
431
  const caseById = new Map(seed.cases.map((row) => [row.case_id, row]));
@@ -439,13 +474,15 @@ seed.observations = extensions.quantitative_observations.map((values) => {
439
 
440
  const sourceById = new Map(seed.sources.map((row) => [row.source_id, row]));
441
  seed.claim_evidence = [];
 
442
  for (const claim of seed.claims) {
443
  const evidenceScope = claim.claim_type === "reach" ? "measurement" : claim.claim_type === "response" ? "institutional_action" : claim.claim_type === "agency_transfer" ? "researcher_inference" : "underlying_fact";
444
  for (const [relation, ids] of [["supports", claim.source_ids], ["counterevidence", claim.counter_source_ids]]) {
445
  for (const sourceId of String(ids || "").split("|").filter(Boolean)) {
446
  const source = sourceById.get(sourceId);
447
  const directness = source?.primary_secondary === "primary" ? (/official|legal|regulatory|court/.test(source.source_type) ? "official_record_or_allegation" : "firsthand_artifact_or_measurement") : "independent_secondary_reporting";
448
- seed.claim_evidence.push({ claim_evidence_id: `ce-${claim.claim_id}-${sourceId}-${relation}`, claim_id: claim.claim_id, source_id: sourceId, relation, evidence_scope: evidenceScope, directness, locator: "", extracted_at: claim.verified_at });
 
449
  }
450
  }
451
  }
@@ -495,8 +532,8 @@ const sourceCountByCase = new Map();
495
  for (const link of seed.case_sources) sourceCountByCase.set(link.case_id, (sourceCountByCase.get(link.case_id) || 0) + 1);
496
  seed.case_catalog = [
497
  ...seed.cases.map((row) => ({ catalog_id: row.case_id, record_layer: "claim_coded_core", record_type: row.record_type, title: row.title, country: row.country, region: row.region, election_name: row.election_name, election_date: row.election_date_start, case_status: row.case_status, manipulation_assessment: row.manipulation_assessment, ai_role: row.ai_role, generative_ai_status: row.generative_ai_status, evidence_maturity: evidenceForCase(row.case_id), incident_count_eligible: row.record_type === "preparedness_file" ? "false" : "true", research_status: "included_claim_coded", source_count_or_links: sourceCountByCase.get(row.case_id) || 0, main_caveat: row.counterevidence, last_checked: row.last_verified })),
498
- ...seed.candidates.map((row) => ({ catalog_id: row.candidate_id, record_layer: "screening_register", record_type: "candidate_lead", title: row.title, country: row.country, region: row.region, election_name: row.election_name, election_date: row.election_date, case_status: row.research_status, manipulation_assessment: "not_yet_claim_coded", ai_role: row.ai_role, generative_ai_status: row.generative_ai_status, evidence_maturity: row.occurrence_status, incident_count_eligible: "false", research_status: row.research_status, source_count_or_links: String(row.source_urls || "").split("|").filter(Boolean).length, main_caveat: row.main_caveat, last_checked: row.last_checked })),
499
- ...seed.model_evaluations.map((row) => ({ catalog_id: row.evaluation_id, record_layer: "empirical_model_study", record_type: "model_evaluation_or_experiment", title: row.title, country: row.country, region: regionForCountry(row.country), election_name: row.election_or_context, election_date: row.evaluation_window, case_status: "completed_study", manipulation_assessment: "not_an_incident", ai_role: "tested_system_capability", generative_ai_status: "confirmed_tested_system", evidence_maturity: "study_design_specific", incident_count_eligible: "false", research_status: "included_empirical_study", source_count_or_links: 1, main_caveat: row.causal_scope, last_checked: "2026-08-12" }))
500
  ];
501
 
502
  const frameNotes = {
@@ -697,7 +734,7 @@ const dataPackage = {
697
  profile: "tabular-data-package",
698
  name: "agency-transfer-election-cases",
699
  title: "AI, Elections and Agency Transfer Evidence Index",
700
- version: "0.3.0",
701
  description: "Purposive, claim-level research corpus with normalized pathways, observations, empirical model studies, screening records and official electoral context. Not a global prevalence sample.",
702
  licenses: [{ name: "CC-BY-4.0", path: "https://creativecommons.org/licenses/by/4.0/" }],
703
  resources: Object.entries(schemas).map(([table, columns]) => ({
@@ -713,6 +750,15 @@ const dataPackage = {
713
  }
714
  }))
715
  };
 
 
 
 
 
 
 
 
 
716
  const dataPackageText = JSON.stringify(dataPackage, null, 2) + "\n";
717
  fs.writeFileSync(path.join(outDir, "datapackage.json"), dataPackageText);
718
  fileHashes["datapackage.json"] = sha256(dataPackageText);
 
11
  const officialElectoralDataPath = path.join(root, "research", "official_electoral_data.json");
12
  const extensionsPath = path.join(root, "research", "v0.3_extensions.json");
13
  const outDir = path.join(root, "data");
14
+ const releaseVersion = "0.3.1";
15
  const seed = JSON.parse(fs.readFileSync(seedPath, "utf8"));
16
  const officialElectoralData = JSON.parse(fs.readFileSync(officialElectoralDataPath, "utf8"));
17
  const extensions = JSON.parse(fs.readFileSync(extensionsPath, "utf8"));
 
222
  ["off-md-2025-cc-h12", "moldova-elections-2024-2025", "Moldova", "Constitutional Court of Moldova", "Decision 12 of 16 October 2025 confirming legality and validating 101 mandates", "https://constcourt.md/ccdocview.php?docid=882&l=ro&tip=hotariri", "legal_validation_and_mandates", "final", "HTML legal record", "national", "landing page", "finalized election record", "official legal record", "2026-08-12", "Confirms the election and validates 101 mandates."],
223
  ["off-br-2026-contests", "brazil-general-2026", "Brazil", "Superior Electoral Court", "Resolution 23.751/2026 on offices contested and voting rules", "https://www.tse.jus.br/legislacao/compilada/res/2026/resolucao-no-23-751-de-26-de-fevereiro-de-2026", "contest_definition", "current", "HTML legal record", "national and state", "landing page", "election cycle", "official legal record", "2026-08-12", "Second round applies only to president and governors when required."],
224
  ["off-us-congress-election-law", "us-midterms-2026", "United States", "United States Congress", "2 U.S.C. sections 1 and 7: congressional election timing", "https://uscode.house.gov/view.xhtml?edition=prelim&num=0&req=granuleid%3AUSC-prelim-title2-section7", "contest_timing_context", "current", "HTML legal code", "federal and state/district", "landing page", "statutory", "public law", "2026-08-12", "The national date bundles separate House, Senate and special contests administered and certified by states."],
225
+ ["off-nh-2024-primary-law", "new-hampshire-biden-robocall-2024", "New Hampshire", "New Hampshire General Court", "RSA 659:73 and RSA 654:34 primary counting and undeclared-voter context", "https://gc.nh.gov/rsa/html/LXIII/659/659-73.htm", "denominator_and_counting_context", "current", "HTML legal code", "state", "landing page", "statutory", "public law", "2026-08-12", "Explains why the all-party checklist is not a Democratic-primary turnout denominator."],
226
+ ["off-nh-2024-dnc-status", "new-hampshire-biden-robocall-2024", "New Hampshire", "New Hampshire Department of Justice", "Unlawful Voter Suppression Cease and Desist Order", "https://www.doj.nh.gov/news-and-media/unlawful-voter-suppression-cease-and-desist-order", "institutional_primary_and_delegate_status", "final", "HTML official statement", "state", "landing page", "finalized election record", "official state statement", "2026-08-12", "Documents the institutional dispute and that the DNC did not award delegates from the 23 January state-run result; do not describe the election as legally nonexistent or infer a delegate allocation from its vote tally."]
227
  ].map((values) => {
228
  const oldColumns = ["official_source_id", "case_family_id", "jurisdiction", "electoral_institution", "title", "url", "dataset_role", "data_status", "format", "geographic_granularity", "access_method", "update_frequency", "license_or_terms", "retrieved_at", "notes"];
229
  const row = Object.fromEntries(oldColumns.map((column, index) => [column, values[index] ?? ""]));
230
+ return { ...row, landing_url: row.url, download_url: /direct.*download/i.test(row.access_method) ? row.url : "", published_or_updated_at: "", content_sha256: "", content_bytes: "", source_schema_version: "", snapshot_cutoff: "2026-08-12" };
231
  });
232
  seed.official_data_sources.push(...additionalOfficialSources);
233
  seed.official_data_sources = seed.official_data_sources.map((row) => ({
234
  ...row,
235
  landing_url: row.landing_url || row.url,
236
+ download_url: row.download_url || (/direct.*download/i.test(row.access_method || "") ? row.url : ""),
237
  published_or_updated_at: row.published_or_updated_at || "",
238
  content_sha256: row.content_sha256 || "",
239
  content_bytes: row.content_bytes || "",
 
295
  election.official_source_ids = appendPipe(election.official_source_ids, "off-us-congress-election-law");
296
  election.notes = "Not one national contest: 435 House districts, Senate Class II and special/delegate contests are administered and certified by states; some jurisdictions can hold later runoffs. FEC files are calendar/finance snapshots, not ballot-access or result certification.";
297
  }
298
+ if (election.election_id === "elec-us-nh-dem-primary-2024") {
299
+ election.official_source_ids = appendPipe(appendPipe(election.official_source_ids, "off-nh-2024-primary-law"), "off-nh-2024-dnc-status");
300
+ election.notes = "The 23 January event was a state-run primary with a final state tally, but the DNC did not award delegates from that result. The tally therefore has delegate_effect=none_from_Jan23_results. The all-party checklist is not a valid Democratic-primary turnout denominator because undeclared voters may choose a party ballot and same-day registration or party changes occur.";
301
+ }
302
  }
303
 
304
  const mdTurnout = {
 
368
  if (row.election_id.startsWith("elec-md-")) row.result_status = "CEC_final_and_Constitutional_Court_confirmed";
369
  if (row.result_id === "result-md24r1-maia-sandu") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PAS"; }
370
  if (row.result_id === "result-md24r1-alexandr-stoianoglo") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PSRM"; }
371
+ if (row.result_id === "result-md24r2-maia-sandu") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PAS"; }
372
+ if (row.result_id === "result-md24r2-alexandr-stoianoglo") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PSRM"; }
373
+ if (row.coverage_status === "complete_national_contest" && /Top-(?:three|five) extract|Top-five vote extract/i.test(row.notes || "")) {
374
+ row.notes = "Complete national contest field in this release.";
375
+ }
376
  }
377
 
378
  const extraResults = [];
 
419
  return { ...claim, coder_confidence_in_label: claim.confidence, claim_status: claimStatus, evidence_strength: evidenceStrength };
420
  });
421
 
422
+ const claimTypesByCase = new Map();
423
+ for (const claim of seed.claims) {
424
+ if (!claimTypesByCase.has(claim.case_id)) claimTypesByCase.set(claim.case_id, new Set());
425
+ claimTypesByCase.get(claim.case_id).add(claim.claim_type);
426
+ }
427
+ seed.case_sources = seed.case_sources.map((link) => {
428
+ const availableTypes = claimTypesByCase.get(link.case_id) || new Set();
429
+ const declaredTypes = String(link.supports_claim_types || "").split("|").filter(Boolean);
430
+ const supportedTypes = declaredTypes.filter((type) => availableTypes.has(type));
431
+ const removedTypes = declaredTypes.filter((type) => !availableTypes.has(type));
432
+ return {
433
+ ...link,
434
+ supports_claim_types: supportedTypes.join("|"),
435
+ notes: removedTypes.length
436
+ ? `${link.notes ? `${link.notes} ` : ""}Contextual source roles not represented by an atomic claim in this release were omitted from supports_claim_types: ${removedTypes.join("|")}.`
437
+ : link.notes
438
+ };
439
+ });
440
+
441
  seed.sources = seed.sources.map((source) => {
442
  const interestedTypes = /campaign|platform|provider|party/.test(source.source_type);
443
  const reproducibleTypes = /model_evaluation|peer_reviewed|dataset|methodology/.test(source.source_type);
 
456
  seed.content_items = rowsFromArrays(extensions.content_items, schemas.content_items);
457
  seed.pathways = rowsFromArrays(extensions.agency_transfer_assessments, schemas.pathways);
458
  seed.model_evaluations = rowsFromArrays(extensions.model_evaluations, schemas.model_evaluations);
459
+ for (const actor of seed.case_actors) {
460
+ if (actor.case_actor_id === "act-usca11-chan" && actor.attribution_status === "established") {
461
+ actor.attribution_status = "credibly_reported";
462
+ }
463
+ }
464
 
465
  const pathwayByCase = new Map(seed.pathways.map((row) => [row.case_id, row.pathway_id]));
466
  const caseById = new Map(seed.cases.map((row) => [row.case_id, row]));
 
474
 
475
  const sourceById = new Map(seed.sources.map((row) => [row.source_id, row]));
476
  seed.claim_evidence = [];
477
+ const claimEvidenceLocators = extensions.claim_evidence_locators || {};
478
  for (const claim of seed.claims) {
479
  const evidenceScope = claim.claim_type === "reach" ? "measurement" : claim.claim_type === "response" ? "institutional_action" : claim.claim_type === "agency_transfer" ? "researcher_inference" : "underlying_fact";
480
  for (const [relation, ids] of [["supports", claim.source_ids], ["counterevidence", claim.counter_source_ids]]) {
481
  for (const sourceId of String(ids || "").split("|").filter(Boolean)) {
482
  const source = sourceById.get(sourceId);
483
  const directness = source?.primary_secondary === "primary" ? (/official|legal|regulatory|court/.test(source.source_type) ? "official_record_or_allegation" : "firsthand_artifact_or_measurement") : "independent_secondary_reporting";
484
+ const locatorKey = `${claim.claim_id}|${sourceId}|${relation}`;
485
+ seed.claim_evidence.push({ claim_evidence_id: `ce-${claim.claim_id}-${sourceId}-${relation}`, claim_id: claim.claim_id, source_id: sourceId, relation, evidence_scope: evidenceScope, directness, locator: claimEvidenceLocators[locatorKey] || "", extracted_at: claim.verified_at });
486
  }
487
  }
488
  }
 
532
  for (const link of seed.case_sources) sourceCountByCase.set(link.case_id, (sourceCountByCase.get(link.case_id) || 0) + 1);
533
  seed.case_catalog = [
534
  ...seed.cases.map((row) => ({ catalog_id: row.case_id, record_layer: "claim_coded_core", record_type: row.record_type, title: row.title, country: row.country, region: row.region, election_name: row.election_name, election_date: row.election_date_start, case_status: row.case_status, manipulation_assessment: row.manipulation_assessment, ai_role: row.ai_role, generative_ai_status: row.generative_ai_status, evidence_maturity: evidenceForCase(row.case_id), incident_count_eligible: row.record_type === "preparedness_file" ? "false" : "true", research_status: "included_claim_coded", source_count_or_links: sourceCountByCase.get(row.case_id) || 0, main_caveat: row.counterevidence, last_checked: row.last_verified })),
535
+ ...seed.candidates.map((row) => ({ catalog_id: row.candidate_id, record_layer: "screening_register", record_type: "candidate_lead", title: row.title, country: row.country, region: row.region, election_name: row.election_name, election_date: row.election_date, case_status: "screening", manipulation_assessment: "not_yet_claim_coded", ai_role: row.ai_role, generative_ai_status: row.generative_ai_status, evidence_maturity: row.occurrence_status, incident_count_eligible: "false", research_status: row.research_status, source_count_or_links: String(row.source_urls || "").split("|").filter(Boolean).length, main_caveat: row.main_caveat, last_checked: row.last_checked })),
536
+ ...seed.model_evaluations.map((row) => ({ catalog_id: row.evaluation_id, record_layer: "empirical_model_study", record_type: "model_evaluation_or_experiment", title: row.title, country: row.country, region: regionForCountry(row.country), election_name: row.election_or_context, election_date: "", case_status: "completed_study", manipulation_assessment: "not_an_incident", ai_role: "tested_system_capability", generative_ai_status: "confirmed_tested_system", evidence_maturity: "study_design_specific", incident_count_eligible: "false", research_status: "included_empirical_study", source_count_or_links: 1, main_caveat: `Evaluation window: ${row.evaluation_window}. ${row.causal_scope}`, last_checked: "2026-08-12" }))
537
  ];
538
 
539
  const frameNotes = {
 
734
  profile: "tabular-data-package",
735
  name: "agency-transfer-election-cases",
736
  title: "AI, Elections and Agency Transfer Evidence Index",
737
+ version: releaseVersion,
738
  description: "Purposive, claim-level research corpus with normalized pathways, observations, empirical model studies, screening records and official electoral context. Not a global prevalence sample.",
739
  licenses: [{ name: "CC-BY-4.0", path: "https://creativecommons.org/licenses/by/4.0/" }],
740
  resources: Object.entries(schemas).map(([table, columns]) => ({
 
750
  }
751
  }))
752
  };
753
+ const catalogResource = dataPackage.resources.find((resource) => resource.name === "case_catalog");
754
+ const catalogDateField = catalogResource?.schema.fields.find((field) => field.name === "election_date");
755
+ if (catalogDateField) {
756
+ catalogDateField.description = "ISO election date for core cases and screening leads; blank for empirical studies whose evaluation window is stored in model_evaluations.";
757
+ }
758
+ const observationResource = dataPackage.resources.find((resource) => resource.name === "observations");
759
+ if (observationResource) {
760
+ observationResource.description = "Selected decision-relevant quantitative observations normalized from claims; absence of a row does not imply absence of all numeric text in the evidence corpus.";
761
+ }
762
  const dataPackageText = JSON.stringify(dataPackage, null, 2) + "\n";
763
  fs.writeFileSync(path.join(outDir, "datapackage.json"), dataPackageText);
764
  fileHashes["datapackage.json"] = sha256(dataPackageText);
scripts/build-parquet.mjs CHANGED
@@ -5,12 +5,20 @@ import { createRequire } from "node:module";
5
  import { fileURLToPath } from "node:url";
6
 
7
  const require = createRequire(import.meta.url);
8
- const parquet = require("parquetjs-lite");
 
 
 
 
 
9
  const here = path.dirname(fileURLToPath(import.meta.url));
10
  const root = path.resolve(here, "..");
11
  const dataDir = path.join(root, "data");
12
  const outDir = path.join(root, "parquet");
13
  await fs.mkdir(outDir, { recursive: true });
 
 
 
14
 
15
  function parseCsv(text) {
16
  const records = [];
 
5
  import { fileURLToPath } from "node:url";
6
 
7
  const require = createRequire(import.meta.url);
8
+ let parquet;
9
+ try {
10
+ parquet = require("parquetjs-lite");
11
+ } catch (error) {
12
+ throw new Error("Missing pinned dependency parquetjs-lite. Run npm install from the package root before rebuilding Parquet files.", { cause: error });
13
+ }
14
  const here = path.dirname(fileURLToPath(import.meta.url));
15
  const root = path.resolve(here, "..");
16
  const dataDir = path.join(root, "data");
17
  const outDir = path.join(root, "parquet");
18
  await fs.mkdir(outDir, { recursive: true });
19
+ for (const entry of await fs.readdir(outDir)) {
20
+ if (entry.endsWith(".parquet") || entry === "manifest.json") await fs.rm(path.join(outDir, entry));
21
+ }
22
 
23
  function parseCsv(text) {
24
  const records = [];
scripts/build-workbook-v03.mjs CHANGED
@@ -6,7 +6,7 @@ import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
6
  const here = path.dirname(fileURLToPath(import.meta.url));
7
  const root = process.env.DATASET_ROOT ? path.resolve(process.env.DATASET_ROOT) : path.resolve(here, "..");
8
  const dataDir = path.join(root, "data");
9
- const outputDir = process.argv[2] || path.join(root, "outputs", "v0.3.0-workbook");
10
  const previewDir = path.join(outputDir, "previews");
11
  await fs.mkdir(previewDir, { recursive: true });
12
 
@@ -146,19 +146,20 @@ function addSectionTitle(sheet, range, text, fill = colors.charcoal) {
146
  const overview = wb.worksheets.add("00 Overview");
147
  overview.showGridLines = false;
148
  overview.getRange("A1:H2").merge();
149
- overview.getRange("A1:H2").values = [["AI, Elections and Agency Transfer — Evidence Index v0.3.0"]];
150
  overview.getRange("A1:H2").format = { fill: colors.ink, font: { bold: true, color: colors.white, size: 18 }, verticalAlignment: "center" };
151
  overview.getRange("A3:H3").merge();
152
  overview.getRange("A3:H3").values = [["Research cutoff 2026-08-12 · Purposive evidence corpus, not a global prevalence sample · Start with 01 Research View"]];
153
  overview.getRange("A3:H3").format = { fill: colors.paleBlue, font: { italic: true, color: colors.blue, size: 10 }, verticalAlignment: "center" };
154
 
155
- overview.getRange("A5:B17").values = [
156
  ["Release metric", "Rows"],
157
  ["Claim-coded records", data.cases.length],
158
  ["Incident-count eligible records", data.case_catalog.filter((row) => row.record_layer === "claim_coded_core" && row.incident_count_eligible === "true").length],
159
  ["Preparedness files (excluded)", data.cases.filter((row) => row.record_type === "preparedness_file").length],
160
  ["Atomic claims", data.claims.length],
161
- ["Sources", data.sources.length],
 
162
  ["Screening leads", data.candidates.length],
163
  ["Empirical model studies", data.model_evaluations.length],
164
  ["Typed observations", data.observations.length],
@@ -168,7 +169,7 @@ overview.getRange("A5:B17").values = [
168
  ["Automated audit errors", audit.summary.error_count]
169
  ];
170
  overview.getRange("A5:B5").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
171
- overview.getRange("A6:B17").format = { fill: colors.light, borders: { preset: "all", style: "thin", color: "#D9DEE3" } };
172
 
173
  addSectionTitle(overview, "D5:H5", "Read the layers in this order");
174
  overview.getRange("D6:H14").values = [[
@@ -177,15 +178,15 @@ overview.getRange("D6:H14").values = [[
177
  overview.getRange("D6:H14").merge();
178
  overview.getRange("D6:H14").format = { fill: colors.light, borders: { preset: "all", style: "thin", color: "#D9DEE3" }, wrapText: true, verticalAlignment: "top", font: { color: colors.ink, size: 10 } };
179
 
180
- addSectionTitle(overview, "A19:H19", "What changed in v0.3.0", colors.blue);
181
  overview.getRange("A20:H25").values = [[
182
- "The release no longer treats all rows as comparable incidents. It separates election-wide cases, observed networks, bounded incidents, campaign sets and preparedness files; preparedness is excluded from incident counts. Agency transfer is now a structured pathway rather than a narrative field. Reach is stored as typed observations with denominator, window, uniqueness and causal status. Model audits and randomized experiments are a separate empirical-study layer. Official Moldovan turnout now preserves protocol fields C and D and states the legal numerator. Romania and Moldova national result fields are complete; New Hampshire remains explicitly partial."
183
  ]];
184
  overview.getRange("A20:H25").merge();
185
  overview.getRange("A20:H25").format = { fill: colors.paleBlue, borders: { preset: "all", style: "thin", color: colors.blue }, wrapText: true, verticalAlignment: "top", font: { color: colors.ink, size: 10 } };
186
 
187
  overview.getRange("A27:H29").merge();
188
- overview.getRange("A27:H29").values = [["Hard limit: this package is comprehensive within its declared evidence files, not across all elections. Six regional sampling-frame warnings remain because systematic negative searches were not recorded there. Do not estimate global prevalence or votes changed from this release."]];
189
  overview.getRange("A27:H29").format = { fill: colors.paleRed, font: { bold: true, color: colors.red, size: 10 }, borders: { preset: "outside", style: "medium", color: colors.red }, wrapText: true, verticalAlignment: "center" };
190
  overview.freezePanes.freezeRows(3);
191
  for (const [column, width] of [["A", 235], ["B", 110], ["C", 35], ["D", 190], ["E", 190], ["F", 190], ["G", 190], ["H", 190]]) overview.getRange(`${column}1:${column}30`).format.columnWidthPx = width;
@@ -248,7 +249,7 @@ qa.getRange("A1:D2").values = [["Release quality assurance"]];
248
  qa.getRange("A1:D2").format = { fill: colors.ink, font: { bold: true, color: colors.white, size: 17 }, verticalAlignment: "center" };
249
  qa.getRange("A4:D4").values = [["Check", "Result", "Expected", "Interpretation"]];
250
  qa.getRange("A5:D16").values = [
251
- ["Automated audit status", audit.status.toUpperCase(), "PASS", "Deterministic v0.3 audit."],
252
  ["Blocking errors", audit.summary.error_count, 0, "Must remain zero."],
253
  ["Sampling-frame warnings", audit.summary.warning_count, 6, "Expected until negative searches are recorded in six frames."],
254
  ["Research-view rows", data.research_view.length, data.pathways.length, "One row per pathway."],
@@ -264,7 +265,7 @@ qa.getRange("A5:D16").values = [
264
  qa.getRange("A4:D4").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
265
  qa.getRange("A5:D16").format = { borders: { preset: "all", style: "thin", color: "#D9DEE3" }, wrapText: true, verticalAlignment: "top" };
266
  qa.getRange("A18:D21").merge();
267
- qa.getRange("A18:D21").values = [["Warnings are not failed checks. They deliberately block prevalence claims: the package records a null/negative search for South America, but not systematic negative searches for Europe, North America, Asia, Africa, Oceania or the cross-national study layer."]];
268
  qa.getRange("A18:D21").format = { fill: colors.paleAmber, font: { bold: true, color: colors.amber }, borders: { preset: "all", style: "thin", color: colors.amber }, wrapText: true, verticalAlignment: "top" };
269
  for (const [column, width] of [["A", 330], ["B", 180], ["C", 180], ["D", 520]]) qa.getRange(`${column}1:${column}22`).format.columnWidthPx = width;
270
  qa.freezePanes.freezeRows(4);
@@ -308,7 +309,7 @@ const formulaErrors = await wb.inspect({ kind: "match", searchTerm: "#REF!|#DIV/
308
  verification.push(formulaErrors.ndjson || String(formulaErrors));
309
  await fs.writeFile(path.join(outputDir, "verification.ndjson"), verification.join("\n"));
310
 
311
- const outputPath = path.join(outputDir, "agency-transfer-election-evidence-index-v0.3.0.xlsx");
312
  const output = await SpreadsheetFile.exportXlsx(wb);
313
  await output.save(outputPath);
314
  process.stdout.write(`${outputPath}\n`);
 
6
  const here = path.dirname(fileURLToPath(import.meta.url));
7
  const root = process.env.DATASET_ROOT ? path.resolve(process.env.DATASET_ROOT) : path.resolve(here, "..");
8
  const dataDir = path.join(root, "data");
9
+ const outputDir = process.argv[2] || path.join(root, "outputs", "v0.3.1-workbook");
10
  const previewDir = path.join(outputDir, "previews");
11
  await fs.mkdir(previewDir, { recursive: true });
12
 
 
146
  const overview = wb.worksheets.add("00 Overview");
147
  overview.showGridLines = false;
148
  overview.getRange("A1:H2").merge();
149
+ overview.getRange("A1:H2").values = [["AI, Elections and Agency Transfer — Evidence Index v0.3.1"]];
150
  overview.getRange("A1:H2").format = { fill: colors.ink, font: { bold: true, color: colors.white, size: 18 }, verticalAlignment: "center" };
151
  overview.getRange("A3:H3").merge();
152
  overview.getRange("A3:H3").values = [["Research cutoff 2026-08-12 · Purposive evidence corpus, not a global prevalence sample · Start with 01 Research View"]];
153
  overview.getRange("A3:H3").format = { fill: colors.paleBlue, font: { italic: true, color: colors.blue, size: 10 }, verticalAlignment: "center" };
154
 
155
+ overview.getRange("A5:B18").values = [
156
  ["Release metric", "Rows"],
157
  ["Claim-coded records", data.cases.length],
158
  ["Incident-count eligible records", data.case_catalog.filter((row) => row.record_layer === "claim_coded_core" && row.incident_count_eligible === "true").length],
159
  ["Preparedness files (excluded)", data.cases.filter((row) => row.record_type === "preparedness_file").length],
160
  ["Atomic claims", data.claims.length],
161
+ ["Claim-evidence sources", data.sources.length],
162
+ ["Official data sources", data.official_data_sources.length],
163
  ["Screening leads", data.candidates.length],
164
  ["Empirical model studies", data.model_evaluations.length],
165
  ["Typed observations", data.observations.length],
 
169
  ["Automated audit errors", audit.summary.error_count]
170
  ];
171
  overview.getRange("A5:B5").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
172
+ overview.getRange("A6:B18").format = { fill: colors.light, borders: { preset: "all", style: "thin", color: "#D9DEE3" } };
173
 
174
  addSectionTitle(overview, "D5:H5", "Read the layers in this order");
175
  overview.getRange("D6:H14").values = [[
 
178
  overview.getRange("D6:H14").merge();
179
  overview.getRange("D6:H14").format = { fill: colors.light, borders: { preset: "all", style: "thin", color: "#D9DEE3" }, wrapText: true, verticalAlignment: "top", font: { color: colors.ink, size: 10 } };
180
 
181
+ addSectionTitle(overview, "A19:H19", "What changed in v0.3.1", colors.blue);
182
  overview.getRange("A20:H25").values = [[
183
+ "This maintenance release fixes machine-readable dates, complete-result notes, Moldova second-round designating entities and a drifting actor-attribution literal. It adds six bounded quantitative observations, explicit preparedness context, a documented single-coder limitation, a strict 26-table audit and pinned Parquet tooling. New Hampshire's state tally is now separated from its non-awarding delegate effect. Source locators and hashes remain blank where no verifiable archived snapshot exists."
184
  ]];
185
  overview.getRange("A20:H25").merge();
186
  overview.getRange("A20:H25").format = { fill: colors.paleBlue, borders: { preset: "all", style: "thin", color: colors.blue }, wrapText: true, verticalAlignment: "top", font: { color: colors.ink, size: 10 } };
187
 
188
  overview.getRange("A27:H29").merge();
189
+ overview.getRange("A27:H29").values = [["Hard limit: this package is internally complete for its declared records and tables, not across all elections. Six regional sampling-frame warnings flag missing systematic negative searches. Do not estimate global prevalence or votes changed from this release."]];
190
  overview.getRange("A27:H29").format = { fill: colors.paleRed, font: { bold: true, color: colors.red, size: 10 }, borders: { preset: "outside", style: "medium", color: colors.red }, wrapText: true, verticalAlignment: "center" };
191
  overview.freezePanes.freezeRows(3);
192
  for (const [column, width] of [["A", 235], ["B", 110], ["C", 35], ["D", 190], ["E", 190], ["F", 190], ["G", 190], ["H", 190]]) overview.getRange(`${column}1:${column}30`).format.columnWidthPx = width;
 
249
  qa.getRange("A1:D2").format = { fill: colors.ink, font: { bold: true, color: colors.white, size: 17 }, verticalAlignment: "center" };
250
  qa.getRange("A4:D4").values = [["Check", "Result", "Expected", "Interpretation"]];
251
  qa.getRange("A5:D16").values = [
252
+ ["Automated audit status", audit.status.toUpperCase(), "PASS", "Deterministic v0.3.1 audit across all 26 tables."],
253
  ["Blocking errors", audit.summary.error_count, 0, "Must remain zero."],
254
  ["Sampling-frame warnings", audit.summary.warning_count, 6, "Expected until negative searches are recorded in six frames."],
255
  ["Research-view rows", data.research_view.length, data.pathways.length, "One row per pathway."],
 
265
  qa.getRange("A4:D4").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
266
  qa.getRange("A5:D16").format = { borders: { preset: "all", style: "thin", color: "#D9DEE3" }, wrapText: true, verticalAlignment: "top" };
267
  qa.getRange("A18:D21").merge();
268
+ qa.getRange("A18:D21").values = [["Warnings are not failed checks. They flag that prevalence inference is unsupported: the package records a null/negative search for South America, but not systematic negative searches for Europe, North America, Asia, Africa, Oceania or the cross-national study layer."]];
269
  qa.getRange("A18:D21").format = { fill: colors.paleAmber, font: { bold: true, color: colors.amber }, borders: { preset: "all", style: "thin", color: colors.amber }, wrapText: true, verticalAlignment: "top" };
270
  for (const [column, width] of [["A", 330], ["B", 180], ["C", 180], ["D", 520]]) qa.getRange(`${column}1:${column}22`).format.columnWidthPx = width;
271
  qa.freezePanes.freezeRows(4);
 
309
  verification.push(formulaErrors.ndjson || String(formulaErrors));
310
  await fs.writeFile(path.join(outputDir, "verification.ndjson"), verification.join("\n"));
311
 
312
+ const outputPath = path.join(outputDir, "agency-transfer-election-evidence-index-v0.3.1.xlsx");
313
  const output = await SpreadsheetFile.exportXlsx(wb);
314
  await output.save(outputPath);
315
  process.stdout.write(`${outputPath}\n`);
scripts/validate-data.mjs CHANGED
@@ -1,66 +1,204 @@
 
 
 
 
 
 
 
 
 
 
1
  import fs from "node:fs";
2
  import path from "node:path";
3
  import { createHash } from "node:crypto";
 
4
  import { fileURLToPath } from "node:url";
5
 
6
  const here = path.dirname(fileURLToPath(import.meta.url));
7
- const root = path.resolve(here, "..");
8
- const dataDir = path.join(root, "data");
9
- const expected = [
 
 
10
  "cases", "claims", "sources", "events", "case_sources", "watchlist", "candidates",
11
- "official_elections", "official_turnout", "official_results", "official_data_sources"
12
- ];
13
- let failed = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  function sha256(value) {
16
  return createHash("sha256").update(value).digest("hex");
17
  }
18
 
19
- for (const name of expected) {
20
- const file = path.join(dataDir, name + ".csv");
21
- if (!fs.existsSync(file)) {
22
- process.stderr.write("missing: " + file + "\n");
23
- failed = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  continue;
25
  }
26
- const text = fs.readFileSync(file, "utf8");
27
- if (!text.endsWith("\n")) {
28
- process.stderr.write("missing trailing newline: " + file + "\n");
29
- failed = true;
30
  }
31
- if (text.includes("\u0000")) {
32
- process.stderr.write("NUL byte: " + file + "\n");
33
- failed = true;
 
34
  }
35
  }
36
 
37
- const statsPath = path.join(dataDir, "stats.json");
38
- if (!fs.existsSync(statsPath)) {
39
- process.stderr.write("missing: " + statsPath + "\n");
40
- failed = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  } else {
42
- const stats = JSON.parse(fs.readFileSync(statsPath, "utf8"));
43
- const integrity = stats._integrity;
44
- if (!integrity?.input_sha256 || !integrity?.file_sha256) {
45
- process.stderr.write("missing integrity hashes in data/stats.json\n");
46
- failed = true;
 
47
  } else {
48
- for (const [relativePath, expectedHash] of Object.entries(integrity.input_sha256)) {
49
- const file = path.join(root, relativePath);
50
- if (!fs.existsSync(file) || sha256(fs.readFileSync(file)) !== expectedHash) {
51
- process.stderr.write("stale or missing generated input: " + relativePath + "\n");
52
- failed = true;
53
- }
 
54
  }
55
- for (const [filename, expectedHash] of Object.entries(integrity.file_sha256)) {
56
- const file = path.join(dataDir, filename);
57
- if (!fs.existsSync(file) || sha256(fs.readFileSync(file)) !== expectedHash) {
58
- process.stderr.write("generated file hash mismatch: data/" + filename + "\n");
59
- failed = true;
60
- }
61
  }
62
  }
63
  }
64
 
65
- if (failed) process.exit(1);
66
- process.stdout.write("dataset files present, current, and structurally validated\n");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Read-only release validator.
5
+ *
6
+ * This wrapper keeps byte/hash integrity separate from the semantic audit. It
7
+ * writes one deterministic JSON report and exits non-zero when either layer
8
+ * fails. Semantic warnings remain non-blocking.
9
+ */
10
+
11
  import fs from "node:fs";
12
  import path from "node:path";
13
  import { createHash } from "node:crypto";
14
+ import { spawnSync } from "node:child_process";
15
  import { fileURLToPath } from "node:url";
16
 
17
  const here = path.dirname(fileURLToPath(import.meta.url));
18
+ const packageRoot = path.resolve(here, "..");
19
+ const dataDir = path.resolve(process.argv[2] || path.join(packageRoot, "data"));
20
+ const auditScript = path.join(here, "audit-v03.mjs");
21
+
22
+ const EXPECTED_TABLES = Object.freeze([
23
  "cases", "claims", "sources", "events", "case_sources", "watchlist", "candidates",
24
+ "official_elections", "official_turnout", "official_results", "official_data_sources",
25
+ "official_election_metrics", "research_view", "case_catalog", "case_actors",
26
+ "technology_uses", "content_items", "pathways", "observations", "model_evaluations",
27
+ "claim_evidence", "analytic_record_claims", "case_elections", "election_sources",
28
+ "sampling_frame", "coverage_summary"
29
+ ]);
30
+ const HASHED_DATA_FILES = Object.freeze([
31
+ ...EXPECTED_TABLES.map((name) => `${name}.csv`),
32
+ "schema.json",
33
+ "datapackage.json"
34
+ ]);
35
+
36
+ const fileErrors = [];
37
+ function fileError(code, file, message) {
38
+ fileErrors.push({ code, file: file || null, message });
39
+ }
40
 
41
  function sha256(value) {
42
  return createHash("sha256").update(value).digest("hex");
43
  }
44
 
45
+ function isPlainObject(value) {
46
+ return value !== null && typeof value === "object" && !Array.isArray(value);
47
+ }
48
+
49
+ function pathInside(base, relativePath) {
50
+ if (typeof relativePath !== "string" || path.isAbsolute(relativePath)) return null;
51
+ const resolvedBase = path.resolve(base);
52
+ const resolved = path.resolve(resolvedBase, relativePath);
53
+ return resolved === resolvedBase || resolved.startsWith(`${resolvedBase}${path.sep}`) ? resolved : null;
54
+ }
55
+
56
+ function cleanOutput(value) {
57
+ return String(value || "").trim().replace(/\s+/g, " ").slice(0, 500);
58
+ }
59
+
60
+ if (!fs.existsSync(dataDir) || !fs.statSync(dataDir).isDirectory()) {
61
+ fileError("DATA_DIRECTORY_MISSING", dataDir, "Data directory is missing or is not a directory");
62
+ }
63
+
64
+ const actualCsvNames = fs.existsSync(dataDir)
65
+ ? fs.readdirSync(dataDir).filter((filename) => filename.endsWith(".csv")).sort()
66
+ : [];
67
+ const expectedCsvNames = EXPECTED_TABLES.map((name) => `${name}.csv`).sort();
68
+ for (const filename of expectedCsvNames) {
69
+ if (!actualCsvNames.includes(filename)) fileError("EXPECTED_CSV_MISSING", filename, "Expected release table is missing");
70
+ }
71
+ for (const filename of actualCsvNames) {
72
+ if (!expectedCsvNames.includes(filename)) fileError("UNEXPECTED_CSV", filename, "Unexpected CSV table is present");
73
+ }
74
+
75
+ for (const filename of expectedCsvNames) {
76
+ const filepath = path.join(dataDir, filename);
77
+ if (!fs.existsSync(filepath)) continue;
78
+ const contents = fs.readFileSync(filepath);
79
+ if (!contents.length || contents.at(-1) !== 0x0a) {
80
+ fileError("TRAILING_NEWLINE_MISSING", filename, "CSV must end with a newline");
81
+ }
82
+ if (contents.includes(0x00)) fileError("NUL_BYTE", filename, "CSV contains a NUL byte");
83
+ }
84
+
85
+ const statsPath = path.join(dataDir, "stats.json");
86
+ let stats = null;
87
+ if (!fs.existsSync(statsPath)) {
88
+ fileError("STATS_MISSING", "stats.json", "Integrity manifest is missing");
89
+ } else {
90
+ try {
91
+ stats = JSON.parse(fs.readFileSync(statsPath, "utf8"));
92
+ } catch (caught) {
93
+ fileError("STATS_INVALID_JSON", "stats.json", `Invalid JSON: ${caught.message}`);
94
+ }
95
+ }
96
+
97
+ const inputHashes = stats?._integrity?.input_sha256;
98
+ const fileHashes = stats?._integrity?.file_sha256;
99
+ if (stats && !isPlainObject(inputHashes)) {
100
+ fileError("INPUT_HASHES_MISSING", "stats.json", "_integrity.input_sha256 must be an object");
101
+ }
102
+ if (stats && !isPlainObject(fileHashes)) {
103
+ fileError("FILE_HASHES_MISSING", "stats.json", "_integrity.file_sha256 must be an object");
104
+ }
105
+ if (isPlainObject(inputHashes) && !Object.keys(inputHashes).length) {
106
+ fileError("INPUT_HASHES_EMPTY", "stats.json", "At least one generated-input hash is required");
107
+ }
108
+ if (isPlainObject(fileHashes)) {
109
+ for (const filename of HASHED_DATA_FILES) {
110
+ if (!(filename in fileHashes)) fileError("DATA_HASH_ENTRY_MISSING", filename, "stats.json has no SHA-256 entry for this release file");
111
+ }
112
+ }
113
+
114
+ for (const [relativePath, expectedHash] of Object.entries(isPlainObject(inputHashes) ? inputHashes : {}).sort(([a], [b]) => a.localeCompare(b))) {
115
+ const filepath = pathInside(packageRoot, relativePath);
116
+ if (!filepath) {
117
+ fileError("INPUT_HASH_PATH_INVALID", relativePath, "Generated-input hash path must remain inside the package root");
118
  continue;
119
  }
120
+ if (!/^[a-f0-9]{64}$/.test(String(expectedHash))) {
121
+ fileError("INPUT_HASH_INVALID", relativePath, "Expected input SHA-256 is not a lowercase 64-character digest");
122
+ continue;
 
123
  }
124
+ if (!fs.existsSync(filepath)) {
125
+ fileError("GENERATED_INPUT_MISSING", relativePath, "Hashed generated input is missing");
126
+ } else if (sha256(fs.readFileSync(filepath)) !== expectedHash) {
127
+ fileError("GENERATED_INPUT_HASH_MISMATCH", relativePath, "Generated input differs from stats.json");
128
  }
129
  }
130
 
131
+ for (const [filename, expectedHash] of Object.entries(isPlainObject(fileHashes) ? fileHashes : {}).sort(([a], [b]) => a.localeCompare(b))) {
132
+ if (path.basename(filename) !== filename) {
133
+ fileError("DATA_HASH_PATH_INVALID", filename, "Generated-file hash keys must be plain filenames");
134
+ continue;
135
+ }
136
+ const filepath = path.join(dataDir, filename);
137
+ if (!/^[a-f0-9]{64}$/.test(String(expectedHash))) {
138
+ fileError("DATA_HASH_INVALID", filename, "Expected data SHA-256 is not a lowercase 64-character digest");
139
+ continue;
140
+ }
141
+ if (!fs.existsSync(filepath)) {
142
+ fileError("HASHED_DATA_FILE_MISSING", filename, "File listed in stats.json is missing");
143
+ } else if (sha256(fs.readFileSync(filepath)) !== expectedHash) {
144
+ fileError("DATA_HASH_MISMATCH", filename, "File differs from stats.json");
145
+ }
146
+ }
147
+
148
+ let auditReport = null;
149
+ let auditFailure = null;
150
+ if (!fs.existsSync(auditScript)) {
151
+ auditFailure = "Semantic audit script is missing";
152
  } else {
153
+ const result = spawnSync(process.execPath, [auditScript, dataDir], {
154
+ encoding: "utf8",
155
+ maxBuffer: 16 * 1024 * 1024
156
+ });
157
+ if (result.error) {
158
+ auditFailure = `Semantic audit could not run: ${result.error.message}`;
159
  } else {
160
+ try {
161
+ auditReport = JSON.parse(result.stdout);
162
+ } catch (caught) {
163
+ auditFailure = `Semantic audit did not return valid JSON: ${caught.message}`;
164
+ }
165
+ if (auditReport && ![0, 1].includes(result.status)) {
166
+ auditFailure = `Semantic audit terminated with unexpected exit status ${result.status}: ${cleanOutput(result.stderr)}`;
167
  }
168
+ if (auditReport && ((auditReport.status === "pass") !== (result.status === 0))) {
169
+ auditFailure = `Semantic audit exit status ${result.status} disagrees with report status ${auditReport.status}`;
 
 
 
 
170
  }
171
  }
172
  }
173
 
174
+ fileErrors.sort((a, b) => a.code.localeCompare(b.code) || String(a.file).localeCompare(String(b.file)) || a.message.localeCompare(b.message));
175
+ const auditIntegrity = auditReport?.integrity;
176
+ const semanticAudit = auditReport?.semantic_audit;
177
+ const integrityFailed = fileErrors.length > 0 || auditFailure !== null || auditIntegrity?.status !== "pass";
178
+ const semanticFailed = auditFailure !== null || semanticAudit?.status !== "pass";
179
+ const report = {
180
+ validator: "agency-transfer-election-cases-v0.3.1/validate-data",
181
+ status: integrityFailed || semanticFailed ? "fail" : "pass",
182
+ integrity: {
183
+ status: integrityFailed ? "fail" : "pass",
184
+ expected_table_count: EXPECTED_TABLES.length,
185
+ present_table_count: expectedCsvNames.filter((filename) => actualCsvNames.includes(filename)).length,
186
+ hashed_release_file_count: isPlainObject(fileHashes) ? Object.keys(fileHashes).length : 0,
187
+ hashed_input_count: isPlainObject(inputHashes) ? Object.keys(inputHashes).length : 0,
188
+ file_error_count: fileErrors.length,
189
+ contract_error_count: Number.isInteger(auditIntegrity?.error_count) ? auditIntegrity.error_count : null,
190
+ errors: fileErrors
191
+ },
192
+ semantic_audit: auditFailure ? {
193
+ status: "fail",
194
+ failure: auditFailure
195
+ } : {
196
+ status: semanticAudit.status,
197
+ audited_table_count: semanticAudit.audited_table_count,
198
+ error_count: semanticAudit.error_count,
199
+ warning_count: semanticAudit.warning_count
200
+ }
201
+ };
202
+
203
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
204
+ if (report.status === "fail") process.exitCode = 1;