apol commited on
Commit
57e5bea
·
verified ·
1 Parent(s): d9223e7

Publish v0.3.0 reproducibility scripts

Browse files

Build, validation, audit, Parquet and workbook generation scripts for the v0.3.0 release.

scripts/audit-v03.mjs ADDED
@@ -0,0 +1,1018 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
8
+ *
9
+ * The script writes nothing. It prints one stable JSON report and exits 1 only
10
+ * when blocking errors exist. Warnings never change the exit status.
11
+ */
12
+
13
+ import fs from "node:fs";
14
+ import path from "node:path";
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
+
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,
30
+ row_id: rowId || null,
31
+ message
32
+ };
33
+ (severity === "error" ? blocking : advisory).push(item);
34
+ }
35
+
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 = [];
42
+ let record = [];
43
+ let field = "";
44
+ let quoted = false;
45
+
46
+ for (let i = 0; i < input.length; i += 1) {
47
+ const char = input[i];
48
+ if (quoted) {
49
+ if (char === '"') {
50
+ if (input[i + 1] === '"') {
51
+ field += '"';
52
+ i += 1;
53
+ } else {
54
+ quoted = false;
55
+ }
56
+ } else {
57
+ field += char;
58
+ }
59
+ continue;
60
+ }
61
+ if (char === '"' && field === "") {
62
+ quoted = true;
63
+ } else if (char === ",") {
64
+ record.push(field);
65
+ field = "";
66
+ } else if (char === "\n") {
67
+ record.push(field);
68
+ records.push(record);
69
+ record = [];
70
+ field = "";
71
+ } else if (char !== "\r") {
72
+ field += char;
73
+ }
74
+ }
75
+
76
+ if (quoted) {
77
+ error("T00_SCHEMA", "CSV_UNCLOSED_QUOTE", filename, null, "CSV ends inside a quoted field");
78
+ }
79
+ if (field !== "" || record.length > 0) {
80
+ record.push(field);
81
+ records.push(record);
82
+ }
83
+ while (records.length && records.at(-1).every((value) => value === "")) records.pop();
84
+ if (!records.length) {
85
+ error("T00_SCHEMA", "CSV_EMPTY", filename, null, "CSV has no header row");
86
+ return { headers: [], rows: [] };
87
+ }
88
+
89
+ const headers = records[0].map((value) => value.trim());
90
+ const duplicateHeaders = headers.filter((value, index) => headers.indexOf(value) !== index);
91
+ for (const header of [...new Set(duplicateHeaders)].sort()) {
92
+ error("T00_SCHEMA", "DUPLICATE_HEADER", filename, null, `Duplicate header: ${header}`);
93
+ }
94
+
95
+ const rows = [];
96
+ for (let i = 1; i < records.length; i += 1) {
97
+ const values = records[i];
98
+ if (values.every((value) => value === "")) continue;
99
+ if (values.length !== headers.length) {
100
+ error(
101
+ "T00_SCHEMA",
102
+ "CSV_WIDTH",
103
+ filename,
104
+ `line:${i + 1}`,
105
+ `Expected ${headers.length} cells; found ${values.length}`
106
+ );
107
+ }
108
+ const row = { __line: i + 1 };
109
+ headers.forEach((header, index) => {
110
+ row[header] = values[index] ?? "";
111
+ });
112
+ rows.push(row);
113
+ }
114
+ return { headers, rows };
115
+ }
116
+
117
+ function loadTable(name, requiredHeaders, required = true) {
118
+ const filename = `${name}.csv`;
119
+ const filepath = path.join(dataDir, filename);
120
+ if (!fs.existsSync(filepath)) {
121
+ (required ? error : warn)(
122
+ "T00_SCHEMA",
123
+ required ? "REQUIRED_TABLE_MISSING" : "OPTIONAL_TABLE_MISSING",
124
+ name,
125
+ null,
126
+ `${filename} is missing`
127
+ );
128
+ const empty = { headers: [], rows: [], exists: false };
129
+ loaded.set(name, empty);
130
+ return empty;
131
+ }
132
+ const parsed = parseCsv(fs.readFileSync(filepath, "utf8"), name);
133
+ const headerSet = new Set(parsed.headers);
134
+ for (const header of requiredHeaders) {
135
+ if (!headerSet.has(header)) {
136
+ error("T00_SCHEMA", "REQUIRED_COLUMN_MISSING", name, null, `Required column is missing: ${header}`);
137
+ }
138
+ }
139
+ const table = { ...parsed, exists: true };
140
+ loaded.set(name, table);
141
+ return table;
142
+ }
143
+
144
+ const requiredColumns = {
145
+ cases: [
146
+ "case_id", "case_family_id", "title", "country", "region", "election_date_start",
147
+ "case_status", "as_of_date", "record_type", "manipulation_assessment", "last_verified"
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",
154
+ "incident_count_eligible", "research_status"
155
+ ],
156
+ case_actors: [
157
+ "case_actor_id", "case_id", "actor_name", "actor_role", "actor_type",
158
+ "attribution_status", "control_dimension", "source_claim_ids"
159
+ ],
160
+ technology_uses: [
161
+ "tech_use_id", "case_id", "provider", "product_or_model", "version", "access_type",
162
+ "technology_role", "use_status", "provenance_status", "evidence_label", "source_claim_ids", "notes"
163
+ ],
164
+ content_items: ["content_item_id", "case_id", "source_claim_ids"],
165
+ pathways: [
166
+ "pathway_id", "case_id", "affected_agency", "control_shift_from", "control_shift_to",
167
+ "mechanism", "power_recipient", "harm_pathway", "agency_transfer_status",
168
+ "assessment_label", "source_claim_ids"
169
+ ],
170
+ observations: [
171
+ "observation_id", "case_id", "pathway_id", "claim_id", "metric_family", "metric_name",
172
+ "value_low", "value_best", "value_high", "unit", "denominator", "unique_entity_status",
173
+ "platform", "geographic_scope", "measurement_window", "measurement_method", "causal_status",
174
+ "source_id", "as_of_date", "limitations"
175
+ ],
176
+ model_evaluations: [
177
+ "evaluation_id", "title", "country", "evaluation_window", "election_or_context",
178
+ "systems_tested", "versions_known", "interface", "languages", "sample_unit", "sample_size",
179
+ "design", "primary_metrics", "headline_results", "causal_scope", "source_id",
180
+ "data_availability", "notes"
181
+ ],
182
+ claim_evidence: ["claim_evidence_id", "claim_id", "source_id", "relation", "evidence_scope", "directness"],
183
+ case_elections: ["case_election_id", "case_id", "election_id", "relation"],
184
+ sampling_frame: [
185
+ "frame_id", "region", "selection_basis", "search_status", "search_languages", "source_channels",
186
+ "included_case_count", "candidate_count", "negative_search_recorded", "known_gap", "last_searched"
187
+ ],
188
+ coverage_summary: ["region", "included_case_count", "candidate_count", "model_evaluation_count", "coverage_note"],
189
+ research_view: [
190
+ "pathway_id", "case_id", "record_type", "manipulation_assessment", "system_or_model",
191
+ "controller", "influence_vector", "target", "affected_agency", "agency_transfer_status",
192
+ "power_recipient", "reach_summary", "behavioural_effect", "electoral_effect", "evidence_strength"
193
+ ],
194
+ official_data_sources: ["official_source_id", "case_family_id", "data_status", "retrieved_at"],
195
+ official_elections: [
196
+ "election_id", "case_family_id", "linked_case_ids", "election_date", "election_status",
197
+ "legal_result_status", "official_source_ids", "as_of_date"
198
+ ],
199
+ official_turnout: [
200
+ "turnout_id", "election_id", "geographic_unit_type", "geographic_unit_code", "data_status",
201
+ "electorate_measure", "participation_measure", "registered_voters", "ballots_cast", "valid_votes",
202
+ "invalid_votes", "turnout_rate", "reporting_units_total", "reporting_units_counted",
203
+ "official_source_id", "as_of_date", "notes"
204
+ ],
205
+ official_results: [
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}`;
229
+ }
230
+
231
+ function requireNonBlank(row, fields, test, table, id) {
232
+ for (const field of fields) {
233
+ if (isBlank(row[field])) error(test, "REQUIRED_VALUE_MISSING", table, id, `Required value is blank: ${field}`);
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
+ }
249
+ }
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) {
265
+ const values = ids(row[field]);
266
+ const id = rowId(row, table);
267
+ if (!values.length && !allowBlank) {
268
+ error(test, "FOREIGN_KEY_MISSING", table, id, `${field} is blank; expected ${targetTable}`);
269
+ return;
270
+ }
271
+ for (const value of values) {
272
+ if (!targetIndex?.has(value)) {
273
+ error(test, "FOREIGN_KEY_UNKNOWN", table, id, `${field} references unknown ${targetTable}: ${value}`);
274
+ }
275
+ }
276
+ }
277
+
278
+ const caseFamilyIds = new Set(rows("cases").map((row) => clean(row.case_family_id)).filter(Boolean));
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",
285
+ "preparedness_file", "observational_null_case", "negative_case"
286
+ ]);
287
+ const validManipulationAssessments = new Set([
288
+ "manipulation_confirmed", "manipulation_probable", "mixed_documented_manipulation",
289
+ "transparent_contested_use", "manipulation_not_established", "no_manipulation_observed",
290
+ "preparedness_not_incident", "not_applicable"
291
+ ]);
292
+ for (const row of rows("cases")) {
293
+ const id = rowId(row, "cases");
294
+ requireNonBlank(row, ["record_type", "manipulation_assessment"], "T01_RECORD_CLASSIFICATION", "cases", id);
295
+ if (!validRecordTypes.has(clean(row.record_type))) {
296
+ error("T01_RECORD_CLASSIFICATION", "RECORD_TYPE_INVALID", "cases", id, `Unknown record_type: ${clean(row.record_type)}`);
297
+ }
298
+ if (!validManipulationAssessments.has(clean(row.manipulation_assessment))) {
299
+ error(
300
+ "T01_RECORD_CLASSIFICATION", "MANIPULATION_ASSESSMENT_INVALID", "cases", id,
301
+ `Unknown manipulation_assessment: ${clean(row.manipulation_assessment)}`
302
+ );
303
+ }
304
+ if (!isIsoDate(row.as_of_date) || !isIsoDate(row.last_verified)) {
305
+ error("T01_RECORD_CLASSIFICATION", "CASE_DATE_INVALID", "cases", id, "as_of_date and last_verified must be ISO dates");
306
+ } else if (clean(row.last_verified) > clean(row.as_of_date)) {
307
+ error("T01_RECORD_CLASSIFICATION", "VERIFIED_AFTER_AS_OF", "cases", id, "last_verified is after as_of_date");
308
+ }
309
+ if (/^(manipulation_confirmed|manipulation_probable|mixed_documented_manipulation)$/.test(clean(row.manipulation_assessment))) {
310
+ const processClaims = rows("claims").filter(
311
+ (claim) => clean(claim.case_id) === clean(row.case_id) &&
312
+ ["occurrence", "mechanism", "attribution", "intent"].includes(clean(claim.claim_type)) &&
313
+ ["established_evidence", "strong_inference"].includes(clean(claim.evidence_label)) &&
314
+ ids(claim.source_ids).length > 0
315
+ );
316
+ if (!processClaims.length) {
317
+ error(
318
+ "T01_RECORD_CLASSIFICATION", "MANIPULATION_WITHOUT_PROCESS_EVIDENCE", "cases", id,
319
+ "Confirmed/probable/mixed manipulation requires an evidence-backed process claim"
320
+ );
321
+ }
322
+ }
323
+ }
324
+
325
+ // T02 — preparedness and model-evaluation records can never inflate incident counts.
326
+ const trueValues = new Set(["true"]);
327
+ const falseValues = new Set(["false"]);
328
+ for (const row of rows("cases")) {
329
+ const id = rowId(row, "cases");
330
+ const isPreparedness = clean(row.record_type) === "preparedness_file";
331
+ if (isPreparedness && clean(row.manipulation_assessment) !== "preparedness_not_incident") {
332
+ error(
333
+ "T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_ASSESSMENT", "cases", id,
334
+ "preparedness_file must use manipulation_assessment=preparedness_not_incident"
335
+ );
336
+ }
337
+ if (!isPreparedness && clean(row.manipulation_assessment) === "preparedness_not_incident") {
338
+ error(
339
+ "T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_TYPE_MISMATCH", "cases", id,
340
+ "preparedness_not_incident is only valid for record_type=preparedness_file"
341
+ );
342
+ }
343
+ }
344
+ for (const row of rows("case_catalog")) {
345
+ const id = rowId(row, "case_catalog");
346
+ const eligibility = lower(row.incident_count_eligible);
347
+ if (!trueValues.has(eligibility) && !falseValues.has(eligibility)) {
348
+ error(
349
+ "T02_INCIDENT_DENOMINATOR", "INCIDENT_ELIGIBILITY_INVALID", "case_catalog", id,
350
+ "incident_count_eligible must be an explicit boolean"
351
+ );
352
+ }
353
+ if (
354
+ clean(row.record_type) === "preparedness_file" ||
355
+ /model.?evaluation/i.test(clean(row.record_layer)) ||
356
+ /model.?evaluation/i.test(clean(row.research_status))
357
+ ) {
358
+ if (!falseValues.has(eligibility)) {
359
+ error(
360
+ "T02_INCIDENT_DENOMINATOR", "NON_INCIDENT_COUNTED", "case_catalog", id,
361
+ "Preparedness and model-evaluation records must have incident_count_eligible=false"
362
+ );
363
+ }
364
+ }
365
+ }
366
+ const preparednessCatalogCount = rows("case_catalog").filter((row) => clean(row.record_type) === "preparedness_file").length;
367
+ const preparednessCaseCount = rows("cases").filter((row) => clean(row.record_type) === "preparedness_file").length;
368
+ if (rows("case_catalog").length && preparednessCatalogCount !== preparednessCaseCount) {
369
+ error(
370
+ "T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_CATALOG_COUNT_MISMATCH", "case_catalog", null,
371
+ `case_catalog has ${preparednessCatalogCount} preparedness rows; cases.csv has ${preparednessCaseCount}`
372
+ );
373
+ }
374
+ const modelCatalogCount = rows("case_catalog").filter((row) => clean(row.record_layer) === "empirical_model_study").length;
375
+ if (rows("case_catalog").length && modelCatalogCount !== rows("model_evaluations").length) {
376
+ error(
377
+ "T02_INCIDENT_DENOMINATOR", "MODEL_EVALUATION_CATALOG_COUNT_MISMATCH", "case_catalog", null,
378
+ `case_catalog has ${modelCatalogCount} model-evaluation rows; model_evaluations.csv has ${rows("model_evaluations").length}`
379
+ );
380
+ }
381
+ for (const row of rows("pathways")) {
382
+ const parent = index.cases.get(clean(row.case_id));
383
+ if (parent?.record_type === "preparedness_file" && clean(row.agency_transfer_status) !== "not_an_incident") {
384
+ error(
385
+ "T02_INCIDENT_DENOMINATOR", "PREPAREDNESS_PATHWAY_STATUS", "pathways", rowId(row, "pathways"),
386
+ "A preparedness pathway must use agency_transfer_status=not_an_incident"
387
+ );
388
+ }
389
+ }
390
+
391
+ // T03 — relational integrity across the research and official-election layers.
392
+ for (const row of rows("claims")) requireFk("T03_FOREIGN_KEYS", "claims", row, "case_id", "cases");
393
+ for (const table of ["case_actors", "technology_uses", "content_items", "pathways", "observations", "case_elections"]) {
394
+ for (const row of rows(table)) requireFk("T03_FOREIGN_KEYS", table, row, "case_id", "cases");
395
+ }
396
+ for (const table of ["case_actors", "technology_uses", "content_items", "pathways"]) {
397
+ for (const row of rows(table)) {
398
+ requireFk("T03_FOREIGN_KEYS", table, row, "source_claim_ids", "claims");
399
+ for (const claimId of ids(row.source_claim_ids)) {
400
+ const claim = index.claims.get(claimId);
401
+ if (claim && clean(claim.case_id) !== clean(row.case_id)) {
402
+ error(
403
+ "T03_FOREIGN_KEYS", "CROSS_CASE_SOURCE_CLAIM", table, rowId(row, table),
404
+ `source_claim_ids references a claim from another case: ${claimId}`
405
+ );
406
+ }
407
+ }
408
+ }
409
+ }
410
+ for (const row of rows("observations")) {
411
+ requireFk("T03_FOREIGN_KEYS", "observations", row, "pathway_id", "pathways");
412
+ requireFk("T03_FOREIGN_KEYS", "observations", row, "claim_id", "claims");
413
+ requireFk("T03_FOREIGN_KEYS", "observations", row, "source_id", "sources");
414
+ const caseId = clean(row.case_id);
415
+ const pathway = index.pathways.get(clean(row.pathway_id));
416
+ const claim = index.claims.get(clean(row.claim_id));
417
+ if (pathway && clean(pathway.case_id) !== caseId) {
418
+ error("T03_FOREIGN_KEYS", "CROSS_CASE_PATHWAY", "observations", rowId(row, "observations"), "pathway_id belongs to another case");
419
+ }
420
+ if (claim && clean(claim.case_id) !== caseId) {
421
+ error("T03_FOREIGN_KEYS", "CROSS_CASE_CLAIM", "observations", rowId(row, "observations"), "claim_id belongs to another case");
422
+ }
423
+ }
424
+ for (const row of rows("model_evaluations")) requireFk("T03_FOREIGN_KEYS", "model_evaluations", row, "source_id", "sources");
425
+ for (const row of rows("claim_evidence")) {
426
+ requireFk("T03_FOREIGN_KEYS", "claim_evidence", row, "claim_id", "claims");
427
+ requireFk("T03_FOREIGN_KEYS", "claim_evidence", row, "source_id", "sources");
428
+ }
429
+ for (const row of rows("case_elections")) requireFk("T03_FOREIGN_KEYS", "case_elections", row, "election_id", "official_elections");
430
+ for (const row of rows("official_elections")) {
431
+ requireFk("T03_FOREIGN_KEYS", "official_elections", row, "linked_case_ids", "cases");
432
+ requireFk("T03_FOREIGN_KEYS", "official_elections", row, "official_source_ids", "official_data_sources");
433
+ if (!caseFamilyIds.has(clean(row.case_family_id))) {
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");
441
+ const election = index.official_elections.get(clean(row.election_id));
442
+ const source = index.official_data_sources.get(clean(row.official_source_id));
443
+ if (election && source && clean(election.case_family_id) !== clean(source.case_family_id)) {
444
+ error("T03_FOREIGN_KEYS", "OFFICIAL_SOURCE_FAMILY_MISMATCH", table, rowId(row, table), "Official source and election belong to different case families");
445
+ }
446
+ }
447
+ }
448
+ for (const row of rows("official_data_sources")) {
449
+ if (!caseFamilyIds.has(clean(row.case_family_id))) {
450
+ error("T03_FOREIGN_KEYS", "CASE_FAMILY_UNKNOWN", "official_data_sources", rowId(row, "official_data_sources"), `Unknown case_family_id: ${clean(row.case_family_id)}`);
451
+ }
452
+ }
453
+ for (const row of rows("research_view")) {
454
+ requireFk("T03_FOREIGN_KEYS", "research_view", row, "case_id", "cases");
455
+ requireFk("T03_FOREIGN_KEYS", "research_view", row, "pathway_id", "pathways");
456
+ const pathway = index.pathways.get(clean(row.pathway_id));
457
+ if (pathway && clean(pathway.case_id) !== clean(row.case_id)) {
458
+ error("T03_FOREIGN_KEYS", "RESEARCH_VIEW_PATHWAY_CASE_MISMATCH", "research_view", rowId(row, "research_view"), "Research-view pathway belongs to another case");
459
+ }
460
+ }
461
+
462
+ // T04 — a pathway is an auditable control-transfer proposition, not a narrative blob.
463
+ const validAgencyStatuses = new Set([
464
+ "full_chain_observed", "partial_chain_observed", "mechanism_observed_effect_unknown",
465
+ "mechanism_inferred", "plausible_hypothesis", "no_transfer_observed", "insufficient_evidence",
466
+ "not_an_incident"
467
+ ]);
468
+ const validAssessmentLabels = new Set([
469
+ "established_evidence", "strong_inference", "plausible_hypothesis", "speculative_scenario",
470
+ "open_question", "not_applicable"
471
+ ]);
472
+ const pathwaysByCase = new Map();
473
+ for (const row of rows("pathways")) {
474
+ const id = rowId(row, "pathways");
475
+ requireNonBlank(
476
+ row,
477
+ [
478
+ "case_id", "affected_agency", "control_shift_from", "control_shift_to", "mechanism",
479
+ "power_recipient", "harm_pathway", "agency_transfer_status", "assessment_label", "source_claim_ids"
480
+ ],
481
+ "T04_PATHWAY", "pathways", id
482
+ );
483
+ if (!validAgencyStatuses.has(clean(row.agency_transfer_status))) {
484
+ error("T04_PATHWAY", "AGENCY_STATUS_INVALID", "pathways", id, `Unknown agency_transfer_status: ${clean(row.agency_transfer_status)}`);
485
+ }
486
+ if (!validAssessmentLabels.has(clean(row.assessment_label))) {
487
+ error("T04_PATHWAY", "ASSESSMENT_LABEL_INVALID", "pathways", id, `Unknown assessment_label: ${clean(row.assessment_label)}`);
488
+ }
489
+ if (clean(row.agency_transfer_status) === "not_an_incident" && index.cases.get(clean(row.case_id))?.record_type !== "preparedness_file") {
490
+ warn("T04_PATHWAY", "NON_PREPAREDNESS_NOT_INCIDENT", "pathways", id, "not_an_incident is attached to a non-preparedness case; verify deliberate negative-case coding");
491
+ }
492
+ const text = [row.mechanism, row.harm_pathway, row.observed_outcome].join(" ").toLowerCase();
493
+ if (/(defen[cs]e|mitigat|monitoring|safeguard|enforcement)/.test(text) && /(manipulat|impersonat|decept|amplif|influence)/.test(text)) {
494
+ warn("T04_PATHWAY", "OFFENSE_DEFENSE_CONFLATED", "pathways", id, "Pathway text appears to combine offensive influence and defensive response; split if they are distinct mechanisms");
495
+ }
496
+ const caseId = clean(row.case_id);
497
+ if (!pathwaysByCase.has(caseId)) pathwaysByCase.set(caseId, []);
498
+ pathwaysByCase.get(caseId).push(row);
499
+ }
500
+ for (const row of rows("cases")) {
501
+ if (!pathwaysByCase.has(clean(row.case_id))) {
502
+ error("T04_PATHWAY", "CASE_WITHOUT_PATHWAY", "cases", rowId(row, "cases"), "Every case must have at least one pathway assessment");
503
+ }
504
+ }
505
+ for (const row of rows("case_actors")) {
506
+ requireNonBlank(row, ["actor_name", "actor_role", "actor_type", "attribution_status", "control_dimension"], "T04_PATHWAY", "case_actors", rowId(row, "case_actors"));
507
+ }
508
+ for (const row of rows("technology_uses")) {
509
+ const id = rowId(row, "technology_uses");
510
+ requireNonBlank(row, ["provider", "product_or_model", "technology_role", "use_status", "provenance_status", "evidence_label"], "T04_PATHWAY", "technology_uses", id);
511
+ if (isBlank(row.version) && !/(not established|not identified|unknown|not disclosed|unavailable)/i.test(clean(row.notes))) {
512
+ error("T04_PATHWAY", "MODEL_VERSION_BLANK_UNEXPLAINED", "technology_uses", id, "A blank version requires an explicit limitation in notes");
513
+ }
514
+ if (
515
+ lower(row.version) === "unknown" &&
516
+ !/(unknown|not disclosed|not identified|unavailable|does not identify|does not establish which service|not product-level|exact model|exact producer|exact models|provider identification|public record|predominantly non-ai|do not infer|exact model, api)/i.test(clean(row.notes))
517
+ ) {
518
+ error("T04_PATHWAY", "UNKNOWN_MODEL_VERSION_UNEXPLAINED", "technology_uses", id, "version=unknown requires an explicit limitation in notes");
519
+ }
520
+ }
521
+ const actorCaseIds = new Set(rows("case_actors").map((row) => clean(row.case_id)));
522
+ const technologyCaseIds = new Set(rows("technology_uses").map((row) => clean(row.case_id)));
523
+ for (const row of rows("cases")) {
524
+ const id = rowId(row, "cases");
525
+ if (clean(row.record_type) !== "preparedness_file" && !actorCaseIds.has(clean(row.case_id))) {
526
+ error("T04_PATHWAY", "CASE_WITHOUT_ACTOR", "case_actors", id, "Every case must identify at least one actor or explicitly coded unknown actor");
527
+ }
528
+ if (
529
+ clean(row.record_type) !== "preparedness_file" &&
530
+ /^(confirmed|probable|mixed)$/.test(clean(row.generative_ai_status)) &&
531
+ !technologyCaseIds.has(clean(row.case_id))
532
+ ) {
533
+ error("T04_PATHWAY", "AI_CASE_WITHOUT_TECHNOLOGY", "technology_uses", id, "A case with material generative AI must have at least one technology-use row");
534
+ }
535
+ }
536
+
537
+ // T05 — all quantitative observations retain numeric values, denominators and causal status.
538
+ function parseNumber(value) {
539
+ if (isBlank(value)) return null;
540
+ const number = Number(value);
541
+ return Number.isFinite(number) ? number : Number.NaN;
542
+ }
543
+ function isCountMetric(row) {
544
+ return /(count|reach|engagement|volume|audience|network|views?|impressions?|accounts?|followers?|posts?|likes?|shares?|comments?|calls?|questions?|votes?|ballots?)/i.test(
545
+ [row.metric_family, row.metric_name, row.unit].join(" ")
546
+ );
547
+ }
548
+ const causalValues = new Set([
549
+ "descriptive_only", "descriptive_non_causal", "non_causal", "no", "unknown", "not_applicable", "association_only",
550
+ "experimental_causal_estimate", "quasi_experimental_causal_estimate", "causal_estimate", "causal_estimate_limited"
551
+ ]);
552
+ for (const row of rows("observations")) {
553
+ const id = rowId(row, "observations");
554
+ requireNonBlank(
555
+ row,
556
+ [
557
+ "case_id", "pathway_id", "claim_id", "metric_family", "metric_name", "unit", "denominator",
558
+ "unique_entity_status", "platform", "geographic_scope", "measurement_window", "measurement_method",
559
+ "causal_status", "source_id", "as_of_date", "limitations"
560
+ ],
561
+ "T05_OBSERVATIONS", "observations", id
562
+ );
563
+ const values = ["value_low", "value_best", "value_high"].map((field) => [field, parseNumber(row[field])]);
564
+ if (values.every(([, value]) => value === null)) {
565
+ error("T05_OBSERVATIONS", "NUMERIC_VALUE_MISSING", "observations", id, "At least one of value_low, value_best or value_high is required");
566
+ }
567
+ for (const [field, value] of values) {
568
+ if (Number.isNaN(value)) error("T05_OBSERVATIONS", "NUMERIC_VALUE_INVALID", "observations", id, `${field} is not a finite number`);
569
+ if (value !== null && isCountMetric(row) && value < 0) error("T05_OBSERVATIONS", "COUNT_NEGATIVE", "observations", id, `${field} is negative for a count/reach metric`);
570
+ }
571
+ const lowValue = parseNumber(row.value_low);
572
+ const bestValue = parseNumber(row.value_best);
573
+ const highValue = parseNumber(row.value_high);
574
+ if (lowValue !== null && bestValue !== null && lowValue > bestValue) {
575
+ error("T05_OBSERVATIONS", "INTERVAL_ORDER", "observations", id, "value_low exceeds value_best");
576
+ }
577
+ if (bestValue !== null && highValue !== null && bestValue > highValue) {
578
+ error("T05_OBSERVATIONS", "INTERVAL_ORDER", "observations", id, "value_best exceeds value_high");
579
+ }
580
+ if (lowValue !== null && highValue !== null && lowValue > highValue) {
581
+ error("T05_OBSERVATIONS", "INTERVAL_ORDER", "observations", id, "value_low exceeds value_high");
582
+ }
583
+ const causalStatus = clean(row.causal_status);
584
+ if (!causalValues.has(causalStatus)) {
585
+ error("T05_OBSERVATIONS", "CAUSAL_STATUS_INVALID", "observations", id, `Unknown causal_status: ${causalStatus}`);
586
+ }
587
+ if (/causal_estimate/.test(causalStatus)) {
588
+ const claim = index.claims.get(clean(row.claim_id));
589
+ if (!claim || !["behavioural_effect", "electoral_effect"].includes(clean(claim.claim_type))) {
590
+ error("T05_OBSERVATIONS", "CAUSAL_CLAIM_TYPE", "observations", id, "A causal estimate must link to a behavioural_effect or electoral_effect claim");
591
+ }
592
+ if (lowValue === null || bestValue === null || highValue === null) {
593
+ error("T05_OBSERVATIONS", "CAUSAL_UNCERTAINTY_MISSING", "observations", id, "A causal estimate requires low, best and high values");
594
+ }
595
+ if (/(official.?result|turnout|administrative total)/i.test(clean(row.measurement_method))) {
596
+ error("T05_OBSERVATIONS", "OFFICIAL_OUTCOME_AS_CAUSAL_DESIGN", "observations", id, "Official results or turnout alone cannot identify a causal effect");
597
+ }
598
+ }
599
+ const metricUnitText = [row.metric_family, row.metric_name, row.unit].join(" ");
600
+ if (/(^|[_ -])(rate|share|percent|percentage|proportion)([_ -]|$)/i.test(metricUnitText)) {
601
+ if (/^(unknown|not_applicable|n\/a)$/i.test(clean(row.denominator))) {
602
+ error("T05_OBSERVATIONS", "RATE_DENOMINATOR_UNKNOWN", "observations", id, "A rate/share/percentage requires an identified denominator");
603
+ }
604
+ const ceiling = /percent|percentage|%/i.test(clean(row.unit)) ? 100 : 1;
605
+ for (const [field, value] of values) {
606
+ if (value !== null && Number.isFinite(value) && (value < 0 || value > ceiling)) {
607
+ error("T05_OBSERVATIONS", "RATE_OUT_OF_RANGE", "observations", id, `${field} is outside 0-${ceiling} for the stated unit`);
608
+ }
609
+ }
610
+ }
611
+ if (!isIsoDate(row.as_of_date)) error("T05_OBSERVATIONS", "OBSERVATION_DATE_INVALID", "observations", id, "as_of_date must be an ISO date");
612
+ }
613
+
614
+ // T06 — platform activity and delivery proxies are never relabelled as unique people or voters.
615
+ const proxyMetric = /(views?|impressions?|accounts?|followers?|posts?|likes?|shares?|comments?|call_attempts?|completed_calls?|submitted_questions?|interactions?|engagements?)/i;
616
+ const uniquePerson = /(unique[_ -]?(person|people|human|user|voter)|deduplicated[_ -]?(person|people|human|user|voter)|^people$|^voters?$)/i;
617
+ for (const row of rows("observations")) {
618
+ const id = rowId(row, "observations");
619
+ const metricText = [row.metric_family, row.metric_name, row.unit].join(" ");
620
+ if (proxyMetric.test(metricText) && uniquePerson.test(clean(row.unique_entity_status))) {
621
+ error("T06_REACH_UNIQUENESS", "PROXY_AS_UNIQUE_PERSON", "observations", id, "A platform/delivery proxy is coded as unique people or voters");
622
+ }
623
+ if (
624
+ proxyMetric.test(metricText) &&
625
+ /\b(?:represents?|counts?|measures?|equals?|is|are)\s+(?:an?\s+)?(?:estimate of\s+)?unique\s+(?:people|persons|users|voters)\b/i.test(clean(row.limitations)) &&
626
+ !/\b(?:not|non-)\s*unique\s+(?:people|persons|users|voters)\b/i.test(clean(row.limitations))
627
+ ) {
628
+ error("T06_REACH_UNIQUENESS", "PROXY_LIMITATION_CONTRADICTION", "observations", id, "Limitations text affirmatively promotes a non-unique proxy to unique-person reach");
629
+ }
630
+ }
631
+ for (const row of rows("research_view")) {
632
+ const id = rowId(row, "research_view");
633
+ const caseObservations = rows("observations").filter((item) => clean(item.case_id) === clean(row.case_id));
634
+ const hasVerifiedUniquePeople = caseObservations.some((item) => uniquePerson.test(clean(item.unique_entity_status)) && !proxyMetric.test([item.metric_family, item.metric_name, item.unit].join(" ")));
635
+ if (/\b\d[\d,.+]*\s+(people|persons|users|voters)\b|\b(reached|exposed)\s+\d[\d,.+]*\s+(people|persons|users|voters)\b/i.test(clean(row.reach_summary)) && !hasVerifiedUniquePeople) {
636
+ error("T06_REACH_UNIQUENESS", "RESEARCH_VIEW_UNIQUE_REACH_UNSUPPORTED", "research_view", id, "Unique-person reach appears in the simple view without a qualifying observation");
637
+ }
638
+ }
639
+
640
+ // T07 — model tests retain their tested system, version, interface and causal scope.
641
+ for (const row of rows("model_evaluations")) {
642
+ const id = rowId(row, "model_evaluations");
643
+ requireNonBlank(
644
+ row,
645
+ [
646
+ "evaluation_window", "election_or_context", "systems_tested", "versions_known", "interface",
647
+ "languages", "sample_unit", "design", "primary_metrics", "headline_results",
648
+ "causal_scope", "source_id", "data_availability", "notes"
649
+ ],
650
+ "T07_MODEL_EVALUATIONS", "model_evaluations", id
651
+ );
652
+ const sampleSize = parseNumber(row.sample_size);
653
+ if (isBlank(row.sample_size)) {
654
+ if (!/(sample|participant|question|prompt|benchmark|row count|output|denominator|experiment|not (?:reported|available|coded)|consult)/i.test([row.design, row.notes, row.data_availability].join(" "))) {
655
+ error("T07_MODEL_EVALUATIONS", "SAMPLE_SIZE_MISSING_UNEXPLAINED", "model_evaluations", id, "Blank sample_size requires a scoped sample/denominator explanation");
656
+ } else {
657
+ warn("T07_MODEL_EVALUATIONS", "SAMPLE_SIZE_NOT_STRUCTURED", "model_evaluations", id, "Sample size is not available as a structured integer; retain study-specific denominators before quantitative synthesis");
658
+ }
659
+ } else if (!Number.isInteger(sampleSize) || sampleSize <= 0) {
660
+ error("T07_MODEL_EVALUATIONS", "SAMPLE_SIZE_INVALID", "model_evaluations", id, "sample_size must be a positive integer for the stated sample unit");
661
+ }
662
+ if (/unknown/i.test(clean(row.versions_known)) && !/(unknown|not visible|not disclosed|unavailable|consumer|version)/i.test([row.notes, row.versions_known, row.causal_scope].join(" "))) {
663
+ error("T07_MODEL_EVALUATIONS", "UNKNOWN_VERSION_SCOPE_UNEXPLAINED", "model_evaluations", id, "Unknown versions must be explained in notes");
664
+ }
665
+ if (!/(not |no |point-in-time|capability|scope|limited|cannot|does not|may differ|laboratory|audit)/i.test(clean(row.causal_scope))) {
666
+ warn("T07_MODEL_EVALUATIONS", "CAUSAL_SCOPE_TOO_VAGUE", "model_evaluations", id, "causal_scope does not contain an explicit non-generalisation or design limitation");
667
+ }
668
+ if (/\b(changed|caused|determined|swung)\b.*\b(actual ballots?|observed votes?|turnout|aggregate election (?:result|outcome)|seats won)\b/i.test(clean(row.headline_results))) {
669
+ error("T07_MODEL_EVALUATIONS", "HEADLINE_CAUSAL_OVERCLAIM", "model_evaluations", id, "Headline results make an election-effect claim that a model evaluation cannot establish on its own");
670
+ }
671
+ const source = index.sources.get(clean(row.source_id));
672
+ if (source && !/(model_evaluation|research|scholarly|methodology|report|peer_reviewed|experiment|benchmark|audit)/i.test(clean(source.source_type))) {
673
+ warn("T07_MODEL_EVALUATIONS", "SOURCE_TYPE_UNEXPECTED", "model_evaluations", id, `Source type does not identify an evaluation or research record: ${clean(source.source_type)}`);
674
+ }
675
+ }
676
+
677
+ // T08 — the denominator of searched elections/regions is explicit and internally counted.
678
+ const framesByRegion = new Map();
679
+ const validSearchStatuses = new Set([
680
+ "complete", "systematic", "substantial", "partial", "partial_search_recorded", "ongoing", "not_started", "gap"
681
+ ]);
682
+ const regionParent = (region) => {
683
+ if (["East Asia", "South Asia", "Southeast Asia", "Central Asia", "West Asia"].includes(region)) return "Asia";
684
+ if (["East Africa", "West Africa", "Southern Africa", "North Africa", "Central Africa"].includes(region)) return "Africa";
685
+ return region;
686
+ };
687
+ for (const row of rows("sampling_frame")) {
688
+ const id = rowId(row, "sampling_frame");
689
+ requireNonBlank(
690
+ row,
691
+ [
692
+ "region", "selection_basis", "search_status", "search_languages", "source_channels",
693
+ "included_case_count", "candidate_count", "negative_search_recorded", "known_gap", "last_searched"
694
+ ],
695
+ "T08_SAMPLING_FRAME", "sampling_frame", id
696
+ );
697
+ const region = clean(row.region);
698
+ if (framesByRegion.has(region)) {
699
+ error("T08_SAMPLING_FRAME", "REGION_DUPLICATE", "sampling_frame", id, `Duplicate sampling-frame region: ${region}`);
700
+ }
701
+ framesByRegion.set(region, row);
702
+ if (!validSearchStatuses.has(clean(row.search_status))) {
703
+ error("T08_SAMPLING_FRAME", "SEARCH_STATUS_INVALID", "sampling_frame", id, `Unknown search_status: ${clean(row.search_status)}`);
704
+ }
705
+ for (const field of ["included_case_count", "candidate_count"]) {
706
+ const number = parseNumber(row[field]);
707
+ if (!Number.isInteger(number) || number < 0) {
708
+ error("T08_SAMPLING_FRAME", "FRAME_COUNT_INVALID", "sampling_frame", id, `${field} must be a non-negative integer`);
709
+ }
710
+ }
711
+ if (!trueValues.has(lower(row.negative_search_recorded)) && !falseValues.has(lower(row.negative_search_recorded))) {
712
+ error("T08_SAMPLING_FRAME", "NEGATIVE_SEARCH_FLAG_INVALID", "sampling_frame", id, "negative_search_recorded must be an explicit boolean");
713
+ } else if (falseValues.has(lower(row.negative_search_recorded))) {
714
+ warn("T08_SAMPLING_FRAME", "NEGATIVE_SEARCH_NOT_RECORDED", "sampling_frame", id, "No negative/null search was recorded for this frame; prevalence inference is unsafe");
715
+ }
716
+ if (!isIsoDate(row.last_searched)) {
717
+ error("T08_SAMPLING_FRAME", "LAST_SEARCHED_INVALID", "sampling_frame", id, "last_searched must be an ISO date");
718
+ } else if (cutoff && clean(row.last_searched) > cutoff) {
719
+ error("T08_SAMPLING_FRAME", "LAST_SEARCHED_AFTER_CUTOFF", "sampling_frame", id, `last_searched is after dataset cutoff ${cutoff}`);
720
+ }
721
+ const actualCases = rows("cases").filter((item) => regionParent(clean(item.region)) === region).length;
722
+ const actualCandidates = rows("candidates").filter((item) => regionParent(clean(item.region)) === region).length;
723
+ if (parseNumber(row.included_case_count) !== actualCases) {
724
+ error("T08_SAMPLING_FRAME", "INCLUDED_COUNT_MISMATCH", "sampling_frame", id, `included_case_count=${clean(row.included_case_count)} but cases.csv has ${actualCases} for ${region}`);
725
+ }
726
+ if (parseNumber(row.candidate_count) !== actualCandidates) {
727
+ error("T08_SAMPLING_FRAME", "CANDIDATE_COUNT_MISMATCH", "sampling_frame", id, `candidate_count=${clean(row.candidate_count)} but candidates.csv has ${actualCandidates} for ${region}`);
728
+ }
729
+ }
730
+ for (const region of [...new Set([...rows("cases"), ...rows("candidates")].map((row) => regionParent(clean(row.region))).filter(Boolean))].sort()) {
731
+ if (!framesByRegion.has(region)) error("T08_SAMPLING_FRAME", "REGION_UNCOVERED", "sampling_frame", region, "Cases or candidates exist without a sampling-frame row");
732
+ }
733
+ if (rows("sampling_frame").length && !rows("sampling_frame").some((row) => trueValues.has(lower(row.negative_search_recorded)))) {
734
+ warn("T08_SAMPLING_FRAME", "NO_NEGATIVE_SEARCH_ANYWHERE", "sampling_frame", null, "The release records no systematic negative/null search in any sampling frame; incident prevalence claims remain unsupported");
735
+ }
736
+
737
+ // T09 — official election status is coherent with the release cutoff.
738
+ const validElectionStatuses = new Set(["completed", "scheduled", "conditional"]);
739
+ const officialDataStatuses = new Set(["current", "final", "pre_election", "scheduled", "not_yet_available"]);
740
+ for (const row of rows("official_data_sources")) {
741
+ const id = rowId(row, "official_data_sources");
742
+ if (!officialDataStatuses.has(clean(row.data_status))) {
743
+ error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_SOURCE_STATUS_INVALID", "official_data_sources", id, `Unknown data_status: ${clean(row.data_status)}`);
744
+ }
745
+ if (!isIsoDate(row.retrieved_at)) {
746
+ error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_SOURCE_DATE_INVALID", "official_data_sources", id, "retrieved_at must be an ISO date");
747
+ } else if (cutoff && clean(row.retrieved_at) > cutoff) {
748
+ error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_SOURCE_AFTER_CUTOFF", "official_data_sources", id, `retrieved_at is after dataset cutoff ${cutoff}`);
749
+ }
750
+ }
751
+ for (const row of rows("official_elections")) {
752
+ const id = rowId(row, "official_elections");
753
+ if (!isIsoDate(row.election_date) || !isIsoDate(row.as_of_date)) {
754
+ error("T09_OFFICIAL_ELECTION_STATUS", "OFFICIAL_DATE_INVALID", "official_elections", id, "election_date and as_of_date must be ISO dates");
755
+ }
756
+ if (!validElectionStatuses.has(clean(row.election_status))) {
757
+ error("T09_OFFICIAL_ELECTION_STATUS", "ELECTION_STATUS_INVALID", "official_elections", id, `Unknown election_status: ${clean(row.election_status)}`);
758
+ }
759
+ const legalStatus = clean(row.legal_result_status);
760
+ if (!/^(not_yet_available|annulled|certified|final)$|(?:validated|confirmed|certified|final|void|annul|mandate|law_adopted)/i.test(legalStatus)) {
761
+ error("T09_OFFICIAL_ELECTION_STATUS", "LEGAL_STATUS_INVALID", "official_elections", id, `legal_result_status does not encode a recognized official chronology: ${legalStatus}`);
762
+ }
763
+ if (cutoff && clean(row.election_date) > cutoff && clean(row.election_status) === "completed") {
764
+ error("T09_OFFICIAL_ELECTION_STATUS", "FUTURE_ELECTION_COMPLETED", "official_elections", id, `Election is after dataset cutoff ${cutoff} but marked completed`);
765
+ }
766
+ if (cutoff && clean(row.election_date) <= cutoff && clean(row.election_status) !== "completed") {
767
+ warn("T09_OFFICIAL_ELECTION_STATUS", "PAST_ELECTION_NOT_COMPLETED", "official_elections", id, `Election is on/before dataset cutoff ${cutoff} but not marked completed`);
768
+ }
769
+ }
770
+
771
+ // T10 — turnout figures are numeric and arithmetically reconcilable.
772
+ function optionalNonNegative(row, field, table, test) {
773
+ if (isBlank(row[field])) return null;
774
+ const value = parseNumber(row[field]);
775
+ if (!Number.isFinite(value) || value < 0) {
776
+ error(test, "NON_NEGATIVE_NUMBER_INVALID", table, rowId(row, table), `${field} must be a non-negative number when present`);
777
+ return null;
778
+ }
779
+ return value;
780
+ }
781
+ const turnoutByElection = new Map();
782
+ for (const row of rows("official_turnout")) {
783
+ const id = rowId(row, "official_turnout");
784
+ requireNonBlank(row, ["electorate_measure", "participation_measure", "data_status", "official_source_id", "as_of_date"], "T10_TURNOUT", "official_turnout", id);
785
+ if (!officialDataStatuses.has(clean(row.data_status))) {
786
+ error("T10_TURNOUT", "TURNOUT_STATUS_INVALID", "official_turnout", id, `Unknown data_status: ${clean(row.data_status)}`);
787
+ }
788
+ const values = {};
789
+ for (const field of ["registered_voters", "ballots_cast", "valid_votes", "invalid_votes", "reporting_units_total", "reporting_units_counted"]) {
790
+ values[field] = optionalNonNegative(row, field, "official_turnout", "T10_TURNOUT");
791
+ }
792
+ if (loaded.get("official_turnout")?.headers.includes("turnout_numerator")) {
793
+ values.turnout_numerator = optionalNonNegative(row, "turnout_numerator", "official_turnout", "T10_TURNOUT");
794
+ }
795
+ if (values.reporting_units_total !== null && values.reporting_units_counted !== null && values.reporting_units_counted > values.reporting_units_total) {
796
+ error("T10_TURNOUT", "REPORTING_UNITS_EXCEED_TOTAL", "official_turnout", id, "reporting_units_counted exceeds reporting_units_total");
797
+ }
798
+ if (!isBlank(row.turnout_rate)) {
799
+ const rate = parseNumber(row.turnout_rate);
800
+ if (!Number.isFinite(rate) || rate < 0 || rate > 1) {
801
+ error("T10_TURNOUT", "TURNOUT_RATE_INVALID", "official_turnout", id, "turnout_rate must be between 0 and 1");
802
+ } else if (values.registered_voters > 0 && (values.turnout_numerator ?? values.ballots_cast) !== null) {
803
+ const numerator = values.turnout_numerator ?? values.ballots_cast;
804
+ const derived = numerator / values.registered_voters;
805
+ if (Math.abs(rate - derived) > 0.0001) {
806
+ error("T10_TURNOUT", "TURNOUT_RATE_DENOMINATOR_MISMATCH", "official_turnout", id, `turnout_rate=${rate} but stated turnout numerator/registered_voters=${derived}`);
807
+ }
808
+ }
809
+ }
810
+ if (values.ballots_cast !== null && values.valid_votes !== null && values.invalid_votes !== null) {
811
+ const derived = values.valid_votes + values.invalid_votes;
812
+ if (values.ballots_cast !== derived && !/(differ|reconcil|special ballot|blank vote)/i.test(clean(row.notes))) {
813
+ error("T10_TURNOUT", "BALLOT_ARITHMETIC", "official_turnout", id, `ballots_cast=${values.ballots_cast} but valid_votes+invalid_votes=${derived}; no reconciliation note`);
814
+ }
815
+ }
816
+ const election = index.official_elections.get(clean(row.election_id));
817
+ if (cutoff && election && clean(election.election_date) > cutoff && clean(row.data_status) === "final") {
818
+ error("T10_TURNOUT", "FUTURE_FINAL_TURNOUT", "official_turnout", id, "Future election has final turnout data");
819
+ }
820
+ if (!turnoutByElection.has(clean(row.election_id))) turnoutByElection.set(clean(row.election_id), []);
821
+ turnoutByElection.get(clean(row.election_id)).push(row);
822
+ }
823
+
824
+ // T11 — official result shares, totals and temporal status are coherent.
825
+ const coverageStatuses = new Set(["complete", "complete_national_contest", "partial"]);
826
+ const completeGroups = new Map();
827
+ for (const row of rows("official_results")) {
828
+ const id = rowId(row, "official_results");
829
+ requireNonBlank(
830
+ row,
831
+ ["votes", "valid_vote_share", "result_status", "coverage_status", "official_source_id", "as_of_date"],
832
+ "T11_OFFICIAL_RESULTS", "official_results", id
833
+ );
834
+ const resultStatus = clean(row.result_status);
835
+ if (!/^(final|certified|annulled)$|(?:final|validat|confirm|certif|void|annul)/i.test(resultStatus)) {
836
+ error("T11_OFFICIAL_RESULTS", "RESULT_STATUS_INVALID", "official_results", id, `result_status does not encode a recognized official chronology: ${resultStatus}`);
837
+ }
838
+ if (!coverageStatuses.has(clean(row.coverage_status))) {
839
+ error("T11_OFFICIAL_RESULTS", "COVERAGE_STATUS_INVALID", "official_results", id, `Unknown coverage_status: ${clean(row.coverage_status)}`);
840
+ }
841
+ const votes = optionalNonNegative(row, "votes", "official_results", "T11_OFFICIAL_RESULTS");
842
+ const share = parseNumber(row.valid_vote_share);
843
+ if (!Number.isFinite(share) || share < 0 || share > 1) {
844
+ error("T11_OFFICIAL_RESULTS", "VOTE_SHARE_INVALID", "official_results", id, "valid_vote_share must be between 0 and 1");
845
+ }
846
+ const rank = parseNumber(row.rank);
847
+ if (!isBlank(row.rank) && (!Number.isInteger(rank) || rank <= 0)) {
848
+ error("T11_OFFICIAL_RESULTS", "RANK_INVALID", "official_results", id, "rank must be a positive integer when present");
849
+ }
850
+ if (isBlank(row.rank) && !/excluded|invalidated|withdrawn|not_ranked/i.test(clean(row.outcome))) {
851
+ error("T11_OFFICIAL_RESULTS", "RANK_MISSING", "official_results", id, "rank may be blank only for an explicitly excluded, invalidated, withdrawn or unranked option");
852
+ }
853
+ const election = index.official_elections.get(clean(row.election_id));
854
+ if (cutoff && election && clean(election.election_date) > cutoff) {
855
+ error("T11_OFFICIAL_RESULTS", "FUTURE_RESULT_ROW", "official_results", id, "Future election has an official result row");
856
+ }
857
+ if (["complete", "complete_national_contest"].includes(clean(row.coverage_status))) {
858
+ const key = [row.election_id, row.geographic_unit_type, row.geographic_unit_code, row.contest_name].map(clean).join("::");
859
+ if (!completeGroups.has(key)) completeGroups.set(key, []);
860
+ completeGroups.get(key).push({ row, votes, share });
861
+ }
862
+ }
863
+ const nationalCompleteGroupsByElection = new Map();
864
+ for (const [key, group] of completeGroups) {
865
+ const shares = group.map((item) => item.share);
866
+ if (shares.every(Number.isFinite)) {
867
+ const total = shares.reduce((sum, value) => sum + value, 0);
868
+ if (Math.abs(total - 1) > 0.001) error("T11_OFFICIAL_RESULTS", "COMPLETE_SHARES_NOT_ONE", "official_results", key, `Complete-group shares sum to ${total}, not 1`);
869
+ }
870
+ if (clean(group[0].row.geographic_unit_type) === "national") {
871
+ const electionId = clean(group[0].row.election_id);
872
+ if (!nationalCompleteGroupsByElection.has(electionId)) nationalCompleteGroupsByElection.set(electionId, []);
873
+ nationalCompleteGroupsByElection.get(electionId).push(group);
874
+ }
875
+ }
876
+ for (const [electionId, groups] of nationalCompleteGroupsByElection) {
877
+ const nationalTurnouts = (turnoutByElection.get(electionId) || []).filter((row) => clean(row.geographic_unit_type) === "national" && !isBlank(row.valid_votes));
878
+ if (groups.length === 1 && nationalTurnouts.length === 1) {
879
+ const voteTotal = groups[0].reduce((sum, item) => sum + (item.votes ?? 0), 0);
880
+ const validVotes = parseNumber(nationalTurnouts[0].valid_votes);
881
+ if (Number.isFinite(validVotes) && voteTotal !== validVotes) {
882
+ error("T11_OFFICIAL_RESULTS", "RESULT_TURNOUT_TOTAL_MISMATCH", "official_results", electionId, `Complete national results total ${voteTotal}; official_turnout valid_votes=${validVotes}`);
883
+ }
884
+ } else if (groups.length > 1 && nationalTurnouts.length) {
885
+ warn("T11_OFFICIAL_RESULTS", "MULTIPLE_NATIONAL_CONTESTS", "official_results", electionId, "Multiple complete national contests prevent an automatic result-to-turnout total match");
886
+ }
887
+ }
888
+
889
+ // T12 — simple researcher view and coverage summaries reproduce the underlying rows.
890
+ const researchViewKeys = new Set();
891
+ for (const row of rows("research_view")) {
892
+ const id = rowId(row, "research_view");
893
+ requireNonBlank(
894
+ row,
895
+ [
896
+ "case_id", "pathway_id", "record_type", "manipulation_assessment", "controller",
897
+ "influence_vector", "target", "affected_agency", "agency_transfer_status",
898
+ "power_recipient", "evidence_strength"
899
+ ],
900
+ "T12_DERIVED_VIEWS", "research_view", id
901
+ );
902
+ const key = `${clean(row.case_id)}::${clean(row.pathway_id)}`;
903
+ if (researchViewKeys.has(key)) error("T12_DERIVED_VIEWS", "RESEARCH_VIEW_DUPLICATE", "research_view", id, `Duplicate case/pathway row: ${key}`);
904
+ researchViewKeys.add(key);
905
+ const parent = index.cases.get(clean(row.case_id));
906
+ const pathway = index.pathways.get(clean(row.pathway_id));
907
+ if (parent && clean(parent.record_type) !== clean(row.record_type)) {
908
+ error("T12_DERIVED_VIEWS", "VIEW_RECORD_TYPE_MISMATCH", "research_view", id, "record_type differs from cases.csv");
909
+ }
910
+ if (parent && clean(parent.manipulation_assessment) !== clean(row.manipulation_assessment)) {
911
+ error("T12_DERIVED_VIEWS", "VIEW_MANIPULATION_MISMATCH", "research_view", id, "manipulation_assessment differs from cases.csv");
912
+ }
913
+ if (pathway && clean(pathway.agency_transfer_status) !== clean(row.agency_transfer_status)) {
914
+ error("T12_DERIVED_VIEWS", "VIEW_AGENCY_STATUS_MISMATCH", "research_view", id, "agency_transfer_status differs from pathways.csv");
915
+ }
916
+ }
917
+ for (const row of rows("pathways")) {
918
+ const key = `${clean(row.case_id)}::${clean(row.pathway_id)}`;
919
+ if (!researchViewKeys.has(key)) error("T12_DERIVED_VIEWS", "PATHWAY_MISSING_FROM_VIEW", "research_view", clean(row.pathway_id), "Every pathway must appear once in research_view.csv");
920
+ }
921
+ const coverageRegions = new Set();
922
+ for (const row of rows("coverage_summary")) {
923
+ const region = clean(row.region);
924
+ if (coverageRegions.has(region)) error("T12_DERIVED_VIEWS", "COVERAGE_REGION_DUPLICATE", "coverage_summary", region, "Duplicate coverage-summary region");
925
+ coverageRegions.add(region);
926
+ const actualCases = rows("cases").filter((item) => regionParent(clean(item.region)) === region).length;
927
+ const actualCandidates = rows("candidates").filter((item) => regionParent(clean(item.region)) === region).length;
928
+ const actualEvaluations = rows("case_catalog").filter(
929
+ (item) => clean(item.record_layer) === "empirical_model_study" && clean(item.region) === region
930
+ ).length;
931
+ if (parseNumber(row.included_case_count) !== actualCases) {
932
+ error("T12_DERIVED_VIEWS", "COVERAGE_CASE_COUNT_MISMATCH", "coverage_summary", region, `included_case_count differs from cases.csv (${actualCases})`);
933
+ }
934
+ if (parseNumber(row.candidate_count) !== actualCandidates) {
935
+ error("T12_DERIVED_VIEWS", "COVERAGE_CANDIDATE_COUNT_MISMATCH", "coverage_summary", region, `candidate_count differs from candidates.csv (${actualCandidates})`);
936
+ }
937
+ // model_evaluations stores country rather than region; only enforce a numeric count here.
938
+ const statedEvaluations = parseNumber(row.model_evaluation_count);
939
+ if (!Number.isInteger(statedEvaluations) || statedEvaluations < 0) {
940
+ error("T12_DERIVED_VIEWS", "COVERAGE_EVALUATION_COUNT_INVALID", "coverage_summary", region, "model_evaluation_count must be a non-negative integer");
941
+ } else if (statedEvaluations !== actualEvaluations) {
942
+ error("T12_DERIVED_VIEWS", "COVERAGE_EVALUATION_COUNT_MISMATCH", "coverage_summary", region, `model_evaluation_count differs from empirical-model rows in case_catalog.csv (${actualEvaluations})`);
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")) {
950
+ const key = `${clean(row.claim_id)}::${clean(row.source_id)}`;
951
+ if (!evidenceRelationsByClaimSource.has(key)) evidenceRelationsByClaimSource.set(key, new Set());
952
+ evidenceRelationsByClaimSource.get(key).add(clean(row.relation));
953
+ }
954
+ for (const claim of rows("claims")) {
955
+ for (const sourceId of ids(claim.source_ids)) {
956
+ const prefix = `${clean(claim.claim_id)}::${sourceId}::`;
957
+ if (![...evidencePairs].some((pair) => pair.startsWith(prefix))) {
958
+ error("T03_FOREIGN_KEYS", "CLAIM_EVIDENCE_JOIN_MISSING", "claim_evidence", clean(claim.claim_id), `Supporting source is absent from normalized join: ${sourceId}`);
959
+ }
960
+ }
961
+ for (const sourceId of ids(claim.counter_source_ids)) {
962
+ const relations = evidenceRelationsByClaimSource.get(`${clean(claim.claim_id)}::${sourceId}`) || new Set();
963
+ if (![...relations].some((relation) => /counter|qualif/i.test(relation))) {
964
+ error("T03_FOREIGN_KEYS", "COUNTEREVIDENCE_JOIN_MISSING", "claim_evidence", clean(claim.claim_id), `Counter-source is absent or not labelled counterevidence: ${sourceId}`);
965
+ }
966
+ }
967
+ }
968
+
969
+ // Reciprocity between the normalized case-election join and the legacy official link list.
970
+ const normalizedCaseElections = new Set(rows("case_elections").map((row) => `${clean(row.case_id)}::${clean(row.election_id)}`));
971
+ for (const election of rows("official_elections")) {
972
+ for (const caseId of ids(election.linked_case_ids)) {
973
+ const pair = `${caseId}::${clean(election.election_id)}`;
974
+ if (!normalizedCaseElections.has(pair)) {
975
+ error("T03_FOREIGN_KEYS", "CASE_ELECTION_JOIN_MISSING", "case_elections", pair, "Official linked_case_ids entry is absent from case_elections.csv");
976
+ }
977
+ }
978
+ }
979
+ for (const row of rows("case_elections")) {
980
+ const election = index.official_elections.get(clean(row.election_id));
981
+ if (election && !ids(election.linked_case_ids).includes(clean(row.case_id))) {
982
+ error("T03_FOREIGN_KEYS", "CASE_ELECTION_NOT_RECIPROCAL", "case_elections", rowId(row, "case_elections"), "Normalized join is absent from official_elections.linked_case_ids");
983
+ }
984
+ }
985
+ for (const caseRow of rows("cases")) {
986
+ if (![...normalizedCaseElections].some((pair) => pair.startsWith(`${clean(caseRow.case_id)}::`))) {
987
+ error("T03_FOREIGN_KEYS", "CASE_WITHOUT_ELECTION", "case_elections", clean(caseRow.case_id), "Every case must link to at least one official election/context row");
988
+ }
989
+ }
990
+
991
+ function stableIssueOrder(a, b) {
992
+ return (
993
+ a.test.localeCompare(b.test) ||
994
+ a.code.localeCompare(b.code) ||
995
+ String(a.table).localeCompare(String(b.table)) ||
996
+ String(a.row_id).localeCompare(String(b.row_id)) ||
997
+ a.message.localeCompare(b.message)
998
+ );
999
+ }
1000
+ 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,
1011
+ table_row_counts: tableCounts
1012
+ },
1013
+ errors: blocking,
1014
+ warnings: advisory
1015
+ };
1016
+
1017
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
1018
+ if (blocking.length) process.exitCode = 1;
scripts/build-data.mjs CHANGED
@@ -9,14 +9,29 @@ const seedPath = path.join(root, "research", "seed.json");
9
  const candidatesPath = path.join(root, "research", "candidates.json");
10
  const europeCandidatesPath = path.join(root, "research", "europe_candidates.json");
11
  const officialElectoralDataPath = path.join(root, "research", "official_electoral_data.json");
 
12
  const outDir = path.join(root, "data");
13
  const seed = JSON.parse(fs.readFileSync(seedPath, "utf8"));
14
  const officialElectoralData = JSON.parse(fs.readFileSync(officialElectoralDataPath, "utf8"));
 
15
  seed.candidates = [
16
  ...JSON.parse(fs.readFileSync(candidatesPath, "utf8")),
17
- ...JSON.parse(fs.readFileSync(europeCandidatesPath, "utf8"))
 
18
  ];
19
  Object.assign(seed, officialElectoralData);
 
 
 
 
 
 
 
 
 
 
 
 
20
  seed.events = [...seed.events].sort(
21
  (a, b) => a.event_date.localeCompare(b.event_date) || a.event_id.localeCompare(b.event_id)
22
  );
@@ -25,7 +40,8 @@ const schemas = {
25
  cases: [
26
  "case_id", "case_family_id", "title", "country", "iso3", "region",
27
  "election_name", "election_type", "election_date_start", "election_date_end",
28
- "case_status", "as_of_date", "anchor_case", "summary", "actor_controlling_system",
 
29
  "actor_type", "actor_attribution_status", "target_population", "influence_vector",
30
  "platforms", "mechanism_class", "ai_role", "generative_ai_status",
31
  "affected_state", "agency_transfer_path", "power_concentrated_in", "democratic_harm",
@@ -36,13 +52,14 @@ const schemas = {
36
  ],
37
  claims: [
38
  "claim_id", "case_id", "claim_type", "claim_text", "evidence_label",
39
- "confidence", "source_ids", "counter_source_ids", "notes", "review_status",
40
- "verified_at"
41
  ],
42
  sources: [
43
  "source_id", "title", "publisher", "author", "publication_date", "url",
44
  "source_type", "primary_secondary", "jurisdiction", "language",
45
- "source_quality", "retrieved_at", "notes"
 
46
  ],
47
  events: [
48
  "event_id", "case_id", "event_date", "event_type", "description",
@@ -72,24 +89,433 @@ const schemas = {
72
  official_turnout: [
73
  "turnout_id", "election_id", "geographic_unit_type", "geographic_unit_code",
74
  "geographic_unit_name", "data_status", "electorate_measure", "participation_measure",
75
- "registered_voters", "ballots_cast",
 
76
  "valid_votes", "invalid_votes", "turnout_rate", "reporting_units_total",
77
  "reporting_units_counted", "official_source_id", "as_of_date", "notes"
78
  ],
79
  official_results: [
80
  "result_id", "election_id", "geographic_unit_type", "geographic_unit_code",
81
  "geographic_unit_name", "contest_name", "candidate_or_option",
82
- "party_or_affiliation", "votes", "valid_vote_share", "rank", "outcome",
83
  "result_status", "coverage_status", "official_source_id", "as_of_date", "notes"
84
  ],
85
  official_data_sources: [
86
  "official_source_id", "case_family_id", "jurisdiction", "electoral_institution",
87
  "title", "url", "dataset_role", "data_status", "format",
88
  "geographic_granularity", "access_method", "update_frequency",
89
- "license_or_terms", "retrieved_at", "notes"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  ]
91
  };
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  function csvCell(value) {
94
  if (value === null || value === undefined) return "";
95
  const s = Array.isArray(value) ? value.join("|") : String(value);
@@ -132,6 +558,17 @@ assertUnique(seed.official_elections, "election_id", "official_elections");
132
  assertUnique(seed.official_turnout, "turnout_id", "official_turnout");
133
  assertUnique(seed.official_results, "result_id", "official_results");
134
  assertUnique(seed.official_data_sources, "official_source_id", "official_data_sources");
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  for (const claim of seed.claims) {
137
  if (!caseIds.has(claim.case_id)) throw new Error("Unknown case in claim " + claim.claim_id);
@@ -182,6 +619,25 @@ for (const row of seed.official_results) {
182
  if (!electionIds.has(row.election_id)) throw new Error("Unknown election in official_results " + row.result_id);
183
  if (!officialSourceIds.has(row.official_source_id)) throw new Error("Unknown official source in official_results " + row.result_id);
184
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
  fs.mkdirSync(outDir, { recursive: true });
187
  const fileHashes = {};
@@ -196,6 +652,71 @@ const schemaText = JSON.stringify(schemas, null, 2) + "\n";
196
  fs.writeFileSync(path.join(outDir, "schema.json"), schemaText);
197
  fileHashes["schema.json"] = sha256(schemaText);
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  const counts = Object.fromEntries(Object.keys(schemas).map((table) => [table, seed[table].length]));
200
  const stats = {
201
  ...counts,
@@ -204,7 +725,8 @@ const stats = {
204
  "research/seed.json": sha256(fs.readFileSync(seedPath)),
205
  "research/candidates.json": sha256(fs.readFileSync(candidatesPath)),
206
  "research/europe_candidates.json": sha256(fs.readFileSync(europeCandidatesPath)),
207
- "research/official_electoral_data.json": sha256(fs.readFileSync(officialElectoralDataPath))
 
208
  },
209
  file_sha256: fileHashes
210
  }
 
9
  const candidatesPath = path.join(root, "research", "candidates.json");
10
  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"));
17
  seed.candidates = [
18
  ...JSON.parse(fs.readFileSync(candidatesPath, "utf8")),
19
+ ...JSON.parse(fs.readFileSync(europeCandidatesPath, "utf8")),
20
+ ...extensions.additional_candidates
21
  ];
22
  Object.assign(seed, officialElectoralData);
23
+ seed.cases = [...seed.cases, ...extensions.additional_cases].map((row) => ({
24
+ ...row,
25
+ ...(extensions.case_metadata[row.case_id] || {})
26
+ }));
27
+ seed.claims = [...seed.claims, ...extensions.additional_claims];
28
+ seed.sources = [...seed.sources, ...extensions.additional_sources];
29
+ seed.events = [...seed.events, ...extensions.additional_events];
30
+ seed.case_sources = [...seed.case_sources, ...extensions.additional_case_sources];
31
+ const usElection = seed.official_elections.find((row) => row.election_id === "elec-us-midterms-2026");
32
+ if (usElection && !usElection.linked_case_ids.includes("us-ca11-2026-wiener-conniechan-chatbot")) {
33
+ usElection.linked_case_ids += "|us-ca11-2026-wiener-conniechan-chatbot";
34
+ }
35
  seed.events = [...seed.events].sort(
36
  (a, b) => a.event_date.localeCompare(b.event_date) || a.event_id.localeCompare(b.event_id)
37
  );
 
40
  cases: [
41
  "case_id", "case_family_id", "title", "country", "iso3", "region",
42
  "election_name", "election_type", "election_date_start", "election_date_end",
43
+ "case_status", "as_of_date", "anchor_case", "record_type", "manipulation_assessment",
44
+ "summary", "actor_controlling_system",
45
  "actor_type", "actor_attribution_status", "target_population", "influence_vector",
46
  "platforms", "mechanism_class", "ai_role", "generative_ai_status",
47
  "affected_state", "agency_transfer_path", "power_concentrated_in", "democratic_harm",
 
52
  ],
53
  claims: [
54
  "claim_id", "case_id", "claim_type", "claim_text", "evidence_label",
55
+ "confidence", "coder_confidence_in_label", "claim_status", "evidence_strength",
56
+ "source_ids", "counter_source_ids", "notes", "review_status", "verified_at"
57
  ],
58
  sources: [
59
  "source_id", "title", "publisher", "author", "publication_date", "url",
60
  "source_type", "primary_secondary", "jurisdiction", "language",
61
+ "source_quality", "source_independence", "method_transparency", "access_status",
62
+ "archive_url", "content_hash", "retrieved_at", "notes"
63
  ],
64
  events: [
65
  "event_id", "case_id", "event_date", "event_type", "description",
 
89
  official_turnout: [
90
  "turnout_id", "election_id", "geographic_unit_type", "geographic_unit_code",
91
  "geographic_unit_name", "data_status", "electorate_measure", "participation_measure",
92
+ "registered_voters", "ballots_cast", "turnout_numerator", "turnout_numerator_measure",
93
+ "authority_reported_turnout_rate",
94
  "valid_votes", "invalid_votes", "turnout_rate", "reporting_units_total",
95
  "reporting_units_counted", "official_source_id", "as_of_date", "notes"
96
  ],
97
  official_results: [
98
  "result_id", "election_id", "geographic_unit_type", "geographic_unit_code",
99
  "geographic_unit_name", "contest_name", "candidate_or_option",
100
+ "party_or_affiliation", "ballot_designating_entity", "votes", "valid_vote_share", "rank", "outcome", "seats",
101
  "result_status", "coverage_status", "official_source_id", "as_of_date", "notes"
102
  ],
103
  official_data_sources: [
104
  "official_source_id", "case_family_id", "jurisdiction", "electoral_institution",
105
  "title", "url", "dataset_role", "data_status", "format",
106
  "geographic_granularity", "access_method", "update_frequency",
107
+ "license_or_terms", "landing_url", "download_url", "published_or_updated_at",
108
+ "retrieved_at", "content_sha256", "content_bytes", "source_schema_version",
109
+ "snapshot_cutoff", "notes"
110
+ ],
111
+ official_election_metrics: [
112
+ "metric_id", "election_id", "geographic_unit_type", "geographic_unit_code",
113
+ "metric_code", "value", "source_field_code", "source_label_original",
114
+ "numerator_metric", "denominator_metric", "authority_reported_rate", "computed_rate",
115
+ "legal_role", "data_status", "official_source_id", "as_of_date", "notes"
116
+ ],
117
+ research_view: [
118
+ "pathway_id", "case_id", "case_title", "country", "election_date", "record_type",
119
+ "case_status", "manipulation_assessment", "generative_ai_status", "ai_role",
120
+ "system_or_model", "controller", "influence_vector", "target", "affected_agency",
121
+ "agency_transfer_status", "power_recipient", "reach_summary", "behavioural_effect",
122
+ "electoral_effect", "evidence_strength", "main_uncertainty", "last_verified"
123
+ ],
124
+ case_catalog: [
125
+ "catalog_id", "record_layer", "record_type", "title", "country", "region",
126
+ "election_name", "election_date", "case_status", "manipulation_assessment",
127
+ "ai_role", "generative_ai_status", "evidence_maturity", "incident_count_eligible",
128
+ "research_status", "source_count_or_links", "main_caveat", "last_checked"
129
+ ],
130
+ case_actors: [
131
+ "case_actor_id", "case_id", "actor_name", "actor_role", "actor_type",
132
+ "attribution_status", "control_dimension", "source_claim_ids", "notes"
133
+ ],
134
+ technology_uses: [
135
+ "tech_use_id", "case_id", "provider", "product_or_model", "version",
136
+ "access_type", "technology_role", "use_status", "provenance_status",
137
+ "evidence_label", "source_claim_ids", "notes"
138
+ ],
139
+ content_items: [
140
+ "content_item_id", "case_id", "title", "media_type", "represented_person",
141
+ "communication_goal", "representation_mode", "ai_disclosure", "authorization_status",
142
+ "disclosure_salience", "presentation_mode", "source_claim_ids", "notes"
143
+ ],
144
+ pathways: [
145
+ "pathway_id", "case_id", "affected_agency", "control_shift_from", "control_shift_to",
146
+ "mechanism", "opacity", "personalization", "contestability", "duration",
147
+ "power_recipient", "harm_pathway", "observed_outcome", "agency_transfer_status",
148
+ "assessment_label", "source_claim_ids", "reviewer_note"
149
+ ],
150
+ observations: [
151
+ "observation_id", "case_id", "pathway_id", "claim_id", "metric_family", "metric_name",
152
+ "value_low", "value_best", "value_high", "value_operator", "unit", "denominator",
153
+ "unique_entity_status", "platform", "geographic_scope", "measurement_window",
154
+ "measurement_method", "causal_status", "source_id", "as_of_date", "limitations"
155
+ ],
156
+ model_evaluations: [
157
+ "evaluation_id", "title", "country", "evaluation_window", "election_or_context",
158
+ "systems_tested", "versions_known", "interface", "languages", "sample_unit",
159
+ "sample_size", "design", "primary_metrics", "headline_results", "causal_scope",
160
+ "source_id", "data_availability", "notes"
161
+ ],
162
+ claim_evidence: [
163
+ "claim_evidence_id", "claim_id", "source_id", "relation", "evidence_scope",
164
+ "directness", "locator", "extracted_at"
165
+ ],
166
+ analytic_record_claims: [
167
+ "record_claim_id", "record_type", "record_id", "case_id", "claim_id", "relation"
168
+ ],
169
+ case_elections: [
170
+ "case_election_id", "case_id", "election_id", "relation"
171
+ ],
172
+ election_sources: [
173
+ "election_source_id", "election_id", "official_source_id", "source_role"
174
+ ],
175
+ sampling_frame: [
176
+ "frame_id", "region", "selection_basis", "search_status", "search_languages",
177
+ "source_channels", "included_case_count", "candidate_count", "negative_search_recorded",
178
+ "known_gap", "last_searched"
179
+ ],
180
+ coverage_summary: [
181
+ "region", "included_case_count", "candidate_count", "model_evaluation_count", "coverage_note"
182
  ]
183
  };
184
 
185
+ function rowsFromArrays(rows, columns) {
186
+ return rows.map((values) => Object.fromEntries(columns.map((column, index) => [column, values[index] ?? ""])));
187
+ }
188
+
189
+ function appendPipe(value, item) {
190
+ const items = new Set(String(value || "").split("|").filter(Boolean));
191
+ items.add(item);
192
+ return [...items].join("|");
193
+ }
194
+
195
+ function regionForCountry(country) {
196
+ const map = {
197
+ Romania: "Europe", Moldova: "Europe", Hungary: "Europe", "United Kingdom": "Europe",
198
+ "European Union": "Europe", Brazil: "South America", Colombia: "South America",
199
+ Ecuador: "South America", Canada: "North America", "United States": "North America",
200
+ Japan: "Asia", Australia: "Oceania", Poland: "Europe"
201
+ };
202
+ if (String(country).includes("|")) return "Cross-national";
203
+ return map[country] || "Other";
204
+ }
205
+
206
+ function canonicalRegion(region) {
207
+ if (["East Asia", "South Asia", "Southeast Asia", "Central Asia", "West Asia"].includes(region)) return "Asia";
208
+ if (["East Africa", "West Africa", "Southern Africa", "North Africa", "Central Africa"].includes(region)) return "Africa";
209
+ return region;
210
+ }
211
+
212
+ const additionalOfficialSources = [
213
+ ["off-ro-2024-ccr-h31", "romania-presidential-2024-2025", "Romania", "Constitutional Court of Romania", "Decision 31 of 2 December 2024 confirming and validating the first-round result", "https://legislatie.just.ro/public/DetaliiDocument/291969", "legal_validation_and_complete_results", "final", "HTML legal record", "national", "landing page", "finalized election record", "official legal record", "2026-08-12", "H31 established the valid first-round order before H32 later voided the entire process."],
214
+ ["off-ro-2025-ccr-h39", "romania-presidential-2024-2025", "Romania", "Constitutional Court of Romania", "Decision 39 of 9 May 2025 confirming and validating the repeat first round", "https://www.ccr.ro/wp-content/uploads/2025/05/Hotarare_39_2025.pdf", "legal_validation_and_complete_results", "final", "PDF", "national", "direct download", "finalized election record", "official legal record", "2026-08-12", "Complete 11-candidate result."],
215
+ ["off-ro-2025-ccr-h43", "romania-presidential-2024-2025", "Romania", "Constitutional Court of Romania", "Decision 43 of 22 May 2025 confirming and validating the second round", "https://www.ccr.ro/wp-content/uploads/2025/05/Hotarare_43_2025.pdf", "legal_validation", "final", "PDF", "national", "direct download", "finalized election record", "official legal record", "2026-08-12", "Second-round confirmation."],
216
+ ["off-ro-2025-ccr-h44", "romania-presidential-2024-2025", "Romania", "Constitutional Court of Romania", "Decision 44 of 22 May 2025 validating the election of Nicușor Dan", "https://www.ccr.ro/wp-content/uploads/2025/05/Hotarare_44_2025.pdf", "winner_validation", "final", "PDF", "national", "direct download", "finalized election record", "official legal record", "2026-08-12", "Validation of president-elect."],
217
+ ["off-md-2024-ref-cc-h24", "moldova-elections-2024-2025", "Moldova", "Constitutional Court of Moldova", "Decision 24 confirming the 2024 constitutional referendum", "https://constcourt.md/ccdocview.php?docid=866&l=ro&tip=hotariri", "legal_validation_and_turnout_definition", "final", "HTML legal record", "national", "landing page", "finalized election record", "official legal record", "2026-08-12", "Defines the referendum validity calculation and confirms adoption."],
218
+ ["off-md-2024-pres-cc-h25", "moldova-elections-2024-2025", "Moldova", "Constitutional Court of Moldova", "Decision 25 confirming the 2024 presidential election", "https://constcourt.md/ccdocview.php?docid=867&l=ro&tip=hotariri", "legal_validation_complete_results_and_turnout_definition", "final", "HTML legal record", "national", "landing page", "finalized election record", "official legal record", "2026-08-12", "Distinguishes protocol fields C and D and confirms both rounds."],
219
+ ["off-md-2025-cec-h4149", "moldova-elections-2024-2025", "Moldova", "Central Electoral Commission of Moldova", "Decision 4149 centralizing the 28 September 2025 parliamentary results", "https://a.cec.md/index.php/ro/cu-privire-la-centralizarea-rezultatelor-alegerilor-parlamentare-din-28-septembr-2751_115473.html", "turnout_and_complete_results_landing", "final", "HTML with attachments", "national and precinct", "landing page", "finalized election record", "official record", "2026-08-12", "Pairs the opaque workbook download with its decision page."],
220
+ ["off-md-2025-cec-h4151", "moldova-elections-2024-2025", "Moldova", "Central Electoral Commission of Moldova", "Decision 4151 allocating parliamentary mandates", "https://a.cec.md/index.php/ro/cu-privire-la-atribuirea-mandatelor-de-deputat-in-parlamentul-republicii-2751_115476.html", "seat_allocation", "final", "HTML with attachments", "national", "landing page", "finalized election record", "official record", "2026-08-12", "Official seat allocation."],
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 || "",
238
+ source_schema_version: row.source_schema_version || "",
239
+ snapshot_cutoff: row.snapshot_cutoff || "2026-08-12"
240
+ }));
241
+
242
+ const officialSourceById = new Map(seed.official_data_sources.map((row) => [row.official_source_id, row]));
243
+ const oldH32 = officialSourceById.get("off-ro-2024-ccr-annulment");
244
+ if (oldH32) {
245
+ oldH32.url = "https://legislatie.just.ro/Public/DetaliiDocumentAfis/292099";
246
+ oldH32.title = "Decision 32 of 6 December 2024 voiding the entire presidential electoral process";
247
+ }
248
+
249
+ for (const election of seed.official_elections) {
250
+ if (election.election_id === "elec-ro-pres-2024-r1") {
251
+ election.legal_result_status = "validated_then_void";
252
+ election.official_source_ids = appendPipe(election.official_source_ids, "off-ro-2024-ccr-h31");
253
+ election.notes = "H31 first confirmed and validated the final first-round tally; H32 subsequently voided the entire process. Preserve final tally, validation, and process status separately.";
254
+ }
255
+ if (election.election_id === "elec-ro-pres-2025-r1") {
256
+ election.legal_result_status = "CCR_confirmed_and_validated_2025-05-09";
257
+ election.official_source_ids = appendPipe(election.official_source_ids, "off-ro-2025-ccr-h39");
258
+ }
259
+ if (election.election_id === "elec-ro-pres-2025-r2") {
260
+ election.legal_result_status = "CCR_confirmed_and_president_elected_2025-05-22";
261
+ election.official_source_ids = appendPipe(appendPipe(election.official_source_ids, "off-ro-2025-ccr-h43"), "off-ro-2025-ccr-h44");
262
+ }
263
+ if (election.election_id === "elec-md-pres-2024-r1" || election.election_id === "elec-md-pres-2024-r2") {
264
+ election.legal_result_status = "CEC_final_and_Constitutional_Court_confirmed";
265
+ election.official_source_ids = appendPipe(election.official_source_ids, "off-md-2024-pres-cc-h25");
266
+ }
267
+ if (election.election_id === "elec-md-referendum-2024") {
268
+ election.legal_result_status = "law_adopted_and_Constitutional_Court_confirmed";
269
+ election.official_source_ids = appendPipe(election.official_source_ids, "off-md-2024-ref-cc-h24");
270
+ election.notes = "Question: Susțineți modificarea Constituției în vederea aderării Republicii Moldova la Uniunea Europeană? Validity threshold: one third; law adopted and confirmed.";
271
+ }
272
+ if (election.election_id === "elec-md-parl-2025") {
273
+ election.legal_result_status = "CEC_valid_Constitutional_Court_confirmed_101_mandates";
274
+ election.official_source_ids = appendPipe(appendPipe(appendPipe(election.official_source_ids, "off-md-2025-cec-h4149"), "off-md-2025-cec-h4151"), "off-md-2025-cc-h12");
275
+ }
276
+ if (election.election_id === "elec-br-general-2026-r1") {
277
+ election.contest_type = "election_bundle";
278
+ election.election_name = "Brazil 2026 first-round election bundle";
279
+ election.official_source_ids = appendPipe(election.official_source_ids, "off-br-2026-contests");
280
+ election.notes = "4 October bundles president, 27 governors, two Senate choices per elector, Chamber of Deputies, state assemblies and the Federal District chamber. Candidate files before the 15 August filing deadline are incomplete snapshots, not ballot qualification.";
281
+ }
282
+ if (election.election_id === "elec-br-general-2026-r2") {
283
+ election.contest_type = "conditional_executive_runoffs";
284
+ election.election_name = "Brazil 2026 conditional presidential and gubernatorial runoffs";
285
+ election.official_source_ids = appendPipe(election.official_source_ids, "off-br-2026-contests");
286
+ election.notes = "25 October is limited to president and governors requiring a runoff; it is not a second round for legislative contests.";
287
+ }
288
+ if (election.election_id === "elec-us-midterms-2026") {
289
+ election.contest_type = "election_bundle";
290
+ election.round = "varies_by_jurisdiction";
291
+ election.election_name = "United States 2026 federal election bundle";
292
+ election.administering_authority = "state and local election authorities; no single national certifier";
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 = {
299
+ "turnout-md-2024-r1-national": { A: 2710856, B: 312650, C: 1564758, D: 1564495, E: 263, F: 18464, H: 1546031, rate: 0.517530972322, reported: 0.5175, numerator: "C", source: "off-md-2024-pres-cc-h25", note: "The protocol distinguishes voters receiving ballots (C) from voters participating (D); the Constitutional Court applied C/(A+B) to the one-third validity threshold." },
300
+ "turnout-md-2024-referendum-national": { A: 2711615, B: 309199, C: 1532264, D: 1531392, E: 872, F: 42518, H: 1488874, rate: 0.507235466997, reported: 0.5072, numerator: "C", source: "off-md-2024-ref-cc-h24", note: "The protocol distinguishes voters receiving ballots (C) from voters participating (D); the Constitutional Court applied C/(A+B) to the one-third validity threshold." },
301
+ "turnout-md-2024-r2-national": { A: 2709867, B: 423820, C: 1701333, D: 1701284, E: 49, F: 20715, H: 1680569, rate: 0.542917336671, reported: 0.5429, numerator: "C", source: "off-md-2024-pres-cc-h25", note: "The protocol distinguishes voters receiving ballots (C) from voters participating (D); the Constitutional Court applied C/(A+B) to the one-fifth validity threshold." },
302
+ "turnout-md-2025-parliament-national": { A: 2738735, B: 342244, C: 1609715, D: 1609579, E: 136, F: 30857, H: 1578722, I: 3662273, J: 2052558, rate: 0.522424528048, reported: 0.5224, numerator: "D", source: "off-md-2025-cec-h4149", note: "CEC declared the election valid on 5 October 2025; the Constitutional Court confirmed legality and 101 mandates on 16 October. For this election the official 52.24% rate uses D/(A+B)." }
303
+ };
304
+ for (const row of seed.official_turnout) {
305
+ row.turnout_numerator = row.ballots_cast;
306
+ row.turnout_numerator_measure = row.participation_measure;
307
+ row.authority_reported_turnout_rate = row.turnout_rate;
308
+ const exact = mdTurnout[row.turnout_id];
309
+ if (exact) {
310
+ row.electorate_measure = "post-election protocol fields A+B: basic-list plus supplementary-list electors; not a conventional fixed ex-ante register";
311
+ row.participation_measure = "protocol field D: voters who participated";
312
+ row.registered_voters = exact.A + exact.B;
313
+ row.ballots_cast = exact.D;
314
+ row.turnout_numerator = exact[exact.numerator];
315
+ row.turnout_numerator_measure = `protocol field ${exact.numerator}: ${exact.numerator === "C" ? "voters receiving ballots" : "voters who participated"}`;
316
+ row.valid_votes = exact.H;
317
+ row.invalid_votes = exact.F;
318
+ row.turnout_rate = exact.rate;
319
+ row.authority_reported_turnout_rate = exact.reported;
320
+ row.notes = `${exact.note} C=${exact.C}; D=${exact.D}; E=C-D=${exact.E}.`;
321
+ }
322
+ if (row.turnout_id === "turnout-nh-2024-dem-primary-state") {
323
+ row.notes += " Official contest votes were 123,996, leaving a 1,815 ballot-minus-contest-vote gap that the source does not classify as invalid or undervote.";
324
+ }
325
+ if (row.turnout_id === "electorate-br-2026-audited-national") {
326
+ row.electorate_measure = "official eligible electorate published by TSE after registration closed";
327
+ }
328
+ }
329
+
330
+ const metricRows = [];
331
+ function addMetric(electionId, geoType, geoCode, code, value, sourceCode, label, numerator, denominator, reported, computed, legalRole, status, sourceId, notes = "") {
332
+ metricRows.push({ metric_id: `metric-${electionId}-${code.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-")}`, election_id: electionId, geographic_unit_type: geoType, geographic_unit_code: geoCode, metric_code: code, value, source_field_code: sourceCode, source_label_original: label, numerator_metric: numerator, denominator_metric: denominator, authority_reported_rate: reported, computed_rate: computed, legal_role: legalRole, data_status: status, official_source_id: sourceId, as_of_date: "2026-08-12", notes });
333
+ }
334
+ for (const row of seed.official_turnout.filter((item) => !mdTurnout[item.turnout_id])) {
335
+ if (row.registered_voters !== "") addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, "registered_voters", row.registered_voters, "", row.electorate_measure, "", "", "", "", "context_or_denominator", row.data_status, row.official_source_id, row.notes);
336
+ if (row.ballots_cast !== "") addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, "ballots_cast", row.ballots_cast, "", row.participation_measure, "", "", "", "", "participation", row.data_status, row.official_source_id, row.notes);
337
+ if (row.valid_votes !== "") addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, "valid_votes", row.valid_votes, "", "valid contest votes", "", "", "", "", "result_denominator", row.data_status, row.official_source_id);
338
+ if (row.turnout_rate !== "") addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, "turnout_rate", row.turnout_rate, "", "turnout rate", "turnout_numerator", "registered_voters", row.authority_reported_turnout_rate, row.turnout_rate, "reported_participation_rate", row.data_status, row.official_source_id, row.notes);
339
+ }
340
+ for (const row of seed.official_turnout.filter((item) => mdTurnout[item.turnout_id])) {
341
+ const m = mdTurnout[row.turnout_id];
342
+ const labels = { A: "electors on basic lists", B: "electors on supplementary lists", C: "electors who received ballots", D: "electors who participated", E: "received ballots minus participated", F: "invalid ballots", H: "valid votes", I: "printed ballots", J: "unused and cancelled ballots" };
343
+ for (const code of ["A", "B", "C", "D", "E", "F", "H", "I", "J"]) {
344
+ if (m[code] !== undefined) addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, code, m[code], code, labels[code], "", "", "", "", code === m.numerator ? "legal_turnout_numerator" : "protocol_component", row.data_status, m.source, row.notes);
345
+ }
346
+ addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, "A_plus_B", m.A + m.B, "A+B", "post-election protocol denominator", "", "", "", "", "legal_turnout_denominator", row.data_status, m.source, row.notes);
347
+ addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, "legal_turnout_rate", m.rate, "", "legal turnout rate", m.numerator, "A+B", m.reported, m.rate, "legal_validity_rate", row.data_status, m.source, row.notes);
348
+ addMetric(row.election_id, row.geographic_unit_type, row.geographic_unit_code, "participation_rate_D", m.D / (m.A + m.B), "", "D/(A+B)", "D", "A+B", m.numerator === "D" ? m.reported : "", m.D / (m.A + m.B), "descriptive_participation_rate", row.data_status, m.source, row.notes);
349
+ }
350
+ addMetric("elec-us-nh-dem-primary-2024", "state", "US-NH", "presidential_contest_votes", 123996, "", "votes counted for the Democratic presidential contest", "", "", "", "", "contest_total", "final", "off-nh-2024-dem-results", "The 1,815 gap from Democratic ballots cast is not classified by the source.");
351
+ addMetric("elec-us-nh-dem-primary-2024", "state", "US-NH", "ballot_minus_contest_vote_gap", 1815, "", "Democratic ballots cast minus presidential contest votes", "", "", "", "", "unclassified_gap", "final", "off-nh-2024-dem-results", "Do not relabel as invalid or undervote without an official classification.");
352
+ seed.official_election_metrics = metricRows;
353
+
354
+ const resultTotals = { "elec-ro-pres-2024-r1": 9242186, "elec-ro-pres-2025-r1": 9430274, "elec-md-pres-2024-r1": 1546031, "elec-md-parl-2025": 1578722 };
355
+ for (const row of seed.official_results) {
356
+ row.ballot_designating_entity = row.ballot_designating_entity || "";
357
+ row.seats = row.seats ?? "";
358
+ if (["elec-ro-pres-2024-r1", "elec-ro-pres-2025-r1", "elec-md-pres-2024-r1", "elec-md-parl-2025"].includes(row.election_id)) row.coverage_status = "complete_national_contest";
359
+ if (row.election_id === "elec-ro-pres-2024-r1") row.result_status = "final_tally_validated_then_process_void";
360
+ if (row.election_id === "elec-ro-pres-2025-r1") row.result_status = "CCR_confirmed_and_validated";
361
+ if (row.election_id === "elec-ro-pres-2025-r2") row.result_status = "CCR_confirmed_and_validated";
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 = [];
368
+ function addResult(id, electionId, name, affiliation, designator, votes, rank, outcome, seats, sourceId, notes = "") {
369
+ const total = resultTotals[electionId];
370
+ extraResults.push({ result_id: id, election_id: electionId, geographic_unit_type: "national", geographic_unit_code: electionId.includes("ro-") ? "ROU" : "MDA", geographic_unit_name: electionId.includes("ro-") ? "Romania" : "Moldova", contest_name: electionId.includes("parl") ? "Parliamentary election" : "Presidential election", candidate_or_option: name, party_or_affiliation: affiliation, ballot_designating_entity: designator, votes, valid_vote_share: total && votes ? votes / total : votes === 0 ? 0 : "", rank, outcome, seats, result_status: electionId === "elec-ro-pres-2024-r1" ? "final_tally_validated_then_process_void" : electionId === "elec-ro-pres-2025-r1" ? "CCR_confirmed_and_validated" : "CEC_final_and_Constitutional_Court_confirmed", coverage_status: "complete_national_contest", official_source_id: sourceId, as_of_date: "2026-08-12", notes });
371
+ }
372
+ [
373
+ ["simion", "George-Nicolae Simion", "AUR", 1281325], ["ciuca", "Nicolae-Ionel Ciucă", "PNL", 811952], ["geoana", "Mircea-Dan Geoană", "independent", 583898], ["kelemen", "Hunor Kelemen", "UDMR", 416353], ["diaconescu", "Cristian Diaconescu", "independent", 286842], ["terhes", "Cristian-Vasile Terheș", "PNCR", 95782], ["birchall", "Ana Birchall", "independent", 42853], ["orban", "Ludovic Orban", "Forța Dreptei", 20089], ["popescu", "Sebastian-Constantin Popescu", "Partidul Noua Românie", 14683], ["bertalan", "Alexandra-Beatrice Bertalan-Păcuraru", "Alternativa pentru Demnitate Națională", 14502], ["predoiu", "Silviu Predoiu", "Partidul Liga Acțiunii Naționale", 11246]
374
+ ].forEach(([slug, name, party, votes], index) => addResult(`result-ro24-${slug}`, "elec-ro-pres-2024-r1", name, party, "", votes, index + 4, "not_advanced_before_annulment", "", "off-ro-2024-ccr-h31", "Final tally first validated by H31, then the process was voided by H32."));
375
+ [
376
+ ["ponta", "Victor-Viorel Ponta", "independent", 1230164], ["lasconi", "Elena-Valerica Lasconi", "USR", 252721], ["sandru", "Marcela-Lavinia Șandru", "PUSL", 60682], ["funeriu", "Petru-Daniel Funeriu", "independent", 49604], ["terhes", "Cristian-Vasile Terheș", "PNCR", 36445], ["popescu", "Sebastian-Constantin Popescu", "Partidul Noua Românie", 25994], ["banu", "John-Ion Banu-Muscel", "independent", 22020], ["predoiu", "Silviu Predoiu", "Partidul Liga Acțiunii Naționale", 17186]
377
+ ].forEach(([slug, name, party, votes], index) => addResult(`result-ro25r1-${slug}`, "elec-ro-pres-2025-r1", name, party, "", votes, index + 4, "not_advanced", "", "off-ro-2025-ccr-h39"));
378
+ [
379
+ ["vlah", "Irina Vlah", "independent", "", 83193], ["furtuna", "Victoria Furtună", "independent", "", 68778], ["tarlev", "Vasile Tarlev", "", "Partidul pentru Viitorul Moldovei", 49316], ["chicu", "Ion Chicu", "", "Partidul Dezvoltării și Consolidării Moldovei", 31797], ["ticu", "Octavian Țîcu", "", "Blocul Electoral Împreună", 14326], ["nastase", "Andrei Năstase", "independent", "", 9946], ["morari", "Natalia Morari", "independent", "", 9444], ["ulianovschi", "Tudor Ulianovschi", "independent", "", 7995]
380
+ ].forEach(([slug, name, party, designator, votes], index) => addResult(`result-md24r1-${slug}`, "elec-md-pres-2024-r1", name, party, designator, votes, index + 4, "not_advanced", "", "off-md-2024-pres-cc-h25"));
381
+
382
+ const mdSeats = {
383
+ "result-mdparl-pas": ["Partidul Acțiune și Solidaritate (PAS)", 55, "gained_seats"],
384
+ "result-mdparl-patriotic-bloc": ["Blocul Electoral Patriotic al Socialiștilor, Comuniștilor, Inima și Viitorul Moldovei", 26, "gained_seats"],
385
+ "result-mdparl-alternative-bloc": ["Blocul Electoral Alternativa", 8, "gained_seats"],
386
+ "result-mdparl-our-party": ["Partidul Nostru", 6, "gained_seats"],
387
+ "result-mdparl-democracy-at-home": ["Partidul Democrația Acasă", 6, "gained_seats"]
388
+ };
389
+ for (const row of seed.official_results) {
390
+ if (mdSeats[row.result_id]) {
391
+ [row.candidate_or_option, row.seats, row.outcome] = mdSeats[row.result_id];
392
+ row.official_source_id = "off-md-2025-cec-h4151";
393
+ }
394
+ }
395
+ [
396
+ ["psde", "Partidul Social Democrat European", 15060, 6], ["andrei-nastase", "Andrei Năstase", 13420, 7], ["cub", "Coaliția pentru Unitate și Bunăstare", 13314, 8], ["respect", "Respect Moldova", 10144, 9], ["loc", "Liga Orașelor și Comunelor", 6120, 10], ["stamate", "Olesea Stamate", 5257, 11], ["impreuna", "Blocul Electoral Împreună", 5030, 12], ["pnm", "Partidul Național Moldovenesc", 4813, 13], ["alde", "ALDE", 3576, 14], ["moldovenii", "Alianța Moldovenii", 3509, 15], ["sanduta", "Victoria Sanduța", 2862, 16], ["ucs", "Uniunea Creștin-Socială", 1837, 17], ["aur", "AUR", 1604, 18], ["cretu", "Tatiana Crețu", 1598, 19], ["liberal", "Partidul Liberal", 1591, 20], ["noi", "Noua Opțiune Istorică", 1412, 21], ["bun", "Blocul Unirea Națiunii", 797, 22]
397
+ ].forEach(([slug, name, votes, rank]) => addResult(`result-mdparl-${slug}`, "elec-md-parl-2025", name, name.includes("Andrei") || name.includes("Olesea") || name.includes("Victoria") || name.includes("Tatiana") ? "independent" : "", "", votes, rank, "no_seats", 0, "off-md-2025-cec-h4151"));
398
+ addResult("result-mdparl-moldova-mare", "elec-md-parl-2025", "Partidul Moldova Mare", "", "", 0, "", "excluded_ballots_invalidated", 0, "off-md-2025-cec-h4151", "Registered competitor; zero valid votes after ballots were invalidated. One Tokyo vote was reclassified invalid according to the official record.");
399
+ seed.official_results.push(...extraResults);
400
+
401
+ seed.claims = seed.claims.map((claim) => {
402
+ const confidence = Number(claim.confidence);
403
+ let claimStatus = "unresolved";
404
+ let evidenceStrength = "none";
405
+ if (claim.evidence_label === "established_evidence") { claimStatus = "supported"; evidenceStrength = confidence >= 0.9 ? "high" : "moderate"; }
406
+ if (claim.evidence_label === "established_as_campaign_report") { claimStatus = "supported_as_attributed_measurement"; evidenceStrength = "moderate"; }
407
+ if (claim.evidence_label === "strong_inference") { claimStatus = "partly_supported"; evidenceStrength = confidence >= 0.8 ? "moderate" : "low"; }
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);
414
+ return {
415
+ ...source,
416
+ source_independence: source.source_independence || (interestedTypes ? "interested_or_mixed" : source.primary_secondary === "primary" ? "independent_or_official" : "independent_secondary"),
417
+ method_transparency: source.method_transparency || (reproducibleTypes ? "sufficiently_described_or_reproducible" : /official|legal|regulatory/.test(source.source_type) ? "not_applicable_official_record" : "limited_to_published_account"),
418
+ access_status: source.access_status || "public_url_at_cutoff",
419
+ archive_url: source.archive_url || "",
420
+ content_hash: source.content_hash || ""
421
+ };
422
+ });
423
+
424
+ seed.case_actors = rowsFromArrays(extensions.case_actors, schemas.case_actors);
425
+ seed.technology_uses = rowsFromArrays(extensions.technology_uses, schemas.technology_uses);
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]));
432
+ const metricFamily = (name) => /view|impression|reach|audience/.test(name) ? "exposure_or_distribution" : /account|page|post|video|question|call|message|asset|content/.test(name) ? "production_or_engagement" : /fine|charge|removal|deadline|response/.test(name) ? "institutional_response" : "descriptive_context";
433
+ seed.observations = extensions.quantitative_observations.map((values) => {
434
+ const [observation_id, case_id, claim_id, metric_name, value_best, value_operator, platform, measurement_window, denominator, unique_entity_status, causalRaw, measurement_method, source_id, limitations] = values;
435
+ const exact = ["exact", "exact_report", "exact_campaign_report"].includes(value_operator);
436
+ const atLeast = String(value_operator).startsWith("at_least");
437
+ return { observation_id, case_id, pathway_id: pathwayByCase.get(case_id) || "", claim_id, metric_family: metricFamily(metric_name), metric_name, value_low: exact || atLeast ? value_best : "", value_best, value_high: exact ? value_best : "", value_operator, unit: metric_name, denominator, unique_entity_status, platform, geographic_scope: caseById.get(case_id)?.country || "", measurement_window, measurement_method, causal_status: causalRaw === "yes" ? "causal_estimate_limited" : "descriptive_only", source_id, as_of_date: caseById.get(case_id)?.last_verified || "2026-08-12", limitations };
438
+ });
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
+ }
452
+
453
+ seed.analytic_record_claims = [];
454
+ for (const [recordType, table, idField] of [
455
+ ["case_actor", seed.case_actors, "case_actor_id"],
456
+ ["technology_use", seed.technology_uses, "tech_use_id"],
457
+ ["content_item", seed.content_items, "content_item_id"],
458
+ ["pathway", seed.pathways, "pathway_id"],
459
+ ["event", seed.events, "event_id"]
460
+ ]) {
461
+ for (const record of table) {
462
+ for (const claimId of String(record.source_claim_ids || record.claim_ids || "").split("|").filter(Boolean)) {
463
+ seed.analytic_record_claims.push({ record_claim_id: `record-claim-${recordType}-${record[idField]}-${claimId}`, record_type: recordType, record_id: record[idField], case_id: record.case_id, claim_id: claimId, relation: "supports_coding" });
464
+ }
465
+ }
466
+ }
467
+
468
+ seed.case_elections = [];
469
+ seed.election_sources = [];
470
+ for (const election of seed.official_elections) {
471
+ for (const caseId of String(election.linked_case_ids || "").split("|").filter(Boolean)) {
472
+ seed.case_elections.push({ case_election_id: `case-election-${caseId}-${election.election_id}`, case_id: caseId, election_id: election.election_id, relation: election.election_status === "scheduled" || election.election_status === "conditional" ? "future_or_campaign_context" : "primary_or_institutional_context" });
473
+ }
474
+ for (const sourceId of String(election.official_source_ids || "").split("|").filter(Boolean)) {
475
+ seed.election_sources.push({ election_source_id: `election-source-${election.election_id}-${sourceId}`, election_id: election.election_id, official_source_id: sourceId, source_role: "supports_election_context_or_status" });
476
+ }
477
+ }
478
+
479
+ function evidenceForCase(caseId) {
480
+ const strengths = seed.claims.filter((claim) => claim.case_id === caseId).map((claim) => claim.evidence_strength);
481
+ return strengths.includes("high") ? "high_for_occurrence_mixed_for_effect" : strengths.includes("moderate") ? "moderate" : "low_or_unresolved";
482
+ }
483
+ function reachForCase(caseId) {
484
+ const rows = seed.observations.filter((row) => row.case_id === caseId).slice(0, 2);
485
+ if (!rows.length) return "No typed population-reach estimate";
486
+ return rows.map((row) => `${Number(row.value_best).toLocaleString("en-US")} ${row.unit}; ${row.measurement_method}; ${row.unique_entity_status}; ${row.measurement_window}`).join(" | ");
487
+ }
488
+ seed.research_view = seed.pathways.map((pathway) => {
489
+ const item = caseById.get(pathway.case_id);
490
+ const tech = seed.technology_uses.filter((row) => row.case_id === pathway.case_id).map((row) => [row.provider, row.product_or_model].filter(Boolean).join(": ")).join(" | ") || "not identified or not applicable";
491
+ return { pathway_id: pathway.pathway_id, case_id: item.case_id, case_title: item.title, country: item.country, election_date: item.election_date_start, record_type: item.record_type, case_status: item.case_status, manipulation_assessment: item.manipulation_assessment, generative_ai_status: item.generative_ai_status, ai_role: item.ai_role, system_or_model: tech, controller: item.actor_controlling_system, influence_vector: item.influence_vector, target: item.target_population, affected_agency: pathway.affected_agency, agency_transfer_status: pathway.agency_transfer_status, power_recipient: pathway.power_recipient, reach_summary: reachForCase(item.case_id), behavioural_effect: item.behavioural_effect_status, electoral_effect: item.electoral_effect_status, evidence_strength: evidenceForCase(item.case_id), main_uncertainty: item.open_questions, last_verified: item.last_verified };
492
+ });
493
+
494
+ 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 = {
503
+ Europe: "Strongest current core coverage; still purposive and concentrated in Romania/Moldova.",
504
+ "North America": "One adjudicated 2024 robocall, two 2026 campaign records, and several model audits; no prevalence frame.",
505
+ "South America": "Brazil core is mainly preparedness/current use; completed Colombia/Ecuador leads remain to be disaggregated.",
506
+ Asia: "Screening leads exist but no claim-coded core case yet.",
507
+ Africa: "Screening leads exist but no claim-coded core case yet.",
508
+ Oceania: "One knowledge-poisoning lead; no claim-coded core case yet.",
509
+ "Cross-national": "Empirical studies span jurisdictions; not incident counts."
510
+ };
511
+ const regions = Object.keys(frameNotes);
512
+ seed.sampling_frame = regions.map((region) => {
513
+ const included = seed.cases.filter((row) => canonicalRegion(row.region) === region).length;
514
+ const candidates = seed.candidates.filter((row) => canonicalRegion(row.region) === region).length;
515
+ return { frame_id: `frame-${region.toLowerCase().replaceAll(/[^a-z]+/g, "-")}`, region, selection_basis: "purposive anchor cases plus structured comparative screening; not a census", search_status: included || candidates ? "partial" : "not_started", search_languages: region === "Europe" ? "en|ro|pt|selected_local_sources" : "primarily_en_with_selected_local_sources", source_channels: "official election bodies|courts|platform reports|peer-reviewed studies|fact-checkers|investigative reporting", included_case_count: included, candidate_count: candidates, negative_search_recorded: region === "South America" ? "true" : "false", known_gap: frameNotes[region], last_searched: "2026-08-12" };
516
+ });
517
+ seed.coverage_summary = regions.map((region) => ({ region, included_case_count: seed.cases.filter((row) => canonicalRegion(row.region) === region).length, candidate_count: seed.candidates.filter((row) => canonicalRegion(row.region) === region).length, model_evaluation_count: seed.model_evaluations.filter((row) => regionForCountry(row.country) === region).length, coverage_note: frameNotes[region] }));
518
+
519
  function csvCell(value) {
520
  if (value === null || value === undefined) return "";
521
  const s = Array.isArray(value) ? value.join("|") : String(value);
 
558
  assertUnique(seed.official_turnout, "turnout_id", "official_turnout");
559
  assertUnique(seed.official_results, "result_id", "official_results");
560
  assertUnique(seed.official_data_sources, "official_source_id", "official_data_sources");
561
+ assertUnique(seed.official_election_metrics, "metric_id", "official_election_metrics");
562
+ assertUnique(seed.case_actors, "case_actor_id", "case_actors");
563
+ assertUnique(seed.technology_uses, "tech_use_id", "technology_uses");
564
+ assertUnique(seed.content_items, "content_item_id", "content_items");
565
+ assertUnique(seed.pathways, "pathway_id", "pathways");
566
+ assertUnique(seed.observations, "observation_id", "observations");
567
+ assertUnique(seed.model_evaluations, "evaluation_id", "model_evaluations");
568
+ assertUnique(seed.claim_evidence, "claim_evidence_id", "claim_evidence");
569
+ assertUnique(seed.analytic_record_claims, "record_claim_id", "analytic_record_claims");
570
+ assertUnique(seed.case_elections, "case_election_id", "case_elections");
571
+ assertUnique(seed.election_sources, "election_source_id", "election_sources");
572
 
573
  for (const claim of seed.claims) {
574
  if (!caseIds.has(claim.case_id)) throw new Error("Unknown case in claim " + claim.claim_id);
 
619
  if (!electionIds.has(row.election_id)) throw new Error("Unknown election in official_results " + row.result_id);
620
  if (!officialSourceIds.has(row.official_source_id)) throw new Error("Unknown official source in official_results " + row.result_id);
621
  }
622
+ for (const row of seed.official_election_metrics) {
623
+ if (!electionIds.has(row.election_id)) throw new Error("Unknown election in official_election_metrics " + row.metric_id);
624
+ if (!officialSourceIds.has(row.official_source_id)) throw new Error("Unknown official source in official_election_metrics " + row.metric_id);
625
+ }
626
+ for (const row of [...seed.case_actors, ...seed.technology_uses, ...seed.content_items, ...seed.pathways, ...seed.observations]) {
627
+ if (!caseIds.has(row.case_id)) throw new Error("Unknown case in analytic record " + (row.case_actor_id || row.tech_use_id || row.content_item_id || row.pathway_id || row.observation_id));
628
+ }
629
+ for (const row of seed.claim_evidence) {
630
+ if (!claimIds.has(row.claim_id) || !sourceIds.has(row.source_id)) throw new Error("Unknown claim/source in " + row.claim_evidence_id);
631
+ }
632
+ for (const row of seed.analytic_record_claims) {
633
+ if (!caseIds.has(row.case_id) || !claimIds.has(row.claim_id)) throw new Error("Unknown case/claim in " + row.record_claim_id);
634
+ }
635
+ for (const row of seed.case_elections) {
636
+ if (!caseIds.has(row.case_id) || !electionIds.has(row.election_id)) throw new Error("Unknown case/election in " + row.case_election_id);
637
+ }
638
+ for (const row of seed.election_sources) {
639
+ if (!electionIds.has(row.election_id) || !officialSourceIds.has(row.official_source_id)) throw new Error("Unknown election/source in " + row.election_source_id);
640
+ }
641
 
642
  fs.mkdirSync(outDir, { recursive: true });
643
  const fileHashes = {};
 
652
  fs.writeFileSync(path.join(outDir, "schema.json"), schemaText);
653
  fileHashes["schema.json"] = sha256(schemaText);
654
 
655
+ const primaryKeys = {
656
+ cases: "case_id", claims: "claim_id", sources: "source_id", events: "event_id",
657
+ watchlist: "watch_id", candidates: "candidate_id", official_elections: "election_id",
658
+ official_turnout: "turnout_id", official_results: "result_id",
659
+ official_data_sources: "official_source_id", official_election_metrics: "metric_id",
660
+ case_catalog: "catalog_id", case_actors: "case_actor_id", technology_uses: "tech_use_id",
661
+ content_items: "content_item_id", pathways: "pathway_id", observations: "observation_id",
662
+ model_evaluations: "evaluation_id", claim_evidence: "claim_evidence_id",
663
+ analytic_record_claims: "record_claim_id", case_elections: "case_election_id",
664
+ election_sources: "election_source_id", sampling_frame: "frame_id"
665
+ };
666
+ const foreignKeys = {
667
+ claims: [["case_id", "cases", "case_id"]],
668
+ events: [["case_id", "cases", "case_id"]],
669
+ case_sources: [["case_id", "cases", "case_id"], ["source_id", "sources", "source_id"]],
670
+ watchlist: [["case_id", "cases", "case_id"]],
671
+ official_turnout: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]],
672
+ official_results: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]],
673
+ official_election_metrics: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]],
674
+ research_view: [["case_id", "cases", "case_id"], ["pathway_id", "pathways", "pathway_id"]],
675
+ case_actors: [["case_id", "cases", "case_id"]],
676
+ technology_uses: [["case_id", "cases", "case_id"]],
677
+ content_items: [["case_id", "cases", "case_id"]],
678
+ pathways: [["case_id", "cases", "case_id"]],
679
+ observations: [["case_id", "cases", "case_id"], ["pathway_id", "pathways", "pathway_id"], ["claim_id", "claims", "claim_id"], ["source_id", "sources", "source_id"]],
680
+ claim_evidence: [["claim_id", "claims", "claim_id"], ["source_id", "sources", "source_id"]],
681
+ analytic_record_claims: [["case_id", "cases", "case_id"], ["claim_id", "claims", "claim_id"]],
682
+ case_elections: [["case_id", "cases", "case_id"], ["election_id", "official_elections", "election_id"]],
683
+ election_sources: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]]
684
+ };
685
+ const integerFields = new Set(["votes", "rank", "seats", "registered_voters", "ballots_cast", "turnout_numerator", "valid_votes", "invalid_votes", "reporting_units_total", "reporting_units_counted", "sample_size", "included_case_count", "candidate_count", "model_evaluation_count", "source_count_or_links", "content_bytes"]);
686
+ const numberFields = new Set(["confidence", "coder_confidence_in_label", "overall_confidence", "turnout_rate", "authority_reported_turnout_rate", "valid_vote_share", "authority_reported_rate", "computed_rate", "value", "value_low", "value_best", "value_high"]);
687
+ const dateFields = new Set(["election_date_start", "election_date_end", "as_of_date", "last_verified", "verified_at", "retrieved_at", "publication_date", "event_date", "election_date", "last_checked", "last_searched", "snapshot_cutoff"]);
688
+ const booleanFields = new Set(["anchor_case", "incident_count_eligible", "negative_search_recorded"]);
689
+ function fieldDescriptor(name) {
690
+ if (booleanFields.has(name)) return { name, type: "boolean", trueValues: ["true"], falseValues: ["false"] };
691
+ if (integerFields.has(name)) return { name, type: "integer" };
692
+ if (numberFields.has(name)) return { name, type: "number" };
693
+ if (dateFields.has(name)) return { name, type: "date" };
694
+ return { name, type: "string" };
695
+ }
696
+ 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]) => ({
704
+ name: table,
705
+ path: `${table}.csv`,
706
+ profile: "tabular-data-resource",
707
+ format: "csv",
708
+ mediatype: "text/csv",
709
+ schema: {
710
+ fields: columns.map(fieldDescriptor),
711
+ ...(primaryKeys[table] ? { primaryKey: primaryKeys[table] } : {}),
712
+ ...(foreignKeys[table]?.length ? { foreignKeys: foreignKeys[table].map(([field, resource, targetField]) => ({ fields: field, reference: { resource, fields: targetField } })) } : {})
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);
719
+
720
  const counts = Object.fromEntries(Object.keys(schemas).map((table) => [table, seed[table].length]));
721
  const stats = {
722
  ...counts,
 
725
  "research/seed.json": sha256(fs.readFileSync(seedPath)),
726
  "research/candidates.json": sha256(fs.readFileSync(candidatesPath)),
727
  "research/europe_candidates.json": sha256(fs.readFileSync(europeCandidatesPath)),
728
+ "research/official_electoral_data.json": sha256(fs.readFileSync(officialElectoralDataPath)),
729
+ "research/v0.3_extensions.json": sha256(fs.readFileSync(extensionsPath))
730
  },
731
  file_sha256: fileHashes
732
  }
scripts/build-parquet.mjs ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ 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 = [];
17
+ let record = [];
18
+ let field = "";
19
+ let quoted = false;
20
+ for (let i = 0; i < text.length; i += 1) {
21
+ const char = text[i];
22
+ if (quoted) {
23
+ if (char === '"' && text[i + 1] === '"') { field += '"'; i += 1; }
24
+ else if (char === '"') quoted = false;
25
+ else field += char;
26
+ } else if (char === '"') quoted = true;
27
+ else if (char === ",") { record.push(field); field = ""; }
28
+ else if (char === "\n") { record.push(field.replace(/\r$/, "")); records.push(record); record = []; field = ""; }
29
+ else field += char;
30
+ }
31
+ if (field || record.length) { record.push(field.replace(/\r$/, "")); records.push(record); }
32
+ const headers = records.shift() || [];
33
+ return records.filter((row) => row.some((value) => value !== "")).map((values) =>
34
+ Object.fromEntries(headers.map((header, index) => [header, values[index] ?? ""]))
35
+ );
36
+ }
37
+
38
+ function parquetType(field) {
39
+ if (field.type === "integer") return "INT64";
40
+ if (field.type === "number") return "DOUBLE";
41
+ if (field.type === "boolean") return "BOOLEAN";
42
+ return "UTF8";
43
+ }
44
+
45
+ function convert(value, field) {
46
+ if (value === "" || value === null || value === undefined) return undefined;
47
+ if (field.type === "integer") return Number.parseInt(value, 10);
48
+ if (field.type === "number") return Number(value);
49
+ if (field.type === "boolean") return String(value).toLowerCase() === "true";
50
+ return String(value);
51
+ }
52
+
53
+ const pkg = JSON.parse(await fs.readFile(path.join(dataDir, "datapackage.json"), "utf8"));
54
+ const manifest = [];
55
+ for (const resource of pkg.resources) {
56
+ const rows = parseCsv(await fs.readFile(path.join(dataDir, resource.path), "utf8"));
57
+ const fields = resource.schema.fields;
58
+ const parquetSchema = new parquet.ParquetSchema(Object.fromEntries(fields.map((field) => [field.name, { type: parquetType(field), optional: true }])));
59
+ const output = path.join(outDir, `${resource.name}.parquet`);
60
+ const writer = await parquet.ParquetWriter.openFile(parquetSchema, output);
61
+ for (const sourceRow of rows) {
62
+ const row = {};
63
+ for (const field of fields) {
64
+ const value = convert(sourceRow[field.name], field);
65
+ if (value !== undefined && !Number.isNaN(value)) row[field.name] = value;
66
+ }
67
+ await writer.appendRow(row);
68
+ }
69
+ await writer.close();
70
+ const stat = await fs.stat(output);
71
+ const digest = createHash("sha256").update(await fs.readFile(output)).digest("hex");
72
+ manifest.push({ table: resource.name, rows: rows.length, file: `parquet/${resource.name}.parquet`, bytes: stat.size, sha256: digest });
73
+ }
74
+ await fs.writeFile(path.join(outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
75
+ process.stdout.write(`${JSON.stringify({ tables: manifest.length, rows: manifest.reduce((sum, item) => sum + item.rows, 0) })}\n`);
scripts/build-workbook-v03.mjs ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";
5
+
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
+
13
+ function parseCsv(text) {
14
+ const records = [];
15
+ let record = [];
16
+ let field = "";
17
+ let quoted = false;
18
+ for (let i = 0; i < text.length; i += 1) {
19
+ const char = text[i];
20
+ if (quoted) {
21
+ if (char === '"' && text[i + 1] === '"') { field += '"'; i += 1; }
22
+ else if (char === '"') quoted = false;
23
+ else field += char;
24
+ } else if (char === '"') quoted = true;
25
+ else if (char === ",") { record.push(field); field = ""; }
26
+ else if (char === "\n") {
27
+ record.push(field.replace(/\r$/, ""));
28
+ records.push(record);
29
+ record = [];
30
+ field = "";
31
+ } else field += char;
32
+ }
33
+ if (field || record.length) { record.push(field.replace(/\r$/, "")); records.push(record); }
34
+ const headers = records.shift() || [];
35
+ return records.filter((row) => row.some((value) => value !== "")).map((values) =>
36
+ Object.fromEntries(headers.map((header, index) => [header, values[index] ?? ""]))
37
+ );
38
+ }
39
+
40
+ const schema = JSON.parse(await fs.readFile(path.join(dataDir, "schema.json"), "utf8"));
41
+ const stats = JSON.parse(await fs.readFile(path.join(dataDir, "stats.json"), "utf8"));
42
+ const audit = JSON.parse(await fs.readFile(path.join(dataDir, "audit-v03.json"), "utf8"));
43
+ const data = {};
44
+ for (const table of Object.keys(schema)) {
45
+ data[table] = parseCsv(await fs.readFile(path.join(dataDir, `${table}.csv`), "utf8"));
46
+ }
47
+
48
+ const wb = Workbook.create();
49
+ const colors = {
50
+ ink: "#111827", charcoal: "#263238", slate: "#4B5563", blue: "#24506A",
51
+ paleBlue: "#EAF2F7", gray: "#E5E7EB", light: "#F8FAFC", white: "#FFFFFF",
52
+ red: "#B42318", paleRed: "#FDECEC", green: "#16794C", paleGreen: "#EAF7F0",
53
+ amber: "#946200", paleAmber: "#FFF6D8"
54
+ };
55
+
56
+ function excelColumn(index) {
57
+ let n = index + 1;
58
+ let out = "";
59
+ while (n > 0) { n -= 1; out = String.fromCharCode(65 + (n % 26)) + out; n = Math.floor(n / 26); }
60
+ return out;
61
+ }
62
+
63
+ const numericFields = new Set([
64
+ "confidence", "coder_confidence_in_label", "overall_confidence", "reach_estimate",
65
+ "registered_voters", "ballots_cast", "turnout_numerator", "valid_votes", "invalid_votes",
66
+ "turnout_rate", "authority_reported_turnout_rate", "reporting_units_total", "reporting_units_counted",
67
+ "votes", "valid_vote_share", "rank", "seats", "value", "authority_reported_rate", "computed_rate",
68
+ "value_low", "value_best", "value_high", "sample_size", "included_case_count", "candidate_count",
69
+ "model_evaluation_count", "source_count_or_links", "content_bytes"
70
+ ]);
71
+ const percentFields = new Set(["turnout_rate", "authority_reported_turnout_rate", "valid_vote_share", "authority_reported_rate", "computed_rate"]);
72
+ const integerFields = new Set(["registered_voters", "ballots_cast", "turnout_numerator", "valid_votes", "invalid_votes", "reporting_units_total", "reporting_units_counted", "votes", "rank", "seats", "sample_size", "included_case_count", "candidate_count", "model_evaluation_count", "source_count_or_links", "content_bytes"]);
73
+
74
+ function valueForCell(column, value) {
75
+ if (value === "" || value === null || value === undefined) return "";
76
+ if (/^(true|false)$/i.test(String(value))) return String(value).toLowerCase() === "true";
77
+ if ((column.endsWith("_date") || column.endsWith("_at") || ["last_verified", "event_date", "last_checked", "last_searched", "as_of_date", "snapshot_cutoff"].includes(column)) && /^\d{4}-\d{2}-\d{2}$/.test(String(value))) {
78
+ return new Date(`${value}T00:00:00Z`);
79
+ }
80
+ if (numericFields.has(column) && Number.isFinite(Number(value))) return Number(value);
81
+ return value;
82
+ }
83
+
84
+ function safeTableName(name) {
85
+ return `T${name.replaceAll(/[^A-Za-z0-9]/g, "").slice(0, 44)}`;
86
+ }
87
+
88
+ function addDataSheet(sheetName, rows, columns, options = {}) {
89
+ const sheet = wb.worksheets.add(sheetName);
90
+ sheet.showGridLines = false;
91
+ const matrix = [columns, ...rows.map((row) => columns.map((column) => valueForCell(column, row[column] ?? "")))];
92
+ const lastCol = excelColumn(columns.length - 1);
93
+ const lastRow = Math.max(matrix.length, 2);
94
+ sheet.getRange(`A1:${lastCol}${matrix.length}`).values = matrix;
95
+ sheet.getRange(`A1:${lastCol}1`).format = {
96
+ fill: options.headerFill || colors.charcoal,
97
+ font: { bold: true, color: colors.white, size: 10 },
98
+ wrapText: true,
99
+ verticalAlignment: "center",
100
+ borders: { preset: "all", style: "thin", color: colors.white }
101
+ };
102
+ sheet.getRange(`A1:${lastCol}1`).format.rowHeightPx = 38;
103
+ sheet.getRange(`A2:${lastCol}${lastRow}`).format = {
104
+ font: { color: colors.ink, size: 9 },
105
+ wrapText: true,
106
+ verticalAlignment: "top",
107
+ borders: { preset: "all", style: "thin", color: "#D9DEE3" }
108
+ };
109
+ sheet.getRange(`A2:${lastCol}${lastRow}`).format.rowHeightPx = options.rowHeight || 58;
110
+ sheet.freezePanes.freezeRows(1);
111
+ sheet.freezePanes.freezeColumns(Math.min(options.freezeColumns ?? 2, columns.length));
112
+ for (let i = 0; i < columns.length; i += 1) {
113
+ const column = columns[i];
114
+ const letter = excelColumn(i);
115
+ const width = options.widths?.[column] || (
116
+ /summary|claim_text|notes|counterevidence|open_questions|description|path|mechanism|outcome|scope|uncertainty|limitation|caveat|headline|selection_basis|coverage_note/.test(column) ? 360 :
117
+ /url/.test(column) ? 300 :
118
+ /title|name|controller|target|actor/.test(column) ? 250 :
119
+ /id$/.test(column) ? 210 : 135
120
+ );
121
+ sheet.getRange(`${letter}1:${letter}${lastRow}`).format.columnWidthPx = width;
122
+ if ((column.endsWith("_date") || column.endsWith("_at") || ["last_verified", "last_checked", "last_searched", "as_of_date", "snapshot_cutoff"].includes(column)) && lastRow >= 2) {
123
+ sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "yyyy-mm-dd";
124
+ } else if (percentFields.has(column) && lastRow >= 2) {
125
+ sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "0.00%";
126
+ } else if (integerFields.has(column) && lastRow >= 2) {
127
+ sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "#,##0";
128
+ } else if (["confidence", "coder_confidence_in_label", "overall_confidence"].includes(column) && lastRow >= 2) {
129
+ sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "0.00";
130
+ }
131
+ }
132
+ if (rows.length) {
133
+ const table = sheet.tables.add(`A1:${lastCol}${matrix.length}`, true, safeTableName(sheetName));
134
+ table.showBandedColumns = false;
135
+ table.showFilterButton = true;
136
+ }
137
+ return { sheet, columns, lastCol, lastRow };
138
+ }
139
+
140
+ function addSectionTitle(sheet, range, text, fill = colors.charcoal) {
141
+ sheet.getRange(range).merge();
142
+ sheet.getRange(range).values = [[text]];
143
+ sheet.getRange(range).format = { fill, font: { bold: true, color: colors.white, size: 11 }, verticalAlignment: "center" };
144
+ }
145
+
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],
165
+ ["Official contests/bundles", data.official_elections.length],
166
+ ["Official long-form metrics", data.official_election_metrics.length],
167
+ ["Official result rows", data.official_results.length],
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 = [[
175
+ "1. Research View — one concise row per agency-transfer pathway.\n\n2. Case Catalog — distinguishes claim-coded records, screening leads and empirical studies.\n\n3. Pathways + Observations — the analytic core: who controls what, what metric was actually measured, and what is not causal.\n\n4. Claims + Evidence — verify every factual sentence before using it.\n\n5. Official Metrics + Results — electoral context only; never evidence of votes caused by manipulation."
176
+ ]];
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;
192
+
193
+ const researchColumns = ["case_id", "case_title", "country", "election_date", "record_type", "manipulation_assessment", "system_or_model", "controller", "influence_vector", "target", "affected_agency", "agency_transfer_status", "power_recipient", "reach_summary", "evidence_strength", "main_uncertainty", "last_verified"];
194
+ const researchSheet = addDataSheet("01 Research View", data.research_view, researchColumns, { headerFill: colors.blue, freezeColumns: 3, rowHeight: 82, widths: { case_title: 310, system_or_model: 280, controller: 300, influence_vector: 330, target: 300, affected_agency: 260, power_recipient: 300, reach_summary: 400, main_uncertainty: 430 } });
195
+ const catalogSheet = addDataSheet("02 Case Catalog", data.case_catalog, schema.case_catalog, { freezeColumns: 3, widths: { title: 330, main_caveat: 440 } });
196
+ const coverageSheet = addDataSheet("03 Coverage", data.coverage_summary, schema.coverage_summary, { headerFill: colors.blue, widths: { coverage_note: 560 } });
197
+ const pathwaySheet = addDataSheet("04 Pathways", data.pathways, schema.pathways, { headerFill: colors.blue, freezeColumns: 2, rowHeight: 78, widths: { control_shift_from: 300, control_shift_to: 300, mechanism: 390, harm_pathway: 390, observed_outcome: 390, reviewer_note: 420 } });
198
+ const observationSheet = addDataSheet("05 Observations", data.observations, schema.observations, { freezeColumns: 3, widths: { limitations: 480, measurement_method: 290, denominator: 260 } });
199
+ const modelSheet = addDataSheet("06 Model Studies", data.model_evaluations, schema.model_evaluations, { headerFill: colors.blue, freezeColumns: 2, rowHeight: 84, widths: { title: 360, systems_tested: 390, design: 430, headline_results: 520, causal_scope: 500, notes: 440 } });
200
+ const claimSheet = addDataSheet("07 Claims", data.claims, schema.claims, { freezeColumns: 3, rowHeight: 72, widths: { claim_text: 520, notes: 390 } });
201
+ const sourceSheet = addDataSheet("08 Sources", data.sources, schema.sources, { freezeColumns: 2, widths: { title: 390, url: 420, notes: 380 } });
202
+ addDataSheet("09 Claim Evidence", data.claim_evidence, schema.claim_evidence, { freezeColumns: 3 });
203
+ addDataSheet("10 Events", data.events, schema.events, { widths: { description: 480 } });
204
+ addDataSheet("11 Actors", data.case_actors, schema.case_actors, { widths: { actor_name: 290, control_dimension: 360, notes: 420 } });
205
+ addDataSheet("12 Technology", data.technology_uses, schema.technology_uses, { widths: { product_or_model: 330, notes: 460 } });
206
+ addDataSheet("13 Content", data.content_items, schema.content_items, { widths: { title: 300, notes: 450 } });
207
+ addDataSheet("14 Cases Detail", data.cases, schema.cases, { freezeColumns: 3, rowHeight: 92, widths: { summary: 430, agency_transfer_path: 510, counterevidence: 430, open_questions: 430 } });
208
+ addDataSheet("15 Screening Leads", data.candidates, schema.candidates, { freezeColumns: 3, rowHeight: 72, widths: { title: 330, comparative_value: 430, main_caveat: 450, source_urls: 520 } });
209
+ addDataSheet("16 Watchlist", data.watchlist, schema.watchlist, { widths: { observable_indicator: 450, defensive_data_source: 390, assessment_rule: 440, notes: 360 } });
210
+ const electionSheet = addDataSheet("17 Official Elections", data.official_elections, schema.official_elections, { widths: { election_name: 360, administering_authority: 330, geographic_scope: 330, notes: 520 } });
211
+ const metricSheet = addDataSheet("18 Official Metrics", data.official_election_metrics, schema.official_election_metrics, { headerFill: colors.blue, widths: { source_label_original: 330, notes: 520 } });
212
+ const turnoutSheet = addDataSheet("19 Turnout Wide", data.official_turnout, schema.official_turnout, { widths: { electorate_measure: 430, participation_measure: 360, turnout_numerator_measure: 360, notes: 540 } });
213
+ const resultSheet = addDataSheet("20 Official Results", data.official_results, schema.official_results, { widths: { candidate_or_option: 360, party_or_affiliation: 290, ballot_designating_entity: 290, notes: 480 } });
214
+ const officialSourceSheet = addDataSheet("21 Official Sources", data.official_data_sources, schema.official_data_sources, { widths: { electoral_institution: 330, title: 430, url: 430, landing_url: 430, download_url: 430, geographic_granularity: 350, notes: 500 } });
215
+
216
+ const codebook = wb.worksheets.add("22 Codebook");
217
+ codebook.showGridLines = false;
218
+ const codebookRows = [
219
+ ["Concept", "Controlled value / rule", "Research meaning"],
220
+ ["record_layer", "claim_coded_core | screening_register | empirical_model_study", "These layers must never be counted together as incidents."],
221
+ ["record_type", "election_wide_case | observed_network | observed_incident | observed_campaign_set | preparedness_file", "Defines the unit. Preparedness is context, not an incident."],
222
+ ["manipulation_assessment", "manipulation_confirmed | mixed_documented_manipulation | transparent_contested_use | preparedness_not_incident", "AI use alone does not prove manipulation."],
223
+ ["claim_status", "supported | supported_as_attributed_measurement | partly_supported | unresolved", "Status of the claim as worded."],
224
+ ["evidence_strength", "high | moderate | low | none", "Evidence at claim level; numeric confidence is coder confidence in the label, not truth probability."],
225
+ ["agency_transfer_status", "full_chain_observed | partial_chain_observed | mechanism_observed_effect_unknown | mechanism_inferred | plausible_hypothesis | no_transfer_observed | insufficient_evidence | not_an_incident", "Separates observed control shift from outcome evidence."],
226
+ ["observations", "one measured quantity per row", "Never sum views, followers, calls, accounts, users or voters without compatible units and denominators."],
227
+ ["causal_status", "descriptive_only | association_only | causal estimates only with a design", "Official results and platform metrics are descriptive unless a causal design is recorded."],
228
+ ["model_evaluations", "study-specific unit, N, design, metrics and scope", "Capability evidence is not incident prevalence or real-world electoral effect."],
229
+ ["official turnout", "turnout_numerator + explicit measure", "For Moldova 2024, legal validity uses protocol C; D remains the participation count. For Moldova 2025 parliament, the official rate uses D."],
230
+ ["official result coverage", "complete_national_contest | complete | partial", "New Hampshire remains partial; complete groups reconcile to valid votes."],
231
+ ["missingness", "blank cell", "Use the literal unknown only when it is a controlled category."],
232
+ ["legacy multi-values", "pipe-delimited", "Prefer normalized claim_evidence, analytic_record_claims, case_elections and election_sources for joins."],
233
+ ["central prohibition", "no global prevalence or votes-changed estimate", "Sampling is purposive and most behavioural/electoral effects remain unknown."]
234
+ ];
235
+ codebook.getRange(`A1:C${codebookRows.length}`).values = codebookRows;
236
+ codebook.getRange("A1:C1").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
237
+ codebook.getRange(`A2:C${codebookRows.length}`).format = { borders: { preset: "all", style: "thin", color: "#D9DEE3" }, wrapText: true, verticalAlignment: "top" };
238
+ codebook.getRange(`A2:C${codebookRows.length}`).format.rowHeightPx = 66;
239
+ codebook.getRange(`A1:A${codebookRows.length}`).format.columnWidthPx = 230;
240
+ codebook.getRange(`B1:B${codebookRows.length}`).format.columnWidthPx = 420;
241
+ codebook.getRange(`C1:C${codebookRows.length}`).format.columnWidthPx = 550;
242
+ codebook.freezePanes.freezeRows(1);
243
+
244
+ const qa = wb.worksheets.add("23 QA");
245
+ qa.showGridLines = false;
246
+ qa.getRange("A1:D2").merge();
247
+ 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."],
255
+ ["Preparedness counted as incident", data.case_catalog.filter((r) => r.record_type === "preparedness_file" && r.incident_count_eligible === "true").length, 0, "Must remain zero."],
256
+ ["Model studies counted as incident", data.case_catalog.filter((r) => r.record_layer === "empirical_model_study" && r.incident_count_eligible === "true").length, 0, "Must remain zero."],
257
+ ["Claims without normalized evidence", data.claims.filter((r) => r.evidence_label !== "open_question" && !data.claim_evidence.some((e) => e.claim_id === r.claim_id)).length, 0, "Must remain zero."],
258
+ ["Typed observations", data.observations.length, stats.observations, "Must match generated stats."],
259
+ ["Complete RO/MD result groups", data.official_results.filter((r) => r.coverage_status === "complete_national_contest").length, 59, "Complete national candidate/party fields."],
260
+ ["Moldova legal-metric rows", data.official_election_metrics.filter((r) => r.geographic_unit_code === "MDA").length, 42, "Fields A–J and derived legal/participation rates."],
261
+ ["New Hampshire contest gap", data.official_election_metrics.find((r) => r.metric_code === "ballot_minus_contest_vote_gap")?.value || "", 1815, "Unclassified; not relabelled invalid/undervote."],
262
+ ["Release cutoff", "2026-08-12", "2026-08-12", "No later evidence is implied."]
263
+ ];
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);
271
+
272
+ for (const [meta, column, values] of [
273
+ [catalogSheet, "incident_count_eligible", ["TRUE", "FALSE"]],
274
+ [pathwaySheet, "assessment_label", ["established_evidence", "strong_inference", "plausible_hypothesis", "speculative_scenario", "open_question", "not_applicable"]],
275
+ [claimSheet, "evidence_strength", ["high", "moderate", "low", "none"]],
276
+ [claimSheet, "claim_status", ["supported", "supported_as_attributed_measurement", "partly_supported", "unresolved"]],
277
+ [sourceSheet, "source_quality", ["A", "B", "C", "D"]],
278
+ [electionSheet, "election_status", ["completed", "scheduled", "conditional"]],
279
+ [resultSheet, "coverage_status", ["complete_national_contest", "complete", "partial"]]
280
+ ]) {
281
+ const index = meta.columns.indexOf(column);
282
+ if (index >= 0 && meta.lastRow >= 2) {
283
+ const letter = excelColumn(index);
284
+ meta.sheet.getRange(`${letter}2:${letter}${meta.lastRow}`).dataValidation = { rule: { type: "list", values } };
285
+ }
286
+ }
287
+
288
+ const renderSheets = [
289
+ "00 Overview", "01 Research View", "02 Case Catalog", "03 Coverage", "04 Pathways", "05 Observations",
290
+ "06 Model Studies", "07 Claims", "08 Sources", "09 Claim Evidence", "10 Events", "11 Actors",
291
+ "12 Technology", "13 Content", "14 Cases Detail", "15 Screening Leads", "16 Watchlist",
292
+ "17 Official Elections", "18 Official Metrics", "19 Turnout Wide", "20 Official Results",
293
+ "21 Official Sources", "22 Codebook", "23 QA"
294
+ ];
295
+ for (const sheetName of renderSheets) {
296
+ const preview = await wb.render({ sheetName, autoCrop: "all", scale: ["00 Overview", "03 Coverage", "23 QA"].includes(sheetName) ? 0.8 : 0.34, format: "png" });
297
+ await fs.writeFile(path.join(previewDir, `${sheetName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-")}.png`), new Uint8Array(await preview.arrayBuffer()));
298
+ }
299
+
300
+ const inspection = await wb.inspect({ kind: "workbook,sheet,table,formula", maxChars: 18000, tableMaxRows: 4, tableMaxCols: 9, tableMaxCellChars: 90 });
301
+ await fs.writeFile(path.join(outputDir, "inspection.ndjson"), inspection.ndjson || String(inspection));
302
+ const verification = [];
303
+ for (const range of ["00 Overview!A1:H29", "01 Research View!A1:Q11", "03 Coverage!A1:E8", "18 Official Metrics!A1:Q20", "23 QA!A1:D21"]) {
304
+ const result = await wb.inspect({ kind: "table", range, include: "values,formulas", tableMaxRows: 30, tableMaxCols: 20 });
305
+ verification.push(result.ndjson || String(result));
306
+ }
307
+ const formulaErrors = await wb.inspect({ kind: "match", searchTerm: "#REF!|#DIV/0!|#VALUE!|#NAME\\?|#N/A", options: { useRegex: true, maxResults: 300 }, summary: "final formula error scan" });
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`);