File size: 33,899 Bytes
57e5bea
 
 
 
 
 
 
 
bdd8da5
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
57e5bea
 
bdd8da5
 
 
 
 
 
 
57e5bea
 
 
bdd8da5
57e5bea
bdd8da5
 
 
 
 
 
 
 
57e5bea
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
57e5bea
bdd8da5
 
 
 
 
 
 
 
 
 
 
57e5bea
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
 
 
 
bdd8da5
 
57e5bea
bdd8da5
 
 
 
 
 
57e5bea
bdd8da5
57e5bea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd8da5
 
57e5bea
bdd8da5
57e5bea
 
 
bdd8da5
 
57e5bea
 
bdd8da5
 
57e5bea
bdd8da5
 
 
 
57e5bea
 
 
 
 
 
 
bdd8da5
57e5bea
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
bdd8da5
57e5bea
 
bdd8da5
57e5bea
 
84110a3
57e5bea
 
 
 
 
bdd8da5
 
 
57e5bea
 
 
 
 
 
 
 
84110a3
57e5bea
 
bdd8da5
57e5bea
bdd8da5
57e5bea
 
 
bdd8da5
 
57e5bea
bdd8da5
57e5bea
 
 
 
bdd8da5
57e5bea
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
bdd8da5
57e5bea
 
bdd8da5
57e5bea
 
bdd8da5
57e5bea
 
 
 
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
bdd8da5
 
 
57e5bea
bdd8da5
 
 
 
 
57e5bea
bdd8da5
 
 
57e5bea
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
bdd8da5
57e5bea
 
 
 
 
 
 
bdd8da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e5bea
 
 
bdd8da5
57e5bea
 
bdd8da5
 
 
 
 
 
 
 
 
57e5bea
 
 
 
 
 
bdd8da5
57e5bea
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { SpreadsheetFile, Workbook } from "@oai/artifact-tool";

const here = path.dirname(fileURLToPath(import.meta.url));
const root = process.env.DATASET_ROOT ? path.resolve(process.env.DATASET_ROOT) : path.resolve(here, "..");
const dataDir = path.join(root, "data");
const packageMetadata = JSON.parse(await fs.readFile(path.join(root, "package.json"), "utf8"));
const releaseVersion = packageMetadata.version;
const releaseDate = "2026-08-15";
const outputDir = process.argv[2] || path.join(root, "outputs", `v${releaseVersion}-workbook`);
const previewDir = path.join(outputDir, "previews");
await fs.mkdir(previewDir, { recursive: true });

function parseCsv(text) {
  const records = [];
  let record = [];
  let field = "";
  let quoted = false;
  for (let i = 0; i < text.length; i += 1) {
    const char = text[i];
    if (quoted) {
      if (char === '"' && text[i + 1] === '"') { field += '"'; i += 1; }
      else if (char === '"') quoted = false;
      else field += char;
    } else if (char === '"') quoted = true;
    else if (char === ",") { record.push(field); field = ""; }
    else if (char === "\n") {
      record.push(field.replace(/\r$/, ""));
      records.push(record);
      record = [];
      field = "";
    } else field += char;
  }
  if (quoted) throw new Error("Unterminated quoted CSV field");
  if (field || record.length) { record.push(field.replace(/\r$/, "")); records.push(record); }
  const headers = records.shift() || [];
  const rows = records.filter((row) => row.some((value) => value !== "")).map((values, rowIndex) => {
    if (values.length !== headers.length) {
      throw new Error(`CSV row ${rowIndex + 2} has ${values.length} values; expected ${headers.length}`);
    }
    return Object.fromEntries(headers.map((header, index) => [header, values[index] ?? ""]));
  });
  return { headers, rows };
}

const schema = JSON.parse(await fs.readFile(path.join(dataDir, "schema.json"), "utf8"));
const datapackage = JSON.parse(await fs.readFile(path.join(dataDir, "datapackage.json"), "utf8"));
const stats = JSON.parse(await fs.readFile(path.join(dataDir, "stats.json"), "utf8"));
const audit = JSON.parse(await fs.readFile(path.join(dataDir, "audit.json"), "utf8"));
const tableNames = Object.keys(schema);
const resourcesByName = new Map(datapackage.resources.map((resource) => [resource.name, resource]));
if (resourcesByName.size !== tableNames.length || tableNames.some((table) => !resourcesByName.has(table))) {
  throw new Error("schema.json and datapackage.json do not declare the same tables");
}

