#!/usr/bin/env node /** * Deterministic v0.4.0 release validator. * * Default mode verifies source CSV/stat manifests, the stored/live semantic * audit, all Parquet files and any v0.4.0 release artifacts. --source-only * omits derived Parquet/release checks so builders can validate inputs first. */ import fs from "node:fs"; import path from "node:path"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { spawnSync } from "node:child_process"; import { fileURLToPath } from "node:url"; const RELEASE_VERSION = "0.4.0"; const AUDITOR_ID = `agency-transfer-election-cases-v${RELEASE_VERSION}/audit-v04`; const VALIDATOR_ID = `agency-transfer-election-cases-v${RELEASE_VERSION}/validate-data`; const here = path.dirname(fileURLToPath(import.meta.url)); const packageRoot = path.resolve(here, ".."); const positional = process.argv.slice(2).filter((arg) => !arg.startsWith("--")); const unknownFlags = process.argv.slice(2).filter((arg) => arg.startsWith("--") && arg !== "--source-only"); const sourceOnly = process.argv.includes("--source-only"); const dataDir = path.resolve(positional[0] || path.join(packageRoot, "data")); const auditScript = path.join(here, "audit-v03.mjs"); const parquetDir = path.join(packageRoot, "parquet"); const releaseDir = path.join(packageRoot, "release"); const EXPECTED_TABLES = Object.freeze([ "cases", "claims", "sources", "events", "case_sources", "watchlist", "candidates", "official_elections", "official_turnout", "official_results", "official_data_sources", "official_election_metrics", "research_view", "case_catalog", "case_actors", "technology_uses", "content_items", "pathways", "observations", "model_evaluations", "claim_evidence", "analytic_record_claims", "case_elections", "election_sources", "sampling_frame", "coverage_summary" ]); const HASHED_DATA_FILES = Object.freeze([ ...EXPECTED_TABLES.map((name) => `${name}.csv`), "schema.json", "datapackage.json" ]); const fileErrors = []; function fileError(code, file, message) { fileErrors.push({ code, file: file || null, message }); } for (const flag of unknownFlags) fileError("UNKNOWN_OPTION", flag, "Unknown validator option"); if (positional.length > 1) fileError("TOO_MANY_ARGUMENTS", null, "Expected at most one data-directory argument"); function sha256(value) { return createHash("sha256").update(value).digest("hex"); } function canonicalJson(value) { if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; if (value && typeof value === "object") { return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`; } return JSON.stringify(value); } function isPlainObject(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function pathInside(base, relativePath) { if (typeof relativePath !== "string" || path.isAbsolute(relativePath)) return null; const resolvedBase = path.resolve(base); const resolved = path.resolve(resolvedBase, relativePath); return resolved === resolvedBase || resolved.startsWith(`${resolvedBase}${path.sep}`) ? resolved : null; } function cleanOutput(value) { return String(value || "").trim().replace(/\s+/g, " ").slice(0, 500); } function readZipMember(zipPath, member) { const result = spawnSync("unzip", ["-p", zipPath, member], { encoding: null, maxBuffer: 128 * 1024 * 1024 }); if (result.error) throw result.error; if (result.status !== 0) { throw new Error(`unzip could not read ${member}: ${String(result.stderr || "").trim()}`); } return Buffer.from(result.stdout); } function readJson(filepath, label, code) { if (!fs.existsSync(filepath)) { fileError(`${code}_MISSING`, label, `${label} is missing`); return null; } try { return JSON.parse(fs.readFileSync(filepath, "utf8")); } catch (caught) { fileError(`${code}_INVALID_JSON`, label, `Invalid JSON: ${caught.message}`); return null; } } function parseCsv(text, filename) { const input = text.replace(/^\uFEFF/, ""); const records = []; let record = []; let field = ""; let quoted = false; for (let index = 0; index < input.length; index += 1) { const char = input[index]; if (quoted) { if (char === '"' && input[index + 1] === '"') { field += '"'; index += 1; } else if (char === '"') quoted = false; else field += char; } else if (char === '"' && field === "") quoted = true; else if (char === ",") { record.push(field); field = ""; } else if (char === "\n") { record.push(field.replace(/\r$/, "")); records.push(record); record = []; field = ""; } else if (char === '"') { fileError("CSV_QUOTE_INVALID", filename, "Quote appears inside an unquoted field"); field += char; } else field += char; } if (quoted) fileError("CSV_UNCLOSED_QUOTE", filename, "CSV ends inside a quoted field"); if (field || record.length) { record.push(field.replace(/\r$/, "")); records.push(record); } while (records.length && records.at(-1).every((value) => value === "")) records.pop(); const headers = records.shift() || []; const rows = records.filter((row) => row.some((value) => value !== "")); for (const [index, row] of rows.entries()) { if (row.length !== headers.length) { fileError("CSV_WIDTH", filename, `Line ${index + 2}: expected ${headers.length} fields; found ${row.length}`); } } return { headers, rows }; } if (!fs.existsSync(dataDir) || !fs.statSync(dataDir).isDirectory()) { fileError("DATA_DIRECTORY_MISSING", dataDir, "Data directory is missing or is not a directory"); } const actualCsvNames = fs.existsSync(dataDir) ? fs.readdirSync(dataDir).filter((filename) => filename.endsWith(".csv")).sort() : []; const expectedCsvNames = EXPECTED_TABLES.map((name) => `${name}.csv`).sort(); for (const filename of expectedCsvNames) { if (!actualCsvNames.includes(filename)) fileError("EXPECTED_CSV_MISSING", filename, "Expected release table is missing"); } for (const filename of actualCsvNames) { if (!expectedCsvNames.includes(filename)) fileError("UNEXPECTED_CSV", filename, "Unexpected CSV table is present"); } const parsedCsv = new Map(); for (const filename of expectedCsvNames) { const filepath = path.join(dataDir, filename); if (!fs.existsSync(filepath)) continue; const contents = fs.readFileSync(filepath); if (!contents.length || contents.at(-1) !== 0x0a) fileError("TRAILING_NEWLINE_MISSING", filename, "CSV must end with a newline"); if (contents.includes(0x00)) fileError("NUL_BYTE", filename, "CSV contains a NUL byte"); parsedCsv.set(filename.slice(0, -4), { ...parseCsv(contents.toString("utf8"), filename), contents }); } const datapackagePath = path.join(dataDir, "datapackage.json"); const datapackage = readJson(datapackagePath, "datapackage.json", "DATAPACKAGE"); const resourceByName = new Map(); for (const resource of Array.isArray(datapackage?.resources) ? datapackage.resources : []) { if (typeof resource?.name === "string" && !resourceByName.has(resource.name)) resourceByName.set(resource.name, resource); } if (datapackage && datapackage.version !== RELEASE_VERSION) { fileError("DATAPACKAGE_VERSION_MISMATCH", "datapackage.json", `Expected ${RELEASE_VERSION}; found ${datapackage.version ?? "missing"}`); } const statsPath = path.join(dataDir, "stats.json"); const stats = readJson(statsPath, "stats.json", "STATS"); const inputHashes = stats?._integrity?.input_sha256; const fileHashes = stats?._integrity?.file_sha256; if (stats && !isPlainObject(inputHashes)) fileError("INPUT_HASHES_MISSING", "stats.json", "_integrity.input_sha256 must be an object"); if (stats && !isPlainObject(fileHashes)) fileError("FILE_HASHES_MISSING", "stats.json", "_integrity.file_sha256 must be an object"); if (isPlainObject(inputHashes) && !Object.keys(inputHashes).length) fileError("INPUT_HASHES_EMPTY", "stats.json", "At least one generated-input hash is required"); if (isPlainObject(fileHashes)) { const actual = Object.keys(fileHashes).sort(); const expected = [...HASHED_DATA_FILES].sort(); for (const filename of expected) if (!(filename in fileHashes)) fileError("DATA_HASH_ENTRY_MISSING", filename, "stats.json has no SHA-256 entry for this release file"); for (const filename of actual) if (!expected.includes(filename)) fileError("DATA_HASH_ENTRY_UNEXPECTED", filename, "stats.json contains an undeclared release-file hash"); } for (const [relativePath, expectedHash] of Object.entries(isPlainObject(inputHashes) ? inputHashes : {}).sort(([a], [b]) => a.localeCompare(b))) { const filepath = pathInside(packageRoot, relativePath); if (!filepath) { fileError("INPUT_HASH_PATH_INVALID", relativePath, "Generated-input hash path must remain inside the package root"); continue; } if (!/^[a-f0-9]{64}$/.test(String(expectedHash))) { fileError("INPUT_HASH_INVALID", relativePath, "Expected input SHA-256 is not a lowercase 64-character digest"); continue; } if (!fs.existsSync(filepath)) fileError("GENERATED_INPUT_MISSING", relativePath, "Hashed generated input is missing"); else if (sha256(fs.readFileSync(filepath)) !== expectedHash) fileError("GENERATED_INPUT_HASH_MISMATCH", relativePath, "Generated input differs from stats.json"); } for (const [filename, expectedHash] of Object.entries(isPlainObject(fileHashes) ? fileHashes : {}).sort(([a], [b]) => a.localeCompare(b))) { if (path.basename(filename) !== filename) { fileError("DATA_HASH_PATH_INVALID", filename, "Generated-file hash keys must be plain filenames"); continue; } const filepath = path.join(dataDir, filename); if (!/^[a-f0-9]{64}$/.test(String(expectedHash))) { fileError("DATA_HASH_INVALID", filename, "Expected data SHA-256 is not a lowercase 64-character digest"); continue; } if (!fs.existsSync(filepath)) fileError("HASHED_DATA_FILE_MISSING", filename, "File listed in stats.json is missing"); else if (sha256(fs.readFileSync(filepath)) !== expectedHash) fileError("DATA_HASH_MISMATCH", filename, "File differs from stats.json"); } // Release version identity across public metadata and package managers. const packageJson = readJson(path.join(packageRoot, "package.json"), "package.json", "PACKAGE_JSON"); const packageLock = readJson(path.join(packageRoot, "package-lock.json"), "package-lock.json", "PACKAGE_LOCK"); if (packageJson && packageJson.version !== RELEASE_VERSION) fileError("PACKAGE_VERSION_MISMATCH", "package.json", `Expected ${RELEASE_VERSION}; found ${packageJson.version ?? "missing"}`); if (packageLock && packageLock.version !== RELEASE_VERSION) fileError("LOCK_VERSION_MISMATCH", "package-lock.json", `Expected ${RELEASE_VERSION}; found ${packageLock.version ?? "missing"}`); if (packageLock && packageLock.packages?.[""]?.version !== RELEASE_VERSION) { fileError("LOCK_ROOT_VERSION_MISMATCH", "package-lock.json", `Expected root package ${RELEASE_VERSION}; found ${packageLock.packages?.[""]?.version ?? "missing"}`); } const readmePath = path.join(packageRoot, "README.md"); if (!fs.existsSync(readmePath)) fileError("README_MISSING", "README.md", "README.md is missing"); else if (!new RegExp(`Version\\s+(?:\\x60|'|")?${RELEASE_VERSION.replaceAll(".", "\\.")}`).test(fs.readFileSync(readmePath, "utf8"))) { fileError("README_VERSION_MISMATCH", "README.md", `README must declare Version ${RELEASE_VERSION}`); } const citationPath = path.join(packageRoot, "CITATION.cff"); if (!fs.existsSync(citationPath)) fileError("CITATION_MISSING", "CITATION.cff", "CITATION.cff is missing"); else { const citation = fs.readFileSync(citationPath, "utf8"); const match = /^version:\s*["']?([^\s"']+)["']?\s*$/m.exec(citation); if (!match || match[1] !== RELEASE_VERSION) fileError("CITATION_VERSION_MISMATCH", "CITATION.cff", `CITATION must declare version ${RELEASE_VERSION}`); } // Stored audits must be identical and must exactly match a fresh deterministic run. const auditPaths = [path.join(dataDir, "audit.json"), path.join(dataDir, "audit-v03.json")]; const auditBuffers = auditPaths.map((filepath) => fs.existsSync(filepath) ? fs.readFileSync(filepath) : null); for (const [index, buffer] of auditBuffers.entries()) { if (!buffer) fileError("STORED_AUDIT_MISSING", path.basename(auditPaths[index]), "Stored audit is missing"); } if (auditBuffers.every(Boolean) && !auditBuffers[0].equals(auditBuffers[1])) { fileError("STORED_AUDIT_DIVERGENCE", "audit.json|audit-v03.json", "Stored audit files must be byte-identical"); } let storedAudit = null; if (auditBuffers[0]) { try { storedAudit = JSON.parse(auditBuffers[0].toString("utf8")); } catch (caught) { fileError("STORED_AUDIT_INVALID_JSON", "audit.json", `Invalid JSON: ${caught.message}`); } } if (storedAudit && storedAudit.auditor !== AUDITOR_ID) fileError("STORED_AUDITOR_MISMATCH", "audit.json", `Expected auditor ${AUDITOR_ID}; found ${storedAudit.auditor ?? "missing"}`); if (storedAudit && storedAudit.status !== "pass") fileError("STORED_AUDIT_NOT_PASS", "audit.json", `Stored audit status is ${storedAudit.status ?? "missing"}`); for (const table of EXPECTED_TABLES) { const actualRows = parsedCsv.get(table)?.rows.length; const storedRows = storedAudit?.summary?.table_row_counts?.[table]; if (Number.isInteger(actualRows) && storedRows !== actualRows) { fileError("STORED_AUDIT_ROW_COUNT_MISMATCH", `${table}.csv`, `Stored audit has ${storedRows ?? "missing"} rows; CSV has ${actualRows}`); } } let auditReport = null; let auditFailure = null; if (!fs.existsSync(auditScript)) auditFailure = "Semantic audit script is missing"; else { const result = spawnSync(process.execPath, [auditScript, dataDir], { encoding: "utf8", maxBuffer: 32 * 1024 * 1024 }); if (result.error) auditFailure = `Semantic audit could not run: ${result.error.message}`; else { try { auditReport = JSON.parse(result.stdout); } catch (caught) { auditFailure = `Semantic audit did not return valid JSON: ${caught.message}`; } if (auditReport && ![0, 1].includes(result.status)) auditFailure = `Semantic audit terminated with unexpected exit status ${result.status}: ${cleanOutput(result.stderr)}`; if (auditReport && ((auditReport.status === "pass") !== (result.status === 0))) auditFailure = `Semantic audit exit status ${result.status} disagrees with report status ${auditReport.status}`; } } if (auditFailure) fileError("LIVE_AUDIT_FAILURE", "scripts/audit-v03.mjs", auditFailure); if (auditReport && auditReport.auditor !== AUDITOR_ID) fileError("LIVE_AUDITOR_MISMATCH", "scripts/audit-v03.mjs", `Expected auditor ${AUDITOR_ID}; found ${auditReport.auditor ?? "missing"}`); if (auditReport && storedAudit && canonicalJson(auditReport) !== canonicalJson(storedAudit)) { fileError("STORED_AUDIT_STALE", "audit.json", "Stored audit does not exactly match the current deterministic audit report"); } let parquetStatus = sourceOnly ? "skipped" : "pass"; let checkedParquetCount = 0; if (!sourceOnly) { const manifestPath = path.join(parquetDir, "manifest.json"); const manifest = readJson(manifestPath, "parquet/manifest.json", "PARQUET_MANIFEST"); let parquetModule = null; let parquetPackage = null; try { const require = createRequire(import.meta.url); parquetModule = require("parquetjs-lite"); parquetPackage = require("parquetjs-lite/package.json"); } catch (caught) { fileError("PARQUET_READER_MISSING", "package.json", `Pinned parquetjs-lite dependency is unavailable: ${caught.message}`); } if (manifest) { if (manifest.manifest_version !== 1) fileError("PARQUET_MANIFEST_VERSION_INVALID", "parquet/manifest.json", "manifest_version must be 1"); if (manifest.dataset_version !== RELEASE_VERSION) fileError("PARQUET_DATASET_VERSION_MISMATCH", "parquet/manifest.json", `Expected ${RELEASE_VERSION}; found ${manifest.dataset_version ?? "missing"}`); if (manifest.generator?.name !== "scripts/build-parquet.mjs" || manifest.generator?.version !== RELEASE_VERSION) { fileError("PARQUET_GENERATOR_INVALID", "parquet/manifest.json", "Generator name/version is missing or inconsistent"); } if (!/^v\d+\.\d+\.\d+/.test(String(manifest.generator?.node || ""))) fileError("PARQUET_NODE_VERSION_INVALID", "parquet/manifest.json", "Generator Node version is missing or invalid"); if (parquetPackage && manifest.generator?.parquetjs_lite !== parquetPackage.version) { fileError("PARQUET_TOOL_VERSION_MISMATCH", "parquet/manifest.json", `Manifest tool ${manifest.generator?.parquetjs_lite ?? "missing"}; installed ${parquetPackage.version}`); } if (fs.existsSync(datapackagePath) && manifest.datapackage_sha256 !== sha256(fs.readFileSync(datapackagePath))) { fileError("PARQUET_DATAPACKAGE_HASH_MISMATCH", "parquet/manifest.json", "datapackage_sha256 differs from data/datapackage.json"); } if (!Array.isArray(manifest.tables)) fileError("PARQUET_TABLES_INVALID", "parquet/manifest.json", "tables must be an array"); else { const tableNames = manifest.tables.map((item) => item?.table); for (const table of EXPECTED_TABLES) if (!tableNames.includes(table)) fileError("PARQUET_ENTRY_MISSING", table, "Parquet manifest entry is missing"); for (const table of tableNames) if (!EXPECTED_TABLES.includes(table)) fileError("PARQUET_ENTRY_UNEXPECTED", String(table), "Unexpected Parquet manifest entry"); if (new Set(tableNames).size !== tableNames.length) fileError("PARQUET_ENTRY_DUPLICATE", "parquet/manifest.json", "Duplicate Parquet table entry"); const actualParquetNames = fs.existsSync(parquetDir) ? fs.readdirSync(parquetDir).filter((name) => name.endsWith(".parquet")).sort() : []; const expectedParquetNames = EXPECTED_TABLES.map((name) => `${name}.parquet`).sort(); for (const name of expectedParquetNames) if (!actualParquetNames.includes(name)) fileError("PARQUET_FILE_MISSING", `parquet/${name}`, "Expected Parquet file is missing"); for (const name of actualParquetNames) if (!expectedParquetNames.includes(name)) fileError("PARQUET_FILE_UNEXPECTED", `parquet/${name}`, "Unexpected Parquet file is present"); for (const item of manifest.tables) { const table = item?.table; if (!EXPECTED_TABLES.includes(table)) continue; const expectedFile = `parquet/${table}.parquet`; const expectedSource = `data/${table}.csv`; const parquetPath = path.join(packageRoot, expectedFile); const csv = parsedCsv.get(table); const fields = resourceByName.get(table)?.schema?.fields; const expectedSchemaHash = Array.isArray(fields) ? sha256(Buffer.from(canonicalJson(fields))) : null; if (item.file !== expectedFile) fileError("PARQUET_PATH_MISMATCH", table, `Expected ${expectedFile}; found ${item.file ?? "missing"}`); if (item.source_csv !== expectedSource) fileError("PARQUET_SOURCE_PATH_MISMATCH", table, `Expected ${expectedSource}; found ${item.source_csv ?? "missing"}`); if (!csv || item.source_csv_sha256 !== sha256(csv.contents)) fileError("PARQUET_SOURCE_HASH_MISMATCH", table, "source_csv_sha256 differs from the CSV source"); if (!csv || item.rows !== csv.rows.length) fileError("PARQUET_SOURCE_ROW_COUNT_MISMATCH", table, `Manifest has ${item.rows ?? "missing"}; CSV has ${csv?.rows.length ?? "missing"}`); if (!expectedSchemaHash || item.schema_sha256 !== expectedSchemaHash) fileError("PARQUET_SCHEMA_HASH_MISMATCH", table, "schema_sha256 differs from datapackage schema.fields"); if (!fs.existsSync(parquetPath)) continue; const buffer = fs.readFileSync(parquetPath); if (item.bytes !== buffer.byteLength) fileError("PARQUET_BYTE_COUNT_MISMATCH", table, `Manifest has ${item.bytes ?? "missing"}; file has ${buffer.byteLength}`); if (item.sha256 !== sha256(buffer)) fileError("PARQUET_FILE_HASH_MISMATCH", table, "Parquet file differs from manifest SHA-256"); if (parquetModule && Array.isArray(fields)) { let reader; try { reader = await parquetModule.ParquetReader.openFile(parquetPath); const rowCount = Number(reader.getRowCount()); if (rowCount !== csv?.rows.length || rowCount !== item.rows) fileError("PARQUET_INTERNAL_ROW_COUNT_MISMATCH", table, `Parquet metadata has ${rowCount}; expected ${csv?.rows.length ?? "missing"}`); const actualFields = reader.getSchema().fields; const actualNames = Object.keys(actualFields); const expectedNames = fields.map((field) => field.name); if (actualNames.length !== expectedNames.length || actualNames.some((name, index) => name !== expectedNames[index])) { fileError("PARQUET_INTERNAL_SCHEMA_ORDER_MISMATCH", table, "Parquet columns/order differ from datapackage schema"); } const expectedTypes = { string: ["BYTE_ARRAY", "UTF8"], integer: ["INT64", undefined], number: ["DOUBLE", undefined], boolean: ["BOOLEAN", undefined], date: ["INT32", "DATE"] }; for (const field of fields) { const actual = actualFields[field.name]; const expected = expectedTypes[field.type]; const repetition = field.constraints?.required === true ? "REQUIRED" : "OPTIONAL"; if (!actual || !expected || actual.primitiveType !== expected[0] || actual.originalType !== expected[1] || actual.repetitionType !== repetition) { fileError("PARQUET_INTERNAL_FIELD_MISMATCH", `${table}.${field.name}`, `Parquet type/repetition differs from datapackage type ${field.type}`); } } checkedParquetCount += 1; } catch (caught) { fileError("PARQUET_READ_FAILURE", table, `Could not inspect Parquet metadata: ${String(caught.message || caught)}`); } finally { if (reader) await reader.close(); } } } } } if (fileErrors.some((item) => item.code.startsWith("PARQUET_"))) parquetStatus = "fail"; } let releaseStatus = sourceOnly ? "skipped" : "not_present"; let checkedReleaseArtifactCount = 0; if (!sourceOnly) { const pattern = new RegExp(`-v${RELEASE_VERSION.replaceAll(".", "\\.")}\\.(?:zip|xlsx)$`); const artifacts = fs.existsSync(releaseDir) ? fs.readdirSync(releaseDir).filter((name) => pattern.test(name)).sort() : []; const manifestPath = path.join(releaseDir, "release-manifest.json"); const sumsPath = path.join(releaseDir, "SHA256SUMS"); const hasMetadata = fs.existsSync(manifestPath) || fs.existsSync(sumsPath); if (artifacts.length || hasMetadata) { releaseStatus = "pass"; if (!artifacts.length) fileError("RELEASE_ARTIFACTS_MISSING", "release/", `Release metadata exists but no v${RELEASE_VERSION} artifact is present`); const manifest = readJson(manifestPath, "release/release-manifest.json", "RELEASE_MANIFEST"); if (!fs.existsSync(sumsPath)) fileError("RELEASE_SUMS_MISSING", "release/SHA256SUMS", "SHA256SUMS is missing"); if (manifest) { if (manifest.manifest_version !== 1) fileError("RELEASE_MANIFEST_VERSION_INVALID", "release/release-manifest.json", "manifest_version must be 1"); if (manifest.dataset_version !== RELEASE_VERSION) fileError("RELEASE_DATASET_VERSION_MISMATCH", "release/release-manifest.json", `Expected ${RELEASE_VERSION}; found ${manifest.dataset_version ?? "missing"}`); if (!Array.isArray(manifest.artifacts)) fileError("RELEASE_ARTIFACT_LIST_INVALID", "release/release-manifest.json", "artifacts must be an array"); else { const names = manifest.artifacts.map((item) => item?.name); if (names.some((name, index) => name !== [...names].sort()[index])) { fileError("RELEASE_ARTIFACT_ORDER_INVALID", "release/release-manifest.json", "Artifact entries must be sorted by filename"); } for (const name of artifacts) if (!names.includes(name)) fileError("RELEASE_ARTIFACT_ENTRY_MISSING", name, "Artifact is absent from release manifest"); for (const name of names) if (!artifacts.includes(name)) fileError("RELEASE_ARTIFACT_ENTRY_UNEXPECTED", String(name), "Manifest lists an absent or wrong-version artifact"); if (new Set(names).size !== names.length) fileError("RELEASE_ARTIFACT_ENTRY_DUPLICATE", "release/release-manifest.json", "Duplicate artifact entry"); const expectedSums = []; for (const item of manifest.artifacts) { if (!artifacts.includes(item?.name)) continue; const artifactPath = path.join(releaseDir, item.name); const buffer = fs.readFileSync(artifactPath); if (item.bytes !== buffer.byteLength) fileError("RELEASE_ARTIFACT_BYTE_COUNT_MISMATCH", item.name, `Manifest has ${item.bytes ?? "missing"}; file has ${buffer.byteLength}`); const digest = sha256(buffer); if (item.sha256 !== digest) fileError("RELEASE_ARTIFACT_HASH_MISMATCH", item.name, "Artifact differs from release manifest SHA-256"); expectedSums.push(`${digest} ${item.name}`); checkedReleaseArtifactCount += 1; } const actualSums = fs.existsSync(sumsPath) ? fs.readFileSync(sumsPath, "utf8") : ""; const canonicalSums = expectedSums.join("\n") + (expectedSums.length ? "\n" : ""); if (actualSums !== canonicalSums) fileError("RELEASE_SUMS_MISMATCH", "release/SHA256SUMS", "SHA256SUMS differs from sorted manifest artifacts"); } const expectedPackageFiles = ["README.md", "CITATION.cff", "package.json", "data/datapackage.json"]; const frozenPackageRoot = `agency-transfer-election-cases-v${RELEASE_VERSION}`; const frozenPackageName = `${frozenPackageRoot}.zip`; const frozenPackagePath = path.join(releaseDir, frozenPackageName); if (!Array.isArray(manifest.package_files)) fileError("RELEASE_PACKAGE_FILES_INVALID", "release/release-manifest.json", "package_files must be an array"); else { const names = manifest.package_files.map((item) => item?.name); if (new Set(names).size !== names.length) { fileError("RELEASE_PACKAGE_FILE_DUPLICATE", "release/release-manifest.json", "Duplicate package-file entry"); } if (JSON.stringify(names) !== JSON.stringify(expectedPackageFiles)) { fileError("RELEASE_PACKAGE_FILE_ORDER_INVALID", "release/release-manifest.json", "Package-file entries must exactly match the declared order"); } for (const name of expectedPackageFiles) if (!names.includes(name)) fileError("RELEASE_PACKAGE_FILE_MISSING", name, "Release manifest lacks package metadata hash"); if (!fs.existsSync(frozenPackagePath)) { fileError("RELEASE_PACKAGE_ARCHIVE_MISSING", frozenPackageName, "Frozen package ZIP is missing"); } for (const item of manifest.package_files) { if (!expectedPackageFiles.includes(item?.name)) { fileError("RELEASE_PACKAGE_FILE_UNEXPECTED", String(item?.name), "Unexpected package-file entry"); continue; } if (!fs.existsSync(frozenPackagePath)) continue; let buffer; try { buffer = readZipMember(frozenPackagePath, `${frozenPackageRoot}/${item.name}`); } catch (caught) { fileError("RELEASE_PACKAGE_FILE_ABSENT", item.name, `Frozen package member is missing or unreadable: ${cleanOutput(caught.message)}`); continue; } if (item.bytes !== buffer.byteLength) fileError("RELEASE_PACKAGE_FILE_BYTE_COUNT_MISMATCH", item.name, "Frozen package member byte count differs"); if (item.sha256 !== sha256(buffer)) fileError("RELEASE_PACKAGE_FILE_HASH_MISMATCH", item.name, "Frozen package member differs from release manifest SHA-256"); } } if (manifest.reproducibility?.workbook !== "checksum_only_external_artifact_runtime_not_in_public_dependency_graph") { fileError("WORKBOOK_REPRODUCIBILITY_CLAIM_INVALID", "release/release-manifest.json", "Workbook must be described as checksum-only while its runtime is not public/pinned"); } } if (fileErrors.some((item) => item.code.startsWith("RELEASE_") || item.code === "WORKBOOK_REPRODUCIBILITY_CLAIM_INVALID")) releaseStatus = "fail"; } } fileErrors.sort((a, b) => a.code.localeCompare(b.code) || String(a.file).localeCompare(String(b.file)) || a.message.localeCompare(b.message)); const auditIntegrity = auditReport?.integrity; const semanticAudit = auditReport?.semantic_audit; const integrityFailed = fileErrors.length > 0 || auditIntegrity?.status !== "pass"; const semanticFailed = !auditReport || semanticAudit?.status !== "pass"; const report = { validator: VALIDATOR_ID, version: RELEASE_VERSION, mode: sourceOnly ? "source-only" : "full-release", status: integrityFailed || semanticFailed ? "fail" : "pass", integrity: { status: integrityFailed ? "fail" : "pass", expected_table_count: EXPECTED_TABLES.length, present_table_count: expectedCsvNames.filter((filename) => actualCsvNames.includes(filename)).length, hashed_release_file_count: isPlainObject(fileHashes) ? Object.keys(fileHashes).length : 0, hashed_input_count: isPlainObject(inputHashes) ? Object.keys(inputHashes).length : 0, parquet_status: parquetStatus, checked_parquet_count: checkedParquetCount, release_artifact_status: releaseStatus, checked_release_artifact_count: checkedReleaseArtifactCount, file_error_count: fileErrors.length, contract_error_count: Number.isInteger(auditIntegrity?.error_count) ? auditIntegrity.error_count : null, errors: fileErrors, contract_errors: Array.isArray(auditReport?.errors) ? auditReport.errors.filter((item) => item.layer === "integrity") : [] }, semantic_audit: semanticAudit ? { status: semanticAudit.status, audited_table_count: semanticAudit.audited_table_count, error_count: semanticAudit.error_count, warning_count: semanticAudit.warning_count, errors: Array.isArray(auditReport?.errors) ? auditReport.errors.filter((item) => item.layer === "semantic") : [] } : { status: "fail", failure: auditFailure || "Semantic audit unavailable" } }; process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); if (report.status === "fail") process.exitCode = 1;