File size: 81,442 Bytes
fb675fc
 
 
 
 
 
 
 
 
 
86456b4
57e5bea
bdd8da5
fb675fc
bdd8da5
fb675fc
86456b4
57e5bea
bdd8da5
 
 
fb675fc
 
57e5bea
 
fb675fc
86456b4
57e5bea
 
 
 
 
 
 
 
 
 
 
 
fb675fc
 
 
 
 
 
 
 
57e5bea
 
fb675fc
 
bdd8da5
fb675fc
 
bdd8da5
fb675fc
 
 
 
bdd8da5
57e5bea
fb675fc
 
 
 
57e5bea
 
fb675fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86456b4
 
 
 
 
 
 
 
 
 
57e5bea
 
86456b4
 
 
 
 
 
57e5bea
86456b4
 
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
57e5bea
bdd8da5
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb675fc
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84110a3
 
57e5bea
 
 
84110a3
57e5bea
 
 
 
 
84110a3
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84110a3
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84110a3
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
bdd8da5
 
 
 
 
 
 
 
57e5bea
 
84110a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
57e5bea
84110a3
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
57e5bea
bdd8da5
57e5bea
bdd8da5
 
57e5bea
bdd8da5
57e5bea
 
84110a3
bdd8da5
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
bdd8da5
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
 
 
 
84110a3
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb675fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86456b4
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
fb675fc
 
 
bdd8da5
 
fb675fc
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb675fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86456b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
bdd8da5
 
 
57e5bea
 
 
 
 
 
 
 
 
 
86456b4
fb675fc
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
bdd8da5
57e5bea
 
 
 
 
 
 
bdd8da5
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
57e5bea
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
 
 
84110a3
bdd8da5
 
57e5bea
 
 
bdd8da5
57e5bea
 
 
 
 
bdd8da5
57e5bea
 
 
 
 
84110a3
 
 
 
 
 
 
 
 
57e5bea
 
 
 
fb675fc
 
 
 
 
 
 
86456b4
57e5bea
bdd8da5
 
fb675fc
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, "..");
const seedPath = path.join(root, "research", "seed.json");
const candidatesPath = path.join(root, "research", "candidates.json");
const europeCandidatesPath = path.join(root, "research", "europe_candidates.json");
const officialElectoralDataPath = path.join(root, "research", "official_electoral_data.json");
const extensionsPath = path.join(root, "research", "v0.3_extensions.json");
const locatorsPath = path.join(root, "research", "v0.4_locators.json");
const outDir = path.join(root, "data");
const releaseVersion = "0.4.0";
const seed = JSON.parse(fs.readFileSync(seedPath, "utf8"));
const officialElectoralData = JSON.parse(fs.readFileSync(officialElectoralDataPath, "utf8"));
const extensions = JSON.parse(fs.readFileSync(extensionsPath, "utf8"));
const locatorAudit = JSON.parse(fs.readFileSync(locatorsPath, "utf8"));
const locatorRecords = locatorAudit.locators || {};
const unresolvedLocatorRecords = locatorAudit.unresolved || {};
seed.candidates = [
  ...JSON.parse(fs.readFileSync(candidatesPath, "utf8")),
  ...JSON.parse(fs.readFileSync(europeCandidatesPath, "utf8")),
  ...extensions.additional_candidates
];
Object.assign(seed, officialElectoralData);
seed.cases = [...seed.cases, ...extensions.additional_cases].map((row) => ({
  ...row,
  ...(extensions.case_metadata[row.case_id] || {})
}));
seed.claims = [...seed.claims, ...extensions.additional_claims];
seed.sources = [...seed.sources, ...extensions.additional_sources];
seed.events = [...seed.events, ...extensions.additional_events];
seed.case_sources = [...seed.case_sources, ...extensions.additional_case_sources];
const usElection = seed.official_elections.find((row) => row.election_id === "elec-us-midterms-2026");
if (usElection && !usElection.linked_case_ids.includes("us-ca11-2026-wiener-conniechan-chatbot")) {
  usElection.linked_case_ids += "|us-ca11-2026-wiener-conniechan-chatbot";
}
seed.events = [...seed.events].sort(
  (a, b) => a.event_date.localeCompare(b.event_date) || a.event_id.localeCompare(b.event_id)
);