const fieldsByTable = new Map();
const data = {};
for (const table of tableNames) {
  const resource = resourcesByName.get(table);
  const resourceColumns = resource.schema.fields.map((field) => field.name);
  if (JSON.stringify(resourceColumns) !== JSON.stringify(schema[table])) {
    throw new Error(`${table}: schema.json and datapackage.json field order differ`);
  }
  if (path.basename(resource.path) !== `${table}.csv`) {
    throw new Error(`${table}: unexpected datapackage path ${resource.path}`);
  }
  const parsed = parseCsv(await fs.readFile(path.join(dataDir, `${table}.csv`), "utf8"));
  if (JSON.stringify(parsed.headers) !== JSON.stringify(schema[table])) {
    throw new Error(`${table}: CSV headers do not exactly match schema.json`);
  }
  data[table] = parsed.rows;
  fieldsByTable.set(table, new Map(resource.schema.fields.map((field) => [field.name, field])));
}

const wb = Workbook.create();
const colors = {
  ink: "#111827", charcoal: "#263238", slate: "#4B5563", blue: "#24506A",
  paleBlue: "#EAF2F7", gray: "#E5E7EB", light: "#F8FAFC", white: "#FFFFFF",
  red: "#B42318", paleRed: "#FDECEC", green: "#16794C", paleGreen: "#EAF7F0",
  amber: "#946200", paleAmber: "#FFF6D8"
};

function excelColumn(index) {
  let n = index + 1;
  let out = "";
  while (n > 0) { n -= 1; out = String.fromCharCode(65 + (n % 26)) + out; n = Math.floor(n / 26); }
  return out;
}

const percentFields = new Set(["turnout_rate", "authority_reported_turnout_rate", "valid_vote_share", "authority_reported_rate", "computed_rate"]);

function fieldDefinition(table, column) {
  const field = fieldsByTable.get(table)?.get(column);
  if (!field) throw new Error(`${table}.${column}: field is not declared in datapackage.json`);
  return field;
}

function valueForCell(table, column, value) {
  if (value === "" || value === null || value === undefined) return "";
  const type = fieldDefinition(table, column).type || "string";
  if (type === "string") return String(value);
  if (type === "boolean") {
    if (!/^(true|false)$/i.test(String(value))) throw new Error(`${table}.${column}: invalid boolean ${value}`);
    return String(value).toLowerCase() === "true";
  }
  if (type === "integer") {
    if (!/^-?(0|[1-9]\d*)$/.test(String(value))) throw new Error(`${table}.${column}: invalid integer ${value}`);
    const parsed = Number(value);
    if (!Number.isSafeInteger(parsed)) throw new Error(`${table}.${column}: integer exceeds Excel-safe precision ${value}`);
    return parsed;
  }
  if (type === "number") {
    const parsed = Number(value);
    if (!Number.isFinite(parsed)) throw new Error(`${table}.${column}: invalid number ${value}`);
    return parsed;
  }
  if (type === "date") {
    if (!/^\d{4}-\d{2}-\d{2}$/.test(String(value))) throw new Error(`${table}.${column}: invalid ISO date ${value}`);
    const parsed = new Date(`${value}T00:00:00Z`);
    if (Number.isNaN(parsed.valueOf()) || parsed.toISOString().slice(0, 10) !== value) {
      throw new Error(`${table}.${column}: invalid calendar date ${value}`);
    }
    return parsed;
  }
  throw new Error(`${table}.${column}: unsupported datapackage type ${type}`);
}

function safeTableName(name) {
  return `T${name.replaceAll(/[^A-Za-z0-9]/g, "").slice(0, 44)}`;
}

const createdSheetNames = [];
function addWorksheet(sheetName) {
  const sheet = wb.worksheets.add(sheetName);
  createdSheetNames.push(sheetName);
  return sheet;
}

