Files
MikrotikManager/backend/src/db/migration-manifest.ts
T
Denozordec ef3d7b6779
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m21s
Docker images / frontend-image (push) Successful in 2m8s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m59s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
fix(poll): снять квоты журналов полного опроса
2026-11-23 11:35:04 +07:00

953 lines
57 KiB
TypeScript

import { createHash } from "node:crypto"
import { readdir, readFile } from "node:fs/promises"
import { join } from "node:path"
/** Inventory only: no database imports, SQL execution, rewrite or dispatcher. */
export type MigrationTransaction = "owner-transaction" | "self-managed-single-transaction"
export interface MigrationReview {
file: string; sha256: string; transaction: MigrationTransaction; selfMarker: boolean
opaqueBodies: number; bodyReview: readonly string[]; effects: readonly string[]
publicTableReset?: true
}
export interface SqlToken { kind: "word" | "identifier" | "string" | "dollar" | "symbol" | "number"; value: string; line: number }
export interface MigrationStatement { line: number; endLine: number; tokens: SqlToken[] }
export class MigrationManifestError extends Error { readonly code = "MIGRATION_MANIFEST_REFUSED" }
const refuse = (message: string): never => { throw new MigrationManifestError(message) }
const hash = (value: Uint8Array | string) => createHash("sha256").update(value).digest("hex")
/** PostgreSQL lexical subset needed by the pinned inventory. Dollar-quoted
* bodies/strings/quoted identifiers are opaque: semicolons and BEGIN inside
* them never become top-level statements. Unsupported/unterminated input
* refuses. This is not a general PL/pgSQL semantic evaluator. */
export function parseMigrationStatements(source: string): MigrationStatement[] {
if (Buffer.byteLength(source) > 2097152 || source.includes("\0")) refuse("Migration source exceeds lexical bounds")
let index = 0, line = 1, count = 0, tokens: SqlToken[] = []
const statements: MigrationStatement[] = []
const advance = (length: number) => { line += (source.slice(index, index + length).match(/\n/g) ?? []).length; index += length }
const push = (kind: SqlToken["kind"], value: string, at: number) => { if (++count > 200000) refuse("Migration token bound exceeded"); tokens.push({ kind, value, line: at }) }
while (index < source.length) {
const tail = source.slice(index), char = source[index], at = line
if (/\s/.test(char)) { advance(1); continue }
if (tail.startsWith("--")) { const end = source.indexOf("\n", index); advance((end < 0 ? source.length : end) - index); continue }
if (tail.startsWith("/*")) {
let depth = 1; advance(2)
while (depth && index < source.length) {
if (source.startsWith("/*", index)) { depth++; advance(2) }
else if (source.startsWith("*/", index)) { depth--; advance(2) }
else advance(1)
}
if (depth) refuse("Unterminated migration block comment")
continue
}
if (char === ";") {
if (tokens.length) { statements.push({ line: tokens[0].line, endLine: line, tokens }); tokens = []; if (statements.length > 5000) refuse("Migration statement bound exceeded") }
advance(1); continue
}
const escapeString = /^[eE]'/.test(tail)
if (char === "'" || char === '"' || escapeString) {
const quote = char === '"' ? '"' : "'"; advance(escapeString ? 2 : 1)
let value = "", closed = false
while (index < source.length) {
if (escapeString && source[index] === "\\") { if (index + 1 >= source.length) refuse("Unterminated escape string"); value += source.slice(index, index + 2); advance(2) }
else if (source[index] === quote) {
if (source[index + 1] === quote) { value += quote; advance(2) }
else { advance(1); closed = true; break }
} else { value += source[index]; advance(1) }
}
if (!closed) refuse("Unterminated migration quote")
push(quote === '"' ? "identifier" : "string", value, at); continue
}
const dollar = /^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(tail)?.[0]
if (dollar) {
const end = source.indexOf(dollar, index + dollar.length)
if (end < 0) refuse("Unterminated migration dollar body")
const body = source.slice(index + dollar.length, end)
if (Buffer.byteLength(body) > 1048576) refuse("Migration body bound exceeded")
push("dollar", body, at); advance(end + dollar.length - index); continue
}
if (/^[uU]&['"]/.test(tail) || char === "\\") refuse("Unsupported migration lexical construct")
const word = /^[A-Za-z_][A-Za-z_0-9$]*/.exec(tail)?.[0]
if (word) { push("word", word.toUpperCase(), at); advance(word.length); continue }
const number = /^\d+(?:\.\d+)?/.exec(tail)?.[0]
if (number) { push("number", number, at); advance(number.length); continue }
if (/[(),.=<>:+\-/%\[\]|!?^~*]/.test(char)) { push("symbol", char, at); advance(1); continue }
refuse("Unsupported migration token at line " + line)
}
if (tokens.length) refuse("Migration has an unterminated top-level statement")
return statements
}
const words = (statement: MigrationStatement) => statement.tokens.filter(token => token.kind === "word").map(token => token.value)
function target(statement: MigrationStatement) {
const tokens = statement.tokens
let position = tokens.findIndex(token => token.kind === "word" && ["TABLE", "INDEX", "FUNCTION", "TRIGGER", "INTO"].includes(token.value)) + 1
if (!position) return undefined
while (tokens[position]?.kind === "word" && ["IF", "NOT", "EXISTS"].includes(tokens[position].value)) position++
const first = tokens[position]
if (!first || !["word", "identifier"].includes(first.kind)) return undefined
const name = first.kind === "word" ? first.value.toLowerCase() : first.value
if (tokens[position + 1]?.value === ".") {
const second = tokens[position + 2]
if (!second || !["word", "identifier"].includes(second.kind)) refuse("Invalid qualified migration target")
return name + "." + (second.kind === "word" ? second.value.toLowerCase() : second.value)
}
return name
}
export function analyzeMigration(file: string, bytes: Uint8Array, review: MigrationReview) {
if (!/^\d{4}_[a-z_0-9]+\.sql$/.test(file) || review.file !== file || !/^[a-f0-9]{64}$/.test(review.sha256) || hash(bytes) !== review.sha256) refuse("Unclassified or changed migration file: " + file)
const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes)
const statements = parseMigrationStatements(source)
if (!statements.length) refuse("Empty migration file")
const controls = statements.flatMap((statement, index) => {
const first = words(statement)[0]
if (!["BEGIN", "START", "COMMIT", "END", "ROLLBACK", "SAVEPOINT", "RELEASE", "PREPARE"].includes(first)) return []
if (statement.tokens.length !== 1 || !["BEGIN", "COMMIT"].includes(first)) refuse("Unsupported migration transaction boundary")
return [{ index, kind: first, line: statement.line }]
})
const transaction: MigrationTransaction = controls.length ? "self-managed-single-transaction" : "owner-transaction"
if (controls.length && (controls.length !== 2 || controls[0].index !== 0 || controls[0].kind !== "BEGIN" || controls[1].index !== statements.length - 1 || controls[1].kind !== "COMMIT")) refuse("Migration has split or nonterminal transaction boundaries")
if (transaction !== review.transaction) refuse("Migration transaction contract changed")
const opaque = statements.flatMap((statement, index) => {
const head = words(statement).slice(0, 4).join(" "), isDo = head.startsWith("DO"), isFunction = /^CREATE (?:OR REPLACE )?FUNCTION\b/.test(head)
const bodies = statement.tokens.filter(token => token.kind === "dollar")
if ((isDo || isFunction) && bodies.length !== 1) refuse("Executable/stored migration body requires an explicitly reviewed dollar body")
return bodies.map(token => ({ statement: index, line: token.line, sha256: hash(token.value), kind: isDo ? "executed-do-body" : isFunction ? "stored-function-body" : "dollar-literal" }))
})
if (opaque.length !== review.opaqueBodies || review.bodyReview.length !== opaque.length) refuse("Migration opaque body lacks exact semantic review")
const selfMarkers = statements.flatMap((statement, index) => {
if (words(statement)[0] !== "INSERT" || !["schema_migrations", "public.schema_migrations"].includes(target(statement) ?? "")) return []
const tokens = statement.tokens, literal = tokens.filter(token => token.kind === "string")
const shape = tokens.map(token => token.kind === "string" ? "?" : token.value).join(" ")
if (!/^INSERT INTO (?:PUBLIC \. )?SCHEMA_MIGRATIONS \( ID \) VALUES \( \? \) ON CONFLICT \( ID \) DO NOTHING$/.test(shape) || literal.length !== 1 || literal[0].value !== file.slice(0, -4)) refuse("Migration self-marker is not the exact declared id INSERT")
return [{ statement: index, line: statement.line, id: literal[0].value }]
})
if (selfMarkers.length !== Number(review.selfMarker) || selfMarkers.length && (transaction !== "self-managed-single-transaction" || selfMarkers[0].statement !== statements.length - 2)) refuse("Migration self-marker is not atomic with all file effects")
for (const statement of statements) {
const tokens = words(statement), command = tokens[0]
if (!["BEGIN", "COMMIT", "CREATE", "ALTER", "INSERT", "DROP", "DO", "LOCK"].includes(command)) refuse("Unclassified migration command: " + command)
if (tokens.includes("CONCURRENTLY") || tokens.includes("SETVAL") || tokens.includes("NEXTVAL") || tokens.slice(0, 2).join(" ") === "ALTER SYSTEM") refuse("Migration contains an unclassified nontransactional effect")
}
return {
file, id: file.slice(0, -4), sha256: review.sha256, byteLength: bytes.length, transaction,
topLevelTransactionControls: controls, statementCount: statements.length,
selfMarker: selfMarkers[0] ? { ...selfMarkers[0], atomicWithAllFileEffects: true } : null,
currentOuterMarkerGap: !review.selfMarker,
futureDispatcher: transaction === "owner-transaction" ? "may-run-verbatim-in-owned-transaction-with-marker-and-receipt-after-durable-intent" : review.selfMarker ? "verbatim-self-managed-file-with-audited-atomic-legacy-marker-and-separate-durable-receipt" : "verbatim-self-managed-file-needs-durable-pre-intent-and-post-file-terminal-receipt-gap-refusal",
effects: [...review.effects], publicTableReset: review.publicTableReset === true,
opaqueBodies: opaque.map((body, index) => ({ ...body, review: review.bodyReview[index] })),
nontransactionalExecution: "none-observed-in-exact-reviewed-bytes; identity definitions and nondeterministic defaults are separately described",
operations: statements.map((statement, index) => ({ statement: index, line: statement.line, endLine: statement.endLine, command: words(statement)[0], objectKind: words(statement).find(word => ["TABLE", "INDEX", "FUNCTION", "TRIGGER"].includes(word)) ?? (words(statement)[0] === "INSERT" ? "TABLE" : null), target: target(statement) ?? null })),
}
}
// Exact byte pins and semantic reviews. Additions or any byte change require
// an explicit reviewed entry; the inventory never auto-enrolls discovered SQL.
const classifiedMigrationPins: readonly MigrationReview[] = [
{
"file": "0000_postgresql.sql",
"sha256": "eb6ce1449add311611634845aa6608327821ca2cbe33c1e7b214dde37d85027e",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Initial public application tables, indexes, FK cascades, identity sequence definitions and settings/data_migration seeds; no marker INSERT in file; generated identity definitions are not evidence of nextval execution."
]
},
{
"file": "0002_compact_schema.sql",
"sha256": "0ffcbb8d54dd386a1d709ee03a2e556f4caee102c1b9ef7b0faeef6019056deb",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 1,
"bodyReview": [
"Executed DO: catalog loop dynamically DROP TABLE IF EXISTS public.%I CASCADE, excludes ONLY public schema_migrations; data-destructive after commit; no top-level transaction statements hidden in this body."
],
"effects": [
"DESTRUCTIVE executed DO enumerates public pg_tables and DROP TABLE ... CASCADE for every table except schema_migrations; destroys application data and any public recovery tables.",
"Recreates compact public tables/indexes/FK cascades and identity definitions; initializes settings/data_migration, which removes the previous import-completion state; no file marker."
],
"publicTableReset": true
},
{
"file": "0003_backup_s3.sql",
"sha256": "59cda0660a0f487330058735ad2ee75021ca236480c28a81a2cf32bb4cd77be7",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 1,
"bodyReview": [
"Executed DO: catalog existence check and conditional ALTER TABLE backup_entries ADD CONSTRAINT; no transaction control, external call or nontransactional sequence advance."
],
"effects": [
"Creates/seeds backup_storage_settings; adds backup_entries storage/S3 columns; executed DO conditionally adds storage CHECK constraint."
]
},
{
"file": "0004_geoip_settings.sql",
"sha256": "a0c6e7b918df2c43dd4dd2f76aa0fea3c24b6c6e304390708d9c601521b6343c",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates/seeds geoip_settings; enabled/update defaults are schema metadata, no downloader/network execution."
]
},
{
"file": "0005_flow_facts.sql",
"sha256": "26254ce080c9bc1b8d33431c4c00ed7f8601d49c035a3bb0c0d9cf00d268c8a1",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates partitioned flow_hour_facts and flow_daily_facts parents with server FK cascades; no leaf creation or retention execution."
]
},
{
"file": "0006_config_revisions.sql",
"sha256": "aed6b7abaeb8b895c019b32ee5badf5c68fb457d50a4187fbb5c58a8c8728b8f",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates config_revisions with server FK cascade and server/section/time index; retention is comment only."
]
},
{
"file": "0007_flow_buckets_nat.sql",
"sha256": "2cab88bea14f338b72127c3c7e39ab7d88baa2d11a728389724ba5574ecdecdd",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds four NAT address/port columns to flow_buckets."
]
},
{
"file": "0008_alert_outbox_outcomes.sql",
"sha256": "d16e97a48da5d957b9797309bc0e7b48a826ef861d6734cf4da1ee756539b825",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Drops/replaces alert_outbox status CHECK to permit processing/unknown states; no historical row UPDATE."
]
},
{
"file": "0009_alert_outbox_resolution.sql",
"sha256": "e3d66a133862e443320d83213899e96d7de84e1c8144962615895176c8c62b11",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds alert_outbox resolution_version and nonnegative CHECK."
]
},
{
"file": "0010_ping_measurement_known.sql",
"sha256": "4cc2f13a489f3b300d238a205a41b75d495a4aa26e3d1468f26b1f682c4a94aa",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds uptime_probe_samples measurement_known default true and observation_error; default backfill changes existing row interpretation transactionally."
]
},
{
"file": "0011_traffic_collection_state.sql",
"sha256": "83e3b6958ea289e594cc68b0646c894c703104ca95a9c73e203886950fc94b9b",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates traffic_collection_state with server FK cascade."
]
},
{
"file": "0012_traffic_counter_identity.sql",
"sha256": "491bb39fe85554d16881696a10d5d5732f60ecec1be92a8dd7b9584ce5a8a9b8",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds traffic_samples native_counter_identity."
]
},
{
"file": "0013_scheduler_retention_index.sql",
"sha256": "8ae429ba11fa02163bb3a12f25fc8fdd9708b98badf4a37dfc3a5124740ced0e",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates ordinary scheduler_runs finished_at index; CONCURRENTLY appears ONLY in comments/deployment advice, not executed SQL."
]
},
{
"file": "0014_router_logs.sql",
"sha256": "6f82eeb26101bf20574a0c6cb1f5778d6e8151290f0733e7896c5b6e26fe985f",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates/seeds router_log_settings, collection state, identity-backed log entries and six log indexes; log history deliberately lacks server FK."
]
},
{
"file": "0015_mcp.sql",
"sha256": "13c279fe2ecbabeef1b1c588fbf58a374141d931b45914aac5803efc496496b7",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates initial public MCP settings/connections/credentials/audit/requests/protections/plans/operations/steps/budgets/read leases/grants/secrets/artifacts/OAuth/routing profiles/drift tables and indexes; settings seed; identity definition on audit; no file marker."
]
},
{
"file": "0016_mcp_routing_observations.sql",
"sha256": "7b35e4ca6522a7d0e086c518a9f84bfb7bf6eabc3d6ce3a6f537117cc49b6e8e",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates MCP routing observations and leg index."
]
},
{
"file": "0017_mcp_controller.sql",
"sha256": "bb48c740b4770d979babc2684d9ad7d9e7577083197a74fe00c47e3ce59c1673",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds routing profile credential/generation/policy-version fields and enabled/open-drift indexes."
]
},
{
"file": "0018_mcp_owner_validation.sql",
"sha256": "e52f618f7dfd2085b888032367d0d2b56a4004efa4fd6a0561dc3fb1e5f83a61",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds owner_valid_until default now to connections; transactionally backfills existing owner-validity metadata."
]
},
{
"file": "0019_mcp_recovery.sql",
"sha256": "820899500c0d00c67a9b34dfd6769cd146c7688e39014d8b4b4cc7bfb6180bb0",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates encrypted operation checkpoints."
]
},
{
"file": "0020_mcp_management.sql",
"sha256": "cdd5c527965793060818a4eb600443376470f315e621e451d6ef882840b140ab",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates management channels with server FK cascade."
]
},
{
"file": "0021_mcp_path_checks.sql",
"sha256": "8f7c67a99848ecc6ce48c2573ac95f44bd9222c4c74da2aa3283598dff304d35",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates path checks and latest-check index."
]
},
{
"file": "0022_mcp_recovery_intents.sql",
"sha256": "a40c06e73a552400ee903848f9149923d85d2176e211c6c91681fff61ffc2b04",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates recovery intents tied to operation/profile."
]
},
{
"file": "0023_mcp_protocol_limits.sql",
"sha256": "0feac9580a7f6af649b664cfc129135c5c6a682bc50f0534550ed65f3b82fb10",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates unauthorized request buckets."
]
},
{
"file": "0024_user_interface_types.sql",
"sha256": "dd381cb3a33a41e9dc1ca351c632646f9dce7f018b6f40e93e0c393437c9e7b5",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Drops/replaces interface type CHECK, adding ipsec."
]
},
{
"file": "0025_mcp_portal_revocation.sql",
"sha256": "c47b01c4976f39f13d77c67606c6681c17fb1c83b0036c9157134ccf322f6f37",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates portal owner revocations/events and event-time index."
]
},
{
"file": "0026_mcp_owner_claims_issued.sql",
"sha256": "5569287afd46676a9e8d738dcce2a143c7125b329ad8d892d2f59719b221e815",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds owner_claims_issued_at default epoch; transactionally backfills legacy claim timestamp."
]
},
{
"file": "0027_mcp_readiness.sql",
"sha256": "c90b16fcd376bac8c907be715b8e2d4ecd4a7171e624b9e93f884dd5f12ac159",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates handshake cooldown, credential-expiry/readiness and grant-credential indexes."
]
},
{
"file": "0028_mcp_artifact_scope.sql",
"sha256": "ad76f4f4c981d6cc3dfabdaf31eddf1f65d4ba3444940e6ad6ad5b7f5bc71ac4",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds artifact access_scope and expiry index."
]
},
{
"file": "0029_mcp_routing_sources.sql",
"sha256": "4e9f739407a6a6d969c746485f90de3dc0f62c09292f7ccea425697fe6317c5c",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 2,
"bodyReview": [
"Stored PL/pgSQL trigger function: assigns gen_random_uuid to NEW epoch only when endpoint fields change, otherwise preserves OLD epoch; RETURN NEW; body is not executed by CREATE.",
"Executed DO: conditionally adds mcp_routing_observation_source_proof CHECK; no transaction control or external effects."
],
"effects": [
"Adds server routing_endpoint_epoch with gen_random_uuid default/backfill; creates/replaces epoch trigger function, drops/recreates UPDATE trigger, adds observation source_proof and guarded CHECK.",
"Stored trigger function generates fresh endpoint UUID on future endpoint-field changes; function definition is not top-level execution of its body; preserves unsigned historical observations."
]
},
{
"file": "0030_mcp_scoped_configuration_checkpoint.sql",
"sha256": "4f99d83cd803be616e6512c39227eaa63e24e5335e23994af059ce8c6f10c148",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds sealed scoped configuration checkpoint/proof fields."
]
},
{
"file": "0031_mcp_scoped_recovery.sql",
"sha256": "3d6380a57f18b940168f9bf584586ccbe99de0b07293e6dae033ea7071088a3f",
"transaction": "self-managed-single-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates scoped recovery intents and consistency checks."
]
},
{
"file": "0032_flow_write_receipts.sql",
"sha256": "ca89054c375261f847d1f4a6e87ccf8f83f1f7279f957b89b0ae447b6a468020",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates immutable-purpose flow_write_receipts schema; no pruning or receipt insertion in migration."
]
},
{
"file": "0033_flow_settings_intents.sql",
"sha256": "a341295c9a6f4ab09d62dbc7b30c4b0e6c947845a6ceac36bb581ff44964f748",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates flow_settings_intents claim schema and seeds traffic_flow_settings."
]
},
{
"file": "0034_vrf_production_tickets.sql",
"sha256": "b5317f326f54e46e3efaf4b1969673d33b6dd2835c12ca61fa7d73abbc9b3d10",
"transaction": "owner-transaction",
"selfMarker": false,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Creates precondition-only VRF production tickets and bounded validity/state CHECKs; no executor capability."
]
},
{
"file": "0035_server_probe_journal.sql",
"sha256": "ccc2a61b8329b083c6a5aac4d68b7dca3cf7cc715e702912a4bd1c15de36706d",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 3,
"bodyReview": [
"Stored trigger: reject DELETE/terminal identity changes or quarantined execution, RETURN NEW.",
"Stored trigger: lock execution row, reject DELETE/noncontiguous stages/invalid terminal change, RETURN NEW.",
"Stored trigger: always reject quarantine mutation; definitions execute no journal DML."
],
"effects": [
"Creates probe executions/stages/quarantines with three stored immutability functions/triggers; one exact file-id marker is penultimate before COMMIT.",
"Trigger bodies reject future journal mutations but do not execute UPDATE/DELETE during migration; no existing journal history deletion."
]
},
{
"file": "0036_diagnostic_cancellations.sql",
"sha256": "3a9058ac307cf5b63d35f1eec081a5442baa381d29dd9bc6c1df4dded625f007",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Stored trigger function always raises immutability exception; not an executable migration transaction BEGIN."
],
"effects": [
"Creates cancellation requests with stored rejecting immutability function/trigger; exact file-id marker is penultimate before COMMIT; no cancellation request inserted."
]
},
{
"file": "0037_server_probe_storage_v2.sql",
"sha256": "b691f5748362e13feeef58b53734feb0ca3e7cc907fc7a803f103f3ce97f0748",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 11,
"bodyReview": [
"Executed DO under ACCESS EXCLUSIVE locks refuses any legacy anchor/stage/quarantine/cancellation, any existing named v2 relation in any namespace, or unavailable retention; no backfill or target data write.",
"Stored GC predicate requires opt-in transaction GUC, serialized storage advisory lock, elapsed original authority/retention/safety, actual terminal MCP source and exact owner/connection/cancellation mapping; no DELETE is executed.",
"Stored admission trigger serializes storage; fresh admission must carry current authority or cancellation; immutable scope and irreversible consume/purge/cancel transitions; DELETE only through lifetime predicate.",
"Stored anchor trigger locks matching consumed admission and rejects expired, cancelled, purged or mismatched owner/execution/binding before INSERT/UPDATE.",
"Replacement execution trigger preserves immutable identities and terminal receipts, rejects quarantined completion, and permits DELETE only through lifetime predicate.",
"Stored stage trigger requires a live consumed matching admission before INSERT/UPDATE under storage advisory lock.",
"Stored quarantine trigger requires a committed matching admission under storage advisory lock before INSERT.",
"Stored payload trigger rejects UPDATE; INSERT requires live admission, exact terminal identity/proof and no quarantine; DELETE requires prior payload purge or full lifetime predicate.",
"Replacement stage trigger preserves serial contiguous execution and immutable received state; DELETE only through lifetime predicate.",
"Replacement quarantine trigger rejects mutation except DELETE independently admitted by lifetime predicate.",
"Replacement cancellation trigger rejects mutation except DELETE whose exact operation/connection/owner maps to admission and satisfies lifetime predicate."
],
"effects": [
"Atomically locks all four legacy diagnostic tables and refuses any history or unmarked v2 relation before schema DDL; fresh-only, never a historical source-generation/backfill authorization.",
"Creates usage/admission/payload tables, one owner-age index and guarded storage functions/triggers; seeds only zero global usage, with no copied payload, admission, cancellation or owner usage.",
"Removes inline ciphertext only from the locked empty anchor table and installs separated-payload terminal CHECK; no historical data transformation; exact file marker is penultimate before COMMIT.",
"Stored GC definitions schedule nothing and execute no cleanup during migration; the GUC alone is insufficient to authorize future DELETE."
]
},
{
"file": "0038_server_poll_journal_and_writer_guards.sql",
"sha256": "2db0bb00f561dd01ace54066d6649478e06fa26e7e417db113d0801dcdac9fa2",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 3,
"bodyReview": [
"Executed DO first owns exclusive transaction advisory key8723110, then refuses any preexisting unmarked poll relation, journal/writer function or writer trigger before schema installation; no user rows copied or inferred.",
"Stored immutable journal trigger always raises on UPDATE/DELETE; no mutation executes during function creation.",
"Stored partition writer row trigger acquires shared transaction advisory key8723110 and returns OLD for DELETE or NEW otherwise; not a substitute for pre-relation writer admission."
],
"effects": [
"Owns exclusive transaction advisory writer exclusion before target DDL; installs five append-only poll tables and five immutability triggers without inserting poll data.",
"Installs ALWAYS row guards on every pinned partition root, inherited by descendants; no ordinary data or partition deletion, exact atomic file marker immediately precedes COMMIT. Mixed unadopted replicas require deployment drain."
]
},
{
"file": "0039_server_poll_storage.sql",
"sha256": "ce3957c2c0196114e85856c93db63fc6e31b61a4866486bc685e017477023f27",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 6,
"bodyReview": [
"Executed DO refuses any nonempty prior poll journal, missing authoritative retention, or unmarked storage table/function/trigger before schema changes; no historical rows copied or inferred.",
"Stored GC predicate owns the global storage advisory lock and locks the actual current retention row and requires explicit GC mode, original expiry and persisted/current retention after latest activity, with exact terminal MCP poll operation/connection/owner proof; no deletion occurs in the predicate.",
"Stored admission guard atomically charges fixed global/owner quotas on fresh identity; only one-token consume and monotonic actual-row metering are allowed; guarded expired all-child-free deletion atomically refunds both counters.",
"Stored row guard requires matching charged admission, consumed live identity and bounded private-plan stages; quarantine uses matching original charged scope, and server clock normalizes all journal activity.",
"Stored AFTER INSERT meter charges only actual inserted journal rows, bounded to 8MiB and the private stage-row budget; skipped ON CONFLICT rows never charge.",
"Stored replacement immutability guard continues to reject every UPDATE; DELETE requires the independently verified complete original lifetime and terminal source, not merely the GC session flag."
],
"effects": [
"Locks five prior journal tables and installs two storage tables, bounded fixed reservation triggers and expiry guards in one transaction; only the global zero-usage seed is inserted.",
"No automatic GC/worker/public route activation or backfill is granted; exact file marker immediately precedes COMMIT. Nonempty intermediate installations fail without data loss."
]
}
,{
"file": "0040_mcp_routing_reservations.sql",
"sha256": "7fd6533442a6756065685c1905cf71af333c284ca4f96e571284602d5e0852ef",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Executed preflight under exclusive shared-slot lock refuses every legacy reserved row and unmarked proposal relation, column or constraint; no evidence, debit or authority is reconstructed."
],
"effects": [
"Adds two empty reservation ledgers and same-source slot columns and shape constraints, preserving all existing manual ciphertext and proofs; no capabilities, backfill, controller or public dispatch activation.",
"Existing legacy reserved data fails before DDL; atomic file marker immediately precedes COMMIT."
]
}
,{
"file": "0041_server_poll_terminal_archives.sql",
"sha256": "fbb8935ce977cfc507801f01beb8f303d4817ed63c6bdd4c05799768dfaac9d4",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 13,
"bodyReview": [
"Executed preflight owns the existing poll storage advisory lock and refuses unmarked archive relations, fields, functions or triggers before schema changes.",
"Executed locked preflight checks the entire nonempty previous full-admission ledger and exact original accounting CHECK names/definitions before replacing only those two constraints; no old receipt, ciphertext, proof or identity is rewritten or inferred.",
"Stored eligibility predicate locks the admission, nonblockingly acquires real operation/execution/receipt advisory keys and NOWAIT source rows, and requires approved applied error-free MCP source, one verified global step, original plan/approval/admission time ordering, exact receipt mapping, all four confirmed native stages and complete contiguous confirmed publications recorded before original expiry, no quarantine and elapsed original expiry/activity plus safety; final generic publication may finish later without renewing authority.",
"Stored source producer returns the complete raw admission, every journal row and exact terminal operation/plan/step in stable order only after eligibility; retains all fields and bounds decoded JSON to16MiB; no archive is produced during migration.",
"Stored aggregate predicate compares global and every owner heavy/compact/archive-byte charges with all admission rows and archive presence; no usage certificate or refunded free slot is fabricated.",
"Stored archive INSERT guard requires a one-shot compaction claim from a distinct prior SQL transaction and recomputes exact source-text SHA256 and length under ownership locks, validates fixed encoded gzip/encryption bounds and original activity/expiry, and stamps current SQL transaction and time; private archive and historical MAC authentication remains the fixed application producer/reader responsibility.",
"Replacement journal immutability function permits DELETE only for a current-transaction immutable archive transition or independently admitted original-lifetime GC; no session flag grants compaction.",
"Replacement admission guard permits one independently durable null-to-UUID compaction claim only for an eligible verified full source, with server-stamped time/xid8 and every other column unchanged; caller cannot supply the claim xid and claim cannot reset, retimestamp or change during metering/compaction. It preserves original identities and used counters, atomically charges heavy or compact reservations, refuses replay/reopen and exact-ledger drift, and refunds only original-lifetime child-free GC; old byte/row caps remain unchanged.",
"Stored AFTER archive INSERT removes every old stage/receipt/anchor and transitions the matching admission with exact two-row and ciphertext-plus32768 charge; no data is compacted during migration.",
"Replacement GC predicate preserves persisted/current retention and original activity/expiry for both layouts; terminal source locks are nonblocking and never lock current connection authority; unknown full records retain their existing full-lifetime GC path.",
"Stored archive immutability function rejects every UPDATE and permits DELETE only under the independent full original lifetime GC predicate.",
"Stored deferred final guard checks no old journal children survive compaction and the complete final ledger/archive shape; partial deletion, orphan archive or incomplete charge rolls back the whole transaction.",
"Stored early row guard rejects every late insertion, including quarantine, against a compacted tombstone; no source or claim is reopened."
],
"effects": [
"Additively preserves nonempty0040 full poll admissions and journal bytes while adding one immutable archive table, full/compact state and exact aggregate accounting under existing fixed owner/global byte and row caps.",
"No archive, compaction, historical backfill, current authority renewal, worker schedule, native request or production public activation occurs; only the atomic file marker is inserted immediately before COMMIT."
]
}
,{
"file": "0042_server_poll_settings_epoch.sql",
"sha256": "b0bcfe9afffda346c9f2fd2ba867ce1708716af0823735583a6bc9217c72de60",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Stored fixed-target invoker trigger stamps a fresh UUID on INSERT and every complete configuration change; only last_collected_at,last_duration_ms,last_error,updated_at and the epoch itself are excluded from UPDATE comparison. Caller epochs are ignored, unknown future fields remain significant and ENABLE ALWAYS enforces replica-mode writes. No native work or capability is issued."
],
"effects": [
"Locks the three settings tables and additively backfills one non-null UUID column while preserving every existing field; repeated or colliding unmarked DDL refuses atomically.",
"Adds one pinned fixed-search-path function and three always row triggers. No journal source, plan, receipt, quota, runtime flag or old migration is rewritten; delayed approval remains inactive until separately integrated."
]
},
{
"file": "0043_mcp_routing_forward_charges.sql",
"sha256": "ef556e6d83dfad47bee7476b9aed0e83127e8dc15649048a6d77b2df079ed84d",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 3,
"bodyReview": [
"Executed collision preflight refuses an existing unmarked forward-charge table; all DDL and the exact file marker share one transaction.",
"Stored invoker source trigger checks actual pending operation, executing v7 routing plan, profile and connection identity at INSERT. It is consistency only, never a permission or MAC verifier.",
"Stored invoker immutable guard refuses UPDATE/TRUNCATE and recent or unresolved DELETE. Retention uses locked current settings and SQL clock; logical historical identities intentionally have no lifetime FK or cascade."
],
"effects": [
"Adds one immutable one-unit persistent-forward charge table, two bounded-read indexes and three triggers; existing0040 two-slot reservations and0031 inverse accounting remain unchanged.",
"No backfill, timestamp aging, operation replay, new grants, worker activation, source enrollment or READY occurs. Historical issuer42 artifacts do not attest this schema."
]
},
{
"file": "0044_mcp_routing_manual_inverse_charges.sql",
"sha256": "37b88d1679be9bb47f16ccc8cae7373f20f9c05e7a8f662c3775f18d78bb5613",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 4,
"bodyReview": [
"Collision preflight refuses an unmarked manual-inverse table; additive DDL and exact marker commit atomically.",
"Invoker source trigger checks actual pending recover7/executing plan, source switch7, profile version and owner/connection; it does not authenticate MAC or confer permission.",
"Invoker immutable parent trigger refuses UPDATE/TRUNCATE and retained/current-hour or pending/running DELETE; no family lifetime FK or cascade.",
"Invoker manual-intent INSERT fence acquires the existing global admission advisory key nonblockingly and requires exact running recover7/generic intent; old6 fresh claims refuse. Already-claimed old writers still require drained cutover."
],
"effects": [
"Adds one one-unit immutable manual inverse charge table, two charge indexes, one manual-history page index, and four triggers. Existing43 bytes, reserved2 and generic debit ownership remain unchanged.",
"No inferred/backfilled identity, legacy timestamp debit, permission change, source enrollment, public controller activation or READY. Full RT3/all-writer/family-deletion proof remains open."
]
},
{
"file": "0045_mcp_operation_replay_tombstones.sql",
"sha256": "8edf5b074c7eef49dad7835c44ac2539df4347f19eb9dd9b2aa7005bafaadbc0",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds one empty replay identity table with plan/operation uniqueness and connection-scoped idempotency digest uniqueness.",
"Table creation refuses an unmarked collision; the exact marker commits with the schema. No backfill, operation deletion, or worker activation."
]
},
{
"file": "0046_server_poll_operation_retirement.sql",
"sha256": "75d7956ea8134b01bcc88da083b77eb52f6e1ad70ad854918ed3380cb0e8cf88",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 4,
"bodyReview": [
"Archive guard permits only fixed receipt-scoped V1 to V2 updates with matching approved terminal operation, tombstone and SQL 180-day cutoff.",
"Deferred guard independently requires the tombstone, physically absent operation and plan, and exact ledger accounting.",
"Admission guard retains existing paths and applies exact V2 archive-byte delta to both owners without changing row charges or lifetime fields.",
"Existing GC retains its authority/activity cutoff and admits retired identity only with exact poll tombstone and compatible V2 archive when present."
],
"effects": [
"Extends the same archive table to a bounded version 2, changes three guards and adds one deferred retirement guard.",
"No automatic conversion, worker activation, operation deletion or retention-window adjustment in migration."
]
},
{
"file": "0047_server_poll_retirement_claims.sql",
"sha256": "8c01ab14d241f715af021e8a7d7f5bb273b450b32f566140359260282524e01d",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 2,
"bodyReview": [
"Protects exact current-transaction V1 claim insertion and permits deletion only as the owning admission is cascaded by GC.",
"Requires exact receipt, V1 archive proof and claim token already committed in another transaction before V2 update."
],
"effects": [
"Adds one durable one-shot poll retirement claim per admission, cascading only with that admission's existing guarded GC.",
"No migration-time conversion, backfill, dispatch, or quota change."
]
},
{
"file": "0048_mcp_ordinary_retirement_claims.sql",
"sha256": "5bc3598c9f5d09611e98d05345accda6d39b199a583bba789b97a24140fafbfd",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Makes ordinary claims immutable and allows insert only for the exact linked settled and aged logs.settings.update v1 operation."
],
"effects": [
"Adds one durable ordinary-operation claim with an authenticated source digest. No migration-time data purge or backfill."
]
},
{
"file": "0049_mcp_ordinary_telemetry_retirement.sql",
"sha256": "68993e924d20db6b08973846a0da367fe89fe2948c414c810e9b171dbbae6761",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Extends the same immutable ordinary claim guard to four explicitly versioned settled telemetry settings families."
],
"effects": [
"Replaces only the ordinary claim guard function. No backfill, data purge, or changes to poll or diagnostic storage."
]
},
{
"file": "0050_server_probe_retired_sources.sql",
"sha256": "0468ac7e53638b532557273f55d065ff4cde092d8b08073f5860bab35263aead",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Refuses update, delete, and truncate of a signed retired diagnostic source pending a separately reviewed lifecycle."
],
"effects": [
"Creates empty bounded storage linking exact diagnostic admission and replay tombstone IDs. No backfill, retirement, or GC activation."
]
},
{
"file": "0051_server_probe_retirement_claims.sql",
"sha256": "b38876b5da44cf14e20a9df0baaa233ea4de81e471b38dddd370e149c8116243",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 2,
"bodyReview": [
"Restricts diagnostic claims to their original settled 180-day source and makes each claim permanent.",
"Restricts archival insertion to the exact committed claim and current original source and tombstone identity."
],
"effects": [
"Creates empty diagnostic retirement claims and guards the archive insert. No conversion, backfill, or GC activation."
]
},
{
"file": "0052_server_probe_retired_gc.sql",
"sha256": "ea56a1f1bdabfce606bdfec56b6a7b31d45b0187fbea4c900bc656ae320f2fdd",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 3,
"bodyReview": [
"Validates the exact retired diagnostic identity and the later of current and persisted retention plus the original safety window.",
"Only permits archive removal during an exact guarded admission cascade after journal removal.",
"Adds the exact retired GC branch while retaining the live admission eligibility predicate."
],
"effects": [
"Changes only the retired source admission FK to guarded cascade and adds an explicit exact GC path. No collection runs during migration."
]
},
{
"file": "0053_server_probe_terminal_proofs.sql",
"sha256": "759ec8c349fcb24c43af410ad6ade714432678b3a021c94bd982080d6a8986be",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 2,
"bodyReview": [
"Pins terminal proof to the current retained original on insert and an exact committed retirement claim on delete.",
"Extends claims only to the identical signed terminal proof when the original diagnostic admission is gone."
],
"effects": [
"Creates empty bounded private terminal proof storage. Existing payload retention, scheduler, and archive GC remain unchanged."
]
},
{
"file": "0054_mcp_geoip_retirement.sql",
"sha256": "680390f98076e3047dbb5a34eab417b253853703932d16c17e4fa3a11060accc",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Adds only exact settled GeoIP settings version 1 to the existing immutable ordinary retirement claim guard."
],
"effects": [
"Replaces the ordinary claim guard function without changing settings or retiring existing rows during migration."
]
},
{
"file": "0055_mcp_backup_schedule_retirement.sql",
"sha256": "07e63c1245ea547176d613933a81ad354e734fa64218dadced67ee8f965c01b6",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Adds only exact settled backup schedule settings version 1 to the existing immutable ordinary retirement claim guard."
],
"effects": [
"Replaces the ordinary claim guard function without changing backup settings, metadata or entries during migration."
]
},
{
"file": "0056_mcp_manual_inverse_recovery_v8.sql",
"sha256": "1dece1d9c5a9cf69e51336f35f868561dad9da6d21556ea31ef5b102634ed9ee",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 2,
"bodyReview": [
"The manual inverse charge-source guard requires recovery version 8 and preserves its pending operation, source version, owner and profile checks.",
"The manual inverse intent guard requires recovery version 8 and preserves its advisory lock and exact running service intent checks."
],
"effects": [
"Replaces the two live version guard functions and preserves existing charges, intents, and plans."
]
},
{
"file": "0057_mcp_routing_charge_audit_index.sql",
"sha256": "499cb91836618e2859e2bb014f4642d8e95770267e9527844c3dcb95ecb32b7f",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Adds the partial routing charge audit lookup index. Retains all rows and permissions."
]
},
{
"file": "0058_internet_exchange.sql",
"sha256": "75e2842f8d45909c37d1387bdfadf659606e6227b5542289e8c1d98269f5a0cd",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 0,
"bodyReview": [],
"effects": [
"Allows the IX Node server type without changing existing rows.",
"Adds versioned IX configuration and device references."
]
},
{
"file": "0059_server_poll_journal_limits.sql",
"sha256": "9b638ed5649ef75359b24ef61c80bf59390372c98c713447ddb6e32e61b6f5be",
"transaction": "self-managed-single-transaction",
"selfMarker": true,
"opaqueBodies": 1,
"bodyReview": [
"Replaces the existing invoker admission trigger function and removes only the aggregate count, row and byte ceilings from the insertion path. Authority, locking, accounting, compaction and GC checks remain enforced."
],
"effects": [
"Removes the journal quota while preserving exact reconciliation constraints and all previously retained histories."
]
}
]
export const MIGRATION_MANIFEST: readonly MigrationReview[] = Object.freeze(classifiedMigrationPins.map(entry => Object.freeze({ ...entry, bodyReview: Object.freeze([...entry.bodyReview]), effects: Object.freeze([...entry.effects]) })))
export function validateMigrationFileSet(files: readonly string[]) {
if (JSON.stringify([...files].sort()) !== JSON.stringify(MIGRATION_MANIFEST.map(entry => entry.file))) refuse("Migration file set changed; classify additions/removals before dispatch")
}
export async function inventoryMigrationDirectory(directory: string) {
const entries = (await readdir(directory, { withFileTypes: true })).filter(entry => entry.name.toLowerCase().endsWith(".sql"))
if (entries.some(entry => !entry.isFile())) refuse("Migration SQL entry is not an ordinary file")
const files = entries.map(entry => entry.name).sort()
validateMigrationFileSet(files)
return Promise.all(MIGRATION_MANIFEST.map(async entry => analyzeMigration(entry.file, await readFile(join(directory, entry.file)), entry)))
}
export const migrationManifestDigest = () => hash(JSON.stringify(MIGRATION_MANIFEST))
// Mandatory current table presence derived from every pinned CREATE TABLE,
// resetting the accumulated public table set at the reviewed destructive0002.
// This is a necessary presence check, not a substitute for exact live column,
// constraint/index/function/trigger comparison by the control protocol.
export const CURRENT_REQUIRED_TABLES: readonly string[] = Object.freeze(["acme_settings","alert_engine_confirm_pending","alert_engine_cursor","alert_engine_prev_live","alert_engine_state","alert_groups","alert_history","alert_outbox","alert_rule_conditions","alert_rule_targets","alert_rules","alert_telegram_settings","app_users","backup_entries","backup_schedule_settings","backup_storage_settings","certificate_issue_jobs","certificate_renew_settings","config_revisions","data_migration","events","evobgp_settings","filter_rules","flow_asn_meta","flow_buckets","flow_daily_dims","flow_daily_facts","flow_hour_facts","flow_ip_meta","flow_minute_dims","flow_minute_stats","flow_settings_intents","flow_write_receipts","geoip_settings","internet_path_settings","internet_path_snapshots","ix_segment_devices","ix_segment_revisions","ix_segments","mcp_artifacts","mcp_audit","mcp_budget_buckets","mcp_connections","mcp_credentials","mcp_diagnostic_cancellations","mcp_drift","mcp_grants","mcp_management_channels","mcp_oauth_clients","mcp_oauth_requests","mcp_operation_checkpoints","mcp_operation_replay_tombstones","mcp_operation_steps","mcp_operations","mcp_ordinary_retirement_claims","mcp_owner_revocations","mcp_path_checks","mcp_plans","mcp_portal_events","mcp_protections","mcp_read_leases","mcp_recovery_intents","mcp_requests","mcp_routing_forward_charges","mcp_routing_manual_inverse_charges","mcp_routing_observations","mcp_routing_profiles","mcp_routing_reservation_slots","mcp_routing_reservations","mcp_scoped_recovery_intents","mcp_secrets","mcp_settings","mcp_unauthorized_buckets","recursive_routes","router_log_collection_state","router_log_entries","router_log_settings","scheduler_runs","schema_migrations","server_poll_acks","server_poll_archives","server_poll_executions","server_poll_intents","server_poll_quarantines","server_poll_receipts","server_poll_retirement_claims","server_poll_storage_admissions","server_poll_storage_usage","server_probe_execution_payloads","server_probe_execution_quarantines","server_probe_execution_stages","server_probe_executions","server_probe_retired_sources","server_probe_retirement_claims","server_probe_storage_admissions","server_probe_storage_usage","server_probe_terminal_proofs","server_snapshots","servers","servers_api_ping_settings","servers_rest_ping_samples","traffic_collection_state","traffic_flow_settings","traffic_samples","traffic_settings","uptime_probe_samples","uptime_probes","uptime_resource_samples","uptime_settings","uptime_speed_probes","uptime_speed_test_runs","user_interface_bindings","vrf_production_tickets"])
export interface LegacyBaselineEvidence {
inventoryComplete: boolean; databaseGeneration: string; unresolvedAttemptIds: readonly string[]
markerTable: "absent" | "present"; markerIds: readonly string[]
applicationObjects: readonly { schema: string; name: string; kind: string }[]
/** Receipt from a separately trusted complete schema comparator. This module
* only checks its binding; it does not manufacture a live schema attestation. */
verifiedSchema?: { manifestDigest: string; databaseGeneration: string; exactCurrentSchema: true; observedSchemaDigest: string }
}
export function assessLegacyMigrationBaseline(evidence: LegacyBaselineEvidence) {
const blocked = (reason: string) => ({ state: "blocked" as const, reason, dispatchAuthorized: false as const })
if (!evidence.inventoryComplete || !evidence.databaseGeneration || evidence.unresolvedAttemptIds.length) return blocked("Incomplete inventory, missing generation or unresolved durable attempt")
if (evidence.applicationObjects.length > 50000 || evidence.applicationObjects.some(object => !object.schema || !object.name || !object.kind)) return blocked("Malformed or unbounded schema object evidence")
const ids = MIGRATION_MANIFEST.map(entry => entry.file.slice(0, -4)), actual = [...evidence.markerIds].sort()
if (new Set(actual).size !== actual.length || actual.some(id => !ids.includes(id)) || evidence.markerTable === "absent" && actual.length) return blocked("Unknown, duplicate or inconsistent legacy marker evidence")
const objects = evidence.applicationObjects.filter(object => !(object.schema === "public" && object.name === "schema_migrations" && object.kind === "table"))
if (!actual.length && !objects.length) return { state: "clean-database-candidate" as const, reason: "Complete object inventory shows no application objects, independently of marker absence", dispatchAuthorized: false as const }
if (JSON.stringify(actual) !== JSON.stringify(ids)) return blocked("Unmarked application state or legacy prefix requires private reconciliation; missing marker is not fresh/never-run evidence")
const proof = evidence.verifiedSchema
const present = new Set(evidence.applicationObjects.filter(object => object.schema === "public" && ["table", "partitioned-table"].includes(object.kind)).map(object => object.name))
if (!proof || !proof.exactCurrentSchema || proof.manifestDigest !== migrationManifestDigest() || proof.databaseGeneration !== evidence.databaseGeneration || !/^[a-f0-9]{64}$/.test(proof.observedSchemaDigest) || CURRENT_REQUIRED_TABLES.some(table => !present.has(table))) return blocked("All markers need a separately verified exact current-schema attestation and mandatory table inventory before enrollment")
return { state: "legacy-current-enrollment-candidate" as const, reason: "All exact known ids plus complete schema comparator receipt; historical executed file hashes remain unproven", dispatchAuthorized: false as const }
}