const schemas = {
  cases: [
    "case_id", "case_family_id", "title", "country", "iso3", "region",
    "election_name", "election_type", "election_date_start", "election_date_end",
    "case_status", "as_of_date", "anchor_case", "record_type", "manipulation_assessment",
    "summary", "actor_controlling_system",
    "actor_type", "actor_attribution_status", "target_population", "influence_vector",
    "platforms", "mechanism_class", "ai_role", "generative_ai_status",
    "affected_state", "control_shift_hypothesis", "hypothesized_power_recipient", "democratic_harm",
    "occurrence_status", "reach_status", "reach_estimate", "reach_unit",
    "behavioural_effect_status", "electoral_effect_status", "institutional_outcome",
    "response", "inclusion_tier", "counterevidence",
    "open_questions", "last_verified"
  ],
  claims: [
    "claim_id", "case_id", "claim_type", "claim_text", "evidence_label",
    "claim_status", "evidence_basis", "evidence_scope",
    "source_ids", "counter_source_ids", "notes", "review_status", "verified_at"
  ],
  sources: [
    "source_id", "title", "publisher", "author", "publication_date", "url",
    "source_type", "primary_secondary", "jurisdiction", "language",
    "source_quality", "source_independence", "method_transparency", "access_status",
    "archive_url", "content_hash", "retrieved_at", "notes"
  ],
  events: [
    "event_id", "case_id", "event_date", "event_type", "description",
    "claim_ids", "source_ids", "event_status"
  ],
  case_sources: [
    "case_id", "source_id", "source_role", "supports_claim_types", "notes"
  ],
  watchlist: [
    "watch_id", "case_id", "jurisdiction", "election_date", "monitoring_window",
    "signal_category", "observable_indicator", "defensive_data_source",
    "assessment_rule", "status", "last_checked", "notes"
  ],
  candidates: [
    "candidate_id", "title", "country", "region", "election_name", "election_date",
    "research_status", "manipulation_class", "ai_role", "generative_ai_status",
    "occurrence_status", "attribution_status", "reach_status",
    "behavioural_effect_status", "electoral_effect_status", "comparative_value",
    "main_caveat", "source_urls", "last_checked"
  ],
  official_elections: [
    "election_id", "case_family_id", "linked_case_ids", "jurisdiction", "iso3",
    "election_name", "contest_type", "round", "election_date", "election_status",
    "legal_result_status", "administering_authority", "geographic_scope",
    "official_source_ids", "as_of_date", "notes"
  ],
  official_turnout: [
    "turnout_id", "election_id", "geographic_unit_type", "geographic_unit_code",
    "geographic_unit_name", "data_status", "electorate_measure", "participation_measure",
    "registered_voters", "ballots_cast", "turnout_numerator", "turnout_numerator_measure",
    "authority_reported_turnout_rate",
    "valid_votes", "invalid_votes", "turnout_rate", "reporting_units_total",
    "reporting_units_counted", "official_source_id", "as_of_date", "notes"
  ],
  official_results: [
    "result_id", "election_id", "geographic_unit_type", "geographic_unit_code",
    "geographic_unit_name", "contest_name", "candidate_or_option",
    "party_or_affiliation", "ballot_designating_entity", "votes", "valid_vote_share", "rank", "outcome", "seats",
    "result_status", "coverage_status", "official_source_id", "as_of_date", "notes"
  ],
  official_data_sources: [
    "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", "landing_url", "download_url", "published_or_updated_at",
    "retrieved_at", "content_sha256", "content_bytes", "source_schema_version",
    "snapshot_cutoff", "notes"
  ],
  official_election_metrics: [
    "metric_id", "election_id", "geographic_unit_type", "geographic_unit_code",
    "metric_code", "value", "source_field_code", "source_label_original",
    "numerator_metric", "denominator_metric", "authority_reported_rate", "computed_rate",
    "legal_role", "data_status", "official_source_id", "as_of_date", "notes"
  ],
  research_view: [
    "pathway_id", "case_id", "case_title", "country", "election_date", "record_type",
    "case_status", "manipulation_assessment", "generative_ai_status", "ai_role",
    "system_or_model", "controller", "influence_vector", "target", "agency_dimension",
    "capability_status", "control_mechanism_status", "attempted_transfer_status",
    "agency_change_status", "agency_preservation_status", "maximum_conclusion",
    "hypothesized_power_recipient", "reach_summary", "behavioural_effect",
    "electoral_effect", "case_evidence_summary", "main_uncertainty", "last_verified"
  ],
  case_catalog: [
    "catalog_id", "record_layer", "record_type", "title", "country", "region",
    "election_name", "election_date", "case_status", "manipulation_assessment",
    "ai_role", "generative_ai_status", "evidence_maturity", "incident_count_eligible",
    "research_status", "source_count_or_links", "main_caveat", "last_checked"
  ],
  case_actors: [
    "case_actor_id", "case_id", "actor_name", "actor_role", "actor_type",
    "attribution_status", "control_dimension", "source_claim_ids", "notes"
  ],
  technology_uses: [
    "tech_use_id", "case_id", "provider", "product_or_model", "version",
    "access_type", "technology_role", "use_status", "provenance_status",
    "evidence_label", "source_claim_ids", "notes"
  ],
  content_items: [
    "content_item_id", "case_id", "title", "media_type", "represented_person",
    "communication_goal", "representation_mode", "ai_disclosure", "authorization_status",
    "disclosure_salience", "presentation_mode", "source_claim_ids", "notes"
  ],
  pathways: [
    "pathway_id", "case_id", "agency_dimension", "hypothesized_control_shift_from", "hypothesized_control_shift_to",
    "mechanism", "opacity", "personalization", "contestability", "duration",
    "hypothesized_power_recipient", "potential_harm_pathway", "observed_outcome",
    "capability_status", "control_mechanism_status", "attempted_transfer_status",
    "agency_change_status", "agency_preservation_status", "maximum_conclusion",
    "falsification_condition", "comparator", "observed_evidence", "researcher_inference",
    "assessment_label", "source_claim_ids", "reviewer_note"
  ],
  observations: [
    "observation_id", "case_id", "pathway_id", "claim_id", "metric_family", "metric_name",
    "value_low", "value_best", "value_high", "value_operator", "unit", "denominator",
    "unique_entity_status", "platform", "geographic_scope", "measurement_window",
    "measurement_method", "causal_status", "source_id", "as_of_date", "limitations"
  ],
  model_evaluations: [
    "evaluation_id", "title", "country", "evaluation_window", "election_or_context",
    "systems_tested", "versions_known", "interface", "languages", "sample_unit",
    "sample_size", "design", "primary_metrics", "headline_results", "causal_scope",
    "source_id", "data_availability", "notes"
  ],
  claim_evidence: [
    "claim_evidence_id", "claim_id", "source_id", "relation", "evidence_scope",
    "directness", "locator", "locator_coverage", "locator_note", "extracted_at"
  ],
  analytic_record_claims: [
    "record_claim_id", "record_type", "record_id", "case_id", "claim_id", "relation"
  ],
  case_elections: [
    "case_election_id", "case_id", "election_id", "relation"
  ],
  election_sources: [
    "election_source_id", "election_id", "official_source_id", "source_role"
  ],
  sampling_frame: [
    "frame_id", "region", "selection_basis", "search_status", "search_languages",
    "source_channels", "included_case_count", "candidate_count", "negative_search_recorded",
    "known_gap", "last_searched"
  ],
  coverage_summary: [
    "region", "included_case_count", "candidate_count", "model_evaluation_count", "coverage_note"
  ]
};

function rowsFromArrays(rows, columns) {
  return rows.map((values) => Object.fromEntries(columns.map((column, index) => [column, values[index] ?? ""])));
}

function appendPipe(value, item) {
  const items = new Set(String(value || "").split("|").filter(Boolean));
  items.add(item);
  return [...items].join("|");
}

function regionForCountry(country) {
  const map = {
    Romania: "Europe", Moldova: "Europe", Hungary: "Europe", "United Kingdom": "Europe",
    "European Union": "Europe", Brazil: "South America", Colombia: "South America",
    Ecuador: "South America", Canada: "North America", "United States": "North America",
    Japan: "Asia", Australia: "Oceania", Poland: "Europe"
  };
  if (String(country).includes("|")) return "Cross-national";
  return map[country] || "Other";
}

function canonicalRegion(region) {
  if (["East Asia", "South Asia", "Southeast Asia", "Central Asia", "West Asia"].includes(region)) return "Asia";
  if (["East Africa", "West Africa", "Southern Africa", "North Africa", "Central Africa"].includes(region)) return "Africa";
  return region;
}

const additionalOfficialSources = [
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["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."],
  ["off-nh-2024-dnc-status", "new-hampshire-biden-robocall-2024", "New Hampshire", "New Hampshire Department of Justice", "Unlawful Voter Suppression Cease and Desist Order", "https://www.doj.nh.gov/news-and-media/unlawful-voter-suppression-cease-and-desist-order", "institutional_primary_and_delegate_status", "final", "HTML official statement", "state", "landing page", "finalized election record", "official state statement", "2026-08-12", "Documents the institutional dispute and that the DNC did not award delegates from the 23 January state-run result; do not describe the election as legally nonexistent or infer a delegate allocation from its vote tally."]
].map((values) => {
  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"];
  const row = Object.fromEntries(oldColumns.map((column, index) => [column, values[index] ?? ""]));
  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" };
});
seed.official_data_sources.push(...additionalOfficialSources);
seed.official_data_sources = seed.official_data_sources.map((row) => ({
  ...row,
  landing_url: row.landing_url || row.url,
  download_url: row.download_url || (/direct.*download/i.test(row.access_method || "") ? row.url : ""),
  published_or_updated_at: row.published_or_updated_at || "",
  content_sha256: row.content_sha256 || "",
  content_bytes: row.content_bytes || "",
  source_schema_version: row.source_schema_version || "",
  snapshot_cutoff: row.snapshot_cutoff || "2026-08-12"
}));

const officialSourceById = new Map(seed.official_data_sources.map((row) => [row.official_source_id, row]));
const oldH32 = officialSourceById.get("off-ro-2024-ccr-annulment");
if (oldH32) {
  oldH32.url = "https://legislatie.just.ro/Public/DetaliiDocumentAfis/292099";
  oldH32.title = "Decision 32 of 6 December 2024 voiding the entire presidential electoral process";
}