function addDataSheet(table, sheetName, rows, columns, options = {}) {
  const sheet = addWorksheet(sheetName);
  sheet.showGridLines = false;
  const matrix = [columns, ...rows.map((row) => columns.map((column) => valueForCell(table, column, row[column] ?? "")))];
  const lastCol = excelColumn(columns.length - 1);
  const lastRow = Math.max(matrix.length, 2);
  sheet.getRange(`A1:${lastCol}${matrix.length}`).values = matrix;
  sheet.getRange(`A1:${lastCol}1`).format = {
    fill: options.headerFill || colors.charcoal,
    font: { bold: true, color: colors.white, size: 10 },
    wrapText: true,
    verticalAlignment: "center",
    borders: { preset: "all", style: "thin", color: colors.white }
  };
  sheet.getRange(`A1:${lastCol}1`).format.rowHeightPx = 38;
  sheet.getRange(`A2:${lastCol}${lastRow}`).format = {
    font: { color: colors.ink, size: 9 },
    wrapText: true,
    verticalAlignment: "top",
    borders: { preset: "all", style: "thin", color: "#D9DEE3" }
  };
  sheet.getRange(`A2:${lastCol}${lastRow}`).format.rowHeightPx = options.rowHeight || 58;
  sheet.freezePanes.freezeRows(1);
  sheet.freezePanes.freezeColumns(Math.min(options.freezeColumns ?? 2, columns.length));
  for (let i = 0; i < columns.length; i += 1) {
    const column = columns[i];
    const letter = excelColumn(i);
    const width = options.widths?.[column] || (
      /(^|_)ids$|claim_ids|source_ids/.test(column) ? 340 :
      /summary|claim_text|notes|counterevidence|open_questions|description|path|mechanism|outcome|scope|uncertainty|limitation|caveat|headline|selection_basis|coverage_note|hypothesis|democratic_harm|response/.test(column) ? 360 :
      /url/.test(column) ? 300 :
      /title|name|controller|target|actor|author/.test(column) ? 250 :
      /id$/.test(column) ? 210 : 135
    );
    sheet.getRange(`${letter}1:${letter}${lastRow}`).format.columnWidthPx = width;
    const type = fieldDefinition(table, column).type || "string";
    if (type === "date" && lastRow >= 2) {
      sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "yyyy-mm-dd";
    } else if (percentFields.has(column) && lastRow >= 2) {
      sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "0.0000%";
    } else if (type === "integer" && lastRow >= 2) {
      sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "#,##0";
    } else if (type === "number" && lastRow >= 2) {
      sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "#,##0.############";
    } else if (type === "string" && lastRow >= 2) {
      sheet.getRange(`${letter}2:${letter}${lastRow}`).format.numberFormat = "@";
    }
  }
  if (rows.length) {
    const table = sheet.tables.add(`A1:${lastCol}${matrix.length}`, true, safeTableName(sheetName));
    table.showBandedColumns = false;
    table.showFilterButton = true;
  }
  return { table, sheet, sheetName, columns, lastCol, lastRow };
}

function addSectionTitle(sheet, range, text, fill = colors.charcoal) {
  sheet.getRange(range).merge();
  sheet.getRange(range).values = [[text]];
  sheet.getRange(range).format = { fill, font: { bold: true, color: colors.white, size: 11 }, verticalAlignment: "center" };
}

function enumText(table, column) {
  const values = fieldDefinition(table, column).constraints?.enum;
  if (!Array.isArray(values) || values.length === 0) throw new Error(`${table}.${column}: no enum declared`);
  return values.join(" | ");
}

function uniqueValues(table, column) {
  return [...new Set(data[table].map((row) => row[column]).filter(Boolean))].sort().join(" | ");
}

const samplingGapCount = data.sampling_frame.filter((row) => row.negative_search_recorded === "false").length;
const totalDataRows = tableNames.reduce((sum, table) => sum + data[table].length, 0);
const auditDataRows = Object.values(audit.summary.table_row_counts).reduce((sum, count) => sum + count, 0);

const overview = addWorksheet("00 Overview");
overview.showGridLines = false;
overview.getRange("A1:H2").merge();
overview.getRange("A1:H2").values = [[`${datapackage.title} — v${releaseVersion} (exploratory)`]];
overview.getRange("A1:H2").format = { fill: colors.ink, font: { bold: true, color: colors.white, size: 18 }, verticalAlignment: "center" };
overview.getRange("A3:H3").merge();
overview.getRange("A3:H3").values = [[`Released ${releaseDate} · Research cutoff ${audit.cutoff} · Purposive index, not proof or a prevalence sample · Start with 01 Research View`]];
overview.getRange("A3:H3").format = { fill: colors.paleBlue, font: { italic: true, color: colors.blue, size: 10 }, verticalAlignment: "center" };

overview.getRange("A5:B18").values = [
  ["Release metric", "Rows"],
  ["Claim-coded records", data.cases.length],
  ["Incident-count eligible records", data.case_catalog.filter((row) => row.record_layer === "claim_coded_core" && row.incident_count_eligible === "true").length],
  ["Preparedness files (excluded)", data.cases.filter((row) => row.record_type === "preparedness_file").length],
  ["Atomic claims", data.claims.length],
  ["Claim-evidence relations", data.claim_evidence.length],
  ["Distinct claim-linked sources", new Set(data.claim_evidence.map((row) => row.source_id)).size],
  ["Source records overall", data.sources.length],
  ["Screening leads", data.candidates.length],
  ["Empirical model studies", data.model_evaluations.length],
  ["Typed observations", data.observations.length],
  ["Official contests/bundles", data.official_elections.length],
  ["Official result rows", data.official_results.length],
  ["Automated audit errors", audit.summary.error_count]
];
overview.getRange("A5:B5").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
overview.getRange("A6:B18").format = { fill: colors.light, borders: { preset: "all", style: "thin", color: "#D9DEE3" } };

addSectionTitle(overview, "D5:H5", "Read the layers in this order");
overview.getRange("D6:H14").merge();
overview.getRange("D6:H14").values = [[
  `1. Research View — the complete ${schema.research_view.length}-field, one-row-per-pathway comparison table.\n\n2. Pathways — separate observed capability/control, attempted transfer, observed agency change, preservation and insufficient evidence.\n\n3. Claims + Evidence — distinguish facts, attributed assertions and researcher hypotheses.\n\n4. Observations — compare only compatible units and denominators.\n\n5. Official Metrics + Results — electoral context only; never evidence of votes caused by manipulation.`
]];
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 } };

addSectionTitle(overview, "A19:H19", `What changed in v${releaseVersion}`, colors.blue);
overview.getRange("A20:H25").merge();
overview.getRange("A20:H25").values = [[
  "This scientific correction replaces a single agency-transfer ladder with falsifiable dimensions. It records the strongest conclusion permitted by the evidence, the observation that would count against it, and the comparator needed to test it. Allegations, absence statements and researcher hypotheses are no longer coded as underlying facts. Validation now reconciles CSV, Parquet, stored audits and frozen release artifacts. Source locators, archives and hashes remain explicit preservation gaps unless verified."
]];
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 } };

overview.getRange("A27:H29").merge();
overview.getRange("A27:H29").values = [[`Hard limit: v${releaseVersion} contains no observed person-level agency change and no observed agency preservation/extension. It is internally checked for its declared records, not comprehensive across elections. ${samplingGapCount} sampling-frame warnings block prevalence inference. Do not estimate votes changed from this release.`]];
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" };
overview.freezePanes.freezeRows(3);
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;

const dataSheetMetas = [];
function addTableSheet(table, sheetName, options = {}) {
  const meta = addDataSheet(table, sheetName, data[table], schema[table], options);
  dataSheetMetas.push(meta);
  return meta;
}