for (const election of seed.official_elections) {
  if (election.election_id === "elec-ro-pres-2024-r1") {
    election.legal_result_status = "validated_then_void";
    election.official_source_ids = appendPipe(election.official_source_ids, "off-ro-2024-ccr-h31");
    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.";
  }
  if (election.election_id === "elec-ro-pres-2025-r1") {
    election.legal_result_status = "CCR_confirmed_and_validated_2025-05-09";
    election.official_source_ids = appendPipe(election.official_source_ids, "off-ro-2025-ccr-h39");
  }
  if (election.election_id === "elec-ro-pres-2025-r2") {
    election.legal_result_status = "CCR_confirmed_and_president_elected_2025-05-22";
    election.official_source_ids = appendPipe(appendPipe(election.official_source_ids, "off-ro-2025-ccr-h43"), "off-ro-2025-ccr-h44");
  }
  if (election.election_id === "elec-md-pres-2024-r1" || election.election_id === "elec-md-pres-2024-r2") {
    election.legal_result_status = "CEC_final_and_Constitutional_Court_confirmed";
    election.official_source_ids = appendPipe(election.official_source_ids, "off-md-2024-pres-cc-h25");
  }
  if (election.election_id === "elec-md-referendum-2024") {
    election.legal_result_status = "law_adopted_and_Constitutional_Court_confirmed";
    election.official_source_ids = appendPipe(election.official_source_ids, "off-md-2024-ref-cc-h24");
    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.";
  }
  if (election.election_id === "elec-md-parl-2025") {
    election.legal_result_status = "CEC_valid_Constitutional_Court_confirmed_101_mandates";
    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");
  }
  if (election.election_id === "elec-br-general-2026-r1") {
    election.contest_type = "election_bundle";
    election.election_name = "Brazil 2026 first-round election bundle";
    election.official_source_ids = appendPipe(election.official_source_ids, "off-br-2026-contests");
    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.";
  }
  if (election.election_id === "elec-br-general-2026-r2") {
    election.contest_type = "conditional_executive_runoffs";
    election.election_name = "Brazil 2026 conditional presidential and gubernatorial runoffs";
    election.official_source_ids = appendPipe(election.official_source_ids, "off-br-2026-contests");
    election.notes = "25 October is limited to president and governors requiring a runoff; it is not a second round for legislative contests.";
  }
  if (election.election_id === "elec-us-midterms-2026") {
    election.contest_type = "election_bundle";
    election.round = "varies_by_jurisdiction";
    election.election_name = "United States 2026 federal election bundle";
    election.administering_authority = "state and local election authorities; no single national certifier";
    election.official_source_ids = appendPipe(election.official_source_ids, "off-us-congress-election-law");
    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.";
  }
  if (election.election_id === "elec-us-nh-dem-primary-2024") {
    election.official_source_ids = appendPipe(appendPipe(election.official_source_ids, "off-nh-2024-primary-law"), "off-nh-2024-dnc-status");
    election.notes = "The 23 January event was a state-run primary with a final state tally, but the DNC did not award delegates from that result. The tally therefore has delegate_effect=none_from_Jan23_results. The all-party checklist is not a valid Democratic-primary turnout denominator because undeclared voters may choose a party ballot and same-day registration or party changes occur.";
  }
}

const mdTurnout = {
  "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." },
  "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." },
  "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." },
  "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)." }
};
for (const row of seed.official_turnout) {
  row.turnout_numerator = row.ballots_cast;
  row.turnout_numerator_measure = row.participation_measure;
  row.authority_reported_turnout_rate = row.turnout_rate;
  const exact = mdTurnout[row.turnout_id];
  if (exact) {
    row.electorate_measure = "post-election protocol fields A+B: basic-list plus supplementary-list electors; not a conventional fixed ex-ante register";
    row.participation_measure = "protocol field D: voters who participated";
    row.registered_voters = exact.A + exact.B;
    row.ballots_cast = exact.D;
    row.turnout_numerator = exact[exact.numerator];
    row.turnout_numerator_measure = `protocol field ${exact.numerator}: ${exact.numerator === "C" ? "voters receiving ballots" : "voters who participated"}`;
    row.valid_votes = exact.H;
    row.invalid_votes = exact.F;
    row.turnout_rate = exact.rate;
    row.authority_reported_turnout_rate = exact.reported;
    row.notes = `${exact.note} C=${exact.C}; D=${exact.D}; E=C-D=${exact.E}.`;
  }
  if (row.turnout_id === "turnout-nh-2024-dem-primary-state") {
    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.";
  }
  if (row.turnout_id === "electorate-br-2026-audited-national") {
    row.electorate_measure = "official eligible electorate published by TSE after registration closed";
  }
}

const metricRows = [];
function addMetric(electionId, geoType, geoCode, code, value, sourceCode, label, numerator, denominator, reported, computed, legalRole, status, sourceId, notes = "") {
  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 });
}
for (const row of seed.official_turnout.filter((item) => !mdTurnout[item.turnout_id])) {
  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);
  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);
  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);
  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);
}
for (const row of seed.official_turnout.filter((item) => mdTurnout[item.turnout_id])) {
  const m = mdTurnout[row.turnout_id];
  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" };
  for (const code of ["A", "B", "C", "D", "E", "F", "H", "I", "J"]) {
    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);
  }
  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);
  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);
  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);
}
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.");
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.");
seed.official_election_metrics = metricRows;

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 };
for (const row of seed.official_results) {
  row.ballot_designating_entity = row.ballot_designating_entity || "";
  row.seats = row.seats ?? "";
  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";
  if (row.election_id === "elec-ro-pres-2024-r1") row.result_status = "final_tally_validated_then_process_void";
  if (row.election_id === "elec-ro-pres-2025-r1") row.result_status = "CCR_confirmed_and_validated";
  if (row.election_id === "elec-ro-pres-2025-r2") row.result_status = "CCR_confirmed_and_validated";
  if (row.election_id.startsWith("elec-md-")) row.result_status = "CEC_final_and_Constitutional_Court_confirmed";
  if (row.result_id === "result-md24r1-maia-sandu") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PAS"; }
  if (row.result_id === "result-md24r1-alexandr-stoianoglo") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PSRM"; }
  if (row.result_id === "result-md24r2-maia-sandu") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PAS"; }
  if (row.result_id === "result-md24r2-alexandr-stoianoglo") { row.party_or_affiliation = ""; row.ballot_designating_entity = "PSRM"; }
  if (row.coverage_status === "complete_national_contest" && /Top-(?:three|five) extract|Top-five vote extract/i.test(row.notes || "")) {
    row.notes = "Complete national contest field in this release.";
  }
}