const researchSheet = addTableSheet("research_view", "01 Research View", { headerFill: colors.blue, freezeColumns: 4, rowHeight: 92, widths: { case_title: 310, system_or_model: 280, controller: 300, influence_vector: 330, target: 300, agency_dimension: 260, hypothesized_power_recipient: 300, reach_summary: 400, behavioural_effect: 300, electoral_effect: 300, case_evidence_summary: 420, main_uncertainty: 430 } });
const catalogSheet = addTableSheet("case_catalog", "02 Case Catalog", { freezeColumns: 3, rowHeight: 72, widths: { title: 330, main_caveat: 440 } });
const coverageSheet = addTableSheet("coverage_summary", "03 Coverage", { headerFill: colors.blue, widths: { coverage_note: 560 } });
const pathwaySheet = addTableSheet("pathways", "04 Pathways", { headerFill: colors.blue, freezeColumns: 2, rowHeight: 92, widths: { hypothesized_control_shift_from: 300, hypothesized_control_shift_to: 300, mechanism: 390, potential_harm_pathway: 390, observed_outcome: 390, falsification_condition: 430, comparator: 430, observed_evidence: 450, researcher_inference: 450, source_claim_ids: 390, reviewer_note: 420 } });
const observationSheet = addTableSheet("observations", "05 Observations", { freezeColumns: 3, widths: { limitations: 480, measurement_method: 290, denominator: 260 } });
const modelSheet = addTableSheet("model_evaluations", "06 Model Studies", { headerFill: colors.blue, freezeColumns: 2, rowHeight: 84, widths: { title: 360, systems_tested: 390, design: 430, headline_results: 520, causal_scope: 500, notes: 440 } });
const claimSheet = addTableSheet("claims", "07 Claims", { freezeColumns: 3, rowHeight: 78, widths: { claim_text: 520, source_ids: 390, counter_source_ids: 390, notes: 390 } });
const sourceSheet = addTableSheet("sources", "08 Sources", { freezeColumns: 2, rowHeight: 72, widths: { title: 390, author: 300, url: 420, archive_url: 420, content_hash: 460, notes: 380 } });
const claimEvidenceSheet = addTableSheet("claim_evidence", "09 Claim Evidence", { freezeColumns: 3, widths: { locator: 430, locator_coverage: 170, locator_note: 430 } });
addTableSheet("events", "10 Events", { widths: { description: 480 } });
addTableSheet("case_actors", "11 Actors", { widths: { actor_name: 290, control_dimension: 360, source_claim_ids: 390, notes: 420 } });
addTableSheet("technology_uses", "12 Technology", { widths: { product_or_model: 330, source_claim_ids: 390, notes: 460 } });
addTableSheet("content_items", "13 Content", { widths: { title: 300, source_claim_ids: 390, notes: 450 } });
addTableSheet("cases", "14 Cases Detail", { freezeColumns: 3, rowHeight: 104, widths: { summary: 430, affected_state: 300, control_shift_hypothesis: 510, hypothesized_power_recipient: 340, democratic_harm: 430, reach_unit: 390, institutional_outcome: 430, response: 430, counterevidence: 430, open_questions: 430 } });
addTableSheet("candidates", "15 Screening Leads", { freezeColumns: 3, rowHeight: 100, widths: { title: 330, comparative_value: 430, main_caveat: 450, source_urls: 520 } });
addTableSheet("watchlist", "16 Watchlist", { widths: { observable_indicator: 450, defensive_data_source: 390, assessment_rule: 440, notes: 360 } });
const electionSheet = addTableSheet("official_elections", "17 Official Elections", { rowHeight: 78, widths: { linked_case_ids: 390, election_name: 360, administering_authority: 330, geographic_scope: 330, official_source_ids: 390, notes: 520 } });
const metricSheet = addTableSheet("official_election_metrics", "18 Official Metrics", { headerFill: colors.blue, widths: { source_label_original: 330, notes: 520 } });
const turnoutSheet = addTableSheet("official_turnout", "19 Turnout Wide", { widths: { electorate_measure: 430, participation_measure: 360, turnout_numerator_measure: 360, notes: 540 } });
const resultSheet = addTableSheet("official_results", "20 Official Results", { widths: { candidate_or_option: 360, party_or_affiliation: 290, ballot_designating_entity: 290, notes: 480 } });
const officialSourceSheet = addTableSheet("official_data_sources", "21 Official Sources", { widths: { electoral_institution: 330, title: 430, url: 430, landing_url: 430, download_url: 430, geographic_granularity: 350, license_or_terms: 330, content_sha256: 460, notes: 500 } });
addTableSheet("case_sources", "22 Case Sources", { freezeColumns: 2, widths: { supports_claim_types: 360, notes: 420 } });
addTableSheet("analytic_record_claims", "23 Analytic Claim Links", { freezeColumns: 3 });
addTableSheet("case_elections", "24 Case Elections", { freezeColumns: 3 });
addTableSheet("election_sources", "25 Election Sources", { freezeColumns: 3 });
const samplingSheet = addTableSheet("sampling_frame", "26 Sampling Frame", { headerFill: colors.blue, freezeColumns: 2, rowHeight: 84, widths: { selection_basis: 440, search_languages: 300, source_channels: 390, known_gap: 520 } });

if (dataSheetMetas.length !== tableNames.length || new Set(dataSheetMetas.map((meta) => meta.table)).size !== tableNames.length) {
  throw new Error(`Workbook must expose every declared table exactly once; found ${dataSheetMetas.length} of ${tableNames.length}`);
}

const codebook = addWorksheet("27 Codebook");
codebook.showGridLines = false;
const codebookRows = [
  ["Concept", "Controlled value / rule", "Research meaning"],
  ["case_catalog.record_layer", uniqueValues("case_catalog", "record_layer"), "These layers must never be counted together as incidents."],
  ["cases.record_type", enumText("cases", "record_type"), "Defines the claim-coded unit. Preparedness is context, not an incident."],
  ["case_catalog.record_type", uniqueValues("case_catalog", "record_type"), "The unified catalog also contains candidate leads and model studies."],
  ["cases.manipulation_assessment", enumText("cases", "manipulation_assessment"), "AI use alone does not prove manipulation."],
  ["claims.claim_status", enumText("claims", "claim_status"), "Status of the claim exactly as worded; hypotheses and bounded non-identification statements are not source-proven facts."],
  ["claims.evidence_basis", enumText("claims", "evidence_basis"), "Non-ordinal basis for the label; legacy numeric confidence fields were removed."],
  ["claims.evidence_scope", enumText("claims", "evidence_scope"), "Separates an assertion or researcher inference from the underlying fact."],
  ["pathway dimensions", "capability | control mechanism | attempted transfer | agency change | agency preservation", "Separate variables; never collapse them into an automatic causal ladder or score."],
  ["pathways.maximum_conclusion", enumText("pathways", "maximum_conclusion"), "The strongest conclusion permitted by coded evidence, not a severity rank."],
  ["falsifiability", "falsification_condition + comparator", "What would count against the hypothesis and what contrast is needed to test agency change."],
  ["claim_evidence.relation", enumText("claim_evidence", "relation"), "premise means the source supports a factual premise used in a researcher inference; it does not attribute that inference to the source."],
  ["claim_evidence.locator_coverage", enumText("claim_evidence", "locator_coverage"), "A pinpoint is useful only with an explicit statement of how much of the claim wording it covers."],
  ["claim_evidence.locator_note", "required when locator_coverage = not_verified", "Explains why no verified pinpoint is available; it must not imply that the source itself was absent."],
  ["observations", "one measured quantity per row", "Never sum views, followers, calls, accounts, users or voters without compatible units and denominators."],
  ["observations.causal_status", enumText("observations", "causal_status"), "Official results and platform metrics are descriptive unless a causal design is recorded."],
  ["model_evaluations", "study-specific unit, N, design, metrics and scope", "Capability evidence is not incident prevalence or real-world electoral effect."],
  ["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."],
  ["official_results.coverage_status", uniqueValues("official_results", "coverage_status"), "New Hampshire remains partial; complete groups reconcile to valid votes."],
  ["missingness", "blank cell", "Use the literal unknown only when it is a controlled category."],
  ["legacy multi-values", "pipe-delimited", "Prefer normalized claim_evidence, analytic_record_claims, case_elections and election_sources for joins."],
  ["central prohibition", "no proof, prevalence or votes-changed estimate", "Sampling is purposive; no person-level agency change is observed in this release."]
];
codebook.getRange(`A1:C${codebookRows.length}`).values = codebookRows;
codebook.getRange("A1:C1").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
codebook.getRange(`A2:C${codebookRows.length}`).format = { borders: { preset: "all", style: "thin", color: "#D9DEE3" }, wrapText: true, verticalAlignment: "top" };
codebook.getRange(`A2:C${codebookRows.length}`).format.rowHeightPx = 66;
codebook.getRange(`A1:A${codebookRows.length}`).format.columnWidthPx = 230;
codebook.getRange(`B1:B${codebookRows.length}`).format.columnWidthPx = 420;
codebook.getRange(`C1:C${codebookRows.length}`).format.columnWidthPx = 550;
codebook.freezePanes.freezeRows(1);

const completeElectionIds = [...new Set(data.official_results.filter((row) => row.coverage_status === "complete_national_contest").map((row) => row.election_id))];
const validVotesByElection = new Map(data.official_turnout.filter((row) => row.geographic_unit_type === "national" && row.valid_votes !== "").map((row) => [row.election_id, Number(row.valid_votes)]));
const reconciledCompleteGroups = completeElectionIds.filter((electionId) => {
  const resultTotal = data.official_results
    .filter((row) => row.election_id === electionId && row.coverage_status === "complete_national_contest")
    .reduce((sum, row) => sum + Number(row.votes), 0);
  return validVotesByElection.has(electionId) && resultTotal === validVotesByElection.get(electionId);
}).length;

const nhElectionId = "elec-us-nh-dem-primary-2024";
function requiredMetricValue(metricCode) {
  const matches = data.official_election_metrics.filter((row) => row.election_id === nhElectionId && row.metric_code === metricCode);
  if (matches.length !== 1 || !Number.isFinite(Number(matches[0].value))) {
    throw new Error(`${nhElectionId}.${metricCode}: expected one numeric metric`);
  }
  return Number(matches[0].value);
}
const nhGap = requiredMetricValue("ballot_minus_contest_vote_gap");
const nhGapExpected = requiredMetricValue("ballots_cast") - requiredMetricValue("presidential_contest_votes");