const extraResults = [];
function addResult(id, electionId, name, affiliation, designator, votes, rank, outcome, seats, sourceId, notes = "") {
  const total = resultTotals[electionId];
  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 });
}
[
  ["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]
].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."));
[
  ["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]
].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"));
[
  ["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]
].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"));

const mdSeats = {
  "result-mdparl-pas": ["Partidul Acțiune și Solidaritate (PAS)", 55, "gained_seats"],
  "result-mdparl-patriotic-bloc": ["Blocul Electoral Patriotic al Socialiștilor, Comuniștilor, Inima și Viitorul Moldovei", 26, "gained_seats"],
  "result-mdparl-alternative-bloc": ["Blocul Electoral Alternativa", 8, "gained_seats"],
  "result-mdparl-our-party": ["Partidul Nostru", 6, "gained_seats"],
  "result-mdparl-democracy-at-home": ["Partidul Democrația Acasă", 6, "gained_seats"]
};
for (const row of seed.official_results) {
  if (mdSeats[row.result_id]) {
    [row.candidate_or_option, row.seats, row.outcome] = mdSeats[row.result_id];
    row.official_source_id = "off-md-2025-cec-h4151";
  }
}
[
  ["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]
].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"));
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.");
seed.official_results.push(...extraResults);

const claimSemantics = {
  established_evidence: ["supported_as_worded", "supported_as_worded"],
  established_as_campaign_report: ["supported_as_attributed_measurement", "attributed_measurement_only"],
  strong_inference: ["partly_supported", "inferential_synthesis"],
  researcher_hypothesis: ["hypothesis_not_tested", "not_tested"],
  not_identified_in_declared_review: ["not_identified_in_declared_review", "review_bounded_absence"],
  open_question: ["unresolved", "none"]
};
const assertionClaimIds = new Set([
  "clm-ro-002", "clm-ro-005", "clm-ro-011", "clm-ro-013",
  "clm-md-004", "clm-md-005", "clm-md-007", "clm-md-008", "clm-md-012", "clm-md-014",
  "clm-br-012", "clm-br-015", "clm-br-019",
  "clm-us26-004", "clm-us26-006",
  "clm-usca11-003", "clm-usca11-006"
]);
function evidenceScopeForClaim(claim) {
  if (assertionClaimIds.has(claim.claim_id)) return "assertion_was_made";
  if (["strong_inference", "researcher_hypothesis"].includes(claim.evidence_label)) return "researcher_inference";
  if (claim.evidence_label === "not_identified_in_declared_review") return "review_scope_statement";
  if (claim.claim_type === "reach") return "measurement";
  if (claim.claim_type === "response") return "institutional_action";
  if (claim.evidence_label === "open_question") return "researcher_inference";
  return "underlying_fact";
}
seed.claims = seed.claims.map((claim) => {
  const semantics = claimSemantics[claim.evidence_label];
  if (!semantics) throw new Error(`Unknown evidence label in ${claim.claim_id}: ${claim.evidence_label}`);
  return {
    ...claim,
    claim_status: semantics[0],
    evidence_basis: semantics[1],
    evidence_scope: evidenceScopeForClaim(claim)
  };
});

const claimTypesByCase = new Map();
for (const claim of seed.claims) {
  if (!claimTypesByCase.has(claim.case_id)) claimTypesByCase.set(claim.case_id, new Set());
  claimTypesByCase.get(claim.case_id).add(claim.claim_type);
}
seed.case_sources = seed.case_sources.map((link) => {
  const availableTypes = claimTypesByCase.get(link.case_id) || new Set();
  const declaredTypes = String(link.supports_claim_types || "").split("|").filter(Boolean);
  const supportedTypes = declaredTypes.filter((type) => availableTypes.has(type));
  const removedTypes = declaredTypes.filter((type) => !availableTypes.has(type));
  return {
    ...link,
    supports_claim_types: supportedTypes.join("|"),
    notes: removedTypes.length
      ? `${link.notes ? `${link.notes} ` : ""}Contextual source roles not represented by an atomic claim in this release were omitted from supports_claim_types: ${removedTypes.join("|")}.`
      : link.notes
  };
});

seed.sources = seed.sources.map((source) => {
  const interestedTypes = /campaign|platform|provider|party/.test(source.source_type);
  const reproducibleTypes = /model_evaluation|peer_reviewed|dataset|methodology/.test(source.source_type);
  return {
    ...source,
    source_independence: source.source_independence || (interestedTypes ? "interested_or_mixed" : source.primary_secondary === "primary" ? "independent_or_official" : "independent_secondary"),
    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"),
    access_status: source.access_status || "public_url_at_cutoff",
    archive_url: source.archive_url || "",
    content_hash: source.content_hash || ""
  };
});

seed.case_actors = rowsFromArrays(extensions.case_actors, schemas.case_actors);
seed.technology_uses = rowsFromArrays(extensions.technology_uses, schemas.technology_uses);
seed.content_items = rowsFromArrays(extensions.content_items, schemas.content_items);
seed.pathways = rowsFromArrays(extensions.control_shift_assessments, schemas.pathways);
seed.model_evaluations = rowsFromArrays(extensions.model_evaluations, schemas.model_evaluations);
for (const actor of seed.case_actors) {
  if (actor.case_actor_id === "act-usca11-chan" && actor.attribution_status === "established") {
    actor.attribution_status = "credibly_reported";
  }
}

const pathwayByCase = new Map(seed.pathways.map((row) => [row.case_id, row.pathway_id]));
const caseById = new Map(seed.cases.map((row) => [row.case_id, row]));
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";
seed.observations = extensions.quantitative_observations.map((values) => {
  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;
  const exact = ["exact", "exact_report", "exact_campaign_report"].includes(value_operator);
  const atLeast = String(value_operator).startsWith("at_least");
  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 };
});

const sourceById = new Map(seed.sources.map((row) => [row.source_id, row]));
for (const [sourceId, replacement] of Object.entries(locatorAudit.source_replacements || {})) {
  const source = sourceById.get(sourceId);
  if (!source) throw new Error(`Locator audit source replacement is unknown: ${sourceId}`);
  if (source.url !== replacement.url) throw new Error(`Locator audit source replacement was not applied: ${sourceId}`);
}
seed.claim_evidence = [];
const generatedLocatorKeys = new Set();
for (const claim of seed.claims) {
  const evidenceScope = claim.evidence_scope;
  for (const [sourceRelation, ids] of [["supports", claim.source_ids], ["counterevidence", claim.counter_source_ids]]) {
    for (const sourceId of String(ids || "").split("|").filter(Boolean)) {
      const relation = sourceRelation === "supports" && evidenceScope === "researcher_inference" ? "premise" : sourceRelation;
      const source = sourceById.get(sourceId);
      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";
      const locatorKey = `${claim.claim_id}|${sourceId}|${relation}`;
      if (generatedLocatorKeys.has(locatorKey)) throw new Error(`Duplicate claim-evidence locator key: ${locatorKey}`);
      generatedLocatorKeys.add(locatorKey);
      const locatorRecord = locatorRecords[locatorKey];
      const unresolvedLocatorRecord = unresolvedLocatorRecords[locatorKey];
      if (Boolean(locatorRecord) === Boolean(unresolvedLocatorRecord)) {
        throw new Error(`Locator audit must classify exactly once: ${locatorKey}`);
      }
      const locator = locatorRecord?.locator || "";
      const locator_coverage = locatorRecord?.coverage || "not_verified";
      const locator_note = unresolvedLocatorRecord?.reason || "";
      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, locator_coverage, locator_note, extracted_at: claim.verified_at });
    }
  }
}
for (const locatorKey of [...Object.keys(locatorRecords), ...Object.keys(unresolvedLocatorRecords)]) {
  if (!generatedLocatorKeys.has(locatorKey)) throw new Error(`Locator audit key is not present in generated claim evidence: ${locatorKey}`);
}

seed.analytic_record_claims = [];
for (const [recordType, table, idField] of [
  ["case_actor", seed.case_actors, "case_actor_id"],
  ["technology_use", seed.technology_uses, "tech_use_id"],
  ["content_item", seed.content_items, "content_item_id"],
  ["pathway", seed.pathways, "pathway_id"],
  ["event", seed.events, "event_id"]
]) {
  for (const record of table) {
    for (const claimId of String(record.source_claim_ids || record.claim_ids || "").split("|").filter(Boolean)) {
      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" });
    }
  }
}

seed.case_elections = [];
seed.election_sources = [];
for (const election of seed.official_elections) {
  for (const caseId of String(election.linked_case_ids || "").split("|").filter(Boolean)) {
    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" });
  }
  for (const sourceId of String(election.official_source_ids || "").split("|").filter(Boolean)) {
    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" });
  }
}

function evidenceForCase(caseId) {
  const item = caseById.get(caseId);
  if (item?.record_type === "preparedness_file") return "governance_context_not_incident";
  const claims = seed.claims.filter((claim) => claim.case_id === caseId);
  const occurrenceSupported = claims.some((claim) => ["occurrence", "mechanism", "ai_role"].includes(claim.claim_type) && claim.claim_status === "supported_as_worded");
  const outcomeSupported = claims.some((claim) => ["behavioural_effect", "electoral_effect"].includes(claim.claim_type) && claim.claim_status === "supported_as_worded");
  if (occurrenceSupported && !outcomeSupported) return "occurrence_supported_agency_effect_not_established";
  if (occurrenceSupported && outcomeSupported) return "occurrence_and_bounded_outcome_supported";
  return "mixed_or_unresolved";
}
function reachForCase(caseId) {
  const rows = seed.observations.filter((row) => row.case_id === caseId).slice(0, 2);
  if (!rows.length) return "No typed population-reach estimate";
  return rows.map((row) => `${Number(row.value_best).toLocaleString("en-US")} ${row.unit}; ${row.measurement_method}; ${row.unique_entity_status}; ${row.measurement_window}`).join(" | ");
}
seed.research_view = seed.pathways.map((pathway) => {
  const item = caseById.get(pathway.case_id);
  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";
  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,
    agency_dimension: pathway.agency_dimension,
    capability_status: pathway.capability_status,
    control_mechanism_status: pathway.control_mechanism_status,
    attempted_transfer_status: pathway.attempted_transfer_status,
    agency_change_status: pathway.agency_change_status,
    agency_preservation_status: pathway.agency_preservation_status,
    maximum_conclusion: pathway.maximum_conclusion,
    hypothesized_power_recipient: pathway.hypothesized_power_recipient,
    reach_summary: reachForCase(item.case_id),
    behavioural_effect: item.behavioural_effect_status,
    electoral_effect: item.electoral_effect_status,
    case_evidence_summary: evidenceForCase(item.case_id),
    main_uncertainty: item.open_questions,
    last_verified: item.last_verified
  };
});