const researchCutoffFields = new Set(["last_verified", "verified_at", "last_checked", "as_of_date", "snapshot_cutoff", "last_searched"]);
const researchCutoffDates = [];
for (const table of tableNames) {
  for (const row of data[table]) {
    for (const field of researchCutoffFields) {
      if (/^\d{4}-\d{2}-\d{2}$/.test(row[field] || "")) researchCutoffDates.push(row[field]);
    }
  }
}
const latestResearchCutoffDate = researchCutoffDates.sort().at(-1) || "";
const auditSamplingWarnings = audit.warnings.filter((warning) => warning.code === "NEGATIVE_SEARCH_NOT_RECORDED").length;
const claimsWithoutNormalizedEvidence = data.claims.filter((row) => !["open_question", "researcher_hypothesis", "not_identified_in_declared_review"].includes(row.evidence_label) && !data.claim_evidence.some((evidence) => evidence.claim_id === row.claim_id)).length;

const qaRows = [
  ["Automated audit status", audit.status.toUpperCase(), "PASS", `Deterministic v${releaseVersion} internal audit.`],
  ["Blocking errors", audit.summary.error_count, 0, "Must remain zero."],
  ["CSV tables loaded", audit.integrity.loaded_table_count, tableNames.length, "Stored audit and workbook schema must cover the same tables."],
  ["Rows loaded across all tables", auditDataRows, totalDataRows, "Stored audit row counts must match the workbook inputs."],
  ["Sampling frames lacking a negative search", samplingGapCount, auditSamplingWarnings, "Reconciles the sampling register with the corresponding audit warnings."],
  ["Research-view rows", data.research_view.length, data.pathways.length, "One row per pathway."],
  ["Preparedness counted as incident", data.case_catalog.filter((row) => row.record_type === "preparedness_file" && row.incident_count_eligible === "true").length, 0, "Must remain zero."],
  ["Model studies counted as incident", data.case_catalog.filter((row) => row.record_layer === "empirical_model_study" && row.incident_count_eligible === "true").length, 0, "Must remain zero."],
  ["Observed agency-change pathways", data.pathways.filter((row) => row.agency_change_status === "observed").length, 0, `No decision-relevant agency change is observed in v${releaseVersion}.`],
  ["Observed preservation pathways", data.pathways.filter((row) => row.agency_preservation_status === "observed").length, 0, "Transparent use or disclosure alone is not preservation evidence."],
  ["Claims without normalized evidence", claimsWithoutNormalizedEvidence, 0, "Hypotheses, open questions and bounded non-identification statements are exempt."],
  ["Typed observations", data.observations.length, stats.observations, "Must match generated stats."],
  ["Complete national result groups reconciled", reconciledCompleteGroups, completeElectionIds.length, "Each complete group must sum to its national valid-vote total."],
  ["New Hampshire ballot-minus-contest gap", nhGap, nhGapExpected, "Computed as ballots cast minus presidential-contest votes; it is not relabelled invalid/undervote."],
  ["Research cutoff", audit.cutoff, latestResearchCutoffDate, "Latest substantive verification/as-of/check date must equal the declared cutoff; later link-retrieval and locator-audit dates are provenance metadata."]
];

const qa = addWorksheet("28 QA");
qa.showGridLines = false;
qa.getRange("A1:E2").merge();
qa.getRange("A1:E2").values = [["Release quality assurance"]];
qa.getRange("A1:E2").format = { fill: colors.ink, font: { bold: true, color: colors.white, size: 17 }, verticalAlignment: "center" };
qa.getRange("A4:E4").values = [["Check", "Result", "Expected", "Status", "Interpretation"]];
const qaFirstRow = 5;
const qaLastRow = qaFirstRow + qaRows.length - 1;
qa.getRange(`A${qaFirstRow}:C${qaLastRow}`).values = qaRows.map((row) => row.slice(0, 3));
qa.getRange(`E${qaFirstRow}:E${qaLastRow}`).values = qaRows.map((row) => [row[3]]);
qa.getRange(`D${qaFirstRow}`).formulas = [[`=IF(B${qaFirstRow}=C${qaFirstRow},"PASS","FAIL")`]];
qa.getRange(`D${qaFirstRow}:D${qaLastRow}`).fillDown();
qa.getRange("A4:E4").format = { fill: colors.charcoal, font: { bold: true, color: colors.white } };
qa.getRange(`A${qaFirstRow}:E${qaLastRow}`).format = { borders: { preset: "all", style: "thin", color: "#D9DEE3" }, wrapText: true, verticalAlignment: "top" };
qa.getRange(`A${qaFirstRow}:E${qaLastRow}`).format.rowHeightPx = 54;
qa.getRange(`D${qaFirstRow}:D${qaLastRow}`).conditionalFormats.add("containsText", { text: "PASS", format: { fill: colors.paleGreen, font: { bold: true, color: colors.green } } });
qa.getRange(`D${qaFirstRow}:D${qaLastRow}`).conditionalFormats.add("containsText", { text: "FAIL", format: { fill: colors.paleRed, font: { bold: true, color: colors.red } } });
const qaNoteStart = qaLastRow + 2;
const qaNoteEnd = qaNoteStart + 3;
qa.getRange(`A${qaNoteStart}:E${qaNoteEnd}`).merge();
qa.getRange(`A${qaNoteStart}:E${qaNoteEnd}`).values = [[`Warnings are not failed checks. They flag that prevalence inference is unsupported: ${samplingGapCount} frames lack a systematic negative search. Use 26 Sampling Frame for the exact regions, languages, channels and known gaps.`]];
qa.getRange(`A${qaNoteStart}:E${qaNoteEnd}`).format = { fill: colors.paleAmber, font: { bold: true, color: colors.amber }, borders: { preset: "all", style: "thin", color: colors.amber }, wrapText: true, verticalAlignment: "top" };
for (const [column, width] of [["A", 330], ["B", 180], ["C", 180], ["D", 105], ["E", 520]]) qa.getRange(`${column}1:${column}${qaNoteEnd + 1}`).format.columnWidthPx = width;
qa.freezePanes.freezeRows(4);

function applyListValidation(meta, column, values) {
  const index = meta.columns.indexOf(column);
  if (index >= 0 && meta.lastRow >= 2) {
    const letter = excelColumn(index);
    meta.sheet.getRange(`${letter}2:${letter}${meta.lastRow}`).dataValidation = { rule: { type: "list", values } };
  }
}

for (const meta of dataSheetMetas) {
  for (const column of meta.columns) {
    const field = fieldDefinition(meta.table, column);
    const enumValues = field.constraints?.enum;
    if (Array.isArray(enumValues) && enumValues.length) applyListValidation(meta, column, enumValues);
    else if (field.type === "boolean") applyListValidation(meta, column, ["TRUE", "FALSE"]);
  }
}
for (const [meta, column, values] of [
  [sourceSheet, "source_quality", ["A", "B", "C", "D"]],
  [electionSheet, "election_status", ["completed", "scheduled", "conditional"]],
  [resultSheet, "coverage_status", ["complete_national_contest", "complete", "partial"]]
]) applyListValidation(meta, column, values);

const compactSheets = new Set(["00 Overview", "03 Coverage", "27 Codebook", "28 QA"]);
for (const sheetName of createdSheetNames) {
  const preview = await wb.render({ sheetName, autoCrop: "all", scale: compactSheets.has(sheetName) ? 0.8 : 0.42, format: "png" });
  await fs.writeFile(path.join(previewDir, `${sheetName.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-")}.png`), new Uint8Array(await preview.arrayBuffer()));
}

const inspection = await wb.inspect({ kind: "workbook,sheet,table,formula", maxChars: 30000, tableMaxRows: 4, tableMaxCols: 12, tableMaxCellChars: 90 });
await fs.writeFile(path.join(outputDir, "inspection.ndjson"), inspection.ndjson || String(inspection));
const verification = [];
for (const range of [
  "00 Overview!A1:H29",
  `01 Research View!A1:${researchSheet.lastCol}${researchSheet.lastRow}`,
  `03 Coverage!A1:${coverageSheet.lastCol}${coverageSheet.lastRow}`,
  `18 Official Metrics!A1:${metricSheet.lastCol}${Math.min(metricSheet.lastRow, 20)}`,
  `26 Sampling Frame!A1:${samplingSheet.lastCol}${samplingSheet.lastRow}`,
  `28 QA!A1:E${qaNoteEnd}`
]) {
  const result = await wb.inspect({ kind: "table", range, include: "values,formulas", tableMaxRows: 30, tableMaxCols: 32 });
  verification.push(result.ndjson || String(result));
}
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" });
verification.push(formulaErrors.ndjson || String(formulaErrors));
await fs.writeFile(path.join(outputDir, "verification.ndjson"), verification.join("\n"));

const outputPath = path.join(outputDir, `agency-transfer-election-evidence-index-v${releaseVersion}.xlsx`);
const output = await SpreadsheetFile.exportXlsx(wb);
await output.save(outputPath);
process.stdout.write(`${outputPath}\n`);