const sourceCountByCase = new Map();
for (const link of seed.case_sources) sourceCountByCase.set(link.case_id, (sourceCountByCase.get(link.case_id) || 0) + 1);
seed.case_catalog = [
  ...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 })),
  ...seed.candidates.map((row) => ({ catalog_id: row.candidate_id, record_layer: "screening_register", record_type: "candidate_lead", title: row.title, country: row.country, region: row.region, election_name: row.election_name, election_date: row.election_date, case_status: "screening", manipulation_assessment: "not_yet_claim_coded", ai_role: row.ai_role, generative_ai_status: row.generative_ai_status, evidence_maturity: row.occurrence_status, incident_count_eligible: "false", research_status: row.research_status, source_count_or_links: String(row.source_urls || "").split("|").filter(Boolean).length, main_caveat: row.main_caveat, last_checked: row.last_checked })),
  ...seed.model_evaluations.map((row) => ({ catalog_id: row.evaluation_id, record_layer: "empirical_model_study", record_type: "model_evaluation_or_experiment", title: row.title, country: row.country, region: regionForCountry(row.country), election_name: row.election_or_context, election_date: "", case_status: "completed_study", manipulation_assessment: "not_an_incident", ai_role: "tested_system_capability", generative_ai_status: "confirmed_tested_system", evidence_maturity: "study_design_specific", incident_count_eligible: "false", research_status: "included_empirical_study", source_count_or_links: 1, main_caveat: `Evaluation window: ${row.evaluation_window}. ${row.causal_scope}`, last_checked: "2026-08-12" }))
];

const frameNotes = {
  Europe: "Strongest current core coverage; still purposive and concentrated in Romania/Moldova.",
  "North America": "One adjudicated 2024 robocall, two 2026 campaign records, and several model audits; no prevalence frame.",
  "South America": "Brazil core is mainly preparedness/current use; completed Colombia/Ecuador leads remain to be disaggregated.",
  Asia: "Screening leads exist but no claim-coded core case yet.",
  Africa: "Screening leads exist but no claim-coded core case yet.",
  Oceania: "One knowledge-poisoning lead; no claim-coded core case yet.",
  "Cross-national": "Empirical studies span jurisdictions; not incident counts."
};
const regions = Object.keys(frameNotes);
seed.sampling_frame = regions.map((region) => {
  const included = seed.cases.filter((row) => canonicalRegion(row.region) === region).length;
  const candidates = seed.candidates.filter((row) => canonicalRegion(row.region) === region).length;
  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" };
});
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] }));

function csvCell(value) {
  if (value === null || value === undefined) return "";
  const s = Array.isArray(value) ? value.join("|") : String(value);
  return /[",\n\r]/.test(s) ? '"' + s.replaceAll('"', '""') + '"' : s;
}

function toCsv(rows, columns) {
  const lines = [columns.map(csvCell).join(",")];
  for (const row of rows) {
    lines.push(columns.map((column) => csvCell(row[column])).join(","));
  }
  return lines.join("\n") + "\n";
}

function sha256(value) {
  return createHash("sha256").update(value).digest("hex");
}

function assertUnique(rows, key, table) {
  const seen = new Set();
  for (const row of rows) {
    if (!row[key]) throw new Error(table + " has a row without " + key);
    if (seen.has(row[key])) throw new Error(table + " has duplicate " + key + ": " + row[key]);
    seen.add(row[key]);
  }
  return seen;
}

function splitIds(value) {
  return String(value || "").split("|").map((v) => v.trim()).filter(Boolean);
}

const caseIds = assertUnique(seed.cases, "case_id", "cases");
const claimIds = assertUnique(seed.claims, "claim_id", "claims");
const sourceIds = assertUnique(seed.sources, "source_id", "sources");
assertUnique(seed.events, "event_id", "events");
assertUnique(seed.watchlist, "watch_id", "watchlist");
assertUnique(seed.candidates, "candidate_id", "candidates");
assertUnique(seed.official_elections, "election_id", "official_elections");
assertUnique(seed.official_turnout, "turnout_id", "official_turnout");
assertUnique(seed.official_results, "result_id", "official_results");
assertUnique(seed.official_data_sources, "official_source_id", "official_data_sources");
assertUnique(seed.official_election_metrics, "metric_id", "official_election_metrics");
assertUnique(seed.case_actors, "case_actor_id", "case_actors");
assertUnique(seed.technology_uses, "tech_use_id", "technology_uses");
assertUnique(seed.content_items, "content_item_id", "content_items");
assertUnique(seed.pathways, "pathway_id", "pathways");
assertUnique(seed.observations, "observation_id", "observations");
assertUnique(seed.model_evaluations, "evaluation_id", "model_evaluations");
assertUnique(seed.claim_evidence, "claim_evidence_id", "claim_evidence");
assertUnique(seed.analytic_record_claims, "record_claim_id", "analytic_record_claims");
assertUnique(seed.case_elections, "case_election_id", "case_elections");
assertUnique(seed.election_sources, "election_source_id", "election_sources");

for (const claim of seed.claims) {
  if (!caseIds.has(claim.case_id)) throw new Error("Unknown case in claim " + claim.claim_id);
  if (!claim.source_ids && !["open_question", "researcher_hypothesis", "not_identified_in_declared_review"].includes(claim.evidence_label)) {
    throw new Error("Evidence claim without source: " + claim.claim_id);
  }
  for (const sourceId of [...splitIds(claim.source_ids), ...splitIds(claim.counter_source_ids)]) {
    if (!sourceIds.has(sourceId)) throw new Error("Unknown source " + sourceId + " in " + claim.claim_id);
  }
}

const pathwayStatusEnums = {
  capability_status: new Set(["observed", "not_observed", "not_assessed", "not_applicable"]),
  control_mechanism_status: new Set(["observed", "not_observed", "not_assessed", "not_applicable"]),
  attempted_transfer_status: new Set(["observed", "not_observed", "insufficient_evidence", "not_applicable"]),
  agency_change_status: new Set(["observed", "not_observed", "insufficient_evidence", "not_applicable"]),
  agency_preservation_status: new Set(["observed", "not_observed", "insufficient_evidence", "not_applicable"]),
  maximum_conclusion: new Set(["control_mechanism_observed", "attempted_transfer_observed", "agency_change_observed", "agency_preserved_or_extended", "insufficient_evidence", "not_an_incident"]),
  assessment_label: new Set(["observed_mechanism", "observed_attempt_with_unmeasured_agency", "boundary_case", "not_applicable"])
};
for (const pathway of seed.pathways) {
  for (const [field, allowed] of Object.entries(pathwayStatusEnums)) {
    if (!allowed.has(pathway[field])) throw new Error(`Invalid ${field} in ${pathway.pathway_id}: ${pathway[field]}`);
  }
  if (!pathway.maximum_conclusion || !pathway.falsification_condition || !pathway.comparator || !pathway.observed_evidence) {
    throw new Error(`Incomplete falsifiability fields in ${pathway.pathway_id}`);
  }
  if (pathway.agency_change_status === "observed" && pathway.maximum_conclusion !== "agency_change_observed") {
    throw new Error(`Observed agency change without matching maximum conclusion in ${pathway.pathway_id}`);
  }
}

for (const event of seed.events) {
  if (!caseIds.has(event.case_id)) throw new Error("Unknown case in event " + event.event_id);
  for (const claimId of splitIds(event.claim_ids)) {
    if (!claimIds.has(claimId)) throw new Error("Unknown claim " + claimId + " in " + event.event_id);
  }
  for (const sourceId of splitIds(event.source_ids)) {
    if (!sourceIds.has(sourceId)) throw new Error("Unknown source " + sourceId + " in " + event.event_id);
  }
}

for (const link of seed.case_sources) {
  if (!caseIds.has(link.case_id)) throw new Error("Unknown case in case_sources: " + link.case_id);
  if (!sourceIds.has(link.source_id)) throw new Error("Unknown source in case_sources: " + link.source_id);
}

for (const item of seed.watchlist) {
  if (!caseIds.has(item.case_id)) throw new Error("Unknown case in watchlist " + item.watch_id);
}

const electionIds = new Set(seed.official_elections.map((row) => row.election_id));
const officialSourceIds = new Set(seed.official_data_sources.map((row) => row.official_source_id));
for (const election of seed.official_elections) {
  for (const caseId of splitIds(election.linked_case_ids)) {
    if (!caseIds.has(caseId)) throw new Error("Unknown linked case " + caseId + " in " + election.election_id);
  }
  for (const sourceId of splitIds(election.official_source_ids)) {
    if (!officialSourceIds.has(sourceId)) throw new Error("Unknown official source " + sourceId + " in " + election.election_id);
  }
}
for (const row of seed.official_turnout) {
  if (!electionIds.has(row.election_id)) throw new Error("Unknown election in official_turnout " + row.turnout_id);
  if (!officialSourceIds.has(row.official_source_id)) throw new Error("Unknown official source in official_turnout " + row.turnout_id);
}
for (const row of seed.official_results) {
  if (!electionIds.has(row.election_id)) throw new Error("Unknown election in official_results " + row.result_id);
  if (!officialSourceIds.has(row.official_source_id)) throw new Error("Unknown official source in official_results " + row.result_id);
}
for (const row of seed.official_election_metrics) {
  if (!electionIds.has(row.election_id)) throw new Error("Unknown election in official_election_metrics " + row.metric_id);
  if (!officialSourceIds.has(row.official_source_id)) throw new Error("Unknown official source in official_election_metrics " + row.metric_id);
}
for (const row of [...seed.case_actors, ...seed.technology_uses, ...seed.content_items, ...seed.pathways, ...seed.observations]) {
  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));
}
for (const row of seed.claim_evidence) {
  if (!claimIds.has(row.claim_id) || !sourceIds.has(row.source_id)) throw new Error("Unknown claim/source in " + row.claim_evidence_id);
  if (!["full_claim", "partial_claim", "not_verified"].includes(row.locator_coverage)) throw new Error("Invalid locator coverage in " + row.claim_evidence_id);
  if ((row.locator_coverage === "not_verified") !== !row.locator) throw new Error("Locator and coverage disagree in " + row.claim_evidence_id);
  if (row.locator_coverage === "not_verified" && !row.locator_note) throw new Error("Unverified locator reason missing in " + row.claim_evidence_id);
}
for (const row of seed.analytic_record_claims) {
  if (!caseIds.has(row.case_id) || !claimIds.has(row.claim_id)) throw new Error("Unknown case/claim in " + row.record_claim_id);
}
for (const row of seed.case_elections) {
  if (!caseIds.has(row.case_id) || !electionIds.has(row.election_id)) throw new Error("Unknown case/election in " + row.case_election_id);
}
for (const row of seed.election_sources) {
  if (!electionIds.has(row.election_id) || !officialSourceIds.has(row.official_source_id)) throw new Error("Unknown election/source in " + row.election_source_id);
}

fs.mkdirSync(outDir, { recursive: true });
const fileHashes = {};
for (const [table, columns] of Object.entries(schemas)) {
  const filename = table + ".csv";
  const text = toCsv(seed[table], columns);
  fs.writeFileSync(path.join(outDir, filename), text);
  fileHashes[filename] = sha256(text);
}

const schemaText = JSON.stringify(schemas, null, 2) + "\n";
fs.writeFileSync(path.join(outDir, "schema.json"), schemaText);
fileHashes["schema.json"] = sha256(schemaText);

const primaryKeys = {
  cases: "case_id", claims: "claim_id", sources: "source_id", events: "event_id",
  case_sources: ["case_id", "source_id"],
  watchlist: "watch_id", candidates: "candidate_id", official_elections: "election_id",
  official_turnout: "turnout_id", official_results: "result_id",
  official_data_sources: "official_source_id", official_election_metrics: "metric_id",
  case_catalog: "catalog_id", case_actors: "case_actor_id", technology_uses: "tech_use_id",
  content_items: "content_item_id", pathways: "pathway_id", observations: "observation_id",
  model_evaluations: "evaluation_id", claim_evidence: "claim_evidence_id",
  analytic_record_claims: "record_claim_id", case_elections: "case_election_id",
  election_sources: "election_source_id", sampling_frame: "frame_id",
  research_view: "pathway_id", coverage_summary: "region"
};
const foreignKeys = {
  claims: [["case_id", "cases", "case_id"]],
  events: [["case_id", "cases", "case_id"]],
  case_sources: [["case_id", "cases", "case_id"], ["source_id", "sources", "source_id"]],
  watchlist: [["case_id", "cases", "case_id"]],
  official_turnout: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]],
  official_results: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]],
  official_election_metrics: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]],
  research_view: [["case_id", "cases", "case_id"], ["pathway_id", "pathways", "pathway_id"]],
  case_actors: [["case_id", "cases", "case_id"]],
  technology_uses: [["case_id", "cases", "case_id"]],
  content_items: [["case_id", "cases", "case_id"]],
  pathways: [["case_id", "cases", "case_id"]],
  observations: [["case_id", "cases", "case_id"], ["pathway_id", "pathways", "pathway_id"], ["claim_id", "claims", "claim_id"], ["source_id", "sources", "source_id"]],
  claim_evidence: [["claim_id", "claims", "claim_id"], ["source_id", "sources", "source_id"]],
  analytic_record_claims: [["case_id", "cases", "case_id"], ["claim_id", "claims", "claim_id"]],
  case_elections: [["case_id", "cases", "case_id"], ["election_id", "official_elections", "election_id"]],
  election_sources: [["election_id", "official_elections", "election_id"], ["official_source_id", "official_data_sources", "official_source_id"]]
};
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"]);
const numberFields = new Set(["turnout_rate", "authority_reported_turnout_rate", "valid_vote_share", "authority_reported_rate", "computed_rate", "value", "value_low", "value_best", "value_high"]);
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"]);
const booleanFields = new Set(["anchor_case", "incident_count_eligible", "negative_search_recorded"]);
const fieldMetadata = {
  "cases.record_type": { description: "Unit of analysis; different record types are not automatically exchangeable.", constraints: { required: true, enum: ["election_wide_case", "observed_network", "observed_incident", "observed_campaign_set", "preparedness_file"] } },
  "cases.case_status": { constraints: { required: true, enum: ["retrospective", "ongoing", "prospective_monitoring"] } },
  "cases.manipulation_assessment": { description: "Process assessment kept separate from agency and electoral outcomes.", constraints: { required: true, enum: ["manipulation_confirmed", "manipulation_probable", "mixed_documented_manipulation", "transparent_contested_use", "manipulation_not_established", "no_manipulation_observed", "preparedness_not_incident", "not_an_incident"] } },
  "cases.affected_state": { description: "Decision-relevant dimension examined; not a claim that the state changed." },
  "cases.control_shift_hypothesis": { description: "Falsifiable analytical proposition; not an observed agency outcome." },
  "cases.hypothesized_power_recipient": { description: "Actor that could gain control if the hypothesis is supported; not an observed concentration-of-power finding." },
  "cases.democratic_harm": { description: "Harm assessment that must distinguish documented process or institutional harm from plausible but unmeasured outcome harm." },
  "cases.occurrence_status": { constraints: { required: true, enum: ["confirmed", "partly_confirmed", "alleged", "not_observed"] } },
  "cases.behavioural_effect_status": { description: "Outcome status; unknown must not be interpreted as no effect.", constraints: { required: true, enum: ["measured", "indicated", "not_detected", "unknown"] } },
  "cases.electoral_effect_status": { description: "Causal electoral-effect status; institutional action belongs in institutional_outcome.", constraints: { required: true, enum: ["measured", "not_detected", "unknown"] } },
  "claims.claim_type": {
    description: "Semantic class of the atomic claim; control_shift_hypothesis is explicitly analytical, not an observed agency outcome.",
    constraints: { required: true, enum: ["occurrence", "mechanism", "ai_role", "reach", "attribution", "intent", "behavioural_effect", "electoral_effect", "institutional_outcome", "response", "legal_status", "counterevidence", "control_shift_hypothesis"] }
  },
  "claims.evidence_label": {
    description: "Epistemic form of the claim; not_identified_in_declared_review is bounded to the linked corpus and researcher_hypothesis is untested.",
    constraints: { required: true, enum: Object.keys(claimSemantics) }
  },
  "claims.claim_status": {
    description: "Support status derived from evidence_label without a numeric confidence score.",
    constraints: { required: true, enum: [...new Set(Object.values(claimSemantics).map((value) => value[0]))] }
  },
  "claims.evidence_basis": {
    description: "Non-numeric basis category; it is not an ordinal quality score.",
    constraints: { required: true, enum: [...new Set(Object.values(claimSemantics).map((value) => value[1]))] }
  },
  "claims.evidence_scope": {
    description: "What the evidence establishes: conduct/fact, an attributed assertion, an action, a measurement, a review-scope statement, or researcher inference.",
    constraints: { required: true, enum: ["underlying_fact", "assertion_was_made", "institutional_action", "measurement", "review_scope_statement", "researcher_inference"] }
  },
  "pathways.capability_status": { description: "Whether the relevant technical or organizational capability is directly documented in this record.", constraints: { required: true, enum: [...pathwayStatusEnums.capability_status] } },
  "pathways.control_mechanism_status": { description: "Whether a mechanism capable of controlling a decision-relevant input is directly documented.", constraints: { required: true, enum: [...pathwayStatusEnums.control_mechanism_status] } },
  "pathways.attempted_transfer_status": { description: "Whether evidence shows an attempt to displace, coerce, impersonate, or covertly control a decision-relevant capacity; ordinary persuasion is insufficient.", constraints: { required: true, enum: [...pathwayStatusEnums.attempted_transfer_status] } },
  "pathways.agency_change_status": { description: "Whether a change in a person's decision-relevant agency is directly observed; not_observed is not evidence that no change occurred.", constraints: { required: true, enum: [...pathwayStatusEnums.agency_change_status] } },
  "pathways.agency_preservation_status": { description: "Whether evidence directly shows that agency was preserved or extended; disclosure alone is not sufficient.", constraints: { required: true, enum: [...pathwayStatusEnums.agency_preservation_status] } },
  "pathways.maximum_conclusion": { description: "Strongest conclusion permitted by the coded evidence, not a severity rank.", constraints: { required: true, enum: [...pathwayStatusEnums.maximum_conclusion] } },
  "pathways.assessment_label": { description: "Reasoning posture used for the pathway assessment.", constraints: { required: true, enum: [...pathwayStatusEnums.assessment_label] } },
  "pathways.falsification_condition": { description: "Case-specific observation that would count against the control-shift hypothesis or block a stronger conclusion.", constraints: { required: true } },
  "pathways.comparator": { description: "Empirical or design comparator required to test agency change or preservation.", constraints: { required: true } },
  "pathways.observed_evidence": { description: "Only what the linked evidence directly documents.", constraints: { required: true } },
  "pathways.researcher_inference": { description: "Analytical proposition kept separate from observed evidence; blank for non-incidents where no inference is made." },
  "research_view.capability_status": { constraints: { required: true, enum: [...pathwayStatusEnums.capability_status] } },
  "research_view.control_mechanism_status": { constraints: { required: true, enum: [...pathwayStatusEnums.control_mechanism_status] } },
  "research_view.attempted_transfer_status": { constraints: { required: true, enum: [...pathwayStatusEnums.attempted_transfer_status] } },
  "research_view.agency_change_status": { constraints: { required: true, enum: [...pathwayStatusEnums.agency_change_status] } },
  "research_view.agency_preservation_status": { constraints: { required: true, enum: [...pathwayStatusEnums.agency_preservation_status] } },
  "research_view.maximum_conclusion": { constraints: { required: true, enum: [...pathwayStatusEnums.maximum_conclusion] } },
  "claim_evidence.evidence_scope": { description: "Scope inherited from the claim and applied to this claim-source relation.", constraints: { required: true, enum: ["underlying_fact", "assertion_was_made", "institutional_action", "measurement", "review_scope_statement", "researcher_inference"] } },
  "claim_evidence.relation": { description: "supports = source states the coded factual/attributed proposition; premise = source supports a factual premise used in a researcher inference but does not state that inference; counterevidence = source qualifies or contests it.", constraints: { required: true, enum: ["supports", "premise", "counterevidence"] } },
  "claim_evidence.locator_coverage": { description: "Whether the recorded pinpoint covers the full claim wording, only part of it, or was not verified; never inferred from a nonblank URL alone.", constraints: { required: true, enum: ["full_claim", "partial_claim", "not_verified"] } },
  "claim_evidence.locator_note": { description: "Reason no verified pinpoint was recorded; blank for verified full or partial locators." },
  "observations.causal_status": { description: "Design-bounded causal status; descriptive counts never establish agency or electoral effects.", constraints: { required: true, enum: ["descriptive_only", "association_only", "experimental_causal_estimate", "quasi_experimental_causal_estimate", "causal_estimate", "not_applicable"] } }
};
const resourceDescriptions = {
  cases: "Claim-coded records with incident/preparedness type, mechanism context, effect status and explicitly hypothetical control-shift fields.",
  claims: "Atomic factual, attributed, review-bounded, inferential, or hypothesis claims; no numeric coder-confidence scores.",
  sources: "Source registry with provenance, independence, access and preservation metadata.",
  events: "Dated events linked to cases, claims and sources.",
  case_sources: "Normalized many-to-many case–source links.",
  watchlist: "Prospective observable indicators and assessment rules; not incident evidence.",
  candidates: "Screening leads that are not claim-coded core incidents.",
  official_elections: "Official election and contest context linked to cases.",
  official_turnout: "Wide official turnout records retained for compatibility.",
  official_results: "Official contest results; not evidence of manipulation effects.",
  official_data_sources: "Provenance manifest for official election data.",
  official_election_metrics: "Long-form official metrics with numerator, denominator and legal role.",
  research_view: "Compact comparison view exposing the separate falsifiable pathway dimensions.",
  case_catalog: "Unified catalog of core records, screening leads and empirical model studies.",
  case_actors: "Actors, roles, attribution status and control dimensions.",
  technology_uses: "Case-specific technology provenance and use status.",
  content_items: "Item-level representation, disclosure and authorization coding.",
  pathways: "Falsifiable control-shift hypotheses separating observed mechanisms, attempts, agency change, preservation, and non-incidents.",
  observations: "Typed descriptive or design-bounded quantitative observations.",
  model_evaluations: "Empirical model audits and experiments kept outside incident counts.",
  claim_evidence: "Normalized claim–source support, researcher-premise and counterevidence relations with explicit pinpoint-coverage status.",
  analytic_record_claims: "Links analytic records to the atomic claims supporting their coding.",
  case_elections: "Normalized case–election relations.",
  election_sources: "Normalized election–official-source relations.",
  sampling_frame: "Declared purposive search coverage and negative-search gaps.",
  coverage_summary: "Regional record counts; not prevalence estimates."
};
function fieldDescriptor(table, name) {
  const base = booleanFields.has(name)
    ? { name, type: "boolean", trueValues: ["true"], falseValues: ["false"] }
    : integerFields.has(name)
      ? { name, type: "integer" }
      : numberFields.has(name)
        ? { name, type: "number" }
        : dateFields.has(name)
          ? { name, type: "date" }
          : { name, type: "string" };
  const metadata = fieldMetadata[`${table}.${name}`] || {};
  const key = primaryKeys[table];
  const isPrimaryKey = Array.isArray(key) ? key.includes(name) : key === name;
  const isForeignKey = foreignKeys[table]?.some(([field]) => field === name);
  if (isPrimaryKey || isForeignKey) {
    metadata.constraints = { ...(metadata.constraints || {}), required: true };
  }
  return { ...base, ...metadata };
}
const dataPackage = {
  profile: "tabular-data-package",
  name: "agency-transfer-election-cases",
  title: "AI, Elections and Agency Transfer Evidence Index",
  version: releaseVersion,
  description: "Purposive, exploratory evidence index with normalized claims, pathways, observations, model studies, screening records and official electoral context. It is not proof of agency transfer, a prevalence sample or an election-effect estimate.",
  keywords: ["elections", "artificial intelligence", "information integrity", "agency", "evidence index"],
  licenses: [{ name: "CC-BY-4.0", path: "https://creativecommons.org/licenses/by/4.0/" }],
  resources: Object.entries(schemas).map(([table, columns]) => ({
    name: table,
    description: resourceDescriptions[table],
    path: `${table}.csv`,
    profile: "tabular-data-resource",
    format: "csv",
    mediatype: "text/csv",
    schema: {
      fields: columns.map((column) => fieldDescriptor(table, column)),
      ...(primaryKeys[table] ? { primaryKey: primaryKeys[table] } : {}),
      ...(foreignKeys[table]?.length ? { foreignKeys: foreignKeys[table].map(([field, resource, targetField]) => ({ fields: field, reference: { resource, fields: targetField } })) } : {})
    }
  }))
};
const catalogResource = dataPackage.resources.find((resource) => resource.name === "case_catalog");
const catalogDateField = catalogResource?.schema.fields.find((field) => field.name === "election_date");
if (catalogDateField) {
  catalogDateField.description = "ISO election date for core cases and screening leads; blank for empirical studies whose evaluation window is stored in model_evaluations.";
}
const observationResource = dataPackage.resources.find((resource) => resource.name === "observations");
if (observationResource) {
  observationResource.description = "Selected decision-relevant quantitative observations normalized from claims; absence of a row does not imply absence of all numeric text in the evidence corpus.";
}
const dataPackageText = JSON.stringify(dataPackage, null, 2) + "\n";
fs.writeFileSync(path.join(outDir, "datapackage.json"), dataPackageText);
fileHashes["datapackage.json"] = sha256(dataPackageText);

const counts = Object.fromEntries(Object.keys(schemas).map((table) => [table, seed[table].length]));
const stats = {
  ...counts,
  _integrity: {
    input_sha256: {
      "research/seed.json": sha256(fs.readFileSync(seedPath)),
      "research/candidates.json": sha256(fs.readFileSync(candidatesPath)),
      "research/europe_candidates.json": sha256(fs.readFileSync(europeCandidatesPath)),
      "research/official_electoral_data.json": sha256(fs.readFileSync(officialElectoralDataPath)),
      "research/v0.3_extensions.json": sha256(fs.readFileSync(extensionsPath)),
      "research/v0.4_locators.json": sha256(fs.readFileSync(locatorsPath))
    },
    file_sha256: fileHashes
  }
};
fs.writeFileSync(path.join(outDir, "stats.json"), JSON.stringify(stats, null, 2) + "\n");
process.stdout.write(JSON.stringify(counts) + "\n");