viborm 1.14.0 → 1.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters.d.mts +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache.d.mts +2 -2
- package/dist/cli.mjs +1 -1
- package/dist/{client-BDb96x1r.d.mts → client-CRxfhw2y.d.mts} +1 -1
- package/dist/client-y7TV0PRZ.mjs +9 -0
- package/dist/client-y7TV0PRZ.mjs.map +1 -0
- package/dist/client.d.mts +2 -2
- package/dist/config.d.mts +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/{database-adapter-BhQJPaTf.d.mts → database-adapter-BGqvjeEy.d.mts} +7 -6
- package/dist/{document-D2OQKsOc.d.mts → document-BVTQ-cF-.d.mts} +1 -1
- package/dist/{driver-AeJqJUQb.d.mts → driver-BBEmaJZy.d.mts} +1 -1
- package/dist/driver-BIXhOH2_.mjs.map +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/durable-object.d.mts +1 -1
- package/dist/every-tOgQmaIE.mjs +2 -0
- package/dist/{every-3LgBFWRs.mjs.map → every-tOgQmaIE.mjs.map} +1 -1
- package/dist/{exports-Crs9nBjW.d.mts → exports-COCJ8f2f.d.mts} +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{introspect-6m25Fg-d.mjs → introspect-Bm6xnXcG.mjs} +2 -2
- package/dist/{introspect-6m25Fg-d.mjs.map → introspect-Bm6xnXcG.mjs.map} +1 -1
- package/dist/{libsql-oBy9Irhf.mjs → libsql-DuGR904j.mjs} +3 -3
- package/dist/{libsql-oBy9Irhf.mjs.map → libsql-DuGR904j.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/{memory-CniC_5jH.mjs → memory-G4cSuc6A.mjs} +2 -2
- package/dist/{memory-CniC_5jH.mjs.map → memory-G4cSuc6A.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/snowflake.d.mts +4 -4
- package/dist/migrations/snowflake.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/surrealdb.d.mts +4 -4
- package/dist/migrations/surrealdb.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-CyEtis4b.mjs → mysql-BNXWfTOo.mjs} +8 -8
- package/dist/{mysql-CyEtis4b.mjs.map → mysql-BNXWfTOo.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/{object-store-D5bNfAF2.d.mts → object-store-B_YMoW8u.d.mts} +3 -3
- package/dist/on.d.mts +1 -1
- package/dist/ordering.d.mts +1 -1
- package/dist/permissions.d.mts +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/{planner-Beph-ERw.d.mts → planner-DHjdvjwk.d.mts} +1 -1
- package/dist/{postgres-PJ2p5pPk.mjs → postgres-CDdh5dSP.mjs} +11 -11
- package/dist/{postgres-PJ2p5pPk.mjs.map → postgres-CDdh5dSP.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/schema/introspect.d.mts +2 -2
- package/dist/schema/introspect.mjs +1 -1
- package/dist/schema/json.d.mts +2 -2
- package/dist/schema.d.mts +1 -1
- package/dist/{serializer-DG5kl84q.mjs → serializer-rBq3v1xr.mjs} +3 -3
- package/dist/serializer-rBq3v1xr.mjs.map +1 -0
- package/dist/{snowflake-BgbbuBnq.mjs → snowflake-UOCC820W.mjs} +2 -2
- package/dist/{snowflake-BgbbuBnq.mjs.map → snowflake-UOCC820W.mjs.map} +1 -1
- package/dist/snowflake.d.mts +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql-DYyn6m_F.mjs → sql-Dl6nykFV.mjs} +2 -2
- package/dist/{sql-DYyn6m_F.mjs.map → sql-Dl6nykFV.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/surrealdb.d.mts +7 -2
- package/dist/surrealdb.mjs +1 -1
- package/dist/surrealdb.mjs.map +1 -1
- package/dist/surrealql-C1dp1sWw.mjs +2 -0
- package/dist/surrealql-C1dp1sWw.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/version-CXGIA82S.mjs +2 -0
- package/dist/{version-CP7sZdoU.mjs.map → version-CXGIA82S.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/client-Dkxy0fE6.mjs +0 -9
- package/dist/client-Dkxy0fE6.mjs.map +0 -1
- package/dist/every-3LgBFWRs.mjs +0 -2
- package/dist/serializer-DG5kl84q.mjs.map +0 -1
- package/dist/surrealql-CaTGnLkK.mjs +0 -2
- package/dist/surrealql-CaTGnLkK.mjs.map +0 -1
- package/dist/version-CP7sZdoU.mjs +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-y7TV0PRZ.mjs","names":["location","artifacts","matches","table","column","refuse","isResolveCallback","encoded","index","named","refuse","named"],"sources":["../src/migrations/sqlite-storage-audit.ts","../src/migrations/empty-snapshot.ts","../src/migrations/snapshot-artifacts.ts","../src/migrations/graph.ts","../src/migrations/push/format.ts","../src/migrations/admission.ts","../src/migrations/push/planner.ts","../src/migrations/live-reset.ts","../src/migrations/sql-assembly.ts","../src/migrations/push-plan.ts","../src/migrations/proof.ts","../src/migrations/resume.ts","../src/migrations/apply-v1.ts","../src/migrations/check.ts","../src/migrations/generate-input.ts","../src/migrations/public-view.ts","../src/migrations/push-consent.ts","../src/migrations/push-v1.ts","../src/migrations/generate-v1.ts","../src/migrations/down-input.ts","../src/migrations/reset-v1.ts","../src/migrations/operators.ts","../src/migrations/storage/contract.ts","../src/migrations/client.ts"],"sourcesContent":["import { errorCause } from \"../errors/diagnostic-safety\";\n/**\n * SQLite storage that typed queries compare but never inspect: text DateTime\n * and Time (scalar or JSON list) and checked decimals.\n *\n * `auditStorage` counts what needs repair (`viborm check --db`, runtime and\n * Durable Object callers). `canonicalizeSqliteStorage` rewrites it after\n * manual SQL, inside that program's transaction. Time columns and\n * DateTime lists come from the client's models, because a schema snapshot\n * marks only scalar DateTime and decimals.\n */\n\nimport {\n sqliteCanonicalTemporalUpdate,\n sqliteNoncanonicalTemporalCount,\n} from \"../adapters/databases/sqlite/storage/datetime\";\nimport {\n isSqliteDecimalStorage,\n sqliteDecimalCopyExpression,\n sqliteDecimalStorageKind,\n} from \"../adapters/databases/sqlite/storage/decimal\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { type AnyModel, getTableName, type ModelState } from \"../schema/model\";\nimport { sqliteDateTimePhysicalForm } from \"../schema/scalars/datetime/physical\";\nimport { createIdentifierQuoter } from \"../sql/identifiers\";\nimport type { DecimalDescriptor } from \"../validation/primitives/decimal-codec\";\nimport { sqliteColumnNullable } from \"./drivers/sqlite/introspect\";\nimport { executeExactSql } from \"./execute-dispatch\";\nimport type { MigrationClient } from \"./push/planner\";\nimport type { ColumnDef, SchemaSnapshot } from \"./types\";\nimport type { MigrationOperationV1 } from \"./v1-types\";\n\n/** One audited column; `null` counts and declarations mean the column is missing. */\nexport type StorageColumnAudit = {\n readonly table: string;\n readonly column: string;\n} & (\n | {\n readonly type: \"datetime\" | \"time\";\n readonly list: boolean;\n readonly noncanonical: number | null;\n }\n | {\n readonly type: \"decimal\";\n /** The catalog's declared type. */\n readonly declared: string | null;\n readonly checked: boolean;\n }\n);\n\ntype StorageColumn = {\n readonly table: string;\n readonly column: string;\n readonly list: boolean;\n} & (\n | { readonly type: \"datetime\" | \"time\" }\n | { readonly type: \"decimal\"; readonly decimal: DecimalDescriptor }\n);\n\ninterface CatalogColumn {\n readonly definition: string | null;\n readonly name: string;\n readonly type: string;\n readonly nullable: boolean;\n}\n\nconst quote = createIdentifierQuoter('\"');\n\n/** Every decimal column, and every DateTime/Time column stored as text. */\nfunction storageColumns(models: Record<string, AnyModel>): StorageColumn[] {\n const columns: StorageColumn[] = [];\n for (const [name, model] of Object.entries(models)) {\n const table = getTableName(model, name);\n const state: ModelState = model[\"~\"].state;\n for (const [field, scalar] of Object.entries(state.scalars)) {\n const definition = scalar[\"~\"].state;\n const list = definition.array === true;\n const column = model[\"~\"].getFieldName(field).sql;\n if (definition.type === \"decimal\") {\n columns.push({\n table,\n column,\n list,\n type: \"decimal\",\n decimal: definition.decimal,\n });\n } else if (\n definition.type === \"time\" ||\n (definition.type === \"datetime\" &&\n (list ||\n sqliteDateTimePhysicalForm(scalar[\"~\"].nativeType) === \"text\"))\n ) {\n columns.push({ table, column, list, type: definition.type });\n }\n }\n }\n return columns;\n}\n\n/** One SQLite table's declared columns, each beside the table's stored definition. */\nasync function readCatalog(\n driver: AnyDriver,\n table: string\n): Promise<CatalogColumn[]> {\n const { rows } = await driver._executeRaw<\n Omit<CatalogColumn, \"nullable\"> & {\n notnull: number;\n pk: number;\n keyed: number;\n }\n >(\n `SELECT s.sql AS definition, p.name, p.type, p.\"notnull\", p.pk, EXISTS (SELECT 1 FROM pragma_index_list(s.name) WHERE origin = 'pk') AS keyed FROM sqlite_schema AS s JOIN pragma_table_info(s.name) AS p WHERE s.type = 'table' AND s.name = ?`,\n [table]\n );\n return rows.map(({ notnull, pk, keyed, ...column }) => ({\n ...column,\n nullable: sqliteColumnNullable(\n Number(notnull),\n Number(pk),\n Number(keyed) === 1\n ),\n }));\n}\n\n/**\n * Audit the SQLite storage of `client`'s models: one catalog read per table\n * decides which audited columns exist; each existing text DateTime/Time\n * column's noncanonical rows are counted (one scan each), and each decimal\n * column is checked against the scaled-integer storage of its descriptor.\n * Other dialects store native types and return no audit.\n */\nexport async function auditStorage(\n client: Pick<MigrationClient, \"$driver\" | \"$schema\">\n): Promise<StorageColumnAudit[]> {\n const driver = client.$driver;\n if (driver.dialect !== \"sqlite\") return [];\n const catalogs = new Map<string, Promise<CatalogColumn[]>>();\n const audits: StorageColumnAudit[] = [];\n for (const target of storageColumns(client.$schema)) {\n const { table, column } = target;\n let catalog = catalogs.get(table);\n if (!catalog) {\n catalog = readCatalog(driver, table);\n catalogs.set(table, catalog);\n }\n // A missing table has no catalog rows: each audited column is missing.\n const row = (await catalog).find((entry) => entry.name === column);\n if (target.type === \"decimal\") {\n audits.push({\n table,\n column,\n type: \"decimal\",\n declared: row?.type ?? null,\n checked:\n row !== undefined &&\n isSqliteDecimalStorage(\n row.definition,\n row,\n target.decimal,\n target.list ? \"list\" : \"scalar\",\n quote\n ),\n });\n continue;\n }\n // Never scan a missing column: SQLite may read its quoted name as text.\n const scan =\n row &&\n (await driver._executeRaw<{ noncanonical: number }>(\n sqliteNoncanonicalTemporalCount(table, column, target.type, target.list)\n ));\n audits.push({\n table,\n column,\n type: target.type,\n list: target.list,\n noncanonical: scan ? Number(scan.rows[0]?.noncanonical) : null,\n });\n }\n return audits;\n}\n\n/**\n * The storage one destination column needs canonical, or `undefined`. The\n * snapshot proves scalar text DateTime and decimal lists (a decimal scalar's\n * CHECK already refuses foreign values); it does not mark Time or DateTime\n * lists, so those come from the client's models, held to the column's\n * physical type.\n */\nfunction destinationTarget(\n table: string,\n column: ColumnDef,\n declared: StorageColumn | undefined\n): StorageColumn | undefined {\n const base = { table, column: column.name };\n if (column.dateTime === \"text\") {\n return { ...base, list: false, type: \"datetime\" };\n }\n if (column.decimal) {\n return sqliteDecimalStorageKind(column) === \"list\"\n ? { ...base, list: true, type: \"decimal\", decimal: column.decimal }\n : undefined;\n }\n const temporal =\n declared?.type === \"time\" ||\n (declared?.type === \"datetime\" && declared.list);\n return temporal &&\n column.type.toUpperCase() === (declared.list ? \"JSON\" : \"TEXT\")\n ? declared\n : undefined;\n}\n\n/** Rewrites one column into canonical storage; a value outside its domain aborts the statement. */\nfunction canonicalStatement(target: StorageColumn): string {\n if (target.type !== \"decimal\") {\n return sqliteCanonicalTemporalUpdate(\n target.table,\n target.column,\n target.type,\n target.list\n );\n }\n // The identity conversion routes a member outside the domain to the\n // sentinel the column's own CHECK refuses.\n const source = `${quote(target.table)}.${quote(target.column)}`;\n const checked = sqliteDecimalCopyExpression(\n source,\n target.decimal,\n target.decimal,\n \"list\"\n );\n return `UPDATE ${quote(target.table)} SET ${quote(target.column)} = ${checked} WHERE ${source} IS NOT ${checked}`;\n}\n\n/**\n * After manual SQL — a manual transition, its manual rollback, or the\n * `resolve` that completes one — and inside that program's transaction:\n * rewrite the destination's text DateTime/Time columns (scalar and JSON list)\n * into canonical text, reading SQLite's zone-less text as UTC, and check\n * decimal-list members. A program without a manual operation, or another\n * dialect, has nothing to rewrite. A row that cannot be rewritten stops the\n * program before its marker moves.\n */\nexport async function canonicalizeSqliteStorage(\n producer: AnyDriver,\n operations: readonly MigrationOperationV1[],\n models: Record<string, AnyModel>,\n destination: SchemaSnapshot\n): Promise<void> {\n if (\n producer.dialect !== \"sqlite\" ||\n !operations.some((operation) => operation.origin === \"manual\")\n ) {\n return;\n }\n const declared = new Map(\n storageColumns(models).map((target) => [\n `${target.table}\\0${target.column}`,\n target,\n ])\n );\n for (const table of destination.tables) {\n for (const column of table.columns) {\n const target = destinationTarget(\n table.name,\n column,\n declared.get(`${table.name}\\0${column.name}`)\n );\n if (!target) continue;\n try {\n await executeExactSql(producer, canonicalStatement(target));\n } catch (error) {\n // A malformed value aborts the rewrite; so does a constraint the\n // rewrite meets, such as two spellings of one instant in a unique column.\n throw new MigrationError(\n `The manual SQL left \"${target.table}\".\"${target.column}\" holding a ${target.type}${target.list ? \" list\" : \"\"} value that cannot be rewritten into canonical storage (${error instanceof Error ? error.message : String(error)}); the marker did not move`,\n VibORMErrorCode.MIGRATION_DRIFT,\n { cause: errorCause(error) }\n );\n }\n }\n }\n}\n","/**\n * The one virtual-root snapshot. Not a stored second root.\n */\n\nimport type { SchemaSnapshot } from \"./types\";\n\nexport function emptyManagedSnapshot(): SchemaSnapshot {\n return { tables: [], enums: [] };\n}\n","/**\n * Stored snapshot representation. Logical identity remains the canonical full\n * schema hash; deltas have their own exact-byte address. No DDL meaning lives\n * here. Every consumer receives the existing strictly admitted full schema.\n */\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { isRecord } from \"../validation/value-guards\";\nimport {\n assertCanonicalBytes,\n canonicalizeJson,\n canonicalizeJsonText,\n parseJsonBytes,\n} from \"./canonical-json\";\nimport { domainHash, HASH_DOMAIN, parseSha256, type Sha256 } from \"./identity\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { SchemaSnapshot } from \"./types\";\nimport { exactObject, refuse } from \"./v1-parse-shared\";\nimport { encodeSnapshot, parseSnapshotDocument } from \"./v1-parse-snapshot\";\nimport type {\n SnapshotChangeV1,\n SnapshotDeltaFormat,\n SnapshotDeltaV1,\n} from \"./v1-types\";\n\nexport const MAX_SNAPSHOT_DELTA_DEPTH = 32;\n\nexport interface ResolvedSnapshotArtifact {\n readonly snapshot: SchemaSnapshot;\n readonly snapshotHash: Sha256;\n readonly depth: number;\n readonly baseArtifactHash?: Sha256;\n /** Detached exact bytes admitted for this command, used by history copying. */\n readonly bytes: Uint8Array;\n}\n\nexport interface EncodedSnapshotArtifact {\n readonly artifactHash: Sha256;\n readonly snapshotHash: Sha256;\n /** Null means an authenticated or candidate-owned object can be reused. */\n readonly bytes: Uint8Array | null;\n readonly depth: number;\n readonly baseArtifactHash?: Sha256;\n}\n\nexport type ParsedSnapshotArtifact =\n | { readonly kind: \"full\"; readonly snapshot: SchemaSnapshot }\n | {\n readonly kind: \"delta\";\n readonly delta: SnapshotDeltaV1;\n readonly snapshot?: SchemaSnapshot;\n };\n\nexport interface SnapshotArtifactCache {\n storedSnapshot(bytes: Uint8Array, hash: Sha256): ParsedSnapshotArtifact;\n rememberSnapshot(\n hash: Sha256,\n bytes: Uint8Array,\n snapshot: SchemaSnapshot\n ): void;\n}\n\nexport function parseSnapshotArtifact(\n bytes: Uint8Array,\n hash: Sha256\n): ParsedSnapshotArtifact {\n const value = parseJsonBytes(bytes, `snapshots/${hash}.json`);\n return isRecord(value) && \"format\" in value\n ? { kind: \"delta\", delta: parseDelta(bytes, value, hash) }\n : { kind: \"full\", snapshot: parseSnapshotDocument(bytes, hash) };\n}\n\nfunction corrupt(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_CORRUPTION);\n}\n\nfunction parseChange(\n value: unknown,\n format: SnapshotDeltaFormat\n): SnapshotChangeV1 {\n const inserts = format === \"snapshot-delta-2\";\n if (\n !isRecord(value) ||\n (value.op !== \"set\" &&\n value.op !== \"remove\" &&\n !(inserts && value.op === \"insert\"))\n ) {\n refuse(\n inserts\n ? \"snapshot delta change must set, insert or remove a path\"\n : \"snapshot delta change must set or remove a path\"\n );\n }\n const keys = value.op === \"remove\" ? [\"op\", \"path\"] : [\"op\", \"path\", \"value\"];\n const record = exactObject(value, keys, keys, \"snapshot delta change\");\n if (!Array.isArray(record.path) || record.path.length === 0) {\n refuse(\"snapshot delta path must be a non-empty array\");\n }\n const path = record.path.map((segment) => {\n if (typeof segment === \"string\") return segment;\n if (\n typeof segment === \"number\" &&\n Number.isSafeInteger(segment) &&\n segment >= 0\n )\n return segment;\n return refuse(\n \"snapshot delta path segments must be strings or nonnegative safe integers\"\n );\n });\n return value.op === \"remove\"\n ? { op: \"remove\", path }\n : { op: value.op, path, value: record.value };\n}\n\nfunction parseDelta(\n bytes: Uint8Array,\n value: unknown,\n hash: Sha256\n): SnapshotDeltaV1 {\n const keys = [\"format\", \"baseArtifactHash\", \"snapshotHash\", \"changes\"];\n const record = exactObject(value, keys, keys, \"snapshot delta\");\n const format = record.format;\n if (\n typeof format === \"string\" &&\n format.startsWith(\"snapshot-delta-\") &&\n format !== \"snapshot-delta-1\" &&\n format !== \"snapshot-delta-2\"\n ) {\n refuse(\n `snapshot delta format ${format} is not one this engine reads; a newer VibORM may have written it`\n );\n }\n if (\n (format !== \"snapshot-delta-1\" && format !== \"snapshot-delta-2\") ||\n !Array.isArray(record.changes)\n ) {\n refuse(\"snapshot delta format or changes is invalid\");\n }\n const delta: SnapshotDeltaV1 = {\n format,\n baseArtifactHash: parseSha256(\n record.baseArtifactHash,\n \"snapshot delta baseArtifactHash\"\n ),\n snapshotHash: parseSha256(\n record.snapshotHash,\n \"snapshot delta snapshotHash\"\n ),\n changes: record.changes.map((change) => parseChange(change, format)),\n };\n assertCanonicalBytes(bytes, delta, \"snapshot delta\");\n if (domainHash(HASH_DOMAIN.snapshotDelta, bytes) !== hash) {\n corrupt(`Snapshot delta ${hash} does not match its canonical bytes`);\n }\n return delta;\n}\n\ntype PathLocation =\n | {\n readonly kind: \"array\";\n readonly container: unknown[];\n readonly key: number;\n }\n | {\n readonly kind: \"object\";\n readonly container: Record<string, unknown>;\n readonly key: string;\n };\n\n/** A segment's spelling is interpreted only by its actual container. */\nfunction pathLocation(\n container: unknown,\n segment: string | number,\n append: boolean\n): PathLocation {\n if (Array.isArray(container)) {\n if (\n typeof segment !== \"number\" ||\n segment > container.length ||\n (!append && segment === container.length)\n ) {\n refuse(\n \"snapshot delta array path must name an existing index or append at length\"\n );\n }\n return { kind: \"array\", container, key: segment };\n }\n if (!isRecord(container) || typeof segment !== \"string\") {\n refuse(\"snapshot delta object path must name a string key on an object\");\n }\n return { kind: \"object\", container, key: segment };\n}\n\nfunction applyChange(\n document: unknown,\n change: SnapshotChangeV1,\n format: SnapshotDeltaFormat\n): void {\n let container = document;\n for (const segment of change.path.slice(0, -1)) {\n const location = pathLocation(container, segment, false);\n const descriptor = Object.getOwnPropertyDescriptor(\n location.container,\n location.key\n );\n if (!descriptor)\n refuse(\"snapshot delta path has a missing intermediate property\");\n container = descriptor.value;\n }\n const location = pathLocation(\n container,\n change.path.at(-1)!,\n change.op !== \"remove\"\n );\n if (change.op === \"insert\") {\n if (location.kind !== \"array\")\n refuse(\"snapshot delta insert must name an array index\");\n location.container.splice(location.key, 0, change.value);\n return;\n }\n if (change.op === \"set\") {\n // defineProperty treats __proto__ as a literal key, never a prototype setter.\n Object.defineProperty(location.container, location.key, {\n value: change.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n return;\n }\n if (!Object.hasOwn(location.container, location.key))\n refuse(\"snapshot delta cannot remove a missing property\");\n if (location.kind === \"array\") {\n const { container: array, key: index } = location;\n if (format === \"snapshot-delta-1\" && index !== array.length - 1)\n refuse(\"snapshot delta array removal must remove the final element\");\n array.splice(index, 1);\n } else {\n Reflect.deleteProperty(location.container, location.key);\n }\n}\n\n/** Mutations stay on an independently owned JSON document, including on failure. */\nfunction reconstruct(\n base: SchemaSnapshot,\n delta: SnapshotDeltaV1\n): SchemaSnapshot {\n const document = parseJsonBytes(\n encodeSnapshot(base).bytes,\n \"snapshot delta base\"\n );\n // Cached deltas are frozen and shared; set values belong to this document.\n for (const change of structuredClone(delta.changes))\n applyChange(document, change, delta.format);\n return parseSnapshotDocument(canonicalizeJson(document), delta.snapshotHash);\n}\n\n/**\n * Resolve by physical identity, not logical schema. Absolute depth survives\n * memoization; both a cold chain and a child of a cached chain obey one limit.\n * The same map may be extended to validate orphans, after retaining the separate\n * committed-state dependency closure.\n */\nexport async function resolveSnapshotArtifacts(\n storage: MigrationStorageReader,\n roots: Iterable<Sha256>,\n resolved = new Map<Sha256, ResolvedSnapshotArtifact>(),\n cache?: SnapshotArtifactCache\n): Promise<Map<Sha256, ResolvedSnapshotArtifact>> {\n for (const root of roots) {\n const pending: {\n hash: Sha256;\n delta: SnapshotDeltaV1;\n bytes: Uint8Array;\n snapshot?: SchemaSnapshot;\n }[] = [];\n let hash = root;\n while (!resolved.has(hash)) {\n const bytes = await storage.readSnapshot(hash);\n if (!bytes) corrupt(`Snapshot ${hash} is referenced but missing`);\n const artifact =\n cache?.storedSnapshot(bytes, hash) ??\n parseSnapshotArtifact(bytes, hash);\n if (artifact.kind === \"delta\") {\n const delta = artifact.delta;\n pending.push({\n hash,\n delta,\n bytes: bytes.slice(),\n snapshot: artifact.snapshot,\n });\n if (pending.length > MAX_SNAPSHOT_DELTA_DEPTH)\n refuse(\"snapshot delta chain exceeds 32 links\");\n hash = delta.baseArtifactHash;\n } else {\n resolved.set(hash, {\n snapshot: artifact.snapshot,\n snapshotHash: hash,\n depth: 0,\n bytes: bytes.slice(),\n });\n }\n }\n for (let index = pending.length - 1; index >= 0; index--) {\n const entry = pending[index]!;\n const base = resolved.get(entry.delta.baseArtifactHash)!;\n const depth = base.depth + 1;\n if (depth > MAX_SNAPSHOT_DELTA_DEPTH)\n refuse(\"snapshot delta chain exceeds 32 links\");\n // A cached result is eligible only after every base has been re-read and\n // authenticated, and the absolute dependency depth has been checked.\n const snapshot =\n entry.snapshot ?? reconstruct(base.snapshot, entry.delta);\n cache?.rememberSnapshot(entry.hash, entry.bytes, snapshot);\n resolved.set(entry.hash, {\n snapshot,\n snapshotHash: entry.delta.snapshotHash,\n depth,\n baseArtifactHash: entry.delta.baseArtifactHash,\n bytes: entry.bytes,\n });\n }\n }\n return resolved;\n}\n\n/**\n * An array's element identities when every element has a distinct one: a\n * record's `name` (tables, columns, indexes, constraints, enums) or the string\n * itself (enum values, column lists). Otherwise the array diffs by position.\n */\nfunction elementKeys(array: readonly unknown[]): string[] | undefined {\n const keys = new Set<string>();\n for (const element of array) {\n let key: string | undefined;\n if (typeof element === \"string\") key = `s:${element}`;\n else if (isRecord(element) && typeof element.name === \"string\")\n key = `n:${element.name}`;\n if (key === undefined || keys.has(key)) return undefined;\n keys.add(key);\n }\n return [...keys];\n}\n\n/**\n * The before-indexes of the most shared keys that keep their relative order:\n * with distinct keys, the longest common subsequence is the longest increasing\n * run of after-positions, found in O(n log n) by patience sorting.\n */\nfunction keptInOrder(\n before: readonly string[],\n after: readonly string[]\n): Set<number> {\n const position = new Map(after.map((key, index) => [key, index]));\n // tails[length - 1] is the before-index ending the lowest run of that length.\n const tails: number[] = [];\n const previous = new Map<number, number>();\n for (const [index, key] of before.entries()) {\n const target = position.get(key);\n if (target === undefined) continue;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = Math.floor((low + high) / 2);\n if (position.get(before[tails[middle]!]!)! < target) low = middle + 1;\n else high = middle;\n }\n if (low > 0) previous.set(index, tails[low - 1]!);\n tails[low] = index;\n }\n const kept = new Set<number>();\n for (\n let index = tails.at(-1);\n index !== undefined;\n index = previous.get(index)\n )\n kept.add(index);\n return kept;\n}\n\n/**\n * Keyed edits leave one element's insertion at one change however many follow\n * it: drop the elements that are not kept, last first, then insert the new and\n * moved ones at their final indexes in order, then edit the kept pairs there.\n */\nfunction keyedChangesBetween(\n before: readonly unknown[],\n after: readonly unknown[],\n beforeKeys: readonly string[],\n afterKeys: readonly string[],\n path: readonly (string | number)[],\n changes: SnapshotChangeV1[]\n): void {\n const kept = keptInOrder(beforeKeys, afterKeys);\n const keptAt = new Map([...kept].map((index) => [beforeKeys[index]!, index]));\n for (let index = before.length - 1; index >= 0; index--) {\n if (!kept.has(index))\n changes.push({ op: \"remove\", path: [...path, index] });\n }\n for (const [index, key] of afterKeys.entries()) {\n if (!keptAt.has(key))\n changes.push({\n op: \"insert\",\n path: [...path, index],\n value: after[index],\n });\n }\n for (const [index, key] of afterKeys.entries()) {\n const from = keptAt.get(key);\n if (from !== undefined)\n changesBetween(\n before[from],\n after[index],\n [...path, index],\n changes,\n true\n );\n }\n}\n\nfunction changesBetween(\n before: unknown,\n after: unknown,\n path: readonly (string | number)[],\n changes: SnapshotChangeV1[],\n keyed: boolean\n): void {\n if (canonicalizeJsonText(before) === canonicalizeJsonText(after)) return;\n if (Array.isArray(before) && Array.isArray(after)) {\n const beforeKeys = keyed ? elementKeys(before) : undefined;\n const afterKeys = beforeKeys && elementKeys(after);\n if (beforeKeys && afterKeys) {\n keyedChangesBetween(before, after, beforeKeys, afterKeys, path, changes);\n return;\n }\n const shared = Math.min(before.length, after.length);\n for (let index = 0; index < shared; index++)\n changesBetween(\n before[index],\n after[index],\n [...path, index],\n changes,\n keyed\n );\n for (let index = before.length - 1; index >= after.length; index--)\n changes.push({ op: \"remove\", path: [...path, index] });\n for (let index = shared; index < after.length; index++)\n changes.push({ op: \"set\", path: [...path, index], value: after[index] });\n } else if (isRecord(before) && isRecord(after)) {\n for (const key of Object.keys(before).sort()) {\n if (!Object.hasOwn(after, key))\n changes.push({ op: \"remove\", path: [...path, key] });\n }\n for (const key of Object.keys(after).sort()) {\n if (Object.hasOwn(before, key))\n changesBetween(before[key], after[key], [...path, key], changes, keyed);\n else changes.push({ op: \"set\", path: [...path, key], value: after[key] });\n }\n } else {\n changes.push({ op: \"set\", path, value: after });\n }\n}\n\n/**\n * A function of the parents' artifacts alone, independent of storage listing\n * order: a state's id hashes its artifact, so the same parents and schema give\n * the same id whatever else the history holds.\n */\nexport function encodeSnapshotArtifact(\n snapshot: SchemaSnapshot,\n artifacts: ReadonlyMap<Sha256, ResolvedSnapshotArtifact>,\n parentArtifacts: Iterable<Sha256>\n): EncodedSnapshotArtifact {\n const full = encodeSnapshot(snapshot);\n const bases = [...new Set(parentArtifacts)].sort();\n for (const hash of bases) {\n const base = artifacts.get(hash)!;\n // A parent already stores this schema; publication can omit this object.\n if (base.snapshotHash === full.snapshotHash) {\n return {\n artifactHash: hash,\n snapshotHash: full.snapshotHash,\n bytes: null,\n depth: base.depth,\n };\n }\n }\n let best: EncodedSnapshotArtifact & { readonly bytes: Uint8Array } = {\n artifactHash: full.snapshotHash,\n ...full,\n depth: 0,\n };\n const desired = parseJsonBytes(full.bytes, \"desired snapshot\");\n for (const baseArtifactHash of bases) {\n const base = artifacts.get(baseArtifactHash)!;\n if (base.depth >= MAX_SNAPSHOT_DELTA_DEPTH) continue;\n const document = parseJsonBytes(\n encodeSnapshot(base.snapshot).bytes,\n \"snapshot base\"\n );\n // Keyed edits win on insertions; positional ones still win on an element\n // renamed in place, which a keyed diff spells as a removal and an insert.\n for (const keyed of [true, false]) {\n const changes: SnapshotChangeV1[] = [];\n // Both encoded snapshots are records, so every emitted edit is below the\n // root; the producer cannot emit the empty path that admission refuses.\n changesBetween(document, desired, [], changes, keyed);\n const delta: SnapshotDeltaV1 = {\n format: \"snapshot-delta-2\",\n baseArtifactHash,\n snapshotHash: full.snapshotHash,\n changes,\n };\n const bytes = canonicalizeJson(delta);\n if (bytes.length < best.bytes.length) {\n best = {\n artifactHash: domainHash(HASH_DOMAIN.snapshotDelta, bytes),\n snapshotHash: full.snapshotHash,\n bytes,\n depth: base.depth + 1,\n baseArtifactHash,\n };\n }\n }\n }\n return best;\n}\n","/**\n * One immutable estate graph. Commands consume this instance; they do not\n * rescan storage or invent apply order from names.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { bytesEqual } from \"./canonical-json\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport type { Sha256 } from \"./identity\";\nimport { freezeDeep } from \"./push-fingerprint\";\nimport {\n type ParsedSnapshotArtifact,\n parseSnapshotArtifact,\n type ResolvedSnapshotArtifact,\n resolveSnapshotArtifacts,\n} from \"./snapshot-artifacts\";\nimport { sliceDispatch, validateSqlRanges } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { MigrationTarget, SchemaSnapshot } from \"./types\";\nimport {\n encodeSnapshot,\n encodeSqlBlob,\n parseEstateDescriptor,\n parseStateManifest,\n} from \"./v1-parse\";\nimport type {\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationEstateDescriptorV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n PathWitness,\n SnapshotDeltaV1,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationGraph {\n readonly estateHash: Sha256;\n readonly descriptor: MigrationEstateDescriptorV1;\n readonly states: ReadonlyMap<Sha256, MigrationStateManifestV1>;\n readonly snapshots: ReadonlyMap<Sha256, SchemaSnapshot>;\n readonly snapshotArtifacts: ReadonlyMap<Sha256, ResolvedSnapshotArtifact>;\n readonly sql: ReadonlyMap<Sha256, Uint8Array>;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly emptySnapshotHash: Sha256;\n}\n\n/** Resolve one authenticated graph state to its already-parsed snapshot. */\nexport function requireStateSnapshot(\n graph: MigrationGraph,\n stateId: Sha256 | null\n): SchemaSnapshot {\n const snapshotHash =\n stateId === null\n ? graph.emptySnapshotHash\n : graph.states.get(stateId)?.snapshotHash;\n const snapshot = snapshotHash ? graph.snapshots.get(snapshotHash) : undefined;\n if (!snapshot) {\n throw new MigrationError(\n \"A selected state is missing its authenticated snapshot\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return snapshot;\n}\n\ntype CachedArtifact =\n | { readonly bytes: Uint8Array; readonly snapshot: SchemaSnapshot }\n | {\n readonly bytes: Uint8Array;\n readonly delta: SnapshotDeltaV1;\n readonly snapshot?: SchemaSnapshot;\n readonly decodedBytes?: number;\n }\n | { readonly bytes: Uint8Array; readonly manifest: MigrationStateManifestV1 };\n\n/**\n * Parsed artifacts, keyed by their own content hash: never by the estate\n * hash, which every estate with the same target shares. Only the parse is\n * skipped. Every command still lists and reads the tenant's storage, and an\n * entry answers only bytes identical to the ones it was parsed from, so\n * changed bytes are parsed, and refused, as if nothing were cached. Values\n * are deep-frozen because commands and tenants share them. Least recently\n * used entries are dropped once the held bytes exceed `maxBytes`. A retained\n * delta reconstruction charges its full canonical size as well as delta bytes.\n */\nexport class ArtifactCache {\n private readonly entries = new Map<Sha256, CachedArtifact>();\n private readonly maxBytes: number;\n private held = 0;\n\n constructor(maxBytes: number) {\n this.maxBytes = maxBytes;\n }\n\n get heldBytes(): number {\n return this.held;\n }\n\n storedSnapshot(bytes: Uint8Array, hash: Sha256): ParsedSnapshotArtifact {\n const hit = this.hit(hash, bytes);\n if (hit && \"delta\" in hit)\n return { kind: \"delta\", delta: hit.delta, snapshot: hit.snapshot };\n if (hit && \"snapshot\" in hit)\n return { kind: \"full\", snapshot: hit.snapshot };\n const artifact = freezeDeep(parseSnapshotArtifact(bytes, hash));\n if (artifact.kind === \"full\") {\n this.keep(hash, { bytes: bytes.slice(), snapshot: artifact.snapshot });\n } else {\n this.keep(hash, { bytes: bytes.slice(), delta: artifact.delta });\n }\n return artifact;\n }\n\n rememberSnapshot(\n hash: Sha256,\n bytes: Uint8Array,\n snapshot: SchemaSnapshot\n ): void {\n const entry = this.hit(hash, bytes);\n if (!(entry && \"delta\" in entry) || entry.snapshot) return;\n // Charge the full canonical result as well as the small delta; compressed\n // bytes must not turn the existing cache bound into unbounded decoded state.\n this.entries.delete(hash);\n this.held -= entry.bytes.length;\n this.keep(hash, {\n ...entry,\n snapshot: freezeDeep(snapshot),\n decodedBytes: encodeSnapshot(snapshot).bytes.length,\n });\n }\n\n manifest(id: Sha256, bytes: Uint8Array): MigrationStateManifestV1 {\n const hit = this.hit(id, bytes);\n if (hit && \"manifest\" in hit) return hit.manifest;\n const manifest = freezeDeep(parseStateManifest(bytes, id));\n return this.keep(id, { bytes: bytes.slice(), manifest }).manifest;\n }\n\n private hit(hash: Sha256, bytes: Uint8Array): CachedArtifact | undefined {\n const entry = this.entries.get(hash);\n if (!(entry && bytesEqual(entry.bytes, bytes))) return undefined;\n this.entries.delete(hash);\n this.entries.set(hash, entry);\n return entry;\n }\n\n private keep<T extends CachedArtifact>(hash: Sha256, entry: T): T {\n // Only a miss parses, and a miss on a held hash has other bytes, which\n // the parse refuses, so `hash` is never already held here.\n this.entries.set(hash, entry);\n this.held +=\n entry.bytes.length +\n (\"decodedBytes\" in entry ? (entry.decodedBytes ?? 0) : 0);\n for (const [key, oldest] of this.entries) {\n if (this.held <= this.maxBytes) break;\n this.entries.delete(key);\n this.held -=\n oldest.bytes.length +\n (\"decodedBytes\" in oldest ? (oldest.decodedBytes ?? 0) : 0);\n }\n return entry;\n }\n}\n\n/**\n * One per isolate. 8 MiB of artifact bytes hold a 200-state estate of twenty\n * 15-column tables; the parsed values add about as much again.\n */\nconst artifacts = new ArtifactCache(8 * 1024 * 1024);\n\nexport async function loadMigrationGraph(\n storage: MigrationStorageReader,\n cache: ArtifactCache = artifacts\n): Promise<MigrationGraph> {\n const estateBytes = await storage.readEstate();\n if (!estateBytes) {\n throw new MigrationError(\n \"Estate descriptor is missing\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n const { descriptor, estateHash } = parseEstateDescriptor(estateBytes);\n const emptySnapshotHash = encodeSnapshot(emptyManagedSnapshot()).snapshotHash;\n const stateIds = await storage.listStates();\n const states = new Map<Sha256, MigrationStateManifestV1>();\n const neededSnapshots = new Set<Sha256>();\n const neededSql = new Set<Sha256>();\n\n for (const id of stateIds) {\n const bytes = await storage.readState(id);\n if (!bytes) {\n throw new MigrationError(\n `State ${id} is listed but unreadable`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (states.has(id)) {\n throw new MigrationError(\n `State ${id} is listed more than once`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const manifest = cache.manifest(id, bytes);\n if (manifest.estateHash !== estateHash) {\n throw new MigrationError(\n `State ${id} belongs to a different estate`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n states.set(id, manifest);\n if (\n manifest.snapshotArtifactHash !== undefined ||\n manifest.snapshotHash !== emptySnapshotHash\n ) {\n neededSnapshots.add(\n manifest.snapshotArtifactHash ?? manifest.snapshotHash\n );\n }\n neededSql.add(manifest.sqlHash);\n }\n\n const snapshots = new Map<Sha256, SchemaSnapshot>();\n snapshots.set(emptySnapshotHash, emptyManagedSnapshot());\n const snapshotArtifacts = await resolveSnapshotArtifacts(\n storage,\n neededSnapshots,\n new Map(),\n cache\n );\n for (const artifact of snapshotArtifacts.values()) {\n if (!Object.isFrozen(artifact.snapshot)) freezeDeep(artifact.snapshot);\n }\n for (const manifest of states.values()) {\n if (\n manifest.snapshotArtifactHash === undefined &&\n manifest.snapshotHash === emptySnapshotHash\n )\n continue;\n const artifact = snapshotArtifacts.get(\n manifest.snapshotArtifactHash ?? manifest.snapshotHash\n )!;\n if (artifact.snapshotHash !== manifest.snapshotHash) {\n throw new MigrationError(\n `State ${manifest.stateId} snapshot identity does not match its artifact`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n snapshots.set(manifest.snapshotHash, artifact.snapshot);\n }\n\n const sql = new Map<Sha256, Uint8Array>();\n for (const hash of neededSql) {\n const bytes = await storage.readSql(hash);\n if (!bytes) {\n throw new MigrationError(\n `SQL blob ${hash} is referenced but missing`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (encodeSqlBlob(bytes) !== hash) {\n throw new MigrationError(\n `SQL blob ${hash} does not match its bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n sql.set(hash, bytes);\n }\n\n for (const manifest of states.values()) {\n const blob = sql.get(manifest.sqlHash)!;\n const dispatches: MigrationDispatchV1[] = [];\n for (const parent of manifest.parents) {\n collectDispatches(parent, dispatches);\n }\n collectChecks(manifest.destinationChecks, dispatches);\n validateSqlRanges(blob, dispatches);\n assertStoredParameterDialect(\n dispatches,\n descriptor.target.dialect,\n manifest.name\n );\n assertArtifactExecutionSafe(\n dispatches.map((dispatch) => sliceDispatch(blob, dispatch)),\n descriptor.target.dialect,\n manifest.name\n );\n }\n\n const outgoing = new Map<Sha256, Sha256[]>();\n for (const id of states.keys()) {\n outgoing.set(id, []);\n }\n\n for (const [id, manifest] of states) {\n for (const parent of manifest.parents) {\n assertAdoption(id, parent, descriptor.target, (stateId) => {\n const hash =\n stateId === null\n ? emptySnapshotHash\n : states.get(stateId)?.snapshotHash;\n return hash === undefined ? undefined : snapshots.get(hash);\n });\n if (parent.fromState === null) continue;\n if (!states.has(parent.fromState)) {\n throw new MigrationError(\n `State ${id} has a dangling parent`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n outgoing.get(parent.fromState)!.push(id);\n }\n }\n\n const roots = [...states.keys()].filter((id) =>\n states.get(id)!.parents.some((parent) => parent.fromState === null)\n );\n const leaves = [...states.keys()].filter(\n (id) => (outgoing.get(id) ?? []).length === 0\n );\n assertNoCycle(states, outgoing);\n\n if (states.size > 0 && roots.length === 0) {\n throw new MigrationError(\n \"Estate has states but no virtual-root transition\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n assertReachableFromEmpty(states, outgoing, roots);\n\n return {\n estateHash,\n descriptor,\n states,\n snapshots,\n snapshotArtifacts,\n sql,\n roots,\n leaves,\n emptySnapshotHash,\n };\n}\n\n/**\n * An adoption names only tables of its state that its parent lacks, outside\n * the estate's frozen list: the proofs leave an adopted table out on the\n * parent's side (`managedAt`), which is sound only for such a table.\n */\nfunction assertAdoption(\n stateId: Sha256,\n parent: MigrationParentTransitionV1,\n target: MigrationTarget,\n snapshotOf: (stateId: Sha256 | null) => SchemaSnapshot | undefined\n): void {\n if (parent.adopts === undefined) return;\n const has = (snapshot: SchemaSnapshot | undefined, name: string) =>\n snapshot?.tables.some((table) => table.name === name) === true;\n const own = snapshotOf(stateId);\n const before = snapshotOf(parent.fromState);\n for (const name of parent.adopts) {\n if (\n target.tables === undefined ||\n target.tables.includes(name) ||\n !has(own, name) ||\n has(before, name)\n ) {\n throw new MigrationError(\n `State ${stateId} adopts \"${name}\", which is not a table it adds to an estate with a \\`tables\\` list outside that list`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n\n/**\n * The symbolic namespace is one portable MySQL artifact value. PostgreSQL\n * stores its schema in the estate target and SQLite has no namespace, so the\n * tag in either estate is corruption rather than an executable parameter.\n */\nfunction assertStoredParameterDialect(\n dispatches: readonly MigrationDispatchV1[],\n dialect: MigrationEstateDescriptorV1[\"target\"][\"dialect\"],\n artifact: string\n): void {\n if (dialect === \"mysql\") {\n return;\n }\n for (const dispatch of dispatches) {\n if (\n dispatch.parameters.some(\n (parameter) => parameter.kind === \"target-namespace\"\n )\n ) {\n throw new MigrationError(\n `Migration \"${artifact}\" contains a target-namespace parameter outside a MySQL estate`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { migrationName: artifact } }\n );\n }\n }\n}\n\nfunction collectDispatches(\n parent: MigrationParentTransitionV1,\n into: MigrationDispatchV1[]\n): void {\n collectChecks(parent.originChecks, into);\n collectOperations(parent.operations, into);\n if (parent.rollback.kind !== \"irreversible\") {\n collectOperations(parent.rollback.operations, into);\n }\n}\n\nfunction collectOperations(\n operations: readonly MigrationOperationV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const operation of operations) {\n for (const step of operation.steps) {\n if (step.retry === \"proven\") {\n into.push(step.precheck.query);\n }\n into.push(step.execute);\n if (step.retry === \"proven\") {\n into.push(step.postcheck.query);\n }\n }\n }\n}\n\nfunction collectChecks(\n checks: readonly MigrationBooleanCheckV1[],\n into: MigrationDispatchV1[]\n): void {\n for (const check of checks) {\n into.push(check.query);\n }\n}\n\nfunction assertNoCycle(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>\n): void {\n const color = new Map<Sha256, 0 | 1 | 2>();\n for (const id of states.keys()) color.set(id, 0);\n for (const start of states.keys()) {\n if (color.get(start) !== 0) continue;\n const stack: Array<{ id: Sha256; next: number }> = [{ id: start, next: 0 }];\n color.set(start, 1);\n while (stack.length > 0) {\n const frame = stack.at(-1)!;\n const edges = outgoing.get(frame.id) ?? [];\n if (frame.next < edges.length) {\n const next = edges[frame.next++]!;\n const seen = color.get(next) ?? 0;\n if (seen === 1) {\n throw new MigrationError(\n \"Estate graph contains a cycle\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n if (seen === 0) {\n color.set(next, 1);\n stack.push({ id: next, next: 0 });\n }\n continue;\n }\n color.set(frame.id, 2);\n stack.pop();\n }\n }\n}\n\nfunction assertReachableFromEmpty(\n states: ReadonlyMap<Sha256, MigrationStateManifestV1>,\n outgoing: ReadonlyMap<Sha256, readonly Sha256[]>,\n roots: readonly Sha256[]\n): void {\n const reachable = new Set<Sha256>();\n const pending = [...roots];\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (reachable.has(id)) continue;\n reachable.add(id);\n for (const child of outgoing.get(id) ?? []) {\n pending.push(child);\n }\n }\n for (const id of states.keys()) {\n if (!reachable.has(id)) {\n throw new MigrationError(\n `State ${id} is not reachable from the empty state`,\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n\nexport function resolveStateSelector(\n graph: MigrationGraph,\n selector: StateSelector | undefined\n): Sha256 {\n if (!selector) {\n if (graph.leaves.length === 1) return graph.leaves[0]!;\n if (graph.leaves.length === 0) {\n throw new MigrationError(\n \"Estate has no states to target\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n graph.leaves.map((leaf) => [leaf]),\n \"Multiple leaf states exist; choose the target with --to / { to }\"\n );\n }\n if (\"id\" in selector) {\n if (!graph.states.has(selector.id)) {\n throw new MigrationError(\n `Unknown state ${selector.id}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return selector.id;\n }\n if (\"prefix\" in selector) {\n const matches = [...graph.states.keys()].filter((id) =>\n id.startsWith(selector.prefix)\n );\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n throw new MigrationError(\n `No state has prefix ${selector.prefix}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n matches.map((id) => [id]),\n AMBIGUOUS_SELECTOR\n );\n }\n const matches = [...graph.states.values()]\n .filter((state) => state.name === selector.name)\n .map((state) => state.stateId);\n if (matches.length === 1) return matches[0]!;\n if (matches.length === 0) {\n throw new MigrationError(\n `No state is named ${selector.name}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n matches.map((id) => [id]),\n AMBIGUOUS_SELECTOR\n );\n}\n\nexport function selectRoute(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n via?: readonly Sha256[]\n): readonly Sha256[] {\n if (via && via.length > 0) {\n if (via.at(-1) !== target) {\n throw new MigrationError(\n \"via must end at the resolved target\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n const seen = new Set<string>();\n let previous = origin;\n for (const step of via) {\n if (seen.has(step)) {\n throw new MigrationError(\n \"via repeats a state\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n seen.add(step);\n if (!hasEdge(graph, previous, step)) {\n throw new MigrationError(\n \"via is not a real estate edge\",\n VibORMErrorCode.MIGRATION_PATH_REQUIRED\n );\n }\n previous = step;\n }\n return via;\n }\n\n const routes = enumerateRoutes(graph, origin, target, 2);\n if (routes.length === 1) return routes[0]!;\n if (routes.length === 0) {\n throw new MigrationError(\n \"No path exists from the current marker to the target\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n throw pathRequired(\n routes,\n \"Multiple migration paths exist; choose one with --via / { via }\"\n );\n}\n\nfunction hasEdge(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): boolean {\n const state = graph.states.get(to);\n if (!state) return false;\n return state.parents.some((parent) => parent.fromState === from);\n}\n\n/**\n * Plan T4: what a history pruned at `checkpoint` keeps. The checkpoint, every\n * state after it, and every state those name as a parent, so no kept\n * transition dangles: a merge with older history keeps that history.\n */\nexport function statesFrom(\n graph: MigrationGraph,\n checkpoint: Sha256\n): ReadonlySet<Sha256> {\n const children = childrenIndex(graph);\n const closure = (\n start: Iterable<Sha256>,\n next: (id: Sha256) => readonly (Sha256 | null)[]\n ) => {\n const seen = new Set<Sha256>();\n const pending = [...start];\n while (pending.length > 0) {\n const id = pending.pop()!;\n if (seen.has(id)) continue;\n seen.add(id);\n for (const step of next(id)) if (step !== null) pending.push(step);\n }\n return seen;\n };\n return closure(\n closure([checkpoint], (id) => children.get(id) ?? []),\n (id) => graph.states.get(id)!.parents.map((parent) => parent.fromState)\n );\n}\n\nfunction childrenIndex(graph: MigrationGraph): Map<string, Sha256[]> {\n const index = new Map<string, Sha256[]>();\n index.set(\"null\", []);\n for (const id of graph.states.keys()) {\n index.set(id, []);\n }\n for (const [id, state] of graph.states) {\n for (const parent of state.parents) {\n const key = parent.fromState ?? \"null\";\n const list = index.get(key) ?? [];\n list.push(id);\n index.set(key, list);\n }\n }\n return index;\n}\n\nfunction enumerateRoutes(\n graph: MigrationGraph,\n origin: Sha256 | null,\n target: Sha256,\n limit: number\n): Sha256[][] {\n const children = childrenIndex(graph);\n const found: Sha256[][] = [];\n const stack: Array<{ from: Sha256 | null; path: Sha256[] }> = [\n { from: origin, path: [] },\n ];\n while (stack.length > 0 && found.length < limit) {\n const frame = stack.pop()!;\n for (const child of children.get(frame.from ?? \"null\") ?? []) {\n if (frame.path.includes(child)) continue;\n const next = [...frame.path, child];\n if (child === target) {\n found.push(next);\n if (found.length >= limit) break;\n continue;\n }\n stack.push({ from: child, path: next });\n }\n }\n return found;\n}\n\nconst AMBIGUOUS_SELECTOR =\n \"The state selector matches several states; pass a longer prefix or the full state id\";\n\nfunction pathRequired(\n routes: readonly (readonly Sha256[])[],\n hint: string\n): never {\n const witness: PathWitness = {\n routes: routes.slice(0, 2),\n frontier: firstFrontier(routes),\n more: routes.length > 2,\n };\n throw new MigrationError(\n `${hint}. Candidates: ${witness.routes\n .map((route) => route.join(\" -> \"))\n .join(\" | \")}`,\n VibORMErrorCode.MIGRATION_PATH_REQUIRED,\n { meta: { pathWitness: witness } }\n );\n}\n\nfunction firstFrontier(routes: readonly (readonly Sha256[])[]): Sha256[] {\n if (routes.length < 2) return [];\n const first = routes[0]!;\n const second = routes[1]!;\n const frontier: Sha256[] = [];\n const max = Math.min(first.length, second.length);\n for (let i = 0; i < max; i++) {\n if (first[i] !== second[i]) {\n frontier.push(first[i]!, second[i]!);\n return frontier;\n }\n }\n return frontier;\n}\n\n/** One edge of a route: its endpoints, transition, arrival state and SQL. */\nexport interface RouteEdge {\n readonly from: Sha256 | null;\n readonly to: Sha256;\n readonly transition: MigrationParentTransitionV1;\n readonly state: MigrationStateManifestV1;\n readonly blob: Uint8Array;\n}\n\n/**\n * The edges of `path` walked from `origin`. `parentTransition` refuses a\n * missing edge; the loaded graph holds every state and blob an edge names.\n */\nexport function routeEdges(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): RouteEdge[] {\n return path.map((to, index) => {\n const from = index === 0 ? origin : path[index - 1]!;\n const transition = parentTransition(graph, from, to);\n const state = graph.states.get(to)!;\n return { from, to, transition, state, blob: graph.sql.get(state.sqlHash)! };\n });\n}\n\nexport function parentTransition(\n graph: MigrationGraph,\n from: Sha256 | null,\n to: Sha256\n): MigrationParentTransitionV1 {\n const state = graph.states.get(to);\n if (!state) {\n throw new MigrationError(\n `Unknown state ${to}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const found = state.parents.find((parent) => parent.fromState === from);\n if (!found) {\n throw new MigrationError(\n \"Selected edge has no parent transition\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return found;\n}\n","import type { AmbiguousChange, DiffOperation } from \"../types\";\n\n/**\n * Formats an operation for human-readable display.\n */\nexport function formatOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"createTable\":\n return `+ Create table \"${op.table.name}\" with ${op.table.columns.length} columns`;\n case \"dropTable\":\n return `- Drop table \"${op.tableName}\"`;\n case \"renameTable\":\n return `~ Rename table \"${op.from}\" → \"${op.to}\"`;\n case \"addColumn\":\n return `+ Add column \"${op.column.name}\" (${op.column.type}) to \"${op.tableName}\"`;\n case \"dropColumn\":\n return `- Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"renameColumn\":\n return `~ Rename column \"${op.from}\" → \"${op.to}\" in \"${op.tableName}\"`;\n case \"alterColumn\":\n return `~ Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n case \"createIndex\":\n return `+ Create index \"${op.index.name}\" on \"${op.tableName}\"`;\n case \"dropIndex\":\n return `- Drop index \"${op.indexName}\"`;\n case \"addForeignKey\":\n return `+ Add foreign key \"${op.fk.name}\" to \"${op.tableName}\"`;\n case \"dropForeignKey\":\n return `- Drop foreign key \"${op.fkName}\" from \"${op.tableName}\"`;\n case \"addUniqueConstraint\":\n return `+ Add unique constraint \"${op.constraint.name}\" to \"${op.tableName}\"`;\n case \"dropUniqueConstraint\":\n return `- Drop unique constraint \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"addPrimaryKey\":\n return `+ Add primary key to \"${op.tableName}\"`;\n case \"dropPrimaryKey\":\n return `- Drop primary key \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"createEnum\":\n return `+ Create enum \"${op.enumDef.name}\" with values [${op.enumDef.values.join(\", \")}]`;\n case \"dropEnum\":\n return `- Drop enum \"${op.enumName}\"`;\n case \"alterEnum\": {\n const parts: string[] = [];\n if (op.addValues?.length) parts.push(`add: ${op.addValues.join(\", \")}`);\n if (op.removeValues?.length) {\n parts.push(`remove: ${op.removeValues.join(\", \")}`);\n }\n return `~ Alter enum \"${op.enumName}\" (${parts.join(\"; \")})`;\n }\n default:\n return `Unknown operation: ${getOperationType(op)}`;\n }\n}\n\nexport function formatDestructiveOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"dropTable\":\n return `[destructive] Drop table \"${op.tableName}\"`;\n case \"dropColumn\":\n return `[destructive] Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"addColumn\":\n return `[destructive] Add required column \"${op.tableName}.${op.column.name}\" without a backfill default`;\n case \"alterColumn\":\n return `[destructive] Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n default:\n return `[destructive] ${getOperationType(op)}`;\n }\n}\n\nexport function formatAmbiguousChangeDescription(\n change: AmbiguousChange\n): string {\n if (change.type === \"ambiguousColumn\") {\n return `[ambiguous] Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in \"${change.tableName}\"`;\n }\n return `[ambiguous] Table \"${change.droppedTable}\" → \"${change.addedTable}\"`;\n}\n\nfunction getOperationType(operation: { type: string }): string {\n return operation.type;\n}\n","/**\n * Live-capability admission\n *\n * ONE decision admits a migration command to live database state. Direct\n * `push()` and every high-level migration command reach it here; no command\n * reinterprets either fact for itself.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { canPinSession, runsMigrationBatches } from \"./pinned-session\";\nimport { formatMigrationTarget, readNamespaceAttestation } from \"./target\";\n\n/**\n * What a command asks of live state.\n *\n * - `effectful` — the command can write, or promises a concurrency-stable\n * decision read from live state (apply/down/reset/verify/push, and the live\n * dry down/reset decisions the CLI confirms against).\n * - `batch` — effectful work whose every effect can go out as one atomic\n * request per transactional group (apply): admitted as `effectful` is, and\n * also on a PostgreSQL transport with no session that runs such a request\n * (plan D7), where that work refuses any step needing a session itself.\n * - `read-only` — a point-in-time read that changes nothing (status, log,\n * apply dry-run, push dry-run introspection).\n *\n * Offline and storage-only work — generate, check — never reaches this owner\n * at all.\n */\nexport type MigrationLiveRequirement = \"effectful\" | \"batch\" | \"read-only\";\n\n/**\n * Admits (or refuses) live migration work for one command.\n *\n * The failure precedence for MySQL is exact and is the whole point of the\n * owner: an absent attestation is `DRIVER_NOT_SUPPORTED`, and only AFTER the\n * capability is admitted does an absent namespace become\n * `MIGRATION_INVALID_STATE`. Reversing them would report a missing database\n * name for a driver whose routing was never provable in the first place.\n *\n * PostgreSQL namespaces are proven earlier, when the estate target is resolved\n * — a PostgreSQL driver with no adapter namespace never reaches a live\n * boundary. SQLite has no namespace to prove.\n */\nexport function admitLiveMigrationCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const { target } = migrationDriver;\n\n if (target.dialect === \"postgresql\") {\n admitPinnedSessionCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect === \"sqlite\") {\n admitSqliteFamilyCapability(migrationDriver, requirement, command);\n return;\n }\n\n if (target.dialect !== \"mysql\") {\n return;\n }\n\n if (requirement !== \"read-only\") {\n const attestation = readNamespaceAttestation(\n migrationDriver.executionDriver\n );\n if (attestation === undefined) {\n throw new MigrationError(\n `${command} needs proof that this MySQL driver does not redirect qualified table references, and the driver \"${migrationDriver.executionDriver.driverName}\" carries no non-redirecting migration-namespace attestation. ` +\n \"Effectful and concurrency-stable live migration work is refused: a successful handshake, a driver class, a URL shape or a server version is not proof that a proxy leaves qualified names in the requested database.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target, migrationDriver.namespace),\n },\n }\n );\n }\n }\n\n if (migrationDriver.namespace === undefined) {\n throw new MigrationError(\n `${command} needs a live MySQL database and this client's adapter is unbound. ` +\n \"MySQL migration artifacts are database-relative on purpose, so the live destination comes from the driver's `namespace` — supply it explicitly, in the connection URL, or through the driver's database option.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n driver: migrationDriver.executionDriver.driverName,\n command,\n target: formatMigrationTarget(target),\n },\n }\n );\n }\n}\n\n/**\n * Admits effectful SQLite work only on a driver that declared one of the two\n * effectful migration capabilities.\n *\n * The declaration was read once when the driver was bound (`getMigrationDriver`,\n * where it also chose the implementation); this is where it decides. Stock\n * sqlite3, bun-sqlite and the Durable Object driver declare an effectful one;\n * D1 declares the read-only one, and libSQL none. Those stay refused for\n * effectful work while generation, check and read-only status stay available.\n * Whether the driver runs callback transactions is its `supportsTransactions`,\n * which each command already reads for its own transaction shape.\n */\nfunction admitSqliteFamilyCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const capability = migrationDriver.sqliteMigrationCapability;\n // The bound declarations are a closed table: an exclusion of \"none\" is the\n // read-only one, which is also the one that cannot switch foreign keys off.\n if (\n requirement === \"read-only\" ||\n (capability !== undefined && capability.exclusion !== \"none\")\n ) {\n return;\n }\n const { driverName } = migrationDriver.executionDriver;\n const reason =\n capability === undefined\n ? `the SQLite driver \"${driverName}\" declares no \\`sqliteMigrationCapability\\``\n : `the SQLite driver \"${driverName}\" declares a read-only migration capability: it can neither switch foreign keys off nor hold a migration lock`;\n throw new MigrationError(\n `${command} is refused: ${reason}. Generation, check and status remain available.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n {\n meta: {\n driver: driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n },\n }\n );\n}\n\n/**\n * Refuses an effectful PostgreSQL command on a transport that cannot hold a\n * session lock for it.\n *\n * Neon's HTTP driver is the shipped case of a transport with no interactive\n * session: it speaks a stateless request/reply API, so a `pg_advisory_lock` it\n * issued would be acquired by one request and could never be released by\n * another — the lock would be neither held for the work nor released after it.\n * The answer is `canPinSession(driver)` — the presence of the driver's own\n * pinned-session hook — so nothing declares a capability it does not\n * implement, and a custom PostgreSQL driver is judged by the same fact as a\n * stock one. `batch` work is the exception: such a transport sends each\n * transactional group as one request holding the transaction lock\n * (`runsMigrationBatches`, plan D7).\n *\n * A transaction-pooling endpoint is the same failure behind an ordinary\n * session: Cloudflare Hyperdrive and Neon's `-pooler` endpoints hand\n * consecutive transactions to whichever server session is free, so the lock\n * is taken on one backend and the DDL runs on another. Those hosts, read from\n * the driver's own configuration, are refused unless the caller attests a\n * dedicated session, at their risk. Every path that mutates, or that makes a\n * concurrency-stable decision from live state, is refused HERE: before the\n * connection, before storage writes, and before any other provider work.\n * Application queries, read-only introspection, status/log, push dry-run, and\n * every offline path stay available.\n */\nfunction admitPinnedSessionCapability(\n migrationDriver: BoundMigrationDriver,\n requirement: MigrationLiveRequirement,\n command: string\n): void {\n const driver = migrationDriver.executionDriver;\n if (\n requirement === \"read-only\" ||\n (requirement === \"batch\" && runsMigrationBatches(driver))\n ) {\n return;\n }\n const meta = {\n driver: driver.driverName,\n command,\n target: formatMigrationTarget(migrationDriver.target),\n };\n if (!canPinSession(driver)) {\n throw new MigrationError(\n `${command} needs one physical database session it can hold a migration lock on, and the driver \"${driver.driverName}\" has no interactive session to reserve. ` +\n \"Effectful and concurrency-stable live migration work is refused: a session-scoped lock taken over a stateless transport would be acquired by one request and released by another, so it would protect nothing. Runtime queries, introspection, status, log, push dry-run and every offline command remain available.\",\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta }\n );\n }\n if (driver.migrationSessionAttestation === \"dedicated-session\") {\n return;\n }\n const pooler = driver[\"migrationSessionEndpoints\"]?.()\n .flatMap(endpointHosts)\n .find((host) => HYPERDRIVE_HOST.test(host) || NEON_POOLER_HOST.test(host));\n if (pooler === undefined) {\n return;\n }\n throw new MigrationError(\n `${command} is refused: \"${pooler}\" is a transaction pooler, which cannot hold the migration lock. Use the direct endpoint, or pass migrationSessionAttestation: \"dedicated-session\" at your own risk.`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED,\n { meta }\n );\n}\n\n/** Cloudflare Hyperdrive's local endpoint, as a Worker binding names it. */\nconst HYPERDRIVE_HOST = /\\.hyperdrive\\.local\\.?$/i;\n/** A Neon endpoint id with the pooled-connection suffix. */\nconst NEON_POOLER_HOST = /^ep-[^.]*-pooler\\./i;\n/**\n * A URL's host list and query. Userinfo runs to the LAST `@` before the path,\n * as WHATWG URL (and so `pg-connection-string`) reads an unencoded `@`.\n */\nconst URL_PARTS =\n /^[a-z][a-z\\d+.-]*:\\/\\/(?:[^/?#]*@)?([^/?#]*)[^?#]*\\??([^#]*)/i;\nconst PORT = /:\\d*$/;\n\n/**\n * The host names one configured endpoint names, without ports: a bare host,\n * or every host of a (possibly multi-host) connection URL, including the\n * libpq `host` query parameter that overrides it.\n */\nfunction endpointHosts(endpoint: unknown): string[] {\n if (typeof endpoint !== \"string\") return [];\n const url = URL_PARTS.exec(endpoint);\n const hosts = url\n ? [url[1] ?? \"\", ...new URLSearchParams(url[2]).getAll(\"host\")]\n : [endpoint];\n return hosts.flatMap((list) =>\n list.split(\",\").map((host) => host.replace(PORT, \"\"))\n );\n}\n","import type { AnyDriver } from \"../../drivers/driver\";\nimport { CLIENT_DIAGNOSTICS } from \"../../drivers/execution-context\";\nimport {\n type DiagnosticDisclosure,\n MigrationError,\n VibORMErrorCode,\n} from \"../../errors\";\nimport type { AnyModel } from \"../../schema/model\";\nimport type { ResolvedRelationIndex } from \"../../schema/validation/relation-resolution\";\nimport { admitLiveMigrationCapability } from \"../admission\";\nimport {\n type DiffOptions,\n diff,\n type IndexPredicateCanonicalizer,\n isDestructiveOperation,\n} from \"../differ\";\nimport type { BoundMigrationDriver, MigrationDriver } from \"../drivers\";\nimport { getMigrationDriver } from \"../drivers\";\nimport { emptyManagedSnapshot } from \"../empty-snapshot\";\nimport type { ResolvedMigrationLimits } from \"../limits\";\nimport { applyNativeRename } from \"../native-rename\";\nimport {\n alwaysAddDropResolver,\n ambiguousDropKey,\n ambiguousToResolveChange,\n approveDestructiveOperations,\n resolveAmbiguousChanges,\n validateResolveResult,\n} from \"../resolver\";\nimport { serializeResolvedModels } from \"../serializer\";\nimport { MANAGED_TABLES, MIGRATION_LIMITS } from \"../target\";\nimport type {\n AmbiguousChange,\n ChangeResolution,\n DiffOperation,\n DiffResult,\n ResolveCallback,\n Resolver,\n SchemaSnapshot,\n} from \"../types\";\nimport { prepareSchemaProgram, sortOperations } from \"../utils\";\nimport {\n applyForceEnumResolutions,\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n type EnumRemoval,\n resolveEnumValueRemovalMappings,\n} from \"./enum-removals\";\nimport {\n formatAmbiguousChangeDescription,\n formatDestructiveOperation,\n} from \"./format\";\n\n/**\n * Minimal client interface required for migrations.\n * This allows push() to work with any object that has $driver and $schema.\n */\nexport interface MigrationClient {\n $driver: AnyDriver;\n $schema: Record<string, AnyModel>;\n readonly [MANAGED_TABLES]?: readonly string[] | undefined;\n readonly [MIGRATION_LIMITS]?: ResolvedMigrationLimits | undefined;\n /** The client's own `instrumentation({ diagnostics })`, when it has one. */\n readonly [CLIENT_DIAGNOSTICS]?: DiagnosticDisclosure | undefined;\n}\n\nexport interface PushOptions {\n /** Planner-only auto-resolution; public V1 push does not expose this key. */\n force?: boolean;\n /**\n * Skip schema validation before pushing. Validation catches definition\n * errors that would otherwise corrupt data silently (e.g. two relation\n * pairs sharing one junction table) — only skip it when deliberately\n * pushing a shape the validator flags.\n */\n skipValidation?: boolean;\n /** Preview SQL without executing */\n dryRun?: boolean;\n /**\n * Rebuild from the empty snapshot. Public V1 requires preview consent before\n * executing the resulting force-reset plan.\n */\n forceReset?: boolean;\n /**\n * Unified callback for resolving changes that require user input.\n * Called once per change, allowing granular control over each decision.\n *\n * Each change has methods for valid resolutions:\n * - Destructive: `change.proceed()`, `change.reject()`\n * - Ambiguous: `change.rename()`, `change.addAndDrop()`, `change.reject()`\n * - Enum value removal: `change.mapValues({...})`, `change.useNull()`, `change.reject()`\n *\n * A change the callback leaves undecided (returns `undefined`) refuses the\n * plan with MIGRATION_DESTRUCTIVE_REJECTED. Public `migrations.push()` has no\n * `force`; only the planner-internal `force` above turns an undecided change\n * into add+drop, acceptance or NULL.\n *\n * @example\n * ```ts\n * // Accept dropping a column, refuse everything else\n * await migrations.push({\n * dryRun: true,\n * resolve: async (change) => {\n * if (change.type === \"destructive\" && change.operation === \"dropColumn\") {\n * return change.proceed();\n * }\n * return change.reject();\n * },\n * });\n * ```\n */\n resolve?: ResolveCallback;\n}\n\n// Push deliberately carries NO storage owner. Ordinary push and force-reset\n// synchronize the live namespace and nothing else: they read no journal, write\n// no journal or snapshot, and cannot rewrite an estate's history as a side\n// effect of a schema sync.\n\nexport interface PushPlan {\n operations: DiffOperation[];\n currentSchema: SchemaSnapshot;\n}\n\nexport function getPushMigrationDriver(\n client: MigrationClient\n): BoundMigrationDriver {\n return getMigrationDriver(\n client.$driver,\n client[MANAGED_TABLES],\n client[MIGRATION_LIMITS],\n client[CLIENT_DIAGNOSTICS]\n );\n}\n\n/**\n * Introspects the current database schema without making any changes.\n * Useful for debugging or displaying current state.\n *\n * It changes nothing, but it READS live state, so it is a live migration\n * command and takes the one shared admission owner like every other one —\n * before any provider work. Without this gate an unbound MySQL client would\n * publish an inventory of whatever database its connection happened to default\n * to, which is exactly the ambient-default target §3.3 refuses to accept.\n * `push({ dryRun: true })` performs the same introspection behind the same\n * `read-only` admission; this entry point must not be the way around it.\n */\nexport async function introspect(\n client: MigrationClient\n): Promise<SchemaSnapshot> {\n const migrationDriver = getPushMigrationDriver(client);\n admitLiveMigrationCapability(migrationDriver, \"read-only\", \"introspect()\");\n return introspectSchema(client.$driver, migrationDriver);\n}\n\nexport async function introspectSchema(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): Promise<SchemaSnapshot> {\n return migrationDriver.introspect((sql, params) =>\n driver._executeRaw(sql, params)\n );\n}\n\n/**\n * Hands the differ a way to ask the database for its own spelling of a declared\n * partial-index predicate (Decision 7.4). Returns undefined when nobody can\n * answer, and the differ then compares the two texts raw — the reading that\n * plans a drop and a create, which is the safe direction.\n *\n * The whole canonicalization runs inside ONE transaction, for two reasons that\n * both matter: it pins a single connection (the scratch objects it needs exist\n * only inside their transaction, and a pool hands out a different connection\n * per statement), and a failure anywhere rolls the scratch away instead of\n * leaving it attached to a table this push may be about to drop.\n */\nfunction buildIndexPredicateCanonicalizer(\n driver: AnyDriver,\n migrationDriver: MigrationDriver\n): IndexPredicateCanonicalizer | undefined {\n const canonicalize = migrationDriver.canonicalizeIndexPredicates;\n if (!(canonicalize && driver.supportsTransactions)) return;\n\n return async (tableName, predicates) => {\n try {\n return await driver.withTransaction((tx) =>\n canonicalize.call(\n migrationDriver,\n tableName,\n predicates,\n (sql, params) => tx._executeRaw(sql, params)\n )\n );\n } catch {\n // Fail closed, and stay out of the way. A predicate the database cannot\n // parse, a connection that refused, a dialect that changed under us —\n // none of it may make a push fail, and none of it may be read as \"these\n // two predicates are the same\". Answering nothing leaves the differ with\n // the raw texts, which is exactly the pre-7.4 behavior.\n return predicates.map(() => undefined);\n }\n };\n}\n\n/**\n * The COMPLETE empty-to-desired program, compiled before a force-reset entry.\n *\n * §6.2: \"Before entry, serialize and validate the desired schema, resolve its\n * relation index, compile the empty-to-desired DDL, and prove that program\n * contains no commit-boundary statement.\" Diffing against the LIVE database\n * would describe a program for a database this command is about to empty, so\n * the baseline is the empty snapshot — the state the clear produces.\n *\n * Nothing here reads live state, so it runs before the clear and its result is\n * what the one locked transaction executes.\n */\nexport async function planRebuildFromEmpty(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n const current = emptyManagedSnapshot();\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(operations, current, migrationDriver),\n currentSchema: current,\n };\n}\n\nexport async function planPush(\n client: MigrationClient,\n migrationDriver: MigrationDriver,\n options: PushOptions,\n relations: ResolvedRelationIndex\n): Promise<PushPlan> {\n const desired = serializeResolvedModels(\n client.$schema,\n migrationDriver,\n relations\n );\n // Live introspection sees the private columns and index, but a text\n // discriminator cannot reveal historical public/stored member mappings.\n // Push therefore compares structure only. Stored-value history is owned by\n // file-based generate(), where both serialized snapshots are available.\n const current = withDeclaredRawTemplates(\n await introspectSchema(client.$driver, migrationDriver),\n desired\n );\n const diffOptions: DiffOptions = {\n projectRename: migrationDriver.projectNativeRename.bind(migrationDriver),\n canonicalizeIndexPredicate: buildIndexPredicateCanonicalizer(\n client.$driver,\n migrationDriver\n ),\n // `current` was just introspected. Where that introspection cannot read a\n // constraint's name back, the name it carries is a synthesis and matching\n // on it would make every unchanged constraint read as a change.\n refuseConstraintNameChurn:\n migrationDriver.capabilities.introspectionReadsConstraintNames,\n matchConstraintsByShape:\n !migrationDriver.capabilities.introspectionReadsConstraintNames,\n };\n const diffResult = await diff(current, desired, diffOptions);\n const operations = await resolvePushOperations(\n diffResult,\n desired,\n current,\n options,\n diffOptions\n );\n\n return {\n operations: prepareSchemaProgram(operations, current, migrationDriver),\n currentSchema: current,\n };\n}\n\n/**\n * The live raw indexes with the templates the schema declares for them. A\n * database holds a raw index's rendered text and its marker, never the\n * template, and a statement that re-creates the index as it is (a SQLite table\n * rebuild, a SurrealDB table moved under a new name) renders that template. A\n * template is the declared one when its index has the same name and hash.\n */\nfunction withDeclaredRawTemplates(\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): SchemaSnapshot {\n const templates = new Map<string, string>();\n for (const table of desired.tables)\n for (const index of table.indexes)\n if (index.raw?.template !== undefined)\n templates.set(`${index.name}\\0${index.raw.hash}`, index.raw.template);\n if (templates.size === 0) return current;\n return {\n ...current,\n tables: current.tables.map((table) => ({\n ...table,\n indexes: table.indexes.map((index) => {\n if (!index.raw) return index;\n const { hash } = index.raw;\n const template = templates.get(`${index.name}\\0${hash}`);\n return template === undefined\n ? index\n : { ...index, raw: { hash, template } };\n }),\n })),\n };\n}\n\nasync function resolvePushOperations(\n diffResult: DiffResult,\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n options: PushOptions,\n diffOptions: DiffOptions\n): Promise<DiffOperation[]> {\n const force = options.force ?? false;\n const allEnumRemovals = detectEnumValueRemovals(\n diffResult.operations,\n current\n );\n\n if (options.resolve) {\n return resolveWithCallback(\n diffResult,\n current,\n desired,\n diffOptions,\n allEnumRemovals,\n options.resolve,\n force\n );\n }\n\n if (force) {\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n alwaysAddDropResolver,\n diffOptions\n );\n return applyForceEnumResolutions(resolvedOperations, allEnumRemovals);\n }\n\n rejectUnresolvedChanges(diffResult, allEnumRemovals);\n return [...diffResult.operations];\n}\n\nasync function resolveWithCallback(\n diffResult: DiffResult,\n current: SchemaSnapshot,\n desired: SchemaSnapshot,\n diffOptions: DiffOptions,\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force = false\n): Promise<DiffOperation[]> {\n const admittedAmbiguousDrops = new Set<string>();\n const ambiguityResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = validateResolveResult(\n \"ambiguous\",\n resolveChange,\n await resolve(resolveChange)\n );\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${resolveChange.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n if (result === undefined) {\n if (force) {\n resolutions.set(change, { type: \"addAndDrop\" });\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n continue;\n }\n const advice =\n change.type === \"ambiguousTable\"\n ? `If \"${change.droppedTable}\" is not this schema's table, set migrations.tables so push does not manage it; otherwise name the pair with change.rename() or change.addAndDrop().`\n : \"Return change.rename() or change.addAndDrop() from the resolver.\";\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n${advice}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n resolutions.set(change, {\n type: result === \"rename\" ? \"rename\" : \"addAndDrop\",\n });\n if (result !== \"rename\") {\n admittedAmbiguousDrops.add(ambiguousDropKey(change));\n }\n }\n return resolutions;\n };\n\n const resolvedOperations = await resolveAmbiguousChanges(\n diffResult,\n current,\n desired,\n ambiguityResolver,\n diffOptions\n );\n const resolvedEnumRemovals = retargetEnumRemovals(\n enumRemovals,\n current,\n resolvedOperations,\n diffOptions.projectRename\n );\n await approveDestructiveOperations(\n resolvedOperations,\n resolve,\n force,\n admittedAmbiguousDrops\n );\n const finalOperations: DiffOperation[] = resolvedOperations.filter(\n (op) => op.type !== \"alterEnum\"\n );\n const enumColumnMappings = await resolveEnumValueRemovalMappings(\n resolvedEnumRemovals,\n resolve,\n force\n );\n\n finalOperations.push(\n ...applyResolvedEnumMappings(resolvedOperations, enumColumnMappings)\n );\n\n return sortOperations(finalOperations);\n}\n\nfunction retargetEnumRemovals(\n removals: EnumRemoval[],\n current: SchemaSnapshot,\n operations: DiffOperation[],\n projectRename: typeof applyNativeRename = applyNativeRename\n): EnumRemoval[] {\n let renamedCurrent = current;\n for (const operation of operations) {\n if (operation.type === \"renameTable\" || operation.type === \"renameColumn\") {\n renamedCurrent = projectRename(renamedCurrent, operation);\n }\n }\n\n return removals.map((removal) => {\n const tablePosition = current.tables.findIndex(\n (table) => table.name === removal.tableName\n );\n const currentTable = current.tables[tablePosition];\n const columnPosition = currentTable?.columns.findIndex(\n (column) => column.name === removal.columnName\n );\n const table = renamedCurrent.tables[tablePosition];\n const column =\n columnPosition === undefined ? undefined : table?.columns[columnPosition];\n if (!(currentTable && table && column)) {\n throw new MigrationError(\n `Cannot retarget enum removal for \"${removal.tableName}.${removal.columnName}\" through the accepted renames.`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n return { ...removal, tableName: table.name, columnName: column.name };\n });\n}\n\nfunction rejectUnresolvedChanges(\n diffResult: {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n },\n enumRemovalsNeedingResolution: EnumRemoval[]\n): void {\n const destructiveOps = diffResult.operations.filter(isDestructiveOperation);\n const hasAmbiguous = diffResult.ambiguousChanges.length > 0;\n\n if (\n destructiveOps.length === 0 &&\n !hasAmbiguous &&\n enumRemovalsNeedingResolution.length === 0\n ) {\n return;\n }\n\n const descriptions: string[] = [];\n\n for (const op of destructiveOps) {\n descriptions.push(formatDestructiveOperation(op));\n }\n\n for (const change of diffResult.ambiguousChanges) {\n descriptions.push(formatAmbiguousChangeDescription(change));\n }\n\n for (const removal of enumRemovalsNeedingResolution) {\n descriptions.push(\n `[enumValueRemoval] \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - removing values: ${removal.removedValues.join(\", \")} (non-nullable)`\n );\n }\n\n throw new MigrationError(\n `Changes requiring resolution detected:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Provide a resolve callback to choose each change explicitly.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n}\n","/**\n * The ONE live-namespace reset owner (§6.2).\n *\n * Three programs used to invent reset SQL: the CLI's own dynamic loop, the\n * dialect drivers' `generateResetSQL()`, and `push({ forceReset: true })`. They\n * disagreed — MySQL's dialect answer dropped nothing at all, and PostgreSQL's\n * enumerated `public` regardless of the estate — so this module replaces all\n * three. Migration `reset()` and force-reset push both keep the migration\n * control pair: a clear drops neither table.\n *\n * Containment is the point: the inventory is a bound catalog read scoped to the\n * configured namespace, foreign keys inside it are dropped explicitly rather\n * than cascaded away, and nothing here issues `DROP SCHEMA`, `DROP DATABASE`,\n * or `FOREIGN_KEY_CHECKS = 0`.\n *\n * {@link planLiveNamespaceReset} decides and renders the whole clear from\n * catalog reads, before the first effect. Every refusal lives there, so no\n * caller's commit-model reporter can restate a containment refusal as a failure\n * part-way through a program that never began.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { CONTROL_TABLES } from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { childrenBeforeParents, type TableReference } from \"./drop-order\";\nimport { introspectSchema } from \"./push/planner\";\nimport type { ForeignKeyDef, SchemaSnapshot } from \"./types\";\nimport { createQueryExecutor } from \"./utils\";\n\n/** One table this reset drops, and the statement that drops it. */\ninterface PlannedTableDrop {\n readonly name: string;\n readonly sql: string;\n}\n\n/**\n * The COMPLETE clear, decided and rendered — and nothing executed.\n *\n * The split is the point (§6.2). Everything that can REFUSE the clear —\n * proving the namespace, reading the inventory, both containment refusals, the\n * drop order — is answered from catalog reads, so it belongs before the caller\n * enters a commit model at all. A refusal that has already been wrapped in\n * MySQL's partial-commit reporter tells the caller a database nothing touched\n * \"failed partway through\", and loses the metadata naming the constraint that\n * made it refuse.\n */\nexport interface LiveNamespaceResetPlan {\n /**\n * Every foreign key the estate owns, as an explicit drop, or SQLite's one\n * deferral of them all ({@link clearForeignKeys}).\n */\n readonly dropForeignKeys: string[];\n /** The tables this reset drops, in the order they will be dropped. */\n readonly dropTables: readonly PlannedTableDrop[];\n /** Managed enum drops, which run after the tables that use them. */\n readonly dropEnums: string[];\n /** The whole clear, in the order it runs: keys, then tables, then enums. */\n readonly clear: readonly string[];\n}\n\nexport interface LiveNamespaceInventory {\n /** The estate's dependency graph, as the catalog describes it. */\n readonly snapshot: SchemaSnapshot;\n /** Every table in the configured namespace. */\n readonly tables: string[];\n /** Every managed enum type, on dialects that have them. */\n readonly enums: string[];\n}\n\n/**\n * Proves the configured namespace and reads what a reset would touch.\n *\n * ONE owner for both consumers — the effectful reset and the dry run that\n * previews it — because a preview computed a different way is not a preview.\n * `introspect` is what proves the namespace exists before anything is\n * published, and it refuses a foreign key with exactly one side inside the\n * estate, so a cross-namespace dependency is refused BEFORE the first DDL\n * rather than discovered after half the estate is gone.\n *\n * The snapshot describes the GRAPH; the bound catalog read decides MEMBERSHIP,\n * because a table the snapshot cannot model is still a table in this namespace\n * and a reset that skipped it would leave the estate half-cleared. For the same\n * reason the membership read is the one provider result this owner refuses to\n * treat as advisory: see {@link readNames}.\n */\nexport async function inventoryLiveNamespace(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<LiveNamespaceInventory> {\n const snapshot = await introspectSchema(driver, migrationDriver);\n\n const executor = createQueryExecutor(driver);\n const inventory = migrationDriver.generateInventoryTables();\n const tables = readNames(\n await executor(inventory.sql, inventory.params),\n \"table\"\n ).filter(\n (name) =>\n migrationDriver.target.tables === undefined ||\n migrationDriver.target.tables.includes(name)\n );\n\n const enumInventory = migrationDriver.generateInventoryEnums();\n const enums = enumInventory\n ? readNames(\n await executor(enumInventory.sql, enumInventory.params),\n \"managed enum\"\n )\n : [];\n\n return {\n snapshot,\n tables,\n enums:\n migrationDriver.target.tables === undefined\n ? enums\n : enums.filter((name) =>\n snapshot.enums?.some((item) => item.name === name)\n ),\n };\n}\n\n/**\n * Decides and renders the COMPLETE clear, without executing any of it.\n *\n * Namespace proof, inventory, both containment refusals, foreign-key\n * materialization and drop order all happen here, so every way this clear can\n * refuse is answered from catalog reads alone — before the caller enters a\n * transaction or a sequential program, and therefore before anything can\n * describe a refusal as a partial commit (§6.2). It is also what lets a dry run\n * preview the effectful path rather than a second computation of it.\n *\n * @param driver - the producer to read the catalog on; the caller has already\n * pinned and locked it where its dialect has a lock to take\n * @param migrationDriver - the estate-bound migration driver\n */\nexport async function planLiveNamespaceReset(\n driver: AnyDriver,\n migrationDriver: BoundMigrationDriver\n): Promise<LiveNamespaceResetPlan> {\n const { snapshot, tables, enums } = await inventoryLiveNamespace(\n driver,\n migrationDriver\n );\n\n // MySQL is the one dialect whose DDL commits as it runs, and it cannot make\n // the tracking clear and the destructive DDL one transaction — so an inbound\n // foreign key to the declared tracking table has no safe order: dropping that\n // key first opens a window where the history rows are still there and their\n // schema is going away, and clearing or dropping the referenced table first\n // can simply be blocked.\n if (migrationDriver.target.dialect === \"mysql\") {\n assertNoInboundTrackingReference(snapshot, CONTROL_TABLES.state);\n }\n\n // Drop every foreign key the estate owns, explicitly, before any table\n // drop. This is what replaces `CASCADE` and `FOREIGN_KEY_CHECKS = 0`:\n // cycles and mutually-dropped tables are handled, and a dependency this\n // inventory does NOT represent aborts the operation instead of being\n // deleted with it.\n const dropForeignKeys = clearForeignKeys(\n migrationDriver,\n ownedForeignKeys(snapshot, tables)\n );\n\n // The control pair survives every clear: its structure is the history.\n const droppable = tables.filter(\n (name) => name !== CONTROL_TABLES.state && name !== CONTROL_TABLES.log\n );\n\n const dropTables: PlannedTableDrop[] = [];\n for (const table of dependencySafeOrder(droppable, snapshot)) {\n dropTables.push({\n name: table,\n sql: migrationDriver.generateDropTableSQL(table),\n });\n }\n\n // Managed enums go after their tables: a type still used by a column is\n // a dependency, and `RESTRICT` is the point.\n const dropEnums: string[] = [];\n for (const enumName of enums) {\n const statement = migrationDriver.generateDropEnumSQL(enumName);\n if (statement) {\n dropEnums.push(statement);\n }\n }\n\n return {\n dropForeignKeys,\n dropTables,\n dropEnums,\n clear: [\n ...dropForeignKeys,\n ...dropTables.map((table) => table.sql),\n ...dropEnums,\n ],\n };\n}\n\n/**\n * The statements that take the owned keys out of the way of the table drops.\n *\n * A dialect that keeps keys inline in `CREATE TABLE` (SQLite) cannot drop one\n * short of rebuilding its table, and its `DROP TABLE` checks the keys of every\n * row it removes, which a cycle or a self-referencing `RESTRICT` fails in any\n * order. There one statement defers every key to the COMMIT, by which point\n * each table holding one is gone.\n */\nfunction clearForeignKeys(\n migrationDriver: BoundMigrationDriver,\n owned: Iterable<{ table: string; foreignKey: ForeignKeyDef }>\n): string[] {\n const statements: string[] = [];\n for (const { table, foreignKey } of owned) {\n if (!migrationDriver.capabilities.supportsAddForeignKeyViaAlter) {\n return [\"PRAGMA defer_foreign_keys = ON\"];\n }\n statements.push(\n migrationDriver.generateDDL(\n { type: \"dropForeignKey\", tableName: table, fkName: foreignKey.name },\n { destination: \"live\" }\n )\n );\n }\n return statements;\n}\n\n/** Every foreign key owned by a table this reset is about to drop. */\nfunction* ownedForeignKeys(\n snapshot: SchemaSnapshot,\n tables: readonly string[]\n): Generator<{ table: string; foreignKey: ForeignKeyDef }> {\n const inventoried = new Set(tables);\n for (const table of snapshot.tables) {\n if (!inventoried.has(table.name)) {\n continue;\n }\n for (const foreignKey of table.foreignKeys) {\n yield { table: table.name, foreignKey };\n }\n }\n}\n\n/**\n * Children before parents, with a stable fallback for cycles.\n *\n * Every foreign key inside the estate has already been dropped by the time\n * these run, so the order is defence rather than necessity: it keeps a\n * constraint the inventory could not see from turning a reset into a failure\n * that has already dropped half the estate. A cycle's keys are already\n * dropped too, so its tables go in inventory order rather than deadlocking.\n */\nfunction dependencySafeOrder(\n tables: readonly string[],\n snapshot: SchemaSnapshot\n): string[] {\n const references: TableReference[] = [];\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== table.name) {\n references.push({ from: table.name, to: foreignKey.referencedTable });\n }\n }\n }\n const { ordered, blocked } = childrenBeforeParents(\n tables,\n (name) => name,\n references\n );\n return [...ordered, ...blocked];\n}\n\n/** Refuses an inbound foreign key to the declared tracking table. */\nfunction assertNoInboundTrackingReference(\n snapshot: SchemaSnapshot,\n trackingTableName: string\n): void {\n for (const table of snapshot.tables) {\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.referencedTable !== trackingTableName) {\n continue;\n }\n throw new MigrationError(\n `Table \"${table.name}\" holds a foreign key \"${foreignKey.name}\" referencing the migration tracking table \"${trackingTableName}\", so this reset has no safe order and is refused before any statement runs. ` +\n \"MySQL commits DDL implicitly, so the tracking rows cannot be cleared and the schema torn down as one operation; drop the constraint yourself and re-run.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: table.name,\n constraint: foreignKey.name,\n referencedTable: trackingTableName,\n },\n }\n );\n }\n }\n}\n\n/**\n * Why an inventory this read cannot trust refuses the WHOLE clear.\n *\n * One sentence for both refusals below, because they have one reason: the\n * alternative to refusing is a reset that clears part of a namespace and\n * reports success.\n */\nconst UNTRUSTED_INVENTORY =\n \"A reset drops exactly what its inventory names and leaves everything else, so an inventory this read cannot trust would clear part of the namespace and report that it cleared all of it. The whole clear is refused before any statement runs.\";\n\n/**\n * Reads the `name` column off provider-shaped inventory rows, or REFUSES.\n *\n * The inventory is not a report; it is the DROP LIST. Everything it names is\n * destroyed and everything it does not name survives, so a row this read\n * SKIPPED took a real object off the list — the clear then reported success\n * over a namespace it had half cleared, and the rebuild that followed collided\n * with what was left. A repeated name is the same defect written differently:\n * one object planned twice while another was never planned at all.\n *\n * So the read fails closed, and it fails HERE — among\n * {@link planLiveNamespaceReset}'s catalog reads, before a destructive\n * statement exists to have run.\n */\nfunction readNames(rows: readonly unknown[], inventory: string): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const [index, row] of rows.entries()) {\n const name = readName(row, index, inventory);\n if (seen.has(name)) {\n throw new MigrationError(\n `The ${inventory} inventory for this reset named \"${name}\" twice, at position ${index}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: { type: \"duplicate-reset-inventory-name\", resultIndex: index },\n }\n );\n }\n seen.add(name);\n names.push(name);\n }\n return names;\n}\n\n/** The one object an inventory row names, or the refusal it earns. */\nfunction readName(row: unknown, index: number, inventory: string): string {\n // The cause is already an `Error` here: the one caller that has a thrown value\n // normalizes it through {@link errorCause} first. Deciding it here instead\n // meant a bare `thrown instanceof Error`, which BOTH dropped every non-`Error`\n // a provider row threw and, against a Proxy whose `getPrototypeOf` trap\n // throws, replaced this typed refusal with the trap's own error.\n const refuse = (reason: string, cause?: Error): MigrationError =>\n new MigrationError(\n `The ${inventory} inventory for this reset returned a row at position ${index} that does not name one object: ${reason}. ${UNTRUSTED_INVENTORY}`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n cause,\n meta: { type: \"unreadable-reset-inventory\", resultIndex: index },\n }\n );\n\n // The executor's contract is `unknown[]`, so this is where a provider row\n // becomes an object at all. A driver's own result contract already refuses a\n // non-object row (`drivers/normalized-result.ts`), which is why no falsifier\n // reaches this line through a driver; what it decides is that the answer for\n // a row from anywhere else is a refusal rather than a shorter drop list.\n if (typeof row !== \"object\" || row === null) {\n throw refuse(`the row is ${row === null ? \"null\" : `a ${typeof row}`}`);\n }\n\n let name: unknown;\n try {\n // Reading a column off a provider's row runs the provider's code, and its\n // failure is still this inventory refusing to be read.\n //\n // OWN properties only, because this inventory names objects a CATALOG\n // reported and a catalog reports columns: a `name` reached through the\n // prototype chain is a carrier's property or `Object.prototype` pollution,\n // and honouring one puts an object on the DROP LIST that no catalog ever\n // named. Asking whether the row owns the column runs the provider's code\n // too — a proxy answers that with a trap — so the ownership test shares\n // this `try` and refuses identically. It is not a second read of the value:\n // it consults the descriptor, not the getter.\n name = Object.hasOwn(row, \"name\") ? Reflect.get(row, \"name\") : undefined;\n } catch (failure) {\n throw refuse(\"reading its `name` threw\", errorCause(failure));\n }\n\n if (typeof name !== \"string\") {\n throw refuse(\n `its \\`name\\` is ${name === undefined ? \"not a column of the row\" : `a ${typeof name}`}`\n );\n }\n // An empty name renders as a quoted nothing, so the statement it would\n // produce does not drop the object the provider meant to report.\n if (name.length === 0) {\n throw refuse(\"its `name` is the empty string\");\n }\n return name;\n}\n","/**\n * One SQL blob builder. Every check and effect dispatch in a state shares\n * one content-addressed blob. No second blob for rollback.\n */\n\nimport type { Sha256 } from \"./identity\";\nimport { composeSqlBlob, refuseMysqlDelimiter } from \"./sql-blob\";\nimport { encodeDispatchIdentity } from \"./v1-parse\";\nimport type { MigrationDispatchV1, MigrationParameterV1 } from \"./v1-types\";\n\ninterface PendingFragment {\n readonly text: string;\n readonly parameters: readonly MigrationParameterV1[];\n}\n\nexport class SqlAssembly {\n private readonly pending: PendingFragment[] = [];\n\n add(text: string, parameters: readonly MigrationParameterV1[] = []): number {\n refuseMysqlDelimiter(text);\n this.pending.push({ text, parameters });\n return this.pending.length - 1;\n }\n\n seal(): {\n readonly bytes: Uint8Array;\n readonly sqlHash: Sha256;\n readonly dispatches: readonly MigrationDispatchV1[];\n } {\n const blob = composeSqlBlob(this.pending.map((fragment) => fragment.text));\n const dispatches = this.pending.map((fragment, index) => {\n const range = blob.ranges[index]!;\n return {\n dispatchId: encodeDispatchIdentity(\n blob.sqlHash,\n range.offset,\n range.length,\n fragment.parameters\n ),\n sqlHash: blob.sqlHash,\n offset: range.offset,\n length: range.length,\n parameters: fragment.parameters,\n };\n });\n return { bytes: blob.bytes, sqlHash: blob.sqlHash, dispatches };\n }\n}\n","import { errorCause } from \"../errors/diagnostic-safety\";\nimport { isDestructiveOperation } from \"./differ\";\nimport { formatOperation } from \"./push/format\";\n/**\n * History-free push plan: live diff or force-reset rebuild, compiled\n * statements, and plan hash. This module does not execute SQL.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { isRecord } from \"../validation/value-guards\";\nimport { canonicalizeJson, canonicalizeJsonText } from \"./canonical-json\";\nimport { classifyGeneratedAtomicity, dispatchAt } from \"./compile\";\nimport { CONTROL_TABLES } from \"./control\";\nimport type {\n BoundMigrationDriver,\n DDLContext,\n MigrationDriver,\n} from \"./drivers\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n type LiveNamespaceResetPlan,\n planLiveNamespaceReset,\n} from \"./live-reset\";\nimport {\n type MigrationClient,\n type PushOptions as PlannerPushOptions,\n planPush,\n planRebuildFromEmpty,\n} from \"./push/planner\";\nimport type { ParsedPlanningOptions } from \"./push-consent\";\nimport {\n canonicalValue,\n fingerprintLive,\n freezeDeep,\n hashSnapshot,\n pushTargetIdentity,\n} from \"./push-fingerprint\";\nimport { serializeResolvedModels } from \"./serializer\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport {\n type DiffOperation,\n type ResolveCallback,\n type ResolveChange,\n type ResolveResult,\n readEnumResolutionDecision,\n type SchemaSnapshot,\n} from \"./types\";\nimport type {\n AtomicityClass,\n MigrationDispatchV1,\n PushConsent,\n PushOperation,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PlannedStatement {\n readonly kind: \"clear\" | \"effect\";\n readonly operationId: string;\n /** The index of the operation it is part of, in `operations`; none for a clear. */\n readonly operation?: number | undefined;\n readonly dispatch: MigrationDispatchV1;\n}\n\nexport interface InternalPushPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly desiredSchema: SchemaSnapshot;\n readonly schemaHash: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly reportedOperations: readonly PushOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly previewStatements: readonly PushStatementPreview[];\n readonly sqlBlob: Uint8Array;\n readonly atomicity: AtomicityClass;\n readonly destructive: boolean;\n}\n\ntype ResolutionSource =\n | {\n readonly kind: \"record\";\n readonly callback: ResolveCallback | undefined;\n }\n | {\n readonly kind: \"replay\";\n readonly resolutions: readonly PushResolution[];\n };\n\ninterface ResolutionController {\n readonly callback: ResolveCallback;\n finish(): readonly PushResolution[];\n}\n\nexport async function buildPushPlan(\n client: MigrationClient,\n producer: AnyDriver,\n command: BoundMigrationDriver,\n relations: ResolvedRelationIndex,\n options: ParsedPlanningOptions,\n resolutionSource: ResolutionSource\n): Promise<InternalPushPlan> {\n const controller = resolutionController(resolutionSource);\n const plannerOptions: PlannerPushOptions = {\n skipValidation: options.skipValidation,\n resolve: controller.callback,\n };\n const planningDriver = managedPlanningDriver(command);\n const desired = serializeResolvedModels(\n client.$schema,\n planningDriver,\n relations\n );\n await command.preflightSchemaRequirements(\n [desired],\n (sql, params) => producer._executeRaw(sql, params),\n []\n );\n const mode: PushConsent[\"mode\"] = options.forceReset ? \"force-reset\" : \"diff\";\n\n let reset: LiveNamespaceResetPlan | undefined;\n let current: SchemaSnapshot;\n let operations: readonly DiffOperation[];\n if (options.forceReset) {\n current = await introspectManaged(producer, command);\n reset = await planLiveNamespaceReset(producer, command);\n const rebuild = await planRebuildFromEmpty(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n operations = rebuild.operations;\n } else {\n const planned = await planPush(\n { $driver: producer, $schema: client.$schema },\n planningDriver,\n plannerOptions,\n relations\n );\n current = planned.currentSchema;\n operations = await withEnumDependentChecks(\n producer,\n command,\n planned.operations\n );\n }\n if (!options.forceReset)\n for (const operation of operations) {\n if (\n operation.type !== \"addColumn\" ||\n operation.column.nullable ||\n operation.column.default !== undefined ||\n operation.column.autoIncrement\n )\n continue;\n const tableName = liveTableName(operations, operation.tableName);\n if (!current.tables.some((table) => table.name === tableName)) continue;\n if (await command.tableHoldsRows(producer, tableName))\n throw new MigrationError(\n `Cannot add required column \"${operation.tableName}.${operation.column.name}\" without a database default to a populated table. Application function/generator defaults do not backfill stored rows. Author a manual data migration that adds a nullable column, fills it, and then makes it required. No migration effects were executed.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n {\n meta: {\n table: operation.tableName,\n column: operation.column.name,\n command: \"push\",\n hint: \"Use a reviewed manual migration for explicit backfill before making the column required.\",\n },\n }\n );\n }\n if (!options.forceReset)\n await refuseOrphanedDiscriminators(\n producer,\n command,\n desired,\n current,\n operations\n );\n const resolutions = controller.finish();\n const target = await pushTargetIdentity(producer, command);\n const sourceFingerprint = await fingerprintLive(current, command, producer);\n const desiredFingerprint = await fingerprintLive(desired, command, producer);\n const schemaHash = hashSnapshot(desired);\n const compiled = compilePlanStatements(\n reset,\n operations,\n planningDriver,\n options.forceReset ? emptyManagedSnapshot() : current\n );\n await command.preflightSchemaRequirements(\n [],\n (sql, params) => producer._executeRaw(sql, params),\n compiled.statements.map((statement) =>\n sliceDispatch(compiled.bytes, statement.dispatch)\n ),\n // On Neki each statement commits alone.\n true\n );\n const reportedOperations: PushOperation[] = operations.map(\n (operation, index) => ({\n id: `${operation.type}:${index}`,\n label: formatOperation(operation),\n // A live table rename takes its old name from every other reader, and a\n // history-free push cannot prove that table was ever this schema's.\n risk:\n isDestructiveOperation(operation) || operation.type === \"renameTable\"\n ? \"destructive\"\n : \"safe\",\n })\n );\n const atomicity = classifyGeneratedAtomicity(command, operations, !!reset);\n const destructive =\n mode === \"force-reset\" ||\n reportedOperations.some((operation) => operation.risk === \"destructive\");\n const validation: PushConsent[\"validation\"] = options.skipValidation\n ? \"structural-only\"\n : \"full\";\n const planHash = hashPushPlan({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n schemaHash,\n resolutions,\n operations,\n statements: compiled.statements,\n atomicity,\n });\n\n return freezeDeep({\n mode,\n validation,\n target,\n sourceFingerprint,\n desiredFingerprint,\n desiredSchema: desired,\n schemaHash,\n planHash,\n resolutions,\n operations,\n reportedOperations,\n statements: compiled.statements,\n previewStatements: compiled.statements.map((statement) => ({\n sql: sliceDispatch(compiled.bytes, statement.dispatch),\n parameters: statement.dispatch.parameters,\n })),\n sqlBlob: compiled.bytes,\n atomicity,\n destructive,\n });\n}\n\nexport function compilePlanStatements(\n reset: LiveNamespaceResetPlan | undefined,\n operations: readonly DiffOperation[],\n driver: MigrationDriver,\n currentSchema: SchemaSnapshot\n): {\n readonly bytes: Uint8Array;\n readonly statements: readonly PlannedStatement[];\n} {\n const assembly = new SqlAssembly();\n const pending: Array<{\n readonly kind: PlannedStatement[\"kind\"];\n readonly operationId: string;\n readonly operation?: number;\n readonly index: number;\n }> = [];\n\n for (const [index, sql] of (reset?.clear ?? []).entries()) {\n pending.push({\n kind: \"clear\",\n operationId: `force-reset:clear:${index}`,\n index: assembly.add(sql),\n });\n }\n\n for (const [operationIndex, operation] of operations.entries()) {\n const context: DDLContext = {\n destination: \"live\",\n currentSchema,\n precedingOperations: operations.slice(0, operationIndex),\n followingOperations: operations.slice(operationIndex + 1),\n };\n const statements = driver.compileStatements(operation, context);\n for (const [statementIndex, sql] of statements.entries()) {\n pending.push({\n kind: \"effect\",\n operationId: `${operation.type}:${operationIndex}:${statementIndex}`,\n operation: operationIndex,\n index: assembly.add(sql),\n });\n }\n }\n\n const sealed = assembly.seal();\n return {\n bytes: sealed.bytes,\n statements: pending.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n operation: statement.operation,\n dispatch: dispatchAt(sealed.dispatches, statement.index),\n })),\n };\n}\n\nexport function hashPushPlan(input: {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly desiredFingerprint: Sha256;\n readonly schemaHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n readonly operations: readonly DiffOperation[];\n readonly statements: readonly PlannedStatement[];\n readonly atomicity: AtomicityClass;\n}): Sha256 {\n return domainHash(\n HASH_DOMAIN.plan,\n canonicalizeJson(\n canonicalValue({\n mode: input.mode,\n validation: input.validation,\n target: input.target,\n sourceFingerprint: input.sourceFingerprint,\n desiredFingerprint: input.desiredFingerprint,\n schemaHash: input.schemaHash,\n resolutions: input.resolutions,\n operations: input.operations,\n atomicity: input.atomicity,\n // Review SQL is intentionally absent. Dispatch identity authenticates\n // the sealed statement bytes, exact ranges, and typed parameters.\n statements: input.statements.map((statement) => ({\n kind: statement.kind,\n operationId: statement.operationId,\n dispatch: statement.dispatch,\n })),\n })\n )\n );\n}\n\nexport async function introspectManaged(\n producer: AnyDriver,\n driver: MigrationDriver\n): Promise<SchemaSnapshot> {\n return withoutControlTables(\n await driver.introspect((sql, params) => producer._executeRaw(sql, params))\n );\n}\n\nfunction managedPlanningDriver(\n driver: BoundMigrationDriver\n): BoundMigrationDriver {\n const managed: BoundMigrationDriver = Object.create(driver);\n Object.defineProperty(managed, \"introspect\", {\n value: async (\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ) => withoutControlTables(await driver.introspect(executeRaw)),\n });\n Object.freeze(managed);\n return managed;\n}\n\nfunction withoutControlTables(snapshot: SchemaSnapshot): SchemaSnapshot {\n return {\n ...snapshot,\n tables: snapshot.tables.filter(\n (table) =>\n table.name !== CONTROL_TABLES.state && table.name !== CONTROL_TABLES.log\n ),\n };\n}\n\n/**\n * A schema snapshot models no CHECK constraint, so the ones on the columns an\n * enum change converts are read from the live catalog here and closed into its\n * operation: the preview shows their DROP and ADD, the plan hash covers them,\n * and the locked replan reads them again, so one added or changed after the\n * preview refuses its consent.\n */\nasync function withEnumDependentChecks(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n operations: readonly DiffOperation[]\n): Promise<readonly DiffOperation[]> {\n const enumNames = operations.flatMap((operation) =>\n operation.type === \"alterEnum\" && operation.dependentColumns\n ? [operation.enumName]\n : []\n );\n if (!command.readEnumDependentChecks || enumNames.length === 0)\n return operations;\n const checks = await command.readEnumDependentChecks(\n enumNames,\n (sql, params) => producer._executeRaw(sql, params)\n );\n return operations.map((operation) => {\n if (operation.type !== \"alterEnum\") return operation;\n const dependentChecks = checks.flatMap(({ enumName, ...check }) =>\n enumName === operation.enumName ? [check] : []\n );\n return dependentChecks.length === 0\n ? operation\n : { ...operation, dependentChecks };\n });\n}\n\n/** The live name of a desired table: an accepted rename still reads the old one. */\nfunction liveTableName(\n operations: readonly DiffOperation[],\n tableName: string\n): string {\n const rename = operations.find(\n (candidate) =>\n candidate.type === \"renameTable\" && candidate.to === tableName\n );\n return rename?.type === \"renameTable\" ? rename.from : tableName;\n}\n\n/**\n * Push keeps no polymorphic history — `diff` refuses a stored-value change only\n * between authored snapshots — so the stored discriminators are that history:\n * a row whose discriminator the desired schema no longer declares would be\n * orphaned. Only a to-one slot stores its discriminator in rows; a collection\n * member's junction table is the member itself.\n */\nasync function refuseOrphanedDiscriminators(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n desired: SchemaSnapshot,\n current: SchemaSnapshot,\n operations: readonly DiffOperation[]\n): Promise<void> {\n for (const slot of desired.polymorphicStorage ?? []) {\n if (slot.kind !== \"toOne\") continue;\n const tableName = liveTableName(operations, slot.ownerTable);\n const rename = operations.find(\n (candidate) =>\n candidate.type === \"renameColumn\" &&\n candidate.tableName === slot.ownerTable &&\n candidate.to === slot.storageRef\n );\n const columnName =\n rename?.type === \"renameColumn\" ? rename.from : slot.storageRef;\n const live = current.tables.find((table) => table.name === tableName);\n if (!live?.columns.some((column) => column.name === columnName)) continue;\n const orphan = await command.undeclaredValue(\n producer,\n tableName,\n columnName,\n slot.members.map((member) => member.storedType)\n );\n if (orphan)\n throw new MigrationError(\n `Polymorphic storage \"${slot.ownerTable}.${slot.relation}\" stores \"${String(orphan.stored)}\", which the desired schema no longer declares; those rows would lose their target. Author an explicit manual data transition that rewrites the stored values. No migration effects were executed.`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED,\n {\n meta: {\n table: slot.ownerTable,\n relation: slot.relation,\n command: \"push\",\n },\n }\n );\n }\n}\n\nfunction resolutionController(source: ResolutionSource): ResolutionController {\n if (source.kind === \"record\") {\n const recorded: PushResolution[] = [];\n return {\n callback: async (change) => {\n const result = source.callback\n ? await source.callback(change)\n : defaultResolution(change);\n const decision = closeResolution(change, result);\n if (decision) {\n recorded.push({ id: resolutionId(change), decision });\n }\n return result;\n },\n finish: () => freezeDeep([...recorded]),\n };\n }\n\n let cursor = 0;\n return {\n callback: (change) => {\n const expected = source.resolutions[cursor++];\n if (!expected || expected.id !== resolutionId(change)) {\n throw new MigrationError(\n \"The locked push requested a different set of resolutions\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n return replayResolution(change, expected.decision);\n },\n finish: () => {\n if (cursor !== source.resolutions.length) {\n throw new MigrationError(\n \"The locked push no longer requests every consented resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n return source.resolutions;\n },\n };\n}\n\nfunction defaultResolution(change: ResolveChange): ResolveResult | undefined {\n // Destructive operations have one interpretation. Closing `proceed` lets a\n // preview describe it, while exact plan consent remains mandatory.\n if (change.type === \"destructive\") return change.proceed();\n return undefined;\n}\n\nfunction closeResolution(\n change: ResolveChange,\n result: ResolveResult | undefined | void\n): string | undefined {\n if (result === undefined) return undefined;\n if (result === \"reject\") return \"reject\";\n if (change.type === \"destructive\") {\n if (result !== \"proceed\") invalidResolution(change);\n return \"proceed\";\n }\n if (change.type === \"ambiguous\") {\n if (result !== \"rename\" && result !== \"addAndDrop\") {\n invalidResolution(change);\n }\n return result;\n }\n if (result !== \"enumMapped\") invalidResolution(change);\n const decision = readEnumResolutionDecision(change);\n if (decision?.kind === \"mapValues\") {\n return `map:${canonicalizeJsonText(canonicalValue(decision.mappings))}`;\n }\n if (decision?.kind === \"useNull\") {\n if (!change.isNullable) {\n throw new MigrationError(\n \"A non-nullable enum column cannot resolve removed values to NULL\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n return \"useNull\";\n }\n invalidResolution(change);\n}\n\nfunction invalidResolution(change: ResolveChange): never {\n throw new MigrationError(\n `The resolve callback returned an invalid resolution result for a ${change.type} change. ` +\n \"Return one of the methods on the exact change object that was supplied; a result for another change kind cannot authorize this migration.\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { type: \"invalid-resolution-result\" } }\n );\n}\n\nfunction replayResolution(\n change: ResolveChange,\n decision: string\n): ResolveResult {\n if (change.type === \"destructive\" && decision === \"proceed\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n if (decision === \"rename\") return change.rename();\n if (decision === \"addAndDrop\") return change.addAndDrop();\n }\n if (change.type === \"enumValueRemoval\") {\n if (decision === \"useNull\" && change.isNullable) return change.useNull();\n if (decision.startsWith(\"map:\")) {\n return change.mapValues(parseResolutionMap(decision.slice(4)));\n }\n }\n throw new MigrationError(\n \"Push consent contains a resolution that is invalid for the locked request\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n}\n\nfunction resolutionId(change: ResolveChange): string {\n const identity =\n change.type === \"enumValueRemoval\"\n ? {\n type: change.type,\n enumName: change.enumName,\n tableName: change.tableName,\n columnName: change.columnName,\n isNullable: change.isNullable,\n removedValues: change.removedValues,\n availableValues: change.availableValues,\n }\n : {\n type: change.type,\n operation: change.operation,\n table: change.table,\n column: change.column ?? null,\n oldName:\n change.type === \"ambiguous\" ? (change.oldName ?? null) : null,\n newName:\n change.type === \"ambiguous\" ? (change.newName ?? null) : null,\n oldType:\n change.type === \"ambiguous\" ? (change.oldType ?? null) : null,\n newType:\n change.type === \"ambiguous\" ? (change.newType ?? null) : null,\n };\n return domainHash(HASH_DOMAIN.plan, canonicalizeJson(identity));\n}\n\nfunction parseResolutionMap(text: string): Record<string, string | null> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (cause) {\n throw new MigrationError(\n \"Push consent contains a malformed enum resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n { cause: errorCause(cause) }\n );\n }\n if (!isRecord(parsed) || canonicalizeJsonText(parsed) !== text) {\n throw new MigrationError(\n \"Push consent contains a non-canonical enum resolution\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n const result: Record<string, string | null> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value !== \"string\" && value !== null) {\n throw new MigrationError(\n \"Push consent enum mappings must contain only strings or null\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH\n );\n }\n result[key] = value;\n }\n return result;\n}\n","/**\n * Whether the live database is what the durable record says (plan D5, S5):\n * the marker's standing in a history, drift against an authenticated\n * snapshot, and the lock not let go since a decision. One function per proof;\n * nothing here knows a command or a transport.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n type appendLedger,\n CONTROL_TABLES,\n readControlState,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff } from \"./differ\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport { type MigrationGraph, requireStateSnapshot, routeEdges } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { lockedSinceDecision } from \"./pinned-session\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport { managedTables, withManagedTables } from \"./target\";\nimport type { MarkerIndexPredicateV1, MigrationMarkerV1 } from \"./v1-types\";\n\n/**\n * The command, its inventories selecting what an estate with a `tables` list\n * manages at state `at` (`managedTables`): the estate's frozen list and the\n * state's tables. Across the edge to or from `beside`, the other end's tables\n * too, so a proof on either side of a transition also sees what it creates or\n * drops — except a table the edge adopts, on the parent's side, where it is\n * still the user's raw table. Never the client's list. Without a list, the\n * command as it is.\n */\nexport function managedAt(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n at: Sha256 | null,\n beside?: Sha256 | null\n): BoundMigrationDriver {\n const listed = graph.descriptor.target.tables;\n if (listed === undefined) return command;\n const own = requireStateSnapshot(graph, at);\n if (beside === undefined) {\n return withManagedTables(command, managedTables(listed, [own]));\n }\n // The graph admits an adoption only of a table the parent lacks.\n const edge =\n beside === null\n ? undefined\n : graph.states\n .get(beside)\n ?.parents.find((parent) => parent.fromState === at);\n return withManagedTables(\n command,\n managedTables(\n listed,\n [own, requireStateSnapshot(graph, beside)],\n edge?.adopts\n )\n );\n}\n\n/**\n * Where the live marker stands relative to this history. A marker naming a\n * state the graph holds — or no state — is `known`, and `assertNoDrift` proves\n * the rest. Otherwise its arrival path tells version skew from a stranger: the\n * marker is `ahead` when that path passes through a state of this estate\n * before leaving it (newer code applied the rest), and `unknown` when nothing\n * on it belongs here.\n */\nexport function markerStanding(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null\n): \"known\" | \"ahead\" | \"unknown\" {\n if (!marker?.stateId || graph.states.has(marker.stateId)) return \"known\";\n return marker.estateHash === graph.estateHash &&\n marker.path.some((edge) => graph.states.has(edge.stateId))\n ? \"ahead\"\n : \"unknown\";\n}\n\n/**\n * Refuses a group whose decision was taken under a lock the command has since\n * let go (plans D1, S5): an earlier group committed, or SQLite committed the\n * decision's transaction to switch foreign keys. Read as the group's first\n * statements, under its own lock: if another command moved the marker in\n * between, nothing of this group runs. Apply leaves an attempt of its own open\n * between two groups only inside an edge split at Neki's commit boundaries,\n * and passes it with the steps it has confirmed: the attempt must be the only\n * one open, as far as this command left it, or another command resumed it.\n * Any other unfinished one is another command's. `down` passes `ownAttempt`\n * only for the attempt it resumes, and `reset` once its own attempt is open:\n * while it is, no other command opens one.\n */\nexport async function assertLockedSinceDecision(\n pinned: Parameters<typeof appendLedger>[0],\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n expected: MigrationMarkerV1 | null,\n ownAttempt:\n | boolean\n | { readonly attemptId: Sha256; readonly steps: number } = false\n): Promise<void> {\n if (lockedSinceDecision(pinned)) return;\n const { marker, ledger } = await readControlState(producer, command, {\n ledger: \"open\",\n });\n const open = unfinishedAttempts(ledger);\n const own =\n typeof ownAttempt === \"boolean\"\n ? ownAttempt || open.length === 0\n : open.length === 1 &&\n open[0]!.attemptId === ownAttempt.attemptId &&\n ledger.filter(\n (event) =>\n event.attemptId === ownAttempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n event.effectState === \"committed\"\n ).length === ownAttempt.steps;\n if (sameMarker(marker, expected) && own) {\n return;\n }\n throw new MigrationError(\n \"Another migration command moved the marker between two of this command's transactions. Nothing of the remaining path ran; running the command again re-reads the marker.\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n}\n\nexport async function assertNoDrift(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1\n): Promise<void> {\n await proveLive(producer, command, graph, markedSnapshotHash(graph, marker));\n}\n\n/** The authenticated snapshot a marker names, once its identity is proven. */\nexport function markedSnapshotHash(\n graph: MigrationGraph,\n marker: MigrationMarkerV1\n): Sha256 {\n if (marker.estateHash !== graph.estateHash) {\n throw new MigrationError(\n \"Live marker estate does not match storage\",\n VibORMErrorCode.MIGRATION_DRIFT,\n { meta: { estateHash: marker.estateHash } }\n );\n }\n if (marker.stateId) {\n const state = graph.states.get(marker.stateId);\n if (!state) {\n throw new MigrationError(\n \"Marker state is missing from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (state.snapshotHash !== marker.snapshotHash) {\n throw new MigrationError(\n \"Marker snapshot does not match the authenticated state\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n } else if (marker.snapshotHash !== graph.emptySnapshotHash) {\n throw new MigrationError(\n \"An empty-path marker must name the empty managed snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if ((marker.path.at(-1)?.stateId ?? null) !== marker.stateId) {\n throw new MigrationError(\n \"Marker path does not end at the marked state\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n let from: Sha256 | null = null;\n for (const edge of marker.path) {\n const state = graph.states.get(edge.stateId);\n const parent = state?.parents.find(\n (item) =>\n item.transitionHash === edge.transitionHash && item.fromState === from\n );\n if (!(state && parent)) {\n throw new MigrationError(\n \"Marker path is not an authenticated arrival route\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n from = edge.stateId;\n }\n // Proven above to be the marked state's, which the graph holds.\n return marker.snapshotHash;\n}\n\n/**\n * Proves the live managed schema is the snapshot: on PostgreSQL in one\n * statement (plan D5, the driver's `catalogDigest`), else, and where that digest\n * abstains, through an introspection, read once. On PostgreSQL it returns each\n * partial-index predicate that introspection read, the server's own deparse\n * (`pg_get_expr`), which a forward apply records beside the marker\n * (`casMarker`) for the no-op; the digest abstains on any partial index, so\n * a proof without introspection has none to record. `refusal` words the\n * drift; `differences` describes it on demand.\n */\nexport async function proveLive(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n snapshotHash: Sha256,\n refusal: (\n differences: () => Promise<string>\n ) => Promise<string> | string = async (differences) =>\n `Live managed schema drifted from the authenticated snapshot. Differences: ${await differences()}`\n): Promise<readonly MarkerIndexPredicateV1[]> {\n // `loadMigrationGraph` loads every state's snapshot and seeds the empty one.\n const expected = graph.snapshots.get(snapshotHash)!;\n const fingerprint = await fingerprintLive(expected, command, producer);\n const digest = await command.catalogDigest?.(producer, CONTROL_TABLES);\n if (digest !== undefined && digest === fingerprint) return [];\n const live = await introspectManaged(producer, command);\n if ((await fingerprintLive(live, command, producer)) !== fingerprint) {\n throw new MigrationError(\n await refusal(async () => JSON.stringify(await diff(live, expected))),\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if (digest !== undefined) {\n throw new MigrationError(\n \"The PostgreSQL catalog digest disagrees with the introspected schema, which matches the authenticated snapshot. This is a VibORM defect in the digest (drivers/postgres/catalog-digest.ts), not drift: nothing ran. Please report it with the snapshot.\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n if (command.target.dialect !== \"postgresql\") return [];\n return live.tables.flatMap((table) =>\n table.indexes.flatMap((index) =>\n index.where\n ? [{ table: table.name, index: index.name, deparsed: index.where }]\n : []\n )\n );\n}\n\n/**\n * Refuses, before any effect, a path that adopts a live table carrying what\n * changes how it behaves and no snapshot describes (`adoptionHazards`, each\n * dialect's own reading): the destination proof compares the snapshot's\n * vocabulary only, so it would call that table equal to the declaration. It\n * reads only the tables the path adopts; every other command and table is\n * left as it was.\n */\nexport async function assertAdoptable(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): Promise<void> {\n const adopted = routeEdges(graph, origin, path).flatMap(\n ({ transition }) => transition.adopts ?? []\n );\n if (adopted.length === 0) return;\n const hazards = await command.adoptionHazards(adopted, (sql, params) =>\n producer._executeRaw(sql, params)\n );\n const [first] = hazards;\n if (first === undefined) return;\n const features = hazards\n .filter(({ table }) => table === first.table)\n .map(({ feature }) => feature);\n throw new MigrationError(\n `Cannot adopt \"${first.table}\": it has ${features.join(\", \")}, which its declaration does not state and the adoption proof cannot compare, so the table would not behave as declared. Remove them, or keep the table outside the estate. Nothing ran.`,\n VibORMErrorCode.MIGRATION_DRIFT,\n { meta: { table: first.table } }\n );\n}\n\nexport async function assertEmptyManaged(\n producer: Parameters<typeof introspectManaged>[0],\n command: BoundMigrationDriver\n): Promise<void> {\n const live = await introspectManaged(producer, command);\n if (live.tables.length > 0 || (live.enums?.length ?? 0) > 0) {\n throw new MigrationError(\n \"Ordinary apply requires an empty managed target; use baseline to adopt an existing schema\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n}\n","/**\n * The steps the operator commands and reset share: the command prologue, the\n * control read with its presence policy, and resuming an unfinished attempt\n * from its confirmed prefix (plan S3). Each caller keeps its own event filter:\n * which ledger rows confirm a step is its own rule.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n admitLiveMigrationCapability,\n type MigrationLiveRequirement,\n} from \"./admission\";\nimport {\n type MigrationControlRead,\n readControlState,\n refusePartialControl,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport { assertEstateTargetMatches, withManagedTables } from \"./target\";\nimport type {\n LedgerEventV1,\n MigrationOperationV1,\n MigrationStepV1,\n} from \"./v1-types\";\n\n/**\n * The client's migration driver, proven to address this estate's target, its\n * inventories selecting the estate's own frozen list rather than the client's\n * (which may name tables nothing adopted yet). Each proof restates the tables\n * its states manage (`managedAt`).\n */\nexport function openCommand(\n client: MigrationClient,\n graph: MigrationGraph,\n requirement: MigrationLiveRequirement,\n label: string\n): BoundMigrationDriver {\n const driver = getPushMigrationDriver(client);\n assertEstateTargetMatches(graph.descriptor.target, driver.target);\n admitLiveMigrationCapability(driver, requirement, label);\n return withManagedTables(driver, graph.descriptor.target.tables);\n}\n\n/**\n * The marker and the open ledger, partial control refused; `bootstrap`\n * admits what bootstrapping completes (both tables absent, or the log lost\n * after an interrupted bootstrap).\n */\nexport async function readCommandControl(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n bootstrap = false\n): Promise<MigrationControlRead> {\n const control = await readControlState(producer, command, { ledger: \"open\" });\n if (!bootstrap || control.presence.kind === \"missing-table\") {\n refusePartialControl(control.presence);\n }\n return control;\n}\n\n/** The length of the confirmed prefix; a confirmed step past a gap is refused. */\nexport function confirmedPrefix(\n confirmed: ReadonlySet<number>,\n refusal: string\n): number {\n let length = 0;\n while (confirmed.has(length)) length += 1;\n if ([...confirmed].some((index) => index >= length)) {\n throw new MigrationError(refusal, VibORMErrorCode.MIGRATION_CORRUPTION);\n }\n return length;\n}\n\n/**\n * Refuses to resume at an opaque stepwise dispatch announced and never\n * answered (confirmed, or its refusal recorded): it may have committed, and\n * running it again could repeat it.\n */\nexport function refuseAmbiguousNext(\n next: MigrationStepV1 | undefined,\n boundary: \"transactional\" | \"stepwise\" | undefined,\n announced: boolean,\n refusal: string\n): void {\n if (!(next?.retry === \"opaque\" && boundary === \"stepwise\" && announced)) {\n return;\n }\n throw new MigrationError(\n refusal,\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n lastConfirmedStep: next.execute.dispatchId,\n effectState: \"may-have-committed\",\n partial: true,\n },\n }\n );\n}\n\n/**\n * Counts one step's `step-confirmed` event into `unanswered`, per `key`: each\n * announcement (effect `none`) counts one, and each recorded refusal (`none`\n * with its `failure`: the server refused the statement whole) answers one. A\n * positive count is a dispatch occurrence that may have committed.\n */\nexport function countUnanswered<K>(\n unanswered: Map<K, number>,\n key: K,\n event: LedgerEventV1\n): void {\n if (event.effectState !== \"none\") return;\n unanswered.set(key, (unanswered.get(key) ?? 0) + (event.failure ? -1 : 1));\n}\n\n/** `operations` without their first `skip` steps. */\nexport function sliceOperations(\n operations: readonly MigrationOperationV1[],\n skip: number\n): MigrationOperationV1[] {\n let remaining = skip;\n return operations.flatMap((operation) => {\n if (remaining >= operation.steps.length) {\n remaining -= operation.steps.length;\n return [];\n }\n const steps = operation.steps.slice(remaining);\n remaining = 0;\n return [{ ...operation, steps }];\n });\n}\n\n/** The authenticated edge an attempt's `step-confirmed` events must name. */\nexport interface AttemptEdge {\n readonly direction: \"forward\" | \"rollback\";\n readonly estateHash: Sha256;\n readonly fromState: Sha256 | null;\n readonly toState: Sha256 | null;\n readonly transitionHash: Sha256;\n readonly sqlHash: Sha256;\n readonly operations: readonly MigrationOperationV1[];\n readonly boundary: \"transactional\" | \"stepwise\";\n}\n\n/**\n * What an unfinished attempt left to run of `edge`: its confirmed prefix of\n * steps, read from the attempt's own `step-confirmed` events, and the\n * operations past it. Progress naming another edge or an unknown dispatch, a\n * confirmed step past a gap, and an announced opaque stepwise step neither\n * confirmed nor answered by its recorded refusal (the server refused it\n * whole: it left nothing) are refused. `noun` names the direction in each\n * refusal.\n */\nexport function remainingSteps(\n ledger: readonly LedgerEventV1[],\n attempt: LedgerEventV1,\n edge: AttemptEdge,\n noun: \"Forward\" | \"Rollback\"\n): { readonly completed: number; readonly operations: MigrationOperationV1[] } {\n const steps = edge.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ operation, step }))\n );\n const byDispatch = new Map(\n steps.map(({ step }, index) => [step.execute.dispatchId, index])\n );\n const committed = new Set<number>();\n // Announcements not answered by a recorded refusal, per step.\n const unanswered = new Map<number, number>();\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"step-confirmed\"\n )\n continue;\n if (\n event.direction !== edge.direction ||\n event.estateHash !== edge.estateHash ||\n event.fromState !== edge.fromState ||\n event.toState !== edge.toState ||\n event.transitionHash !== edge.transitionHash ||\n event.sqlHash !== edge.sqlHash ||\n !event.dispatchId\n ) {\n throw new MigrationError(\n `${noun} progress does not match its authenticated edge`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const index = byDispatch.get(event.dispatchId);\n if (\n index === undefined ||\n steps[index]!.operation.id !== event.operationId\n ) {\n throw new MigrationError(\n `${noun} progress names an unknown dispatch`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (event.effectState === \"committed\") committed.add(index);\n countUnanswered(unanswered, index, event);\n }\n const completed = confirmedPrefix(\n committed,\n `${noun} progress is not a contiguous dispatch prefix`\n );\n refuseAmbiguousNext(\n steps[completed]?.step,\n edge.boundary,\n (unanswered.get(completed) ?? 0) > 0,\n `The next ${noun.toLowerCase()} dispatch has an ambiguous commit outcome`\n );\n return { completed, operations: sliceOperations(edge.operations, completed) };\n}\n","/**\n * Apply V1: authenticate the graph, lock, refuse drift, execute exact slices,\n * then CAS the marker. Production never evaluates TypeScript.\n */\n\nimport { isVibORMError, MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./compile\";\nimport {\n type AttemptEvents,\n advanceMarker,\n appendLedger,\n attemptEvents,\n CONTROL_TABLES,\n ensureControlTables,\n markerFromPath,\n markerUnmovedCondition,\n markerWrite,\n readControlState,\n readPostgresDecision,\n refuseIncompatibleHistory,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n annotateMigrationFailure,\n assertAllChecks,\n executeOperations,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n type RouteEdge,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport {\n commitLockedTransaction,\n type MigrationBatch,\n migrationLockFree,\n openMigrationBatch,\n runProgram,\n runsMigrationBatches,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport {\n assertAdoptable,\n assertEmptyManaged,\n assertLockedSinceDecision,\n assertNoDrift,\n managedAt,\n markedSnapshotHash,\n markerStanding,\n proveLive,\n} from \"./proof\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { fingerprintDeparsed, fingerprintSnapshot } from \"./push-fingerprint\";\nimport type { introspectManaged } from \"./push-plan\";\nimport { openCommand, readCommandControl, remainingSteps } from \"./resume\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { canonicalizeSqliteStorage } from \"./sqlite-storage-audit\";\nimport { catalogCommitBoundaries, UNCHANGED_CATALOG } from \"./statement-safety\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport type { SchemaSnapshot } from \"./types\";\nimport type {\n ApplyV1Options,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationBooleanCheckV1,\n MigrationMarkerV1,\n MigrationOperationV1,\n} from \"./v1-types\";\n\nexport interface ApplyV1Result {\n readonly outcome: \"applied\" | \"noop\" | \"preview\";\n readonly path: readonly Sha256[];\n readonly statements: readonly string[];\n /**\n * Present only when the migration committed but releasing a session lock\n * failed after it (MySQL, PostgreSQL). The session was discarded, so the\n * lock does not outlive it.\n */\n readonly warnings?: readonly string[];\n}\n\nexport async function applyV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ApplyV1Options = {}\n): Promise<ApplyV1Result> {\n const graph = await loadMigrationGraph(storage);\n const dryRun = options.dryRun === true;\n const driver = openCommand(\n client,\n graph,\n dryRun ? \"read-only\" : \"batch\",\n dryRun ? \"apply({ dryRun: true })\" : \"apply()\"\n );\n const target = resolveStateSelector(graph, options.to);\n\n if (dryRun) {\n const control = await readCommandControl(client.$driver, driver);\n const decision = decide(graph, control.marker, target, options);\n if (!decision || decision.origin === target) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n const { origin, path, statements } = decision;\n // An edge split at Neki's commit boundaries previews what is left of it.\n const unfinished = unfinishedAttempts(control.ledger);\n const resume = mayResume(unfinished, control.marker)\n ? resumableAttempt(\n driver,\n graph,\n decision,\n unfinished[0]!,\n control.ledger\n )\n : undefined;\n return {\n outcome: \"preview\",\n path,\n statements: resume\n ? routeSql(graph, origin, path, resume).statements\n : statements,\n };\n }\n\n // Set once the path committed: a failure after it is the lock's release.\n const committed: { result?: ApplyV1Result } = {};\n const locked = withLockedMigrationProducer<ApplyV1Result>(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n refuseIncompatibleHistory(marker, ledger);\n const unfinished = unfinishedAttempts(ledger);\n if (unfinished.length > 0 && !mayResume(unfinished, marker)) {\n throw unfinishedAttemptBlocks();\n }\n const decision = decide(graph, marker, target, options);\n // A transport with no session runs no edge as committed parts.\n const resume =\n unfinished.length === 0 || runsMigrationBatches(pinned)\n ? undefined\n : resumableAttempt(command, graph, decision, unfinished[0]!, ledger);\n if (unfinished.length > 0 && !resume) throw unfinishedAttemptBlocks();\n if (!decision) return { outcome: \"noop\", path: [], statements: [] };\n const { origin, path } = decision;\n const route = routeSql(graph, origin, path, resume);\n const splits = await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, origin),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params),\n route.chunks,\n // One request per group holds no part's progress: refused instead.\n !runsMigrationBatches(pinned)\n );\n await assertAdoptable(pinned, command, graph, origin, path);\n // A resumed edge's committed parts are already past the marker's\n // snapshot: the destination proof of its last part proves the rest.\n // Across the first edge: a table it adopts is not proven yet.\n if (resume === undefined && marker) {\n await assertNoDrift(\n pinned,\n managedAt(command, graph, origin, path[0]),\n graph,\n marker\n );\n } else if (resume === undefined) {\n await assertEmptyManaged(\n pinned,\n managedAt(command, graph, null, path[0])\n );\n }\n if (origin === target) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n // On MySQL the whole path is one sequential program.\n await runProgram(pinned, command, undefined, (producer) =>\n applyPathUnderLock(\n producer,\n command,\n graph,\n marker,\n origin,\n path,\n client.$schema,\n needsBootstrap,\n { splits, resume }\n )\n );\n committed.result = {\n outcome: \"applied\",\n path,\n statements: resume ? route.statements : decision.statements,\n };\n return committed.result;\n },\n driver.target.dialect === \"postgresql\"\n ? (session, lockFree) =>\n provenNoop(\n session,\n lockFree,\n managedAt(driver, graph, target),\n graph,\n target,\n options\n )\n : undefined\n );\n return keepCommittedOutcome(committed, locked);\n}\n\n/**\n * Plan D5 (decision 7): a PostgreSQL apply with nothing to do proves it\n * before the lock, in two statements: the control tables' definition, then\n * the marker, the open attempts and the catalog digest, read in one snapshot\n * while no other command holds the lock (`lockFree`). A database at the\n * target, with nothing open and no drift, was there at that instant, which is\n * all a no-op claims, and it writes nothing a lock would protect. Anything\n * else — another command at work included — or anything this read cannot\n * decide, goes to the locked path, which decides again under the lock.\n */\nasync function provenNoop(\n session: Parameters<typeof introspectManaged>[0],\n lockFree: string,\n driver: BoundMigrationDriver,\n graph: MigrationGraph,\n target: Sha256,\n options: ApplyV1Options\n): Promise<ApplyV1Result | undefined> {\n const decision = await readPostgresDecision(session, driver, lockFree);\n const marker = decision?.marker;\n if (!marker || unfinishedAttempts(decision.ledger).length > 0) return;\n // A refusal thrown here is decided again, and thrown, under the lock.\n if (followsAheadPolicy(graph, marker, options)) {\n return { outcome: \"noop\", path: [], statements: [] };\n }\n if (marker.stateId !== target || decision.digest === undefined) return;\n // `markedSnapshotHash` proved the snapshot is in the estate. Partial-index\n // predicates compare as the server deparsed them: the live ones in the\n // digest, the snapshot's from the record beside the marker.\n const expected = graph.snapshots.get(markedSnapshotHash(graph, marker))!;\n return decision.digest ===\n fingerprintDeparsed(expected, decision.predicates, driver)\n ? { outcome: \"noop\", path: [], statements: [] }\n : undefined;\n}\n\n/**\n * The outcome of a command whose work committed, even when ending its session\n * afterwards failed (releasing a session lock, or closing a locked read): the\n * marker already proves the commit (plan S3).\n */\nasync function keepCommittedOutcome(\n committed: { readonly result?: ApplyV1Result },\n command: Promise<ApplyV1Result>\n): Promise<ApplyV1Result> {\n try {\n return await command;\n } catch (failure) {\n if (committed.result === undefined) throw failure;\n return {\n ...committed.result,\n warnings: [\n `The migration committed, but ending its session failed (${describeFailure(failure)}).`,\n ],\n };\n }\n}\n\n/** True when `ifAhead: \"noop\"` applies; refuses every other marker this history does not hold. */\nfunction followsAheadPolicy(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n options: ApplyV1Options\n): boolean {\n const standing = markerStanding(graph, marker);\n if (standing === \"known\") return false;\n if (standing === \"ahead\" && options.ifAhead === \"noop\") return true;\n throw new MigrationError(\n standing === \"ahead\"\n ? `The database marker is ahead of this migration history: it names state ${marker?.stateId}, which newer code applied after a state this estate holds. Deploy that code, or pass apply({ ifAhead: \"noop\" }) to run against the newer schema without migrating.`\n : `The database marker names state ${marker?.stateId}, which is unknown to this migration estate: no state on its arrival path belongs to this history.`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n}\n\n/**\n * What apply does from `marker`, shared by the dry run and the locked apply:\n * its ahead policy, origin, route and authenticated artifacts. `undefined`\n * when `ifAhead: \"noop\"` applies.\n */\nfunction decide(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n target: Sha256,\n options: ApplyV1Options\n):\n | { origin: Sha256 | null; path: readonly Sha256[]; statements: string[] }\n | undefined {\n if (followsAheadPolicy(graph, marker, options)) return;\n const origin = marker?.stateId ?? null;\n const path =\n origin === target ? [] : selectRoute(graph, origin, target, options.via);\n return { origin, path, statements: previewStatements(graph, origin, path) };\n}\n\nasync function applyPathUnderLock(\n pinned: import(\"../drivers/driver\").AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n origin: Sha256 | null,\n path: readonly Sha256[],\n models: MigrationClient[\"$schema\"],\n needsBootstrap: boolean,\n { splits, resume }: { readonly splits: boolean; readonly resume?: Resume }\n): Promise<void> {\n const batched = runsMigrationBatches(pinned);\n const prepared = routeEdges(graph, origin, path).map((edge) => {\n const requested = edge.transition.requestedForwardBoundary;\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions || batched,\n requested\n );\n const boundary = classifyStoredAtomicity(\n command,\n requested,\n edge.transition.operations,\n edge.blob\n );\n refuseSqliteStepwise(command, requested, edge.to);\n if (batched && boundary === \"stepwise\") {\n refuseBatchedStepwise(pinned, edge.to);\n }\n return { ...edge, boundary };\n });\n\n let current = marker;\n const nextPath = marker ? [...marker.path] : [];\n // Before the program, as statements of their own: one request cannot read\n // what the bootstrap reads (plan D7), and a PostgreSQL bootstrap commits.\n if (needsBootstrap) {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n }\n const statementsOf = ({ transition, blob }: PreparedForwardEdge) =>\n stepStatements(blob, transition.operations);\n const groups = groupContiguousAtomicity(prepared, statementsOf);\n const first = groups[0]?.items[0];\n for (const group of splits || resume\n ? splitAtCatalogBoundaries(graph, groups, splits, resume)\n : groups) {\n if (\"split\" in group) {\n current = await applySplitEdge(\n pinned,\n command,\n graph,\n group.split,\n current,\n nextPath,\n models\n );\n continue;\n }\n if (batched) {\n current = await applyGroupBatch(\n pinned,\n command,\n graph,\n group.items,\n current,\n nextPath,\n models\n );\n continue;\n }\n const running: { attempt?: ForwardAttempt } = {};\n // The edge the group is running, which a failure no statement named is.\n const runningEdge: { to?: Sha256 } = {};\n // A resumed stepwise edge: its attempt stays open, as apply left it.\n const resumed = group.items[0] === first ? resume : undefined;\n const run = async (\n producer: Parameters<typeof appendLedger>[0],\n atomic: boolean\n ) => {\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n resumed && {\n attemptId: resumed.attempt.attemptId,\n steps: resumed.completed,\n }\n );\n if (atomic) {\n current = await executeAtomicGroup(\n producer,\n command,\n graph,\n group.items,\n running,\n current,\n nextPath,\n models\n );\n return;\n }\n // Edge by edge, each step probed and recorded as it runs.\n for (const [index, item] of group.items.entries()) {\n runningEdge.to = item.to;\n const own = index === 0 ? resumed : undefined;\n const attempt = forwardAttempt(graph, item, own?.attempt.attemptId);\n if (own === undefined) {\n await appendLedger(\n producer,\n command,\n attempt.event(\"started\", \"none\")\n );\n }\n await runForwardEdge(\n producer,\n command,\n graph,\n attempt,\n nextPath,\n models,\n true,\n undefined,\n own && {\n operations: own.operations,\n origin: false,\n destination: true,\n }\n );\n const { snapshotHash } = item.state;\n current = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n 1,\n await proveLive(\n producer,\n managedAt(command, graph, item.to, item.from),\n graph,\n snapshotHash\n )\n );\n await appendLedger(\n producer,\n command,\n attempt.event(\"applied\", \"committed\")\n );\n }\n };\n const phase = { committing: false, committed: false };\n const program = {\n transactional: group.boundary === \"transactional\",\n statements: group.items.flatMap(statementsOf),\n phase,\n };\n try {\n // On MySQL the path already runs as one sequential program (`applyV1`).\n await (command.target.dialect === \"mysql\"\n ? run(pinned, false)\n : runProgram(pinned, command, program, run));\n } catch (raised) {\n // A failure no statement named is this group's: its commit, its lock.\n const failure = annotateMigrationFailure(raised, {\n step: \"apply\",\n strategy: group.boundary,\n stateId: running.attempt?.item.to ?? runningEdge.to,\n });\n // Past the commit only the foreign-key restore can fail: it is reported.\n if (phase.committed) throw failure;\n if (\n phase.committing &&\n (await commitLanded(pinned, command, group.items, current, failure))\n ) {\n // Its COMMIT landed: what it builds in the background is waited for.\n await command.awaitIndexBuilds?.(pinned, program.statements);\n continue;\n }\n await recordFailedAttempt(pinned, command, running, failure);\n throw failure;\n }\n }\n}\n\n/**\n * Plan D7, refused while the path is prepared, before any of it runs: a\n * transport with no session runs only transactional groups, each as one\n * request.\n */\nfunction refuseBatchedStepwise(\n pinned: import(\"../drivers/driver\").AnyDriver,\n toState: Sha256\n): never {\n throw new MigrationError(\n `The driver \"${pinned.driverName}\" sends each transactional group as one request and has no session for a stepwise transition (CONCURRENTLY, or a manual stepwise step). Nothing ran. Apply it over a session driver: viborm/pg, Neon's WebSocket Pool included.`,\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER,\n { meta: { dialect: \"postgresql\", toState, feature: \"stepwise execution\" } }\n );\n}\n\n/** One committed part of a forward edge: its steps, and which checks it runs. */\ninterface ForwardPart {\n readonly operations: readonly MigrationOperationV1[];\n readonly origin: boolean;\n readonly destination: boolean;\n}\n\n/**\n * One forward edge, from its origin checks to its destination checks, its\n * arrival pushed onto `nextPath`; the caller proves the destination, moves\n * the marker and records the arrival. A `probed` edge runs step by step and\n * records each confirmed step; otherwise it runs inside a real transaction,\n * or one request (`batch`), whose rollback is the proof of every step. A\n * `part` of an edge split at Neki's commit boundaries runs only its steps,\n * each recorded in the part's transaction, and the checks it holds.\n */\nasync function runForwardEdge(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n attempt: ForwardAttempt,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"],\n probed: boolean,\n batch?: MigrationBatch,\n part?: ForwardPart\n): Promise<void> {\n const { from, to, transition, state, blob, boundary } = attempt.item;\n if (part?.origin ?? true) {\n await assertAllChecks(\n producer,\n blob,\n transition.originChecks,\n command.namespace,\n \"Origin checks failed before the first dispatch\",\n batch\n );\n }\n await executeOperations(\n producer,\n blob,\n part?.operations ?? transition.operations,\n probed ? boundary : \"atomic\",\n probed || part\n ? (progress, effect, failure) =>\n appendLedger(\n producer,\n command,\n attempt.event(\"step-confirmed\", effect, progress, failure)\n )\n : undefined,\n command.namespace,\n { fromState: from, toState: to, step: \"apply\" }\n );\n if (!(part?.destination ?? true)) return;\n // Manual SQL may store text typed queries cannot compare (`datetime('now')`).\n await canonicalizeSqliteStorage(\n producer,\n transition.operations,\n models,\n requireStateSnapshot(graph, to)\n );\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Destination checks failed before the marker could advance\",\n batch\n );\n nextPath.push({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: false,\n });\n}\n\n/**\n * One group inside a real transaction (plan D5). Its rollback is the proof\n * of every step, so the statements run unprobed and leave no progress rows\n * or `started` events; the group's last state is proven once, the marker\n * moves once (by one revision per edge, as edge by edge), and every edge's\n * `applied` event lands in one statement. Between the first DDL and the\n * COMMIT this sends the DDL, the authored checks and three control\n * statements.\n */\nasync function executeAtomicGroup(\n producer: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n items: readonly PreparedForwardEdge[],\n running: { attempt?: ForwardAttempt },\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"],\n batch?: MigrationBatch\n): Promise<MigrationMarkerV1> {\n const arrivals: LedgerEventV1[] = [];\n for (const item of items) {\n running.attempt = forwardAttempt(graph, item);\n await runForwardEdge(\n producer,\n command,\n graph,\n running.attempt,\n nextPath,\n models,\n false,\n batch\n );\n arrivals.push(running.attempt.event(\"applied\", \"committed\"));\n }\n const last = items.at(-1)!;\n const { snapshotHash } = last.state;\n // The destination proves every table the last edge adopts.\n const destination = managedAt(command, graph, last.to, last.from);\n let next: MigrationMarkerV1;\n if (batch) {\n assertDigest(batch, destination, requireStateSnapshot(graph, last.to));\n next = markerFromPath(\n graph.estateHash,\n snapshotHash,\n [...nextPath],\n (current?.revision ?? 0) + items.length\n );\n // The request asserted `current` under its lock first.\n const write = markerWrite(command, current, next);\n await producer._executeRaw(write.sql, write.params);\n } else {\n next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n items.length,\n await proveLive(producer, destination, graph, snapshotHash)\n );\n }\n await appendLedger(producer, command, ...arrivals);\n return next;\n}\n\n/**\n * Plan D7: one transactional group as ONE request, on a transport with no\n * session. The request takes the transaction lock, asserts that the marker\n * is still the one this command decided on and that no attempt is open\n * ({@link assertLockedSinceDecision} in SQL), then runs the group as\n * {@link executeAtomicGroup} does, its checks and destination proof asserted\n * in SQL. A request the server refused rolled back; after a lost reply the\n * marker says whether it committed ({@link commitLanded}).\n */\nasync function applyGroupBatch(\n driver: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n items: readonly PreparedForwardEdge[],\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1> {\n const batch = openMigrationBatch(driver, command);\n const unmoved = markerUnmovedCondition(command, current);\n batch.assert(\n unmoved.sql,\n unmoved.params,\n new MigrationError(\n \"Another migration command moved the marker, or opened an attempt, after this command read it. Nothing of this request was applied; running the command again re-reads the marker.\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n )\n );\n const running: { attempt?: ForwardAttempt } = {};\n const next = await executeAtomicGroup(\n batch.producer,\n command,\n graph,\n items,\n running,\n current,\n nextPath,\n models,\n batch\n );\n try {\n await batch.send();\n } catch (failure) {\n if (\n !(failure instanceof MigrationError) &&\n (await commitLanded(driver, command, items, next, failure))\n ) {\n return next;\n }\n // Refused for the lock or a moved marker, the request ran none of the\n // group: a session refuses both before the attempt, recording nothing.\n const refusedBeforeGroup =\n failure instanceof MigrationError &&\n (failure.code === VibORMErrorCode.MIGRATION_LOCK_FAILED ||\n failure.code === VibORMErrorCode.MIGRATION_MARKER_CONFLICT);\n if (!refusedBeforeGroup) {\n await recordFailedAttempt(driver, command, running, failure);\n }\n throw failure;\n }\n return next;\n}\n\n/**\n * The destination proof inside one request (plan D7): the catalog digest\n * (`catalog-digest.ts`) is the snapshot's fingerprint. Where the digest\n * abstains, the request cannot prove the destination, and is refused.\n */\nfunction assertDigest(\n batch: MigrationBatch,\n command: BoundMigrationDriver,\n snapshot: SchemaSnapshot\n): void {\n // A batch runs only on PostgreSQL, whose driver owns the digest.\n const digest = command.catalogDigestQuery!(CONTROL_TABLES);\n batch.assert(\n `(${digest.sql}) IS NOT NULL`,\n digest.parameters,\n new MigrationError(\n \"This change cannot be proven inside one request: the catalog digest abstains on the destination schema (a partial index, or a default it cannot reproduce; see drivers/postgres/catalog-digest.ts). Nothing was applied. Apply it over a session driver: viborm/pg, Neon's WebSocket Pool included.\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n )\n );\n batch.assert(\n `(${digest.sql}) = $7`,\n [...digest.parameters, fingerprintSnapshot(snapshot, command)],\n new MigrationError(\n \"Live managed schema drifted from the authenticated snapshot\",\n VibORMErrorCode.MIGRATION_DRIFT\n )\n );\n}\n\n/**\n * Whether a transaction whose COMMIT was sent, and then failed, committed.\n * The marker it compare-and-swapped answers: it commits with the transition\n * or not at all. When even the marker cannot be read, the outcome is the\n * ambiguous commit V11020 it is (plan S3). Without a session (plan D7) it is\n * read only while no command holds the lock, so never while the request\n * whose reply was lost may still run.\n */\nasync function commitLanded(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n items: readonly PreparedForwardEdge[],\n expected: MigrationMarkerV1 | null,\n failure: unknown\n): Promise<boolean> {\n // On a lost connection the pinned view refuses this read (plan S2).\n const marker = await (runsMigrationBatches(pinned)\n ? readPostgresDecision(pinned, command, migrationLockFree(command)).then(\n (decision) => decision?.marker\n )\n : readControlState(pinned, command, {\n ledger: \"open\",\n }).then((control) => control.marker)\n ).catch(() => undefined);\n if (marker === undefined) {\n const fromState = items[0]?.from ?? null;\n throw new MigrationError(\n \"The migration's COMMIT was sent but its reply was lost, and the marker cannot be re-read, or another request still holds the migration lock: the transition may have committed. status() and apply() re-read the marker.\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n cause: failure instanceof Error ? failure : undefined,\n meta: {\n ...(fromState === null ? {} : { fromState }),\n toState: items.at(-1)?.to,\n effectState: \"may-have-committed\",\n commitCertainty: \"may-have-committed\",\n },\n }\n );\n }\n return marker !== null && sameMarker(marker, expected);\n}\n\n/**\n * Leaves the durable record of a rolled-back attempt, whose own events the\n * rollback took with it: a `failed` event, in a transaction of its own, after\n * bootstrapping the control tables a failed first apply rolled back. The pinned\n * view sends nothing on a lost connection (plan S2), and a record that cannot be written\n * never replaces the failure it records.\n */\nasync function recordFailedAttempt(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n running: { readonly attempt?: ForwardAttempt },\n failure: unknown\n): Promise<void> {\n const { attempt } = running;\n if (attempt === undefined) return;\n const meta = isVibORMError(failure) ? failure.meta : {};\n const event = attempt.event(\n \"failed\",\n \"none\",\n {\n operationId:\n typeof meta.operationId === \"string\" ? meta.operationId : null,\n dispatchId: typeof meta.dispatchId === \"string\" ? meta.dispatchId : null,\n },\n describeFailure(failure)\n );\n try {\n if (runsMigrationBatches(pinned)) {\n // Its control tables were made before the request (plan D7).\n await appendLedger(pinned, command, event);\n return;\n }\n await pinned.withTransaction(async (transaction) => {\n await ensureControlTables(transaction, command);\n await appendLedger(transaction, command, event);\n });\n } catch {\n // Best effort: the caller is owed the failure itself, not this one.\n }\n}\n\nfunction describeFailure(failure: unknown): string {\n if (isVibORMError(failure)) return `${failure.code}: ${failure.message}`;\n return failure instanceof Error ? failure.name : \"a non-error value\";\n}\n\ninterface PreparedForwardEdge extends RouteEdge {\n readonly boundary: \"transactional\" | \"stepwise\";\n}\n\n/** One edge's attempt: the edge, and the builder of its ledger events. */\ninterface ForwardAttempt extends AttemptEvents {\n readonly item: PreparedForwardEdge;\n}\n\nfunction forwardAttempt(\n graph: MigrationGraph,\n item: PreparedForwardEdge,\n attemptId?: Sha256\n): ForwardAttempt {\n return {\n item,\n ...attemptEvents(\n {\n estateHash: graph.estateHash,\n snapshotHash: item.state.snapshotHash,\n sqlHash: item.state.sqlHash,\n fromState: item.from,\n toState: item.to,\n transitionHash: item.transition.transitionHash,\n direction: \"forward\",\n },\n attemptId\n ),\n };\n}\n\nfunction previewStatements(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[]\n): string[] {\n return routeEdges(graph, origin, path).flatMap(({ blob, transition }) =>\n stepStatements(blob, transition.operations)\n );\n}\n\nfunction unfinishedAttemptBlocks(): MigrationError {\n return new MigrationError(\n \"An unfinished migration attempt is blocking ordinary work\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n}\n\n/**\n * Whether the open attempts may be one apply resumes: one forward attempt,\n * opened from the marker. Read before the route, so any other open attempt\n * blocks as it always has.\n */\nfunction mayResume(\n unfinished: readonly LedgerEventV1[],\n marker: MigrationMarkerV1 | null\n): boolean {\n const [attempt] = unfinished;\n return (\n unfinished.length === 1 &&\n attempt?.kind === \"started\" &&\n attempt.direction === \"forward\" &&\n attempt.fromState === (marker?.stateId ?? null)\n );\n}\n\n/**\n * An unfinished edge apply resumes: one split at Neki's commit boundaries\n * whose first parts committed, or a stepwise one stopped at a step the server\n * refused whole.\n */\ninterface Resume {\n readonly attempt: LedgerEventV1;\n /** The steps its committed parts confirmed. */\n readonly completed: number;\n /** The operations past them. */\n readonly operations: readonly MigrationOperationV1[];\n}\n\n/**\n * What apply resumes of `attempt`, which {@link mayResume} admitted, or\n * `undefined`, on the first edge of the route apply selected, on PostgreSQL:\n * - a transactional edge split at Neki's commit boundaries: each committed\n * part recorded its steps in its own transaction, so their prefix is exact;\n * - a stepwise edge whose next step the server refused whole, recorded as\n * such (`execute-dispatch.ts`): that step left nothing, and the steps\n * before it each recorded their commit. Any other stepwise stop — a lost\n * connection, an outcome the server could not prove, a failed check —\n * still blocks.\n * Either way the origin checks ran before the first step, against the\n * origin; the resumed steps run without them, against the confirmed prefix,\n * and the destination checks and proof close the edge.\n */\nfunction resumableAttempt(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n decision: ReturnType<typeof decide>,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): Resume | undefined {\n if (!decision?.path.length || command.target.dialect !== \"postgresql\") {\n return;\n }\n const [edge] = routeEdges(graph, decision.origin, decision.path);\n const { from, to, transition, state, blob } = edge!;\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n const refused = new Set(\n ledger.flatMap((event) =>\n event.attemptId === attempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n event.failure\n ? [event.dispatchId]\n : []\n )\n );\n // Its progress events are matched to this edge by `remainingSteps`; a\n // stepwise attempt that recorded no refusal blocks before they are read.\n if (\n attempt.toState !== to ||\n attempt.transitionHash !== transition.transitionHash ||\n (boundary === \"stepwise\" && refused.size === 0)\n ) {\n return;\n }\n const remaining = remainingSteps(\n ledger,\n attempt,\n {\n direction: \"forward\",\n estateHash: graph.estateHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n sqlHash: state.sqlHash,\n operations: transition.operations,\n boundary,\n },\n \"Forward\"\n );\n const next = remaining.operations[0]?.steps[0]?.execute.dispatchId;\n if (boundary === \"stepwise\" && !(next && refused.has(next))) return;\n return { attempt, ...remaining };\n}\n\n/**\n * The SQL one transaction runs for an edge, in its order: the origin checks\n * (unless `origin` is false: a resumed edge ran them), `operations`' steps\n * and the destination checks. `before` counts the origin checks.\n */\nfunction edgeSql(\n { transition, state, blob }: RouteEdge,\n operations: readonly MigrationOperationV1[],\n origin: boolean\n): {\n readonly chunks: string[];\n readonly steps: string[];\n readonly before: number;\n} {\n const checks = (list: readonly MigrationBooleanCheckV1[]) =>\n list.map((check) => sliceDispatch(blob, check.query));\n const before = origin ? checks(transition.originChecks) : [];\n const steps = stepStatements(blob, operations);\n return {\n chunks: [...before, ...steps, ...checks(state.destinationChecks)],\n steps,\n before: before.length,\n };\n}\n\n/**\n * What apply runs along `path`, a resumed first edge from its remaining\n * steps: every edge's checks and steps (`chunks`, which PlanetScale's Neki\n * reads for commit boundaries) and the steps alone (`statements`).\n */\nfunction routeSql(\n graph: MigrationGraph,\n origin: Sha256 | null,\n path: readonly Sha256[],\n resume: Resume | undefined\n): { readonly chunks: string[]; readonly statements: string[] } {\n const chunks: string[] = [];\n const statements: string[] = [];\n for (const [index, edge] of routeEdges(graph, origin, path).entries()) {\n const resumed = index === 0 ? resume : undefined;\n const sql = edgeSql(\n edge,\n resumed?.operations ?? edge.transition.operations,\n resumed === undefined\n );\n chunks.push(...sql.chunks);\n statements.push(...sql.steps);\n }\n return { chunks, statements };\n}\n\n/** One edge apply runs as committed parts, alone in its group. */\ninterface SplitEdge {\n readonly attempt: ForwardAttempt;\n /** Whether its attempt is open already: its first parts committed earlier. */\n readonly resumed: boolean;\n /** The steps confirmed before this command. */\n readonly completed: number;\n /**\n * Each part's operations, in order. The origin checks run with the first,\n * the destination checks and the marker with the last, which holds no step\n * when the checks themselves need a commit.\n */\n readonly parts: readonly (readonly MigrationOperationV1[])[];\n}\n\ntype PlannedGroup =\n | ReturnType<typeof groupContiguousAtomicity<PreparedForwardEdge>>[number]\n | { readonly split: SplitEdge };\n\n/** The steps `from` (inclusive) to `to` (exclusive) of `operations`. */\nfunction stepRange(\n operations: readonly MigrationOperationV1[],\n from: number,\n to: number\n): MigrationOperationV1[] {\n let index = 0;\n return operations.flatMap((operation) => {\n const first = index;\n index += operation.steps.length;\n const steps = operation.steps.filter(\n (_, position) => first + position >= from && first + position < to\n );\n return steps.length === 0 ? [] : [{ ...operation, steps }];\n });\n}\n\n/**\n * Plan D5's groups, on PlanetScale's Neki (`splits`), cut where its planner\n * needs a commit (`catalogCommitBoundaries`): an edge joins the group before\n * it while none of its statements needs one; one that needs one only because\n * of that group starts a group of its own; one that needs one because of its\n * own changes runs alone, as committed parts. A resumed first edge runs alone\n * from its remaining steps, on any PostgreSQL. A stepwise group commits each\n * statement already.\n */\nfunction splitAtCatalogBoundaries(\n graph: MigrationGraph,\n groups: ReturnType<typeof groupContiguousAtomicity<PreparedForwardEdge>>,\n splits: boolean,\n resume: Resume | undefined\n): PlannedGroup[] {\n const planned: PlannedGroup[] = [];\n const first = groups[0]?.items[0];\n for (const group of groups) {\n if (group.boundary !== \"transactional\") {\n planned.push(group);\n continue;\n }\n let items: PreparedForwardEdge[] = [];\n let changes = UNCHANGED_CATALOG;\n const flush = () => {\n if (items.length > 0) planned.push({ boundary: group.boundary, items });\n items = [];\n changes = UNCHANGED_CATALOG;\n };\n const read = (chunks: readonly string[], since = UNCHANGED_CATALOG) =>\n splits\n ? catalogCommitBoundaries(chunks, since)\n : { boundaries: [], changes: UNCHANGED_CATALOG };\n for (const item of group.items) {\n const resumed = item === first ? resume : undefined;\n const operations = resumed?.operations ?? item.transition.operations;\n const sql = edgeSql(item, operations, resumed === undefined);\n const joined = read(sql.chunks, changes);\n if (resumed === undefined && joined.boundaries.length === 0) {\n items.push(item);\n changes = joined.changes;\n continue;\n }\n flush();\n const alone = read(sql.chunks);\n if (resumed === undefined && alone.boundaries.length === 0) {\n items = [item];\n changes = alone.changes;\n continue;\n }\n // A commit before an origin check or the first step divides nothing.\n const cuts = [\n ...new Set(\n alone.boundaries\n .map((position) =>\n Math.min(position - sql.before, sql.steps.length)\n )\n .filter((cut) => cut > 0)\n ),\n ];\n const ends = [0, ...cuts, sql.steps.length];\n planned.push({\n split: {\n attempt: forwardAttempt(graph, item, resumed?.attempt.attemptId),\n resumed: resumed !== undefined,\n completed: resumed?.completed ?? 0,\n parts: ends\n .slice(1)\n .map((end, index) => stepRange(operations, ends[index]!, end)),\n },\n });\n }\n flush();\n }\n return planned;\n}\n\n/**\n * One edge as successive committed parts (PlanetScale's Neki), each in its\n * own locked transaction: the first runs the origin checks and opens the\n * attempt (`started`), each records its steps (`step-confirmed`) in the\n * transaction they ran in, and the last runs the destination checks, proves\n * the destination, moves the marker and closes the attempt (`applied`).\n *\n * Between two parts the lock is let go, so each part first proves the marker\n * unmoved and the attempt as far as this command left it. A first part that\n * fails leaves nothing, recorded as one `failed` event, as an atomic group\n * does. A later failure leaves the attempt open at its last committed part,\n * the marker on the edge's origin: `status()` reports it unfinished, and the\n * next `apply()` resumes the remaining parts ({@link resumableAttempt}).\n */\nasync function applySplitEdge(\n pinned: import(\"../drivers/driver\").AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n { attempt, resumed, completed, parts }: SplitEdge,\n current: MigrationMarkerV1 | null,\n nextPath: MarkerPathEdgeV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1 | null> {\n const { item } = attempt;\n let confirmed = completed;\n let next = current;\n for (const [index, operations] of parts.entries()) {\n const opens = index === 0 && !resumed;\n const closes = index === parts.length - 1;\n const phase = { committing: false, committed: false };\n // Set once the part holds the lock as this command left it: a failure\n // before that is another command's doing, and records nothing.\n let admitted = false;\n try {\n await runProgram(\n pinned,\n command,\n {\n transactional: true,\n statements: stepStatements(item.blob, operations),\n phase,\n },\n async (producer) => {\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n opens ? false : { attemptId: attempt.attemptId, steps: confirmed }\n );\n admitted = true;\n if (opens) {\n await assertAllChecks(\n producer,\n item.blob,\n item.transition.originChecks,\n command.namespace,\n \"Origin checks failed before the first dispatch\"\n );\n await appendLedger(\n producer,\n command,\n attempt.event(\"started\", \"none\")\n );\n }\n await runForwardEdge(\n producer,\n command,\n graph,\n attempt,\n nextPath,\n models,\n false,\n undefined,\n { operations, origin: false, destination: closes }\n );\n if (!closes) return;\n const { snapshotHash } = item.state;\n next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n [...nextPath],\n snapshotHash,\n 1,\n await proveLive(\n producer,\n managedAt(command, graph, item.to, item.from),\n graph,\n snapshotHash\n )\n );\n await appendLedger(\n producer,\n command,\n attempt.event(\"applied\", \"committed\")\n );\n }\n );\n } catch (failure) {\n if (phase.committed) throw failure;\n if (\n closes &&\n phase.committing &&\n (await commitLanded(pinned, command, [item], next, failure))\n ) {\n return next;\n }\n // Only a first part that rolled back left nothing open to resume: one\n // whose COMMIT failed did when its attempt is open, or unreadable.\n if (\n opens &&\n admitted &&\n !(\n phase.committing &&\n (await attemptOpened(pinned, command, attempt.attemptId))\n )\n ) {\n await recordFailedAttempt(pinned, command, { attempt }, failure);\n }\n throw failure;\n }\n confirmed += operations.reduce(\n (count, operation) => count + operation.steps.length,\n 0\n );\n }\n return next;\n}\n\n/**\n * Whether the attempt `attemptId` is open, read after its first part's\n * COMMIT failed: `true` too when the ledger cannot be read, so a `failed`\n * event never closes an attempt whose part may have committed.\n */\nfunction attemptOpened(\n pinned: Parameters<typeof appendLedger>[0],\n command: BoundMigrationDriver,\n attemptId: Sha256\n): Promise<boolean> {\n return readControlState(pinned, command, { ledger: \"open\" }).then(\n ({ ledger }) =>\n unfinishedAttempts(ledger).some((event) => event.attemptId === attemptId),\n () => true\n );\n}\n","/**\n * Offline estate check. CI-safe. Never creates control tables.\n */\n\nimport { loadMigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { resolveSnapshotArtifacts } from \"./snapshot-artifacts\";\nimport type { MigrationStorageReader } from \"./storage/contract\";\nimport { encodeSqlBlob, parseStateManifest } from \"./v1-parse\";\n\nexport interface CheckFinding {\n readonly code: string;\n readonly message: string;\n}\n\nexport interface CheckResult {\n readonly ok: boolean;\n readonly findings: readonly CheckFinding[];\n}\n\nexport async function checkEstate(\n storage: MigrationStorageReader\n): Promise<CheckResult> {\n const findings: CheckFinding[] = [];\n try {\n const graph = await loadMigrationGraph(storage);\n if (graph.leaves.length > 1) {\n findings.push({\n code: \"unresolved-branch\",\n message: `Estate has ${graph.leaves.length} leaves; apply requires an explicit target or via`,\n });\n }\n const referencedSnapshots = new Set<Sha256>([\n graph.emptySnapshotHash,\n ...graph.snapshotArtifacts.keys(),\n ]);\n const referencedSql = new Set<Sha256>();\n for (const state of graph.states.values()) {\n referencedSql.add(state.sqlHash);\n }\n const inventory = await storage.listSnapshots();\n await resolveSnapshotArtifacts(\n storage,\n inventory,\n new Map(graph.snapshotArtifacts)\n );\n for (const hash of inventory) {\n if (!referencedSnapshots.has(hash)) {\n findings.push({\n code: \"orphan-snapshot\",\n message: `Snapshot ${hash} is not referenced by any state`,\n });\n }\n }\n for (const hash of await storage.listSql()) {\n if (!referencedSql.has(hash)) {\n findings.push({\n code: \"orphan-sql\",\n message: `SQL blob ${hash} is not referenced by any state`,\n });\n }\n const bytes = await storage.readSql(hash);\n if (bytes && encodeSqlBlob(bytes) !== hash) {\n findings.push({\n code: \"corrupt-sql\",\n message: `SQL blob ${hash} does not match its bytes`,\n });\n }\n }\n for (const id of await storage.listStates()) {\n const bytes = await storage.readState(id);\n if (bytes) parseStateManifest(bytes, id);\n }\n } catch (error) {\n findings.push({\n code: \"invalid-estate\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n return {\n ok: findings.every((finding) => finding.code.startsWith(\"orphan-\")),\n findings,\n };\n}\n","/**\n * One hostile-input boundary for generation options and manual definitions.\n * It settles every caller-owned accessor before estate or provider access.\n */\n\nimport { Sql } from \"@sql\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport type { ResolveCallback } from \"./types\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationCheckInput,\n} from \"./v1-types\";\n\nexport function normalizeGenerateOptions(options: unknown): GenerateV1Options {\n const record = snapshotExactRecord(\n options,\n [\n \"name\",\n \"from\",\n \"dryRun\",\n \"resolve\",\n \"skipValidation\",\n \"manualMigration\",\n \"lowLock\",\n \"adopt\",\n ],\n \"generate options\",\n refuseGenerateOptions\n );\n const {\n name,\n from,\n dryRun,\n resolve,\n skipValidation,\n manualMigration,\n lowLock,\n adopt,\n } = record;\n if (name !== undefined && typeof name !== \"string\") {\n return refuseGenerateOptions(\"generate name must be a string\");\n }\n if (from !== undefined && from !== null && typeof from !== \"string\") {\n return refuseGenerateOptions(\"generate from must be a state id or null\");\n }\n if (dryRun !== undefined && typeof dryRun !== \"boolean\") {\n return refuseGenerateOptions(\"generate dryRun must be a boolean\");\n }\n if (skipValidation !== undefined && typeof skipValidation !== \"boolean\") {\n return refuseGenerateOptions(\"generate skipValidation must be a boolean\");\n }\n if (lowLock !== undefined && typeof lowLock !== \"boolean\") {\n return refuseGenerateOptions(\"generate lowLock must be a boolean\");\n }\n if (resolve !== undefined && !isResolveCallback(resolve)) {\n return refuseGenerateOptions(\"generate resolve must be a function\");\n }\n return Object.freeze({\n ...(adopt === undefined ? {} : { adopt: snapshotAdopt(adopt) }),\n ...(name === undefined ? {} : { name }),\n ...(from === undefined ? {} : { from }),\n ...(dryRun === undefined ? {} : { dryRun }),\n ...(resolve === undefined ? {} : { resolve }),\n ...(skipValidation === undefined ? {} : { skipValidation }),\n ...(lowLock === undefined ? {} : { lowLock }),\n ...(manualMigration === undefined\n ? {}\n : { manualMigration: snapshotManualMigration(manualMigration) }),\n });\n}\n\n/** The physical table names `adopt` lists, detached, sorted, unrepeated. */\nfunction snapshotAdopt(value: unknown): readonly string[] {\n const names = snapshotExactArray(\n value,\n \"generate adopt\",\n refuseGenerateOptions\n );\n if (names.length === 0) {\n return refuseGenerateOptions(\"generate adopt must name at least one table\");\n }\n for (const [index, name] of names.entries()) {\n if (typeof name !== \"string\" || name.length === 0) {\n return refuseGenerateOptions(\n \"generate adopt must contain non-empty physical table names\"\n );\n }\n if (names.indexOf(name) !== index) {\n return refuseGenerateOptions(`generate adopt repeats \"${name}\"`);\n }\n }\n return Object.freeze([...(names as string[])].sort());\n}\n\nfunction snapshotManualMigration(value: unknown): ManualMigrationInput {\n const record = snapshotExactRecord(\n value,\n [\"transitions\", \"destinationChecks\"],\n \"manual migration\",\n refuseManualDefinition\n );\n const transitions = snapshotExactArray(\n record.transitions,\n \"manual migration transitions\",\n refuseManualDefinition\n ).map((transition, index) =>\n snapshotManualTransition(transition, `manual transition ${index}`)\n );\n if (transitions.length === 0) {\n return refuseManualDefinition(\n \"A manual migration must define at least one parent transition\"\n );\n }\n const destinationChecks =\n record.destinationChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.destinationChecks,\n \"manual destination checks\",\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `manual destination check ${index}`)\n );\n return Object.freeze({\n transitions: Object.freeze(transitions),\n ...(destinationChecks === undefined\n ? {}\n : { destinationChecks: Object.freeze(destinationChecks) }),\n });\n}\n\nfunction snapshotManualTransition(\n value: unknown,\n label: string\n): ManualTransitionInput {\n const record = snapshotExactRecord(\n value,\n [\"from\", \"execution\", \"up\", \"originChecks\", \"rollback\"],\n label,\n refuseManualDefinition\n );\n const { from, execution } = record;\n if (from !== null && typeof from !== \"string\") {\n return refuseManualDefinition(`${label}.from must be a state id or null`);\n }\n if (execution !== \"transactional\" && execution !== \"stepwise\") {\n return refuseManualDefinition(\n `${label}.execution must be transactional or stepwise`\n );\n }\n const up = snapshotSqlArray(record.up, `${label}.up`);\n const originChecks =\n record.originChecks === undefined\n ? undefined\n : snapshotExactArray(\n record.originChecks,\n `${label}.originChecks`,\n refuseManualDefinition\n ).map((check, index) =>\n snapshotManualCheck(check, `${label}.originChecks[${index}]`)\n );\n return Object.freeze({\n from,\n execution,\n up,\n ...(originChecks === undefined\n ? {}\n : { originChecks: Object.freeze(originChecks) }),\n rollback: snapshotManualRollback(record.rollback, `${label}.rollback`),\n });\n}\n\nfunction snapshotManualRollback(\n value: unknown,\n label: string\n): ManualTransitionInput[\"rollback\"] {\n const discriminant = snapshotExactRecord(\n value,\n [\"kind\", \"execution\", \"sql\", \"reason\"],\n label,\n refuseManualDefinition\n );\n if (discriminant.kind === \"irreversible\") {\n if (\n discriminant.execution !== undefined ||\n discriminant.sql !== undefined ||\n typeof discriminant.reason !== \"string\"\n ) {\n return refuseManualDefinition(\n `${label} has an invalid irreversible shape`\n );\n }\n return Object.freeze({\n kind: \"irreversible\",\n reason: discriminant.reason,\n });\n }\n if (discriminant.kind !== \"manual\") {\n return refuseManualDefinition(`${label}.kind is invalid`);\n }\n if (\n discriminant.reason !== undefined ||\n (discriminant.execution !== \"transactional\" &&\n discriminant.execution !== \"stepwise\")\n ) {\n return refuseManualDefinition(`${label} has an invalid manual shape`);\n }\n return Object.freeze({\n kind: \"manual\",\n execution: discriminant.execution,\n sql: snapshotSqlArray(discriminant.sql, `${label}.sql`),\n });\n}\n\nfunction snapshotManualCheck(\n value: unknown,\n label: string\n): MigrationCheckInput {\n const record = snapshotExactRecord(\n value,\n [\"kind\", \"query\", \"equals\"],\n label,\n refuseManualDefinition\n );\n if (record.kind !== \"trusted-read\" || typeof record.equals !== \"boolean\") {\n return refuseManualDefinition(`${label} has an invalid check shape`);\n }\n return Object.freeze({\n kind: \"trusted-read\",\n query: snapshotSql(record.query, `${label}.query`),\n equals: record.equals,\n });\n}\n\nfunction snapshotSqlArray(value: unknown, label: string): readonly Sql[] {\n const entries = snapshotExactArray(value, label, refuseManualDefinition);\n const sql: Sql[] = [];\n for (let index = 0; index < entries.length; index++) {\n sql.push(snapshotSql(entries[index], `${label}[${index}]`));\n }\n return Object.freeze(sql);\n}\n\nfunction snapshotSql(value: unknown, label: string): Sql {\n try {\n if (!(value instanceof Sql)) {\n return refuseManualDefinition(`${label} must be a Sql value`);\n }\n const rawStrings: unknown = Reflect.get(value, \"strings\");\n const rawValues: unknown = Reflect.get(value, \"values\");\n if (!(Array.isArray(rawStrings) && Array.isArray(rawValues))) {\n return refuseManualDefinition(\n `${label}.strings and ${label}.values must be arrays`\n );\n }\n const strings = Array.from(rawStrings);\n const values = Array.from(rawValues);\n if (!strings.every((entry) => typeof entry === \"string\")) {\n return refuseManualDefinition(`${label}.strings must contain strings`);\n }\n if (strings.length !== values.length + 1) {\n return refuseManualDefinition(\n `${label} has an invalid strings and values shape`\n );\n }\n return new Sql(Object.freeze(strings), Object.freeze(values));\n } catch (failure) {\n return refuseManualDefinition(\n `${label} could not be read`,\n errorCause(failure)\n );\n }\n}\n\nfunction isResolveCallback(value: unknown): value is ResolveCallback {\n return typeof value === \"function\";\n}\n\nfunction refuseGenerateOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction refuseManualDefinition(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_ESTATE, {\n cause,\n });\n}\n","/** Immutable, non-executable migration graph projections for public tooling. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type { MigrationGraph } from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type { MigrationTarget } from \"./types\";\nimport type {\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationDispatchV1,\n MigrationOperationV1,\n MigrationParentTransitionV1,\n MigrationStateManifestV1,\n} from \"./v1-types\";\n\nexport interface MigrationStateListItem {\n readonly stateId: Sha256;\n readonly name: string;\n}\n\nexport interface MigrationStateMetadata extends MigrationStateListItem {\n readonly snapshotHash: Sha256;\n readonly sqlHash: Sha256;\n readonly root: boolean;\n readonly leaf: boolean;\n}\n\nexport type MigrationRollbackMetadata =\n | {\n readonly kind: \"schema\" | \"manual\";\n readonly operationCount: number;\n readonly stepCount: number;\n }\n | {\n readonly kind: \"irreversible\";\n readonly reason: string;\n readonly operationCount: 0;\n readonly stepCount: 0;\n };\n\nexport interface MigrationEdgeMetadata {\n readonly fromState: Sha256 | null;\n readonly toState: Sha256;\n readonly transitionHash: Sha256;\n readonly requestedBoundary: \"transactional\" | \"stepwise\" | null;\n readonly operationCount: number;\n readonly stepCount: number;\n readonly origins: readonly (\"generated\" | \"manual\")[];\n readonly risks: readonly (\"safe\" | \"destructive\" | \"opaque\")[];\n /** The destructive changes approved at `generate`; empty when none was asked. */\n readonly approvals: readonly MigrationApprovalV1[];\n /** The existing tables this edge adopts without DDL; empty when none. */\n readonly adopts: readonly string[];\n readonly rollback: MigrationRollbackMetadata;\n}\n\nexport interface MigrationStateDetails extends MigrationStateMetadata {\n readonly incoming: readonly MigrationEdgeMetadata[];\n readonly outgoing: readonly MigrationEdgeMetadata[];\n}\n\nexport interface GraphResult {\n readonly estateHash: Sha256;\n readonly target: MigrationTarget;\n readonly roots: readonly Sha256[];\n readonly leaves: readonly Sha256[];\n readonly states: readonly MigrationStateMetadata[];\n readonly edges: readonly MigrationEdgeMetadata[];\n}\n\nexport type ListResult = readonly MigrationStateListItem[];\nexport type ShowResult = MigrationStateDetails;\n\nexport function listMigrationStates(graph: MigrationGraph): ListResult {\n return Object.freeze(\n sortedStates(graph).map((state) =>\n Object.freeze({ stateId: state.stateId, name: state.name })\n )\n );\n}\n\nexport function showMigrationState(\n graph: MigrationGraph,\n stateId: Sha256\n): ShowResult {\n const state = graph.states.get(stateId);\n if (!state) {\n throw new MigrationError(\n \"Resolved migration state is absent from its graph\",\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n const edges = graphEdges(graph);\n return Object.freeze({\n ...stateMetadata(graph, state),\n incoming: Object.freeze(edges.filter((edge) => edge.toState === stateId)),\n outgoing: Object.freeze(edges.filter((edge) => edge.fromState === stateId)),\n });\n}\n\nexport function migrationGraphResult(graph: MigrationGraph): GraphResult {\n return Object.freeze({\n estateHash: graph.estateHash,\n target: migrationTarget(graph.descriptor.target),\n roots: Object.freeze([...graph.roots].sort()),\n leaves: Object.freeze([...graph.leaves].sort()),\n states: Object.freeze(\n sortedStates(graph).map((state) => stateMetadata(graph, state))\n ),\n edges: graphEdges(graph),\n });\n}\n\nfunction sortedStates(graph: MigrationGraph): MigrationStateManifestV1[] {\n return [...graph.states.values()].sort((left, right) =>\n left.stateId.localeCompare(right.stateId)\n );\n}\n\nfunction stateMetadata(\n graph: MigrationGraph,\n state: MigrationStateManifestV1\n): MigrationStateMetadata {\n return Object.freeze({\n stateId: state.stateId,\n name: state.name,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n root: graph.roots.includes(state.stateId),\n leaf: graph.leaves.includes(state.stateId),\n });\n}\n\nfunction graphEdges(graph: MigrationGraph): readonly MigrationEdgeMetadata[] {\n const edges: MigrationEdgeMetadata[] = [];\n for (const state of sortedStates(graph)) {\n for (const transition of state.parents) {\n edges.push(edgeMetadata(state.stateId, transition));\n }\n }\n edges.sort((left, right) => {\n const from = (left.fromState ?? \"\").localeCompare(right.fromState ?? \"\");\n return from === 0 ? left.toState.localeCompare(right.toState) : from;\n });\n return Object.freeze(edges);\n}\n\nfunction edgeMetadata(\n toState: Sha256,\n transition: MigrationParentTransitionV1\n): MigrationEdgeMetadata {\n return Object.freeze({\n fromState: transition.fromState,\n toState,\n transitionHash: transition.transitionHash,\n requestedBoundary: transition.requestedForwardBoundary,\n operationCount: transition.operations.length,\n stepCount: stepCount(transition.operations),\n origins: uniqueOperationValues(transition.operations, \"origin\"),\n risks: uniqueOperationValues(transition.operations, \"risk\"),\n approvals: Object.freeze(\n (transition.approvals ?? []).map((approval) =>\n Object.freeze({ ...approval })\n )\n ),\n adopts: Object.freeze([...(transition.adopts ?? [])]),\n rollback: rollbackMetadata(transition),\n });\n}\n\nfunction rollbackMetadata(\n transition: MigrationParentTransitionV1\n): MigrationRollbackMetadata {\n if (transition.rollback.kind === \"irreversible\") {\n return Object.freeze({\n kind: transition.rollback.kind,\n reason: transition.rollback.reason,\n operationCount: 0,\n stepCount: 0,\n });\n }\n const operations = transition.rollback.operations;\n return Object.freeze({\n kind: transition.rollback.kind,\n operationCount: operations.length,\n stepCount: stepCount(operations),\n });\n}\n\nfunction stepCount(operations: readonly MigrationOperationV1[]): number {\n let count = 0;\n for (const operation of operations) count += operation.steps.length;\n return count;\n}\n\nfunction uniqueOperationValues<K extends \"origin\" | \"risk\">(\n operations: readonly MigrationOperationV1[],\n key: K\n): readonly MigrationOperationV1[K][] {\n const values: MigrationOperationV1[K][] = [];\n for (const operation of operations) {\n const value = operation[key];\n if (!values.includes(value)) values.push(value);\n }\n return Object.freeze(values);\n}\n\nfunction migrationTarget(target: MigrationTarget): MigrationTarget {\n return target.dialect === \"postgresql\"\n ? Object.freeze({ dialect: target.dialect, namespace: target.namespace })\n : Object.freeze({ dialect: target.dialect });\n}\n\nconst LINE_BREAKS = /[\\r\\n\\u2028\\u2029]/g;\nconst oneLine = (text: string) => text.replace(LINE_BREAKS, \" \");\n\n/**\n * A labelled read-only projection; dispatch offsets remain the execution authority.\n * `approvalLabel` names the approvals: a preview made without a resolver lists\n * the ones publishing will need, not ones given.\n */\nexport function renderMigrationReview(\n parents: readonly MigrationParentTransitionV1[],\n destinationChecks: readonly MigrationBooleanCheckV1[],\n blob: Uint8Array,\n approvalLabel = \"Approved at generate\"\n): string {\n const lines = [\n \"-- VibORM review: forward, checks and rollback are separate sections.\",\n \"-- Execute authenticated states with migrate apply/down; this review is not an apply script.\",\n ];\n const emit = (label: string, dispatch: MigrationDispatchV1) => {\n lines.push(`-- ${oneLine(label)}`, `${sliceDispatch(blob, dispatch)};`);\n if (dispatch.parameters.length > 0)\n lines.push(`-- Parameters: ${JSON.stringify(dispatch.parameters)}`);\n };\n const operations = (\n direction: string,\n values: readonly MigrationOperationV1[]\n ) => {\n for (const operation of values)\n for (const step of operation.steps) {\n if (step.retry === \"proven\")\n emit(`${direction} precheck ${operation.label}`, step.precheck.query);\n emit(`${direction} execute ${operation.label}`, step.execute);\n if (step.retry === \"proven\")\n emit(\n `${direction} postcheck ${operation.label}`,\n step.postcheck.query\n );\n }\n };\n for (const parent of parents) {\n lines.push(`\\n-- Parent ${parent.fromState ?? \"empty\"}`);\n for (const table of parent.adopts ?? [])\n lines.push(\n `-- Adopts existing table ${oneLine(table)}: no DDL; apply proves its live shape equals the declaration`\n );\n for (const { operation, table, column } of parent.approvals ?? [])\n lines.push(\n `-- ${approvalLabel}: ${oneLine(`${operation} ${table}${column === null ? \"\" : `.${column}`}`)}`\n );\n for (const check of parent.originChecks)\n emit(`Origin check ${check.id}`, check.query);\n operations(\"FORWARD\", parent.operations);\n if (parent.rollback.kind === \"irreversible\")\n lines.push(`-- ROLLBACK unavailable: ${oneLine(parent.rollback.reason)}`);\n else operations(\"ROLLBACK\", parent.rollback.operations);\n }\n for (const check of destinationChecks)\n emit(`Destination check ${check.id}`, check.query);\n return `${lines.join(\"\\n\\n\")}\\n`;\n}\n","/**\n * Hostile admission for push options and inert consent.\n *\n * Consent is not authority. A forged or stale value can only refuse\n * execution. Apply replans under the lock and compares this closed shape.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJsonText } from \"./canonical-json\";\nimport { isSha256, type Sha256 } from \"./identity\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./input-boundary\";\nimport { freezeDeep } from \"./push-fingerprint\";\nimport type { ResolveCallback } from \"./types\";\nimport type {\n PushConsent,\n PushResolution,\n PushTargetIdentity,\n} from \"./v1-types\";\n\ninterface ConsentedPlan {\n readonly mode: PushConsent[\"mode\"];\n readonly validation: PushConsent[\"validation\"];\n readonly target: PushTargetIdentity;\n readonly sourceFingerprint: Sha256;\n readonly planHash: Sha256;\n readonly resolutions: readonly PushResolution[];\n}\n\nexport interface ParsedPlanningOptions {\n readonly forceReset: boolean;\n readonly skipValidation: boolean;\n readonly resolve: ResolveCallback | undefined;\n readonly dryRun: boolean;\n}\n\nexport function snapshotPushOptions(\n value: unknown\n): Readonly<Record<string, unknown>> {\n return snapshotExactRecord(\n value,\n [\"consent\", \"dryRun\", \"forceReset\", \"resolve\", \"skipValidation\"],\n \"push options\",\n invalidOptions\n );\n}\n\nexport function parsePlanningOptions(\n value: unknown,\n dryRun: boolean\n): ParsedPlanningOptions {\n const record = snapshotExactRecord(\n value,\n [\"dryRun\", \"forceReset\", \"resolve\", \"skipValidation\"],\n \"push options\",\n invalidOptions\n );\n return parseSnapshottedPlanningOptions(record, dryRun);\n}\n\nexport function parseSnapshottedPlanningOptions(\n record: Readonly<Record<string, unknown>>,\n dryRun: boolean\n): ParsedPlanningOptions {\n if (record.dryRun !== undefined && typeof record.dryRun !== \"boolean\") {\n invalidOptions(\"push options.dryRun must be boolean\");\n }\n if (\n record.forceReset !== undefined &&\n typeof record.forceReset !== \"boolean\"\n ) {\n invalidOptions(\"push options.forceReset must be boolean\");\n }\n if (\n record.skipValidation !== undefined &&\n typeof record.skipValidation !== \"boolean\"\n ) {\n invalidOptions(\"push options.skipValidation must be boolean\");\n }\n const candidate = record.resolve;\n if (candidate !== undefined && typeof candidate !== \"function\") {\n invalidOptions(\"push options.resolve must be a function\");\n }\n const resolve: ResolveCallback | undefined =\n typeof candidate === \"function\"\n ? (change) => Reflect.apply(candidate, undefined, [change])\n : undefined;\n return {\n dryRun: dryRun || record.dryRun === true,\n forceReset: record.forceReset === true,\n skipValidation: record.skipValidation === true,\n resolve,\n };\n}\n\nexport function parseConsent(value: unknown): PushConsent {\n const record = snapshotExactRecord(\n value,\n [\"format\", \"mode\", \"planHash\", \"resolutions\", \"target\", \"validation\"],\n \"push consent\",\n consentMismatch\n );\n if (record.format !== \"1\") consentMismatch(\"consent.format must be 1\");\n if (record.mode !== \"diff\" && record.mode !== \"force-reset\") {\n consentMismatch(\"consent.mode is invalid\");\n }\n if (record.validation !== \"full\" && record.validation !== \"structural-only\") {\n consentMismatch(\"consent.validation is invalid\");\n }\n if (!isSha256(record.planHash)) {\n consentMismatch(\"consent.planHash is invalid\");\n }\n const resolutionEntries = snapshotExactArray(\n record.resolutions,\n \"consent.resolutions\",\n consentMismatch\n );\n const resolutions = resolutionEntries.map((resolution, index) => {\n const item = snapshotExactRecord(\n resolution,\n [\"decision\", \"id\"],\n `consent.resolutions[${index}]`,\n consentMismatch\n );\n if (typeof item.id !== \"string\" || typeof item.decision !== \"string\") {\n consentMismatch(`consent.resolutions[${index}] is invalid`);\n }\n return { id: item.id, decision: item.decision };\n });\n return freezeDeep({\n format: \"1\",\n target: parseTarget(record.target),\n planHash: record.planHash,\n mode: record.mode,\n validation: record.validation,\n resolutions,\n });\n}\n\nexport function assertAcceptedPlan(\n accepted: ConsentedPlan,\n locked: ConsentedPlan\n): void {\n if (\n accepted.sourceFingerprint !== locked.sourceFingerprint ||\n accepted.planHash !== locked.planHash\n ) {\n throw new MigrationError(\n \"The live push plan changed before the locked replan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: accepted.planHash,\n actualChecksum: locked.planHash,\n planHash: locked.planHash,\n expectedFingerprint: accepted.sourceFingerprint,\n actualFingerprint: locked.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function assertConsent(consent: PushConsent, plan: ConsentedPlan): void {\n const targetMatches =\n canonicalizeJsonText(consent.target) === canonicalizeJsonText(plan.target);\n const resolutionsMatch =\n canonicalizeJsonText(consent.resolutions) ===\n canonicalizeJsonText(plan.resolutions);\n if (\n consent.mode !== plan.mode ||\n consent.validation !== plan.validation ||\n !targetMatches ||\n !resolutionsMatch ||\n consent.planHash !== plan.planHash\n ) {\n throw new MigrationError(\n \"Push consent does not match the locked live plan\",\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n meta: {\n expectedChecksum: consent.planHash,\n actualChecksum: plan.planHash,\n planHash: plan.planHash,\n fingerprint: plan.sourceFingerprint,\n },\n }\n );\n }\n}\n\nexport function hasConsent(\n options: Readonly<Record<string, unknown>>\n): options is Readonly<Record<string, unknown>> & {\n readonly consent: unknown;\n} {\n return \"consent\" in options;\n}\n\nfunction parseTarget(value: unknown): PushTargetIdentity {\n const record = snapshotExactRecord(\n value,\n [\"database\", \"dialect\", \"location\", \"namespace\"],\n \"consent.target\",\n consentMismatch\n );\n if (record.dialect === \"postgresql\") {\n refuseTargetKeys(record, [\"database\", \"dialect\", \"namespace\"]);\n return {\n dialect: \"postgresql\",\n database: requiredString(record.database, \"consent.target.database\"),\n namespace: requiredString(record.namespace, \"consent.target.namespace\"),\n };\n }\n if (record.dialect === \"mysql\" || record.dialect === \"surrealql\") {\n refuseTargetKeys(record, [\"database\", \"dialect\"]);\n return {\n dialect: record.dialect,\n database: requiredString(record.database, \"consent.target.database\"),\n };\n }\n if (record.dialect === \"sqlite\") {\n refuseTargetKeys(record, [\"dialect\", \"location\"]);\n if (record.location !== null && typeof record.location !== \"string\") {\n consentMismatch(\"consent.target.location must be string or null\");\n }\n return { dialect: \"sqlite\", location: record.location };\n }\n consentMismatch(\"consent.target.dialect is invalid\");\n}\n\nfunction refuseTargetKeys(\n target: Readonly<Record<string, unknown>>,\n allowed: readonly string[]\n): void {\n for (const key of Object.keys(target)) {\n if (!allowed.includes(key)) {\n consentMismatch(`consent.target contains unknown key ${key}`);\n }\n }\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n consentMismatch(`${label} must be a non-empty string`);\n }\n return value;\n}\n\nfunction invalidOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n\nfunction consentMismatch(message: string, cause?: Error): never {\n throw new MigrationError(\n message,\n VibORMErrorCode.MIGRATION_CONSENT_MISMATCH,\n {\n cause,\n }\n );\n}\n","/**\n * Authenticated, history-free push.\n *\n * A preview exposes review text and inert consent. The executable program stays\n * private, is rebuilt from the live catalog under the target lock, and is\n * dispatched only through the structured-statement compiler.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { hydrateSchemaNames } from \"../schema/hydration\";\nimport type { ResolvedRelationIndex } from \"../schema/validation/relation-resolution\";\nimport { allRules } from \"../schema/validation/rules\";\nimport {\n resolveSchemaOrThrow,\n validateResolvedSchemaOrThrow,\n} from \"../schema/validation/validator\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { refuseIncompatibleHistory, unfinishedAttempts } from \"./control\";\nimport { diff } from \"./differ\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n executeDispatch,\n executeDispatchGroup,\n rerunsRefusedCommits,\n} from \"./execute-dispatch\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport {\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport {\n assertAcceptedPlan,\n assertConsent,\n hasConsent,\n parseConsent,\n parsePlanningOptions,\n parseSnapshottedPlanningOptions,\n snapshotPushOptions,\n} from \"./push-consent\";\nimport { fingerprintLive, freezeDeep } from \"./push-fingerprint\";\nimport {\n buildPushPlan,\n type InternalPushPlan,\n introspectManaged,\n} from \"./push-plan\";\nimport { readCommandControl } from \"./resume\";\nimport { assertMigrationDecimalDomainsFitProvider } from \"./serializer\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport type { DiffOperation } from \"./types\";\nimport type {\n PushApplyResult as BasePushApplyResult,\n PushPreview as BasePushPreview,\n ExactPushOptions,\n MigrationDispatchV1,\n PushConsent,\n PushOptionsV1,\n PushPlanningOptions,\n} from \"./v1-types\";\n\nexport type {\n ExactPushOptions,\n PushConsent,\n PushOperation,\n PushOptionsV1,\n PushOptionsV1 as PushOptions,\n PushPlanningOptions,\n PushResolution,\n PushStatementPreview,\n PushTargetIdentity,\n} from \"./v1-types\";\n\nexport interface PushAttestation {\n readonly pathHash: Sha256;\n readonly planHash: Sha256;\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport interface PushApplyResult extends BasePushApplyResult {\n readonly attestation: PushAttestation;\n}\n\nexport interface PushPreview extends BasePushPreview {\n readonly schemaHash: Sha256;\n readonly fingerprint: Sha256;\n}\n\nexport type PushResultFor<O> = [O] extends [{ readonly dryRun: true }]\n ? PushPreview\n : PushApplyResult;\n\n/**\n * Effect-free planning. It does not acquire a lock and never receives estate\n * storage. A force reset plans the empty-to-target rebuild rather than diffing\n * the desired schema from the live schema.\n */\nexport async function previewPush(\n client: MigrationClient,\n options: PushPlanningOptions = {}\n): Promise<PushPreview> {\n const parsed = parsePlanningOptions(options, true);\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"read-only\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n const command = await resolveCommandDriver(client.$driver, driver);\n const plan = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n return publicPreview(plan);\n}\n\n/**\n * Replans and executes on one pinned producer under the target lock.\n *\n * Generic force is deliberately absent. Destructive diff work and every\n * force-reset plan require exact preview consent.\n */\nexport function pushV1<O extends PushOptionsV1>(\n client: MigrationClient,\n options?: ExactPushOptions<O>\n): Promise<PushResultFor<O>>;\nexport async function pushV1(\n client: MigrationClient,\n options?: PushOptionsV1\n): Promise<PushApplyResult | PushPreview> {\n const given = snapshotPushOptions(options ?? {});\n if (hasConsent(given)) {\n return applyWithConsent(client, parseConsent(given.consent));\n }\n\n const parsed = parseSnapshottedPlanningOptions(given, given.dryRun === true);\n if (parsed.dryRun) {\n return previewPush(client, parsed);\n }\n\n const { relations, driver } = prepareSchema(client, parsed.skipValidation);\n\n // A resolver may perform arbitrary user work. Run it only during an unlocked\n // read-only plan, then close its normalized answers for the locked replan.\n let accepted: InternalPushPlan | undefined;\n if (parsed.resolve) {\n admitLiveMigrationCapability(driver, \"read-only\", \"push()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n accepted = await buildPushPlan(\n client,\n client.$driver,\n command,\n relations,\n parsed,\n { kind: \"record\", callback: parsed.resolve }\n );\n }\n\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n parsed.forceReset ? \"push({ forceReset: true })\" : \"push()\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n parsed,\n accepted\n ? { kind: \"replay\", resolutions: accepted.resolutions }\n : { kind: \"record\", callback: undefined }\n );\n if (accepted) assertAcceptedPlan(accepted, plan);\n await assertPushControlInterlock(pinned, command, plan);\n if (plan.destructive) {\n throw new MigrationError(\n \"Destructive or force-reset push requires exact preview consent. Call push({ dryRun: true }), review the plan, then pass its consent unchanged to push({ consent }).\",\n VibORMErrorCode.MIGRATION_CONSENT_REQUIRED,\n {\n meta: {\n command: \"push\",\n dialect: plan.target.dialect,\n expectedChecksum: plan.planHash,\n expectedStatementCount: plan.statements.length,\n hint: \"Review push({ dryRun: true }) and pass the returned consent unchanged to push({ consent }).\",\n },\n }\n );\n }\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function applyWithConsent(\n client: MigrationClient,\n consent: PushConsent\n): Promise<PushApplyResult> {\n const skipValidation = consent.validation === \"structural-only\";\n const { relations, driver } = prepareSchema(client, skipValidation);\n admitLiveMigrationCapability(\n driver,\n \"effectful\",\n consent.mode === \"force-reset\"\n ? \"push({ consent: forceResetPreview.consent })\"\n : \"push({ consent })\"\n );\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const plan = await buildPushPlan(\n client,\n pinned,\n command,\n relations,\n {\n forceReset: consent.mode === \"force-reset\",\n skipValidation,\n resolve: undefined,\n dryRun: false,\n },\n { kind: \"replay\", resolutions: consent.resolutions }\n );\n assertConsent(consent, plan);\n await assertPushControlInterlock(pinned, command, plan);\n return executeLockedPlan(pinned, command, plan);\n }\n );\n}\n\nasync function executeLockedPlan(\n pinned: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<PushApplyResult> {\n // A plan with nothing to do still has a MySQL sequential program to run: the\n // interrupted-decimal-conversion recovery belongs to the LOCKED COMMAND, not\n // to having statements. A conversion interrupted after its MODIFY leaves the\n // column already carrying the target domain, so the differ sees no change\n // and the plan is empty — and the remnant CHECK, which no snapshot\n // vocabulary describes, would then survive every later push while refusing\n // values the declared domain admits.\n if (plan.statements.length === 0 && command.target.dialect !== \"mysql\") {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n\n // A driver that makes one transaction of a batch, and runs it again when\n // refused at its commit (SurrealDB), creates new tables one operation per\n // transaction, each one request: a transaction around a whole schema stays\n // open for a round trip per statement, which the server refuses at its\n // commit the more often the longer it ran (SurrealDB Cloud). Part of such a\n // program leaves the operations before the one that failed, which the next\n // push, planning from them, completes; any other program keeps its one\n // transaction.\n const grouped =\n plan.atomicity === \"transactional\" &&\n createsTablesOnly(plan.operations) &&\n rerunsRefusedCommits(pinned)\n ? pinned\n : undefined;\n // In a transaction the destination is proven before its COMMIT, and the\n // lifted foreign-key bracket runs around it (its pragmas, sent again\n // inside, are no-ops there); otherwise once the statements ran — on MySQL\n // after its sequential program.\n const fingerprint = await runProgram(\n pinned,\n command,\n {\n transactional: plan.atomicity === \"transactional\" && !grouped,\n statements: plan.statements.map((statement) =>\n sliceDispatch(plan.sqlBlob, statement.dispatch)\n ),\n },\n async (producer, atomic) => {\n // Each statement alone or, grouped, each operation's statements\n // together: they are contiguous, and each names its operation.\n const groups: MigrationDispatchV1[][] = [];\n for (const [\n index,\n { operation, dispatch },\n ] of plan.statements.entries()) {\n if (grouped && operation === plan.statements[index - 1]?.operation)\n groups.at(-1)!.push(dispatch);\n else groups.push([dispatch]);\n }\n for (const group of groups) {\n await (grouped\n ? executeDispatchGroup(\n grouped,\n plan.sqlBlob,\n group,\n command.namespace\n )\n : executeDispatch(\n producer,\n plan.sqlBlob,\n group[0]!,\n command.namespace\n ));\n }\n return atomic ? attestFinalFingerprint(producer, command, plan) : null;\n }\n );\n if (plan.statements.length === 0) {\n return appliedResult(plan, plan.sourceFingerprint, \"noop\");\n }\n return appliedResult(\n plan,\n fingerprint ?? (await attestFinalFingerprint(pinned, command, plan)),\n \"applied\"\n );\n}\n\n/**\n * Whether `operations` create tables, and references to them, and touch\n * nothing else. A reference to a table created after its own waits for it in\n * an operation of its own (`extractForwardReferenceForeignKeys`), whose table\n * a push stopped between the two has already created.\n */\nfunction createsTablesOnly(operations: readonly DiffOperation[]): boolean {\n const created = new Set(\n operations.flatMap((operation) =>\n operation.type === \"createTable\" ? [operation.table.name] : []\n )\n );\n return operations.every(\n (operation) =>\n operation.type === \"createTable\" ||\n (operation.type === \"addForeignKey\" &&\n created.has(operation.fk.referencedTable))\n );\n}\n\nasync function attestFinalFingerprint(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<Sha256> {\n const finalSnapshot = await introspectManaged(producer, command);\n const fingerprint = await fingerprintLive(finalSnapshot, command, producer);\n const expected = await fingerprintLive(plan.desiredSchema, command, producer);\n if (fingerprint !== expected) {\n throw new MigrationError(\n `Push completed its statements but the final live fingerprint does not match the desired schema: ${JSON.stringify(await diff(finalSnapshot, plan.desiredSchema))}`,\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n }\n );\n }\n return fingerprint;\n}\n\nfunction appliedResult(\n plan: InternalPushPlan,\n fingerprint: Sha256,\n outcome: PushApplyResult[\"outcome\"]\n): PushApplyResult {\n const pathHash = domainHash(\n HASH_DOMAIN.path,\n canonicalizeJson({\n target: plan.target,\n sourceFingerprint: plan.sourceFingerprint,\n fingerprint,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n })\n );\n return freezeDeep({\n outcome,\n target: plan.target,\n planHash: plan.planHash,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n attestation: {\n pathHash,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint,\n },\n });\n}\n\nasync function assertPushControlInterlock(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n plan: InternalPushPlan\n): Promise<void> {\n // A driver holding its own lock keeps no control tables to interlock with.\n if (command.holdLock) return;\n const control = await readCommandControl(producer, command);\n if (control.presence.kind !== \"present\") return;\n const { marker, ledger } = control;\n if (unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking push\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n refuseIncompatibleHistory(marker, ledger);\n if (!marker) {\n return;\n }\n if (plan.operations.length > 0 || plan.mode === \"force-reset\") {\n throw new MigrationError(\n \"Non-empty push against a migration marker is refused; use generate/apply or history-aware reset\",\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { planHash: plan.planHash } }\n );\n }\n if (\n marker.snapshotHash !== plan.schemaHash ||\n plan.sourceFingerprint !== plan.desiredFingerprint\n ) {\n throw new MigrationError(\n \"A no-op push cannot prove agreement between the marker, live schema, and desired schema\",\n VibORMErrorCode.MIGRATION_DRIFT,\n {\n meta: {\n planHash: plan.planHash,\n expectedChecksum: marker.snapshotHash,\n actualChecksum: plan.schemaHash,\n },\n }\n );\n }\n}\n\nfunction publicPreview(plan: InternalPushPlan): PushPreview {\n const consent: PushConsent = {\n format: \"1\",\n target: plan.target,\n planHash: plan.planHash,\n mode: plan.mode,\n validation: plan.validation,\n resolutions: plan.resolutions,\n };\n return freezeDeep({\n outcome: plan.statements.length === 0 ? \"noop\" : \"planned\",\n target: plan.target,\n planHash: plan.planHash,\n schemaHash: plan.schemaHash,\n fingerprint: plan.sourceFingerprint,\n destructive: plan.destructive,\n operations: plan.reportedOperations,\n statements: plan.previewStatements,\n consent,\n });\n}\n\nexport function prepareSchema(\n client: MigrationClient,\n skipValidation: boolean\n): {\n readonly relations: ResolvedRelationIndex;\n readonly driver: BoundMigrationDriver;\n} {\n hydrateSchemaNames(client.$schema);\n const relations = skipValidation\n ? resolveSchemaOrThrow(client.$schema)\n : validateResolvedSchemaOrThrow(client.$schema, allRules());\n const driver = getPushMigrationDriver(client);\n assertMigrationDecimalDomainsFitProvider(client.$schema, driver.dialect);\n return { relations, driver };\n}\n","/**\n * V1 generation: one new state from parent leaves, published atomically.\n * Snapshot and SQL are published before the state manifest.\n */\n\nimport type { SqlDialect } from \"../drivers/types\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport {\n assertManualStepwiseProof,\n type CompiledTransition,\n compileGeneratedTransition,\n compileManualTransition,\n compileTrustedCheck,\n compileValidationTransition,\n hashParent,\n type LowLockState,\n lowLockStates,\n lowLockSteps,\n rebindChecks,\n rebindDispatches,\n rebindRollback,\n sealParent,\n} from \"./compile\";\nimport { type DiffOptions, diff } from \"./differ\";\nimport { emptyManagedSnapshot } from \"./empty-snapshot\";\nimport { normalizeGenerateOptions } from \"./generate-input\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n requireStateSnapshot,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport { renderMigrationReview } from \"./public-view\";\nimport {\n applyResolvedEnumMappings,\n detectEnumValueRemovals,\n resolveEnumValueRemovalMappings,\n} from \"./push/enum-removals\";\nimport type { getPushMigrationDriver, MigrationClient } from \"./push/planner\";\nimport { prepareSchema } from \"./push-v1\";\nimport {\n approveDestructiveOperations,\n callbackAsResolver,\n refuseUnusedDecisions,\n rejectAllResolver,\n resolveAmbiguousChanges,\n strictResolver,\n} from \"./resolver\";\nimport { serializeResolvedModels } from \"./serializer\";\nimport {\n type EncodedSnapshotArtifact,\n encodeSnapshotArtifact,\n} from \"./snapshot-artifacts\";\nimport { SqlAssembly } from \"./sql-assembly\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { assertArtifactExecutionSafe } from \"./statement-safety\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { assertEstateTargetMatches } from \"./target\";\nimport type { DiffOperation, ResolveCallback, SchemaSnapshot } from \"./types\";\nimport { generateMigrationName, prepareSchemaProgram } from \"./utils\";\nimport {\n encodeEstateDescriptor,\n encodeSnapshot,\n encodeStateManifest,\n parseEstateDescriptor,\n} from \"./v1-parse\";\nimport type {\n GenerateV1Options,\n ManualMigrationInput,\n ManualTransitionInput,\n MigrationApprovalV1,\n MigrationBooleanCheckV1,\n MigrationParentTransitionV1,\n} from \"./v1-types\";\n\nexport interface GenerateV1Result {\n readonly outcome: \"published\" | \"preview\" | \"noop\";\n readonly stateId: Sha256 | null;\n readonly name: string | null;\n readonly estateHash: Sha256 | null;\n readonly snapshotHash: Sha256 | null;\n readonly sqlHash: Sha256 | null;\n readonly operations: readonly DiffOperation[];\n readonly warnings: readonly string[];\n readonly operationsByParent: readonly {\n readonly fromState: string | null;\n readonly operations: readonly DiffOperation[];\n }[];\n readonly sql: string;\n readonly reviewSql: string;\n}\n\nconst AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS: DiffOptions = {\n compareDateTimeDeclarations: true,\n};\n\n/**\n * A dry run without a resolver previews the state as an approval would publish\n * it, as push's preview does; publishing still needs the resolver's answer.\n */\nconst previewApproval: ResolveCallback = (change) =>\n change.type === \"destructive\" ? change.proceed() : undefined;\n\nexport async function generateV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: GenerateV1Options = {}\n): Promise<GenerateV1Result> {\n const request = normalizeGenerateOptions(options);\n const { relations, driver } = prepareSchema(\n client,\n request.skipValidation ?? false\n );\n // An estate's own format admits no dialect without a history.\n const dialect = driver.target.dialect as SqlDialect;\n const publishedEstate = await storage.readEstate();\n const estateBytes =\n publishedEstate ?? encodeEstateDescriptor(driver.target).bytes;\n const { estateHash, descriptor } = parseEstateDescriptor(estateBytes);\n assertEstateTargetMatches(descriptor.target, driver.target);\n const loaded = publishedEstate\n ? await loadMigrationGraph(storage)\n : emptyGraph(estateHash, descriptor);\n\n const desired = serializeResolvedModels(client.$schema, driver, relations);\n const desiredEncoded = encodeSnapshot(desired);\n const parents = resolveParents(loaded, request, desired);\n refuseUnprovedMerge(loaded, parents, request.manualMigration);\n const adopts = admitAdoption(request, loaded, desired, parents);\n const parentState =\n parents.length === 1 && parents[0]\n ? loaded.states.get(parents[0])\n : undefined;\n const parentSnapshot =\n parentState && loaded.snapshots.get(parentState.snapshotHash);\n const unchangedSnapshot =\n parentSnapshot !== undefined && sameSchema(parentSnapshot, desired);\n\n const assembly = new SqlAssembly();\n const parentBodies: Omit<MigrationParentTransitionV1, \"transitionHash\">[] =\n [];\n const reported: DiffOperation[] = [];\n const warnings: string[] = [];\n const operationsByParent: {\n fromState: string | null;\n operations: DiffOperation[];\n }[] = [];\n const destinationPlaceholders: MigrationBooleanCheckV1[] = [];\n // Each state a low-lock split publishes before this one, parent first.\n const stepStates: SealedLowLockState[] = [];\n const snapshotArtifacts = new Map(loaded.snapshotArtifacts);\n const snapshotFor = (\n snapshot: SchemaSnapshot,\n fromStates: readonly (Sha256 | null)[]\n ) => {\n const bases = fromStates.flatMap((from) => {\n if (from === null) return [];\n const manifest =\n loaded.states.get(from) ??\n stepStates.find((step) => step.encoded.stateId === from)!.encoded\n .manifest;\n return [manifest.snapshotArtifactHash ?? manifest.snapshotHash].filter(\n (hash) => snapshotArtifacts.has(hash)\n );\n });\n const encoded = encodeSnapshotArtifact(snapshot, snapshotArtifacts, bases);\n if (encoded.bytes) {\n snapshotArtifacts.set(encoded.artifactHash, {\n snapshot,\n snapshotHash: encoded.snapshotHash,\n depth: encoded.depth,\n bytes: encoded.bytes,\n ...(encoded.baseArtifactHash\n ? { baseArtifactHash: encoded.baseArtifactHash }\n : {}),\n });\n }\n return encoded;\n };\n\n if (request.manualMigration) {\n assertManualParents(loaded, request.manualMigration.transitions);\n for (const transition of request.manualMigration.transitions) {\n const compiled = compileManualTransition(\n transition.up,\n transition.rollback,\n dialect,\n transition.execution,\n transition.originChecks,\n assembly\n );\n parentBodies.push(sealParent(transition.from, compiled));\n }\n for (const [index, check] of (\n request.manualMigration.destinationChecks ?? []\n ).entries()) {\n destinationPlaceholders.push(\n compileTrustedCheck(check, dialect, assembly, `destination:${index}`)\n );\n }\n for (const compiled of parentBodies) {\n assertManualStepwiseProof(\n {\n operations: compiled.operations,\n rollback: compiled.rollback,\n originChecks: compiled.originChecks,\n requestedForwardBoundary: compiled.requestedForwardBoundary,\n atomicity: compiled.requestedForwardBoundary ?? \"transactional\",\n },\n destinationPlaceholders\n );\n }\n } else {\n for (const [index, from] of parents.entries()) {\n const current = requireStateSnapshot(loaded, from);\n const diffOptions = {\n ...AUTHENTICATED_SNAPSHOT_DIFF_OPTIONS,\n projectRename: driver.projectNativeRename.bind(driver),\n refuseConstraintNameChurn:\n driver.capabilities.introspectionReadsConstraintNames,\n };\n const diffed = await diff(current, desired, diffOptions);\n const admittedDrops = new Set<string>();\n const resolved = await resolveAmbiguousChanges(\n diffed,\n current,\n desired,\n request.resolve\n ? callbackAsResolver(request.resolve, admittedDrops)\n : strictResolver,\n diffOptions\n );\n const approvals = await approveDestructiveOperations(\n resolved,\n request.resolve ?? (request.dryRun ? previewApproval : undefined),\n false,\n admittedDrops\n );\n const enumMappings = await resolveEnumValueRemovalMappings(\n detectEnumValueRemovals(resolved, current),\n request.resolve ?? rejectAllResolver,\n false\n );\n const withEnumMappings = resolved.map((operation) =>\n operation.type === \"alterEnum\"\n ? applyResolvedEnumMappings([operation], enumMappings)[0]!\n : operation\n );\n const adoption = withoutAdoptedTables(\n withEnumMappings,\n adopts,\n desired,\n current\n );\n const staged = prepareSchemaProgram(\n adoption.operations,\n adoption.current,\n driver\n );\n reported.push(...staged);\n operationsByParent.push({ fromState: from, operations: staged });\n // T2: the plan has asked every decision once its last parent is\n // planned, before a low-lock split publishes. A document already\n // published (a re-drive) asks none and stays a noop.\n if (index === parents.length - 1 && !unchangedSnapshot) {\n refuseUnusedDecisions(request.resolve);\n }\n // T5b, asked for with `lowLock`: one parent's PostgreSQL program gives\n // each low-lock step a commit of its own, as states published before\n // this one. Opt-in, because a step outside a transaction needs the\n // direct session a transaction pooler cannot give.\n const lowLock =\n request.lowLock === true && driver.dialect === \"postgresql\";\n const split =\n lowLock && parents.length === 1\n ? lowLockStates(staged, current, desired)\n : undefined;\n if (lowLock && !split && lowLockSteps(staged).size > 0) {\n warnings.push(\n \"lowLock: this change keeps its blocking index builds and validating foreign keys, because it merges several parents or changes something other than an index or a foreign key after its first index build. Generate those indexes and keys in a migration of their own to get their step form.\"\n );\n }\n let origin = { from, current: adoption.current, approvals };\n const before = split?.states.slice(0, -1) ?? [];\n for (const [index, state] of before.entries()) {\n const step = sealLowLockState(\n estateHash,\n driver,\n `${request.name?.trim() || generateMigrationName(staged)} (step ${index + 1} of ${before.length + 1})`,\n origin,\n state,\n split?.steps,\n snapshotFor\n );\n warnings.push(...step.warnings);\n stepStates.push(step);\n origin = {\n from: step.encoded.stateId,\n current: state.snapshot,\n approvals: [],\n };\n }\n const last = split?.states.at(-1);\n const compiled = last?.validates\n ? compileValidationTransition(\n last.operations,\n driver,\n origin.current,\n assembly\n )\n : compileGeneratedTransition(\n last?.operations ?? staged,\n driver,\n \"artifact\",\n origin.current,\n desired,\n assembly,\n split?.steps\n );\n warnings.push(...transitionWarnings(compiled));\n parentBodies.push(\n sealParent(origin.from, compiled, origin.approvals, adopts)\n );\n }\n }\n\n const named = request.name?.trim() || generateMigrationName(reported);\n const storedSnapshot = snapshotFor(\n desired,\n parentBodies.map((parent) => parent.fromState)\n );\n const { sealed, hashedParents, destinationChecks, encoded } = sealState(\n assembly,\n parentBodies,\n destinationPlaceholders,\n driver.target.dialect,\n estateHash,\n named,\n storedSnapshot\n );\n\n // Decision 8: field and model order is cosmetic, so a document that only\n // reorders them is a noop and publishes nothing.\n const emptyProgram = hashedParents.every((parent) =>\n parent.operations.every((operation) => operation.steps.length === 0)\n );\n if (!request.manualMigration && unchangedSnapshot && emptyProgram) {\n return {\n outcome: \"noop\",\n stateId: null,\n name: null,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: null,\n operations: [],\n warnings: [],\n operationsByParent: [],\n sql: \"\",\n reviewSql: \"\",\n };\n }\n\n const final = { snapshot: storedSnapshot, sealed, encoded };\n const states = [...stepStates, final];\n const sqlText = states\n .map((state) => new TextDecoder().decode(state.sealed.bytes))\n .join(\"\\n\\n\");\n const reviewSql = [\n ...stepStates.map(({ review }) => review),\n renderMigrationReview(\n hashedParents,\n destinationChecks,\n sealed.bytes,\n request.resolve ? undefined : \"Needs approval at generate\"\n ),\n ].join(\"\\n\\n\");\n const candidate = {\n stateId: encoded.stateId,\n name: named,\n estateHash,\n snapshotHash: desiredEncoded.snapshotHash,\n sqlHash: sealed.sqlHash,\n operations: reported,\n warnings,\n operationsByParent,\n sql: sqlText,\n reviewSql,\n };\n if (request.dryRun) return { outcome: \"preview\", ...candidate };\n\n if (!publishedEstate) {\n await storage.publishEstate(estateBytes);\n }\n // Every state is complete before the first publishes. A low-lock split's\n // states publish parent first, each manifest after its snapshot and SQL.\n for (const { snapshot, sealed: sql, encoded: manifest } of states) {\n if (snapshot.bytes)\n await storage.publishSnapshot(snapshot.artifactHash, snapshot.bytes);\n await storage.publishSql(sql.sqlHash, sql.bytes);\n await storage.publishState(manifest.stateId, manifest.bytes);\n }\n return { outcome: \"published\", ...candidate };\n}\n\n/**\n * The tables `adopt` names, once each is admitted: declared by the desired\n * snapshot (which the serializer already keeps inside the client's list),\n * outside the estate's frozen list (a name there is managed already, so a raw\n * table of that name is drift), and absent from every parent's snapshot. An\n * estate without a list manages the whole database and adopts nothing, nor\n * does a manual, low-lock or checkpoint state.\n */\nfunction admitAdoption(\n request: GenerateV1Options,\n graph: MigrationGraph,\n desired: SchemaSnapshot,\n parents: readonly (Sha256 | null)[]\n): readonly string[] {\n const names = request.adopt ?? [];\n if (names.length === 0) return names;\n const refuse = (message: string): never => {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_INVALID_STATE);\n };\n if (request.manualMigration || request.lowLock) {\n refuse(\"generate adopt cannot be combined with manualMigration or lowLock\");\n }\n if (request.from === null && graph.states.size > 0) {\n refuse(\n \"An authored checkpoint creates its whole schema: it adopts nothing\"\n );\n }\n const frozen = graph.descriptor.target.tables;\n if (frozen === undefined) {\n return refuse(\n \"generate adopt needs an estate with a `tables` list: without one the estate manages the whole database, so an existing table is drift\"\n );\n }\n for (const name of names) {\n if (!desired.tables.some((table) => table.name === name)) {\n refuse(\n `generate adopt names \"${name}\", which the schema does not declare`\n );\n }\n if (frozen.includes(name)) {\n refuse(\n `generate adopt names \"${name}\", which the estate already manages: a raw table of that name is drift, not something to adopt`\n );\n }\n for (const parent of parents) {\n if (\n requireStateSnapshot(graph, parent).tables.some(\n (table) => table.name === name\n )\n ) {\n refuse(\n `generate adopt names \"${name}\", which parent ${parent ?? \"empty\"} already has`\n );\n }\n }\n }\n return names;\n}\n\n/**\n * The program without what creates an adopted table: its CREATE TABLE, its\n * indexes and keys, and every enum an adopted table uses. That enum already\n * exists with the table (a PostgreSQL type is the database's, not the\n * table's), even where a new managed table of the same transition uses it\n * too, so it is never created, and a rollback, which drops only what the\n * program created, never drops it. It runs no DDL for them; the destination\n * proof proves the live table and the enum equal the declaration.\n *\n * The program's origin is the parent's schema plus those enums, because the\n * database already has them: the DDL of a new table naming one qualifies it\n * as it would an enum it created (`managedEnumNames`). The origin proof still\n * compares the parent's own snapshot.\n */\nfunction withoutAdoptedTables(\n operations: DiffOperation[],\n adopts: readonly string[],\n desired: SchemaSnapshot,\n current: SchemaSnapshot\n): { operations: DiffOperation[]; current: SchemaSnapshot } {\n if (adopts.length === 0) return { operations, current };\n const enumsOf = (tables: readonly SchemaSnapshot[\"tables\"][number][]) =>\n new Set(\n tables.flatMap((table) =>\n table.columns.map((column) =>\n column.type.endsWith(\"[]\") ? column.type.slice(0, -2) : column.type\n )\n )\n );\n const adoptedEnums = enumsOf(\n desired.tables.filter((table) => adopts.includes(table.name))\n );\n const broughtEnums = (desired.enums ?? []).filter(\n (enumDef) =>\n adoptedEnums.has(enumDef.name) &&\n !current.enums?.some(({ name }) => name === enumDef.name)\n );\n return {\n operations: operations.filter((operation) => {\n if (operation.type === \"createTable\") {\n return !adopts.includes(operation.table.name);\n }\n if (operation.type === \"createEnum\") {\n return !adoptedEnums.has(operation.enumDef.name);\n }\n return !(\n \"tableName\" in operation && adopts.includes(operation.tableName)\n );\n }),\n current:\n broughtEnums.length === 0\n ? current\n : { ...current, enums: [...(current.enums ?? []), ...broughtEnums] },\n };\n}\n\n/** Decision 8: two snapshots that differ only in field and model order. */\nfunction sameSchema(a: SchemaSnapshot, b: SchemaSnapshot): boolean {\n return (\n encodeSnapshot(orderFree(a)).snapshotHash ===\n encodeSnapshot(orderFree(b)).snapshotHash\n );\n}\n\n/** A snapshot with its tables, columns, keys and enums sorted by name. */\nfunction orderFree(snapshot: SchemaSnapshot): SchemaSnapshot {\n const byName = (a: { name: string }, b: { name: string }) =>\n a.name < b.name ? -1 : Number(a.name > b.name);\n return {\n ...snapshot,\n tables: snapshot.tables\n .map((table) => ({\n ...table,\n columns: [...table.columns].sort(byName),\n indexes: [...table.indexes].sort(byName),\n foreignKeys: [...table.foreignKeys].sort(byName),\n uniqueConstraints: [...table.uniqueConstraints].sort(byName),\n }))\n .sort(byName),\n enums: snapshot.enums && [...snapshot.enums].sort(byName),\n };\n}\n\n/**\n * Seals one state's manifest from its compiled parents: refuses unsafe SQL,\n * binds every check and dispatch to the sealed bytes and hashes each parent.\n */\nfunction sealState(\n assembly: SqlAssembly,\n parentBodies: readonly Omit<MigrationParentTransitionV1, \"transitionHash\">[],\n destinationPlaceholders: readonly MigrationBooleanCheckV1[],\n dialect: Parameters<typeof assertArtifactExecutionSafe>[1],\n estateHash: Sha256,\n name: string,\n snapshot: EncodedSnapshotArtifact\n) {\n const sealed = assembly.seal();\n assertArtifactExecutionSafe(\n sealed.dispatches.map((dispatch) => sliceDispatch(sealed.bytes, dispatch)),\n dialect,\n name\n );\n const hashedParents = parentBodies.map((parent) =>\n hashParent({\n ...parent,\n originChecks: rebindChecks(parent.originChecks, sealed.dispatches),\n operations: rebindDispatches(parent.operations, sealed.dispatches),\n rollback: rebindRollback(parent.rollback, sealed.dispatches),\n })\n );\n const destinationChecks = rebindChecks(\n destinationPlaceholders,\n sealed.dispatches\n );\n const encoded = encodeStateManifest({\n format: \"1\",\n estateHash,\n name,\n snapshotHash: snapshot.snapshotHash,\n ...(snapshot.artifactHash === snapshot.snapshotHash\n ? {}\n : { snapshotArtifactHash: snapshot.artifactHash }),\n sqlHash: sealed.sqlHash,\n destinationChecks,\n parents: hashedParents,\n });\n return { sealed, hashedParents, destinationChecks, encoded };\n}\n\ntype SealedLowLockState = ReturnType<typeof sealLowLockState>;\n\n/**\n * Seals one state a low-lock split puts before the generated one (T5b); it\n * becomes the next state's parent. Nothing publishes until every state of the\n * candidate is sealed.\n */\nfunction sealLowLockState(\n estateHash: Sha256,\n driver: ReturnType<typeof getPushMigrationDriver>,\n name: string,\n origin: {\n readonly from: Sha256 | null;\n readonly current: SchemaSnapshot;\n readonly approvals: readonly MigrationApprovalV1[];\n },\n state: LowLockState,\n steps: ReadonlySet<DiffOperation> | undefined,\n encode: (\n snapshot: SchemaSnapshot,\n fromStates: readonly (Sha256 | null)[]\n ) => EncodedSnapshotArtifact\n) {\n const assembly = new SqlAssembly();\n const compiled = compileGeneratedTransition(\n state.operations,\n driver,\n \"artifact\",\n origin.current,\n state.snapshot,\n assembly,\n steps\n );\n const snapshot = encode(state.snapshot, [origin.from]);\n const sealed = sealState(\n assembly,\n [sealParent(origin.from, compiled, origin.approvals)],\n [],\n driver.target.dialect,\n estateHash,\n name,\n snapshot\n );\n return {\n ...sealed,\n snapshot,\n review: renderMigrationReview(\n sealed.hashedParents,\n [],\n sealed.sealed.bytes\n ),\n warnings: transitionWarnings(compiled),\n };\n}\n\n/** What a compiled transition warns of: its own warnings, then irreversibility. */\nfunction transitionWarnings(compiled: CompiledTransition): string[] {\n return [\n ...(compiled.warnings ?? []),\n ...(compiled.rollback.kind === \"irreversible\"\n ? [compiled.rollback.reason]\n : []),\n ];\n}\n\nfunction assertManualParents(\n graph: MigrationGraph,\n transitions: readonly ManualTransitionInput[]\n): void {\n const seen = new Set<string>();\n for (const transition of transitions) {\n if (transition.from === null) {\n if (graph.states.size > 0) {\n throw new MigrationError(\n \"A second virtual-root transition is refused\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n } else if (!graph.states.has(transition.from)) {\n throw new MigrationError(\n `Unknown parent state ${transition.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const key = transition.from ?? \"null\";\n if (seen.has(key)) {\n throw new MigrationError(\n \"A manual migration names a parent more than once\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n seen.add(key);\n }\n}\n\nfunction resolveParents(\n graph: MigrationGraph,\n options: GenerateV1Options,\n desired: SchemaSnapshot\n): Array<Sha256 | null> {\n if (options.from !== undefined) {\n if (options.from === null) {\n // Plan T4 (decision 11): on a populated estate `from: null` authors a\n // checkpoint, a second root restating the single leaf's schema, which\n // reanchor() can move a marker onto once prune() dropped what precedes it.\n const [leaf, ...more] = graph.leaves;\n if (\n leaf &&\n (more.length > 0 ||\n !sameSchema(requireStateSnapshot(graph, leaf), desired))\n ) {\n throw new MigrationError(\n \"A second virtual-root transition is an authored checkpoint: it must restate the schema of the estate's single leaf. Generate the change first, then the checkpoint.\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return [null];\n }\n if (!graph.states.has(options.from)) {\n throw new MigrationError(\n `Unknown parent state ${options.from}`,\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return [options.from];\n }\n if (graph.states.size === 0) return [null];\n // `loadMigrationGraph` refuses a cycle, so a graph with states has a leaf.\n return [...graph.leaves];\n}\n\nfunction emptyGraph(\n estateHash: Sha256,\n descriptor: ReturnType<typeof parseEstateDescriptor>[\"descriptor\"]\n): MigrationGraph {\n const emptySnapshotHash = encodeSnapshot(emptyManagedSnapshot()).snapshotHash;\n return {\n estateHash,\n descriptor,\n states: new Map(),\n snapshots: new Map([[emptySnapshotHash, emptyManagedSnapshot()]]),\n snapshotArtifacts: new Map(),\n sql: new Map(),\n roots: [],\n leaves: [],\n emptySnapshotHash,\n };\n}\n\nfunction ancestryHasCustom(\n graph: MigrationGraph,\n stateId: Sha256 | null,\n seen: Set<string> = new Set()\n): boolean {\n if (stateId === null || seen.has(stateId)) return false;\n seen.add(stateId);\n // Every id here is a validated state or a validated parent edge's source.\n const state = graph.states.get(stateId)!;\n for (const transition of state.parents) {\n if (\n transition.operations.some(\n (operation) => operation.origin === \"manual\"\n ) ||\n transition.requestedForwardBoundary !== null\n ) {\n return true;\n }\n if (ancestryHasCustom(graph, transition.fromState, seen)) return true;\n }\n return false;\n}\n\nfunction refuseUnprovedMerge(\n graph: MigrationGraph,\n parents: Array<Sha256 | null>,\n manual: ManualMigrationInput | undefined\n): void {\n if (parents.length < 2 || manual) return;\n for (const parent of parents) {\n if (ancestryHasCustom(graph, parent)) {\n throw new MigrationError(\n \"A custom or data transition cannot be merged structurally; supply manualMigration for every parent\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n }\n}\n","/** One hostile-input boundary for the public down() selector. */\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport type { ResolveCallback } from \"./types\";\nimport type { StateSelector } from \"./v1-types\";\n\nexport interface NormalizedDownOptions {\n readonly steps: number;\n readonly to?: StateSelector;\n readonly dryRun: boolean;\n readonly expectRevision?: number;\n readonly resolve?: ResolveCallback;\n}\n\nexport function normalizeDownOptions(options: unknown): NormalizedDownOptions {\n const record = snapshotExactRecord(\n options,\n [\"steps\", \"to\", \"dryRun\", \"expectRevision\", \"resolve\"],\n \"down options\",\n refuseDownOptions\n );\n const { steps, to, dryRun, expectRevision, resolve } = record;\n if (steps !== undefined && to !== undefined) {\n return refuseDownOptions(\"down accepts either steps or to, not both\");\n }\n let normalizedSteps = 1;\n if (steps !== undefined) {\n if (\n typeof steps !== \"number\" ||\n !Number.isSafeInteger(steps) ||\n steps <= 0\n ) {\n return refuseDownOptions(\"down steps must be a positive safe integer\");\n }\n normalizedSteps = steps;\n }\n if (dryRun !== undefined && typeof dryRun !== \"boolean\") {\n return refuseDownOptions(\"down dryRun must be a boolean\");\n }\n if (\n expectRevision !== undefined &&\n (typeof expectRevision !== \"number\" ||\n !Number.isSafeInteger(expectRevision) ||\n expectRevision <= 0)\n ) {\n return refuseDownOptions(\n \"down expectRevision must be a positive safe integer\"\n );\n }\n if (resolve !== undefined && !isResolveCallback(resolve)) {\n return refuseDownOptions(\"down resolve must be a function\");\n }\n return Object.freeze({\n steps: normalizedSteps,\n ...(to === undefined ? {} : { to: normalizeStateSelector(to) }),\n dryRun: dryRun === true,\n ...(expectRevision === undefined ? {} : { expectRevision }),\n ...(resolve === undefined ? {} : { resolve }),\n });\n}\n\nfunction normalizeStateSelector(value: unknown): StateSelector {\n const record = snapshotExactRecord(\n value,\n [\"id\", \"prefix\", \"name\"],\n \"down to\",\n refuseDownOptions\n );\n const keys = Object.keys(record);\n if (keys.length !== 1) {\n return refuseDownOptions(\"down to must contain exactly one selector key\");\n }\n // The sole OWN key. `\"id\" in record` walks the prototype chain, so a polluted\n // Object.prototype.id made `down({ to: { name: \"baseline\" } })` select the\n // inherited id and roll back to the wrong state.\n const key = keys[0]!;\n const selected = record[key];\n if (typeof selected !== \"string\" || selected.length === 0) {\n return refuseDownOptions(`down to.${key} must be a non-empty string`);\n }\n if (key === \"id\") return { id: selected };\n if (key === \"prefix\") return { prefix: selected };\n return { name: selected };\n}\n\nfunction isResolveCallback(value: unknown): value is ResolveCallback {\n return typeof value === \"function\";\n}\n\nfunction refuseDownOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n","/**\n * History-aware reset. One lock. Clear, replay from null, then one marker CAS.\n * Never re-enters applyV1.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { canonicalizeJson } from \"./canonical-json\";\nimport { tableExistsProbe } from \"./catalog-probes\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./compile\";\nimport {\n advanceMarker,\n appendLedger,\n attemptEvents,\n ensureControlTables,\n isTableMissing,\n ledgerEvent,\n markerFromPath,\n readControlState,\n refuseIncompatibleHistory,\n sameMarker,\n unfinishedAttempts,\n} from \"./control\";\nimport type { BoundMigrationDriver } from \"./drivers\";\nimport {\n annotateMigrationFailure,\n assertAllChecks,\n executeExactSql,\n executeOperations,\n providerFacts,\n providerRefused,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n type RouteEdge,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n} from \"./graph\";\nimport { domainHash, HASH_DOMAIN, type Sha256 } from \"./identity\";\nimport { planLiveNamespaceReset } from \"./live-reset\";\nimport {\n commitLockedTransaction,\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport { assertAdoptable, assertLockedSinceDecision, proveLive } from \"./proof\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport {\n confirmedPrefix,\n openCommand,\n readCommandControl,\n refuseAmbiguousNext,\n sliceOperations,\n} from \"./resume\";\nimport { encodeSqlText } from \"./sql-blob\";\nimport { canonicalizeSqliteStorage } from \"./sqlite-storage-audit\";\nimport type { MigrationStorageWriter } from \"./storage/contract\";\nimport { managedTables, withManagedTables } from \"./target\";\nimport { encodeDispatchIdentity, encodeSqlBlob } from \"./v1-parse\";\nimport type {\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationDispatchV1,\n MigrationMarkerV1,\n MigrationOperationV1,\n ResetPlanV1,\n ResetV1Options,\n} from \"./v1-types\";\n\nexport async function resetV1(\n client: MigrationClient,\n storage: MigrationStorageWriter,\n options: ResetV1Options = {}\n): Promise<{\n readonly preview: boolean;\n readonly path: readonly Sha256[];\n readonly tables?: readonly string[];\n}> {\n const graph = await loadMigrationGraph(storage);\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n const dryRun = options.dryRun === true;\n const driver = openCommand(\n client,\n graph,\n dryRun ? \"read-only\" : \"effectful\",\n \"reset()\"\n );\n if (dryRun) {\n const command = await resolveCommandDriver(client.$driver, driver);\n // Without a list the whole namespace is cleared, and the marker is not read.\n const marker =\n graph.descriptor.target.tables === undefined\n ? null\n : (await readControlState(client.$driver, command, { ledger: \"open\" }))\n .marker;\n const plan = await planClear(client.$driver, command, graph, marker, path);\n await command.preflightSchemaRequirements(\n path.map((stateId) => requireStateSnapshot(graph, stateId)),\n (sql, params) => client.$driver._executeRaw(sql, params),\n resetProgram(\n plan,\n prepareResetReplay(\n client.$driver.supportsTransactions,\n command,\n graph,\n path\n )\n ),\n true\n );\n await assertAdoptable(client.$driver, command, graph, null, path);\n return {\n preview: true,\n path,\n tables: plan.dropTables.map((table) => table.name),\n };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n const needsBootstrap = control.presence.kind !== \"present\";\n const open = unfinishedAttempts(ledger);\n const resetAttempt =\n open.length === 1 && open[0]!.kind === \"reset-started\"\n ? open[0]!\n : undefined;\n if (open.length > 0 && !resetAttempt) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking reset\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const targetIdentity = `${command.target.dialect}:${command.namespace ?? \"\"}`;\n const storedResetPlan = resetAttempt\n ? matchingResetPlan(resetAttempt, graph, target, path, targetIdentity)\n : undefined;\n if (!resetAttempt) {\n refuseIncompatibleHistory(marker, ledger);\n }\n const targetSnapshot = requireStateSnapshot(graph, target);\n const targetSnapshotHash = graph.states.get(target)!.snapshotHash;\n const edges: MarkerPathEdgeV1[] = routeEdges(graph, null, path).map(\n ({ to, transition }) => ({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: false,\n })\n );\n const resetEvent = {\n estateHash: graph.estateHash,\n snapshotHash: targetSnapshotHash,\n sqlHash: null,\n fromState: marker?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"reset\",\n } as const;\n if (\n resetAttempt &&\n storedResetPlan &&\n marker &&\n resetMarkerProvesApplied(\n marker,\n graph,\n edges,\n targetSnapshotHash,\n storedResetPlan\n ) &&\n (await fingerprintLive(\n await introspectManaged(\n pinned,\n replayedTo(command, graph, marker, target)\n ),\n command,\n pinned\n )) === (await fingerprintLive(targetSnapshot, command, pinned))\n ) {\n await appendLedger(\n pinned,\n command,\n attemptEvents(\n { ...resetEvent, fromState: resetAttempt.fromState },\n resetAttempt.attemptId\n ).event(\"reset-applied\", \"committed\")\n );\n return { preview: false, path };\n }\n if (\n resetAttempt &&\n storedResetPlan &&\n !resetSourceMarkerMatches(\n marker,\n resetAttempt,\n storedResetPlan,\n graph.emptySnapshotHash\n )\n ) {\n throw new MigrationError(\n \"The unfinished reset source marker no longer matches its plan\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n const hasReplayEvidence = resetAttempt\n ? ledger.some(\n (event) =>\n event.attemptId === resetAttempt.attemptId &&\n event.kind === \"reset-step-confirmed\" &&\n (event.fromState !== null ||\n event.toState !== null ||\n event.transitionHash !== null ||\n event.operationId !== null)\n )\n : false;\n const livePlan = hasReplayEvidence\n ? undefined\n : await planClear(pinned, command, graph, marker, path);\n const clearDispatches = resetProgram(livePlan, []).map((sql) =>\n dispatchForClearSql(sql)\n );\n if (\n livePlan &&\n command.target.dialect === \"mysql\" &&\n (livePlan.dropForeignKeys.length > 0 || livePlan.dropEnums.length > 0)\n ) {\n throw new MigrationError(\n \"Stepwise reset refuses clear dispatches without driver-owned pre/post proof\",\n VibORMErrorCode.MIGRATION_UNSUPPORTED_PROVIDER\n );\n }\n const planBody = {\n estateHash: graph.estateHash,\n targetIdentity,\n sourceRevision: marker?.revision ?? 0,\n sourceFingerprint: marker?.snapshotHash ?? graph.emptySnapshotHash,\n replayPath: path,\n clearDispatches,\n referencedStates: path,\n };\n const stored = storedResetPlan;\n if (stored && livePlan) {\n assertStoredResetPlan(stored, planBody);\n }\n const resetPlanHash = stored\n ? stored.resetPlanHash\n : domainHash(HASH_DOMAIN.resetPlan, canonicalizeJson(planBody));\n const plan: ResetPlanV1 = stored ?? { ...planBody, resetPlanHash };\n const prepared = prepareResetReplay(\n pinned.supportsTransactions,\n command,\n graph,\n path\n );\n const remaining = resetAttempt\n ? remainingResetReplay(graph, prepared, resetAttempt, plan, ledger)\n : prepared;\n // The statements this command runs, as apply hands its path over: the\n // dialect refuses what they would lose (S11, T5a, Neki) before effects.\n // The source is the marker's state where this estate holds it; a marker\n // it does not (a history replaced by a fresh one, `markerState:\n // \"unknown\"`) has no snapshot here, and the clear drops what the live\n // inventory names, as the dry run plans it.\n const source = marker?.stateId ?? null;\n await command.preflightSchemaRequirements(\n [\n ...(source === null || graph.states.has(source)\n ? [requireStateSnapshot(graph, source)]\n : []),\n ...path.map((stateId) => requireStateSnapshot(graph, stateId)),\n ],\n (sql, params) => pinned._executeRaw(sql, params),\n resetProgram(livePlan, remaining),\n // Where Neki needs a commit, each statement commits alone.\n true\n );\n await assertAdoptable(pinned, command, graph, null, path);\n const begin = resetAttempt\n ? undefined\n : (producer: Parameters<typeof appendLedger>[0]) =>\n appendLedger(\n producer,\n command,\n attemptEvents(\n { ...resetEvent, resetPlan: plan },\n resetPlanHash\n ).event(\"reset-started\", \"none\")\n );\n const finish = async (producer: Parameters<typeof appendLedger>[0]) => {\n await proveLive(\n producer,\n replayedTo(command, graph, marker, target),\n graph,\n targetSnapshotHash,\n () => \"Reset replay did not reach the target snapshot\"\n );\n await advanceMarker(\n producer,\n command,\n graph.estateHash,\n marker,\n edges,\n targetSnapshotHash\n );\n await appendLedger(\n producer,\n command,\n attemptEvents(resetEvent, resetPlanHash).event(\n \"reset-applied\",\n \"committed\"\n )\n );\n };\n // Committed before the program, whose first group re-reads the marker.\n if (needsBootstrap) {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n }\n await runProgram(pinned, command, undefined, (producer) =>\n executeResetProgram(\n pinned,\n producer,\n command,\n marker,\n graph,\n livePlan,\n plan,\n remaining,\n resetPlanHash,\n begin,\n finish,\n client.$schema\n )\n );\n return { preview: false, path };\n }\n );\n}\n\n/**\n * The tables an estate with a `tables` list holds while the marker stands:\n * the estate's own list and every table its arrival path managed. Never a\n * table only the client lists: nothing adopted it, so it is the user's.\n */\nfunction managedByMarker(\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null\n): readonly string[] | undefined {\n const states = [null, ...(marker?.path ?? []).map((edge) => edge.stateId)];\n return managedTables(\n graph.descriptor.target.tables,\n states\n .filter((state) => state === null || graph.states.has(state))\n .map((state) => requireStateSnapshot(graph, state))\n );\n}\n\n/**\n * The command, its inventory what reset clears (`managedByMarker`), once the\n * replay is proven able to recreate it: an adoption has no DDL, so replaying\n * one whose table the clear drops would lose that table and its rows.\n */\nfunction clearedBy(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n path: readonly Sha256[]\n): BoundMigrationDriver {\n const cleared = managedByMarker(graph, marker);\n for (const { to, transition } of routeEdges(graph, null, path)) {\n const lost = transition.adopts?.find((name) => cleared?.includes(name));\n if (lost !== undefined) {\n throw new MigrationError(\n `reset cannot replay state ${to}, which adopts \"${lost}\": reset clears that table, and an adoption has no DDL to recreate it. Nothing ran.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n }\n return withManagedTables(command, cleared);\n}\n\n/**\n * The clear, once every table the replay creates is accounted for. A live\n * table the replay creates and the clear keeps (no state of the marker's\n * path managed it: it is not adopted yet, or the marker names a history this\n * estate does not hold) is refused before effects: dropping it could drop a\n * user's table, and keeping it would let the replay's CREATE find it.\n */\nasync function planClear(\n producer: AnyDriver,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n path: readonly Sha256[]\n): Promise<Awaited<ReturnType<typeof planLiveNamespaceReset>>> {\n const cleared = clearedBy(command, graph, marker, path);\n const kept = managedByMarker(graph, marker);\n if (kept !== undefined) {\n const route = routeEdges(graph, null, path);\n const adopted = route.flatMap(({ transition }) => transition.adopts ?? []);\n const created = new Set(\n route.flatMap(({ to }) =>\n requireStateSnapshot(graph, to).tables.map(({ name }) => name)\n )\n );\n for (const table of [...created].sort()) {\n if (\n kept.includes(table) ||\n adopted.includes(table) ||\n (await isTableMissing(producer, command, table))\n )\n continue;\n const foreign = marker?.path.some(\n ({ stateId }) => !graph.states.has(stateId)\n );\n throw new MigrationError(\n `reset cannot account for table \"${table}\": it exists, the replay creates it, and no state of this estate the marker reached managed it${foreign ? \" (the marker names states this estate does not hold, so whether it belongs to that history or is yours cannot be told)\" : \"\"}. reset never drops such a table. Drop or rename it yourself if its rows can go, then reset again. Nothing ran.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE,\n { meta: { table } }\n );\n }\n }\n return planLiveNamespaceReset(producer, cleared);\n}\n\n/** The command, proving the replay's target and that the clear left nothing. */\nfunction replayedTo(\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n marker: MigrationMarkerV1 | null,\n target: Sha256\n): BoundMigrationDriver {\n return withManagedTables(\n command,\n managedTables(managedByMarker(graph, marker), [\n requireStateSnapshot(graph, target),\n ])\n );\n}\n\nfunction matchingResetPlan(\n attempt: LedgerEventV1,\n graph: MigrationGraph,\n target: Sha256,\n path: readonly Sha256[],\n targetIdentity: string\n): ResetPlanV1 {\n const targetState = graph.states.get(target);\n const plan = attempt.resetPlan;\n // A source this estate holds fixes the plan's fingerprint; a foreign one (a\n // history replaced by a fresh one) does not, and the plan's own record of\n // the marker is what `resetSourceMarkerMatches` proves the live marker\n // still is.\n const sourceSnapshotHash =\n attempt.fromState === null\n ? graph.emptySnapshotHash\n : graph.states.has(attempt.fromState)\n ? graph.states.get(attempt.fromState)!.snapshotHash\n : plan?.sourceFingerprint;\n if (\n !(targetState && plan) ||\n attempt.direction !== \"reset\" ||\n attempt.attemptId !== plan.resetPlanHash ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== targetState.snapshotHash ||\n attempt.toState !== target ||\n plan.estateHash !== graph.estateHash ||\n plan.targetIdentity !== targetIdentity ||\n plan.sourceFingerprint !== sourceSnapshotHash ||\n !sameIds(plan.replayPath, path) ||\n !sameIds(plan.referencedStates, path)\n ) {\n throw new MigrationError(\n \"The unfinished reset does not match the requested reset\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return plan;\n}\n\nfunction resetMarkerProvesApplied(\n marker: MigrationMarkerV1,\n graph: MigrationGraph,\n edges: MigrationMarkerV1[\"path\"],\n snapshotHash: Sha256,\n plan: ResetPlanV1\n): boolean {\n const expected = markerFromPath(\n graph.estateHash,\n snapshotHash,\n edges,\n plan.sourceRevision + 1\n );\n return (\n marker.estateHash === expected.estateHash &&\n marker.stateId === expected.stateId &&\n marker.snapshotHash === expected.snapshotHash &&\n sameMarker(marker, expected)\n );\n}\n\nfunction resetSourceMarkerMatches(\n marker: MigrationMarkerV1 | null,\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n emptySnapshotHash: Sha256\n): boolean {\n return marker\n ? marker.stateId === attempt.fromState &&\n marker.revision === plan.sourceRevision &&\n marker.snapshotHash === plan.sourceFingerprint\n : attempt.fromState === null &&\n plan.sourceRevision === 0 &&\n plan.sourceFingerprint === emptySnapshotHash;\n}\n\nfunction assertStoredResetPlan(\n stored: ResetPlanV1,\n live: Omit<ResetPlanV1, \"resetPlanHash\">\n): void {\n if (stored.estateHash !== live.estateHash) {\n throw new MigrationError(\n \"A stored reset plan does not match the current estate\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (stored.targetIdentity !== live.targetIdentity) {\n throw new MigrationError(\n \"A stored reset plan does not match the current target\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n stored.sourceRevision !== live.sourceRevision ||\n stored.sourceFingerprint !== live.sourceFingerprint\n ) {\n throw new MigrationError(\n \"A stored reset plan does not match the current marker\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (!sameIds(stored.replayPath, live.replayPath)) {\n throw new MigrationError(\n \"A stored reset plan does not match the requested replay path\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const storedIds = new Set(\n stored.clearDispatches.map((dispatch) => dispatch.dispatchId)\n );\n for (const dispatch of live.clearDispatches) {\n if (!storedIds.has(dispatch.dispatchId)) {\n throw new MigrationError(\n \"Live remaining reset clears are not in the stored reset plan\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n }\n}\n\nfunction sameIds(left: readonly Sha256[], right: readonly Sha256[]): boolean {\n if (left.length !== right.length) return false;\n return left.every((id, index) => id === right[index]);\n}\n\n/** The clear, in the order it runs, then the replay's statements. */\nfunction resetProgram(\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>> | undefined,\n replay: readonly Pick<PreparedResetReplayEdge, \"blob\" | \"operations\">[]\n): string[] {\n return [\n ...(livePlan?.clear ?? []),\n ...replay.flatMap(({ blob, operations }) =>\n stepStatements(blob, operations)\n ),\n ];\n}\n\nfunction dispatchForClearSql(sql: string): MigrationDispatchV1 {\n const bytes = encodeSqlText(sql);\n const sqlHash = encodeSqlBlob(bytes);\n return {\n dispatchId: encodeDispatchIdentity(sqlHash, 0, bytes.length, []),\n sqlHash,\n offset: 0,\n length: bytes.length,\n parameters: [],\n };\n}\n\nasync function executeResetClear(\n pinned: Parameters<typeof executeExactSql>[0],\n command: Parameters<typeof planLiveNamespaceReset>[1],\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>>,\n attemptId: Sha256,\n graph: MigrationGraph,\n strategy: \"transactional\" | \"stepwise\"\n): Promise<void> {\n // Clear statements are numbered in the order they run, as replay ones are.\n let statementIndex = 0;\n const runClearStatement = async (sql: string) => {\n const site = {\n step: \"reset-clear\",\n strategy,\n statementIndex: statementIndex++,\n dispatchId: dispatchForClearSql(sql).dispatchId,\n };\n try {\n await executeExactSql(pinned, sql);\n } catch (error) {\n if (!providerRefused(error)) throw annotateMigrationFailure(error, site);\n throw new MigrationError(\n `Reset clear statement ${site.statementIndex} failed`,\n VibORMErrorCode.MIGRATION_FAILED,\n { cause: error, meta: { ...site, ...providerFacts(error) } }\n );\n }\n };\n for (const sql of livePlan.dropForeignKeys) {\n await runClearStatement(sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n for (const table of livePlan.dropTables) {\n const pre = tableExistsProbe(command, table.name, true);\n const post = tableExistsProbe(command, table.name, false);\n if (!(await evaluateProbe(pinned, pre))) {\n await confirmResetStep(pinned, command, graph, attemptId, table.sql);\n continue;\n }\n await runClearStatement(table.sql);\n if (!(await evaluateProbe(pinned, post))) {\n throw new MigrationError(\n `Reset clear did not drop table ${table.name}`,\n VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n );\n }\n await confirmResetStep(pinned, command, graph, attemptId, table.sql);\n }\n for (const sql of livePlan.dropEnums) {\n await runClearStatement(sql);\n await confirmResetStep(pinned, command, graph, attemptId, sql);\n }\n}\n\nasync function evaluateProbe(\n pinned: Parameters<typeof executeExactSql>[0],\n probe: ReturnType<typeof tableExistsProbe>\n): Promise<boolean> {\n const result = await pinned._executeRaw<Record<string, unknown>>(\n probe.sql,\n probe.parameters.map((parameter) =>\n parameter.kind === \"string\" ? parameter.value : null\n )\n );\n const value = Object.values(result.rows[0] ?? {})[0];\n return (\n (value === true || value === 1 || value === \"1\" || value === \"t\") ===\n probe.equals\n );\n}\n\nasync function confirmResetStep(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n sql: string\n): Promise<void> {\n await confirmResetDispatch(\n pinned,\n command,\n graph,\n attemptId,\n dispatchForClearSql(sql)\n );\n}\n\nasync function confirmResetDispatch(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attemptId: Sha256,\n dispatch: MigrationDispatchV1\n): Promise<void> {\n await appendLedger(\n pinned,\n command,\n ledgerEvent({\n attemptId,\n kind: \"reset-step-confirmed\",\n estateHash: graph.estateHash,\n snapshotHash: graph.emptySnapshotHash,\n sqlHash: dispatch.sqlHash,\n fromState: null,\n toState: null,\n transitionHash: null,\n direction: \"reset\",\n operationId: null,\n dispatchId: dispatch.dispatchId,\n effectState: \"committed\",\n })\n );\n}\n\ninterface PreparedResetReplayEdge extends RouteEdge {\n readonly boundary: \"transactional\" | \"stepwise\";\n readonly operations: readonly MigrationOperationV1[];\n}\n\nfunction prepareResetReplay(\n supportsTransactions: boolean,\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n path: readonly Sha256[]\n): readonly PreparedResetReplayEdge[] {\n return routeEdges(graph, null, path).map((edge) => {\n const requested = edge.transition.requestedForwardBoundary;\n const boundary = classifyStoredAtomicity(\n command,\n requested,\n edge.transition.operations,\n edge.blob\n );\n assertTransactionalBoundaryHonored(supportsTransactions, requested);\n refuseSqliteStepwise(command, requested, edge.to);\n return { ...edge, boundary, operations: edge.transition.operations };\n });\n}\n\nfunction remainingResetReplay(\n graph: MigrationGraph,\n prepared: readonly PreparedResetReplayEdge[],\n attempt: LedgerEventV1,\n plan: ResetPlanV1,\n ledger: readonly LedgerEventV1[]\n): readonly PreparedResetReplayEdge[] {\n const clearByDispatch = new Map(\n plan.clearDispatches.map((dispatch, index) => [dispatch.dispatchId, index])\n );\n const clearCommitted = new Set<number>();\n const steps = prepared.flatMap((edge, edgeIndex) =>\n edge.operations.flatMap((operation) =>\n operation.steps.map((step) => ({ edge, edgeIndex, operation, step }))\n )\n );\n const byDispatch = new Map(\n steps.map((entry, index) => [entry.step.execute.dispatchId, index])\n );\n const completed = new Set<number>();\n const announced = new Set<number>();\n let hasReplayEvidence = false;\n for (const event of ledger) {\n if (\n event.attemptId !== attempt.attemptId ||\n event.kind !== \"reset-step-confirmed\"\n ) {\n continue;\n }\n if (\n event.direction !== \"reset\" ||\n event.estateHash !== graph.estateHash ||\n !event.dispatchId\n ) {\n refuseResetProgress(\n \"Reset progress does not match its authenticated plan\"\n );\n }\n const isClear =\n event.fromState === null &&\n event.toState === null &&\n event.transitionHash === null &&\n event.operationId === null;\n if (isClear) {\n const clearIndex = clearByDispatch.get(event.dispatchId);\n if (\n clearIndex === undefined ||\n event.sqlHash !== plan.clearDispatches[clearIndex]!.sqlHash ||\n event.snapshotHash !== graph.emptySnapshotHash ||\n event.effectState !== \"committed\"\n ) {\n refuseResetProgress(\"Reset clear progress names an unknown dispatch\");\n }\n clearCommitted.add(clearIndex);\n continue;\n }\n hasReplayEvidence = true;\n const index = byDispatch.get(event.dispatchId);\n if (index === undefined) {\n refuseResetProgress(\"Reset replay progress names an unknown dispatch\");\n }\n const entry = steps[index];\n if (\n !entry ||\n event.fromState !== entry.edge.from ||\n event.toState !== entry.edge.to ||\n event.transitionHash !== entry.edge.transition.transitionHash ||\n event.snapshotHash !== entry.edge.state.snapshotHash ||\n event.sqlHash !== entry.edge.state.sqlHash ||\n event.operationId !== entry.operation.id\n ) {\n refuseResetProgress(\"Reset replay progress names an unknown dispatch\");\n }\n if (event.effectState === \"committed\") {\n completed.add(index);\n } else if (event.effectState === \"none\") {\n if (entry.step.retry === \"proven\") completed.add(index);\n else announced.add(index);\n } else {\n throw new MigrationError(\n \"Reset replay progress has an ambiguous commit outcome\",\n VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT\n );\n }\n }\n confirmedPrefix(\n clearCommitted,\n \"Reset clear progress is not a contiguous dispatch prefix\"\n );\n if (\n hasReplayEvidence &&\n clearCommitted.size !== plan.clearDispatches.length\n ) {\n refuseResetProgress(\n \"Reset replay progress exists before the clear prefix is complete\"\n );\n }\n if (!hasReplayEvidence) return prepared;\n const completedCount = confirmedPrefix(\n completed,\n \"Reset replay progress is not a contiguous dispatch prefix\"\n );\n if (\n [...announced].some(\n (index) => !completed.has(index) && index !== completedCount\n )\n ) {\n refuseResetProgress(\"Reset replay progress is not contiguous\");\n }\n const next = steps[completedCount];\n refuseAmbiguousNext(\n next?.step,\n next?.edge.boundary,\n announced.has(completedCount),\n \"The next reset dispatch has an ambiguous commit outcome\"\n );\n const verificationEdge =\n completedCount === 0 ? undefined : steps[completedCount - 1]?.edgeIndex;\n let skipped = completedCount;\n return prepared.flatMap((edge, edgeIndex) => {\n const operationCount = edge.operations.reduce(\n (count, operation) => count + operation.steps.length,\n 0\n );\n if (skipped >= operationCount) {\n skipped -= operationCount;\n return edgeIndex === verificationEdge\n ? [{ ...edge, operations: [] }]\n : [];\n }\n const operations = sliceOperations(edge.operations, skipped);\n skipped = 0;\n return [{ ...edge, operations }];\n });\n}\n\nfunction refuseResetProgress(message: string): never {\n throw new MigrationError(message, VibORMErrorCode.MIGRATION_CORRUPTION);\n}\n\nasync function executeResetProgram(\n pinned: Parameters<typeof executeOperations>[0],\n producer: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n marker: MigrationMarkerV1 | null,\n graph: MigrationGraph,\n livePlan: Awaited<ReturnType<typeof planLiveNamespaceReset>> | undefined,\n plan: ResetPlanV1,\n replay: readonly PreparedResetReplayEdge[],\n attemptId: Sha256,\n beforeFirstEffect:\n | ((producer: Parameters<typeof appendLedger>[0]) => Promise<void>)\n | undefined,\n finish: (producer: Parameters<typeof appendLedger>[0]) => Promise<void>,\n models: MigrationClient[\"$schema\"]\n): Promise<void> {\n const groups = groupContiguousAtomicity(replay, (edge) =>\n resetProgram(undefined, [edge])\n );\n const liveClear = resetProgram(livePlan, []);\n const liveClearDispatches = new Set(\n liveClear.map((sql) => dispatchForClearSql(sql).dispatchId)\n );\n let clearPending = liveClear.length > 0 ? livePlan : undefined;\n // On Neki no program opens a transaction (`runProgram`): what a failure\n // reports as its boundary is the one it ran under.\n const neki = command.commitsSchemaChangesAlone();\n let clearEvidencePending = livePlan !== undefined;\n let admissionPending = beforeFirstEffect;\n // `statements` are the ones the boundary runs: apply's program, so SQLite's\n // foreign keys are lifted (and proven) around a replayed recreation.\n const runBoundary = async (\n boundary: \"transactional\" | \"stepwise\",\n statements: string[],\n body: (target: Parameters<typeof appendLedger>[0]) => Promise<void>\n ) => {\n const guarded = async (target: Parameters<typeof appendLedger>[0]) => {\n // The reset's own attempt is open once admitted (or resumed): before\n // that, an open one was opened while the lock was let go.\n await assertLockedSinceDecision(\n pinned,\n target,\n command,\n marker,\n admissionPending === undefined\n );\n await body(target);\n };\n // On MySQL the reset already runs as one sequential program (`resetV1`).\n try {\n await (command.target.dialect === \"mysql\"\n ? guarded(producer)\n : runProgram(\n pinned,\n command,\n { transactional: boundary === \"transactional\", statements },\n guarded\n ));\n } catch (failure) {\n // A failure no statement named is this boundary's: its commit, its lock.\n throw annotateMigrationFailure(failure, {\n step: \"reset\",\n strategy: neki ? \"stepwise\" : boundary,\n stateId: plan.replayPath.at(-1),\n });\n }\n };\n const completeClearEvidence = async (\n target: Parameters<typeof appendLedger>[0]\n ) => {\n for (const dispatch of plan.clearDispatches) {\n if (!liveClearDispatches.has(dispatch.dispatchId)) {\n await confirmResetDispatch(target, command, graph, attemptId, dispatch);\n }\n }\n };\n const admit = async (target: Parameters<typeof appendLedger>[0]) => {\n const pending = admissionPending;\n if (!pending) return;\n admissionPending = undefined;\n await pending(target);\n };\n // A driver whose index cannot share a transaction with what a clear wrote commits\n // the clear first, whatever boundary the program that follows asks for.\n if (\n clearPending &&\n (groups[0]?.boundary === \"stepwise\" || command.buildsApart?.([], true))\n ) {\n const clear = clearPending;\n clearPending = undefined;\n await runBoundary(\n \"transactional\",\n resetProgram(clear, []),\n async (target) => {\n await admit(target);\n await executeResetClear(\n target,\n command,\n clear,\n attemptId,\n graph,\n neki ? \"stepwise\" : \"transactional\"\n );\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n );\n }\n if (!clearPending && groups[0]?.boundary === \"stepwise\" && admissionPending) {\n await runBoundary(\"transactional\", [], admit);\n }\n if (groups.length === 0) {\n const statements = resetProgram(clearPending, []);\n await runBoundary(\"transactional\", statements, async (target) => {\n await admit(target);\n if (clearPending) {\n await executeResetClear(\n target,\n command,\n clearPending,\n attemptId,\n graph,\n neki ? \"stepwise\" : \"transactional\"\n );\n }\n if (clearEvidencePending) {\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n await finish(target);\n });\n return;\n }\n for (const [index, group] of groups.entries()) {\n const statements = resetProgram(clearPending, group.items);\n await runBoundary(group.boundary, statements, async (target) => {\n await admit(target);\n if (clearPending) {\n await executeResetClear(\n target,\n command,\n clearPending,\n attemptId,\n graph,\n group.boundary\n );\n clearPending = undefined;\n }\n if (clearEvidencePending) {\n await completeClearEvidence(target);\n clearEvidencePending = false;\n }\n for (const edge of group.items) {\n await executeResetReplayEdge(\n target,\n command,\n graph,\n edge,\n attemptId,\n models\n );\n }\n if (index === groups.length - 1) await finish(target);\n });\n }\n}\n\nasync function executeResetReplayEdge(\n pinned: Parameters<typeof executeOperations>[0],\n command: BoundMigrationDriver,\n graph: MigrationGraph,\n edge: PreparedResetReplayEdge,\n attemptId: Sha256,\n models: MigrationClient[\"$schema\"]\n): Promise<void> {\n const { from, to, transition, state, blob, boundary, operations } = edge;\n const events = attemptEvents(\n {\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: from,\n toState: to,\n transitionHash: transition.transitionHash,\n direction: \"reset\",\n },\n attemptId\n );\n await executeOperations(\n pinned,\n blob,\n operations,\n boundary,\n (progress, effect, failure) =>\n appendLedger(\n pinned,\n command,\n events.event(\"reset-step-confirmed\", effect, progress, failure)\n ),\n command.namespace,\n { fromState: from, toState: to, step: \"reset-replay\" }\n );\n // Replayed manual SQL is canonicalized exactly as apply canonicalizes it.\n await canonicalizeSqliteStorage(\n pinned,\n operations,\n models,\n requireStateSnapshot(graph, to)\n );\n await assertAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Reset replay failed destination checks\"\n );\n}\n","/**\n * V1 operator commands: status, verify, log, baseline, reanchor, prune,\n * down, resolve, reset.\n * Status/verify/log are read-only and never bootstrap missing control tables.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { admitLiveMigrationCapability } from \"./admission\";\nimport { bytesEqual, canonicalizeJson } from \"./canonical-json\";\nimport {\n type InvalidIndex,\n qualifiedName,\n readInvalidIndexes,\n} from \"./catalog-probes\";\nimport {\n assertTransactionalBoundaryHonored,\n classifyStoredAtomicity,\n groupContiguousAtomicity,\n refuseSqliteStepwise,\n stepStatements,\n} from \"./compile\";\nimport {\n advanceMarker,\n appendLedger,\n attemptEvents,\n ensureControlTables,\n isTableMissing,\n ledgerEvent,\n type MigrationControlRead,\n readControlState,\n refuseIncompatibleHistory,\n refusePartialControl,\n unfinishedAttempts,\n} from \"./control\";\nimport { diff, isDestructiveOperation } from \"./differ\";\nimport { type NormalizedDownOptions, normalizeDownOptions } from \"./down-input\";\nimport {\n assertAllChecks,\n evaluateAllChecks,\n executeOperations,\n} from \"./execute-dispatch\";\nimport {\n loadMigrationGraph,\n type MigrationGraph,\n parentTransition,\n requireStateSnapshot,\n resolveStateSelector,\n routeEdges,\n selectRoute,\n statesFrom,\n} from \"./graph\";\nimport type { Sha256 } from \"./identity\";\nimport {\n commitLockedTransaction,\n letLockGo,\n resolveCommandDriver,\n runProgram,\n withLockedMigrationProducer,\n} from \"./pinned-session\";\nimport {\n assertAdoptable,\n assertLockedSinceDecision,\n assertNoDrift,\n managedAt,\n markerStanding,\n proveLive,\n} from \"./proof\";\nimport { renderMigrationReview } from \"./public-view\";\nimport { getPushMigrationDriver, type MigrationClient } from \"./push/planner\";\nimport { fingerprintLive } from \"./push-fingerprint\";\nimport { introspectManaged } from \"./push-plan\";\nimport { approveDestructiveOperations } from \"./resolver\";\nimport {\n countUnanswered,\n openCommand,\n readCommandControl,\n remainingSteps,\n} from \"./resume\";\nimport { sliceDispatch } from \"./sql-blob\";\nimport { canonicalizeSqliteStorage } from \"./sqlite-storage-audit\";\nimport type {\n MigrationStorageReader,\n MigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n managedTables,\n selectManagedSnapshot,\n withManagedTables,\n} from \"./target\";\nimport type {\n AmbiguousChange,\n DiffOperation,\n ResolveCallback,\n SchemaSnapshot,\n} from \"./types\";\nimport { encodeSnapshot } from \"./v1-parse-snapshot\";\nimport type {\n BaselineOptions,\n DownPreviewEdgeV1,\n DownV1Options,\n DownV1Result,\n LedgerEventV1,\n MarkerPathEdgeV1,\n MigrationMarkerV1,\n ReanchorOptions,\n ResolveV1Options,\n StateSelector,\n} from \"./v1-types\";\n\nexport { resetV1 } from \"./reset-v1\";\n\nexport interface StatusV1Result {\n readonly control: \"absent\" | \"present\";\n readonly marker: MigrationMarkerV1 | null;\n readonly pending: readonly Sha256[];\n readonly unfinished: boolean;\n /**\n * Present only when the marker names a state this estate does not hold:\n * `\"ahead\"` when its arrival path leaves this history after a state it holds\n * (newer code migrated the database), `\"unknown\"` when nothing on that path\n * belongs here. `pending` is then empty.\n */\n readonly markerState?: \"ahead\" | \"unknown\";\n /** Present only when a managed table carries an INVALID index (PostgreSQL). */\n readonly invalidIndexes?: readonly InvalidIndex[];\n /**\n * The latest `failed` ledger event, present once a rolled-back attempt left\n * one: its `toState`, `dispatchId` and `failure` say what failed and why.\n */\n readonly lastFailure?: LedgerEventV1;\n}\n\nexport async function statusV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<StatusV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"read-only\", \"status()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readCommandControl(client.$driver, command);\n const marked = control.marker?.stateId ?? null;\n const invalidIndexes = await readInvalidIndexes(\n client.$driver,\n marked === null || graph.states.has(marked)\n ? managedAt(command, graph, marked)\n : command\n );\n const listed = invalidIndexes.length === 0 ? {} : { invalidIndexes };\n if (control.presence.kind !== \"present\") {\n return {\n control: \"absent\",\n marker: null,\n pending: [...graph.roots],\n unfinished: false,\n ...listed,\n };\n }\n const { marker, ledger } = control;\n const unfinished = unfinishedAttempts(ledger).length > 0;\n let lastFailure: LedgerEventV1 | undefined;\n for (const event of ledger) {\n if (event.kind === \"failed\") lastFailure = event;\n }\n const standing = markerStanding(graph, marker);\n let pending: Sha256[] = [];\n if (standing === \"known\" && graph.leaves.length === 1) {\n const leaf = graph.leaves[0]!;\n if ((marker?.stateId ?? null) !== leaf) {\n pending = [...selectRoute(graph, marker?.stateId ?? null, leaf)];\n }\n }\n return {\n control: \"present\",\n marker,\n pending,\n unfinished,\n ...(standing === \"known\" ? {} : { markerState: standing }),\n ...listed,\n ...(lastFailure ? { lastFailure } : {}),\n };\n}\n\nexport interface VerifyV1Result {\n readonly ok: boolean;\n /** Present, with `ok: false`, when the marker names a state this estate does not hold. */\n readonly markerState?: \"ahead\" | \"unknown\";\n}\n\nexport async function verifyV1(\n client: MigrationClient,\n storage: MigrationStorageReader\n): Promise<VerifyV1Result> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"verify()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command);\n if (control.presence.kind !== \"present\") {\n throw new MigrationError(\n \"verify requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const { marker } = control;\n if (!marker) {\n throw new MigrationError(\n \"verify requires a migration marker\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const standing = markerStanding(graph, marker);\n if (standing !== \"known\") return { ok: false, markerState: standing };\n const markedSnapshot = requireStateSnapshot(graph, marker.stateId);\n await command.preflightSchemaRequirements(\n [markedSnapshot],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await assertNoDrift(\n pinned,\n managedAt(command, graph, marker.stateId),\n graph,\n marker\n );\n return { ok: true };\n }\n );\n}\n\nexport async function logV1(\n client: MigrationClient\n): Promise<readonly LedgerEventV1[]> {\n const driver = getPushMigrationDriver(client);\n admitLiveMigrationCapability(driver, \"read-only\", \"log()\");\n const command = await resolveCommandDriver(client.$driver, driver);\n const control = await readControlState(client.$driver, command);\n if (control.presence.kind !== \"present\") {\n refusePartialControl(control.presence);\n throw new MigrationError(\n \"log requires present control tables\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return control.ledger;\n}\n\nexport async function baselineV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: BaselineOptions\n): Promise<{ readonly stateId: Sha256 }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"baseline()\");\n const target = resolveStateSelector(graph, options.to);\n const path = selectRoute(graph, null, target, options.via);\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command, true);\n const { marker, ledger } = control;\n if (marker || unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"baseline requires an unmarked database without an unfinished attempt\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n refuseIncompatibleHistory(marker, ledger);\n assertStructuralRoute(graph, path, \"baseline\");\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, target)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await assertAdoptable(pinned, command, graph, null, path);\n // Committed before the proof, which then runs under the lock taken\n // again, as does the marker it publishes.\n if (control.presence.kind !== \"present\") {\n await ensureControlTables(pinned, command);\n await commitLockedTransaction(pinned, command);\n await assertLockedSinceDecision(pinned, pinned, command, null);\n }\n await proveLive(\n pinned,\n managedAt(command, graph, target),\n graph,\n graph.states.get(target)!.snapshotHash,\n async (differences) =>\n `baseline requires exact live equality with the target snapshot. Differences: ${await differences()}`\n );\n await adoptRoute(pinned, command, graph, path, null);\n return { stateId: target };\n }\n );\n}\n\n/**\n * Plan T3: after a restore left this history older than the database, moves\n * a marker naming a state the history lacks onto the one known state the live\n * schema matches, with baseline's proof and a baseline boundary. `to` adopts\n * the state it names instead: the consent several matching states need.\n */\nexport async function reanchorV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ReanchorOptions = {}\n): Promise<{ readonly stateId: Sha256 }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"reanchor()\");\n const named = options.to && resolveStateSelector(graph, options.to);\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const { marker, ledger } = await readCommandControl(pinned, command);\n if (!marker || markerStanding(graph, marker) === \"known\") {\n throw new MigrationError(\n \"reanchor moves only a marker naming a state this history does not hold; apply, verify and baseline handle the others\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (unfinishedAttempts(ledger).length > 0) {\n throw new MigrationError(\n \"reanchor refuses while an attempt is unfinished: resolve it first\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n // One read of everything any candidate manages, then each candidate\n // compared with what it manages, selected in memory.\n const candidates = named ? [named] : [...graph.states.keys()];\n const read = await introspectManaged(\n pinned,\n withManagedTables(\n command,\n managedTables(\n graph.descriptor.target.tables,\n candidates.map((stateId) => requireStateSnapshot(graph, stateId))\n )\n )\n );\n const liveAt = (stateId: Sha256) =>\n selectManagedSnapshot(read, managedAt(command, graph, stateId).target);\n // One fingerprint per distinct selection: without a list, exactly one.\n const liveHashes = new Map<string, Promise<string>>();\n const liveHash = (stateId: Sha256) => {\n const key = JSON.stringify(\n managedAt(command, graph, stateId).target.tables ?? null\n );\n let hash = liveHashes.get(key);\n if (hash === undefined) {\n hash = fingerprintLive(liveAt(stateId), command, pinned);\n liveHashes.set(key, hash);\n }\n return hash;\n };\n const matches: Sha256[] = [];\n for (const stateId of candidates) {\n const snapshot = requireStateSnapshot(graph, stateId);\n if (\n (await liveHash(stateId)) ===\n (await fingerprintLive(snapshot, command, pinned))\n ) {\n matches.push(stateId);\n }\n }\n const reference =\n named ?? (graph.leaves.length === 1 ? graph.leaves[0] : undefined);\n if (matches.length === 0) {\n const differences = reference\n ? ` Differences from ${reference}: ${JSON.stringify(await diff(liveAt(reference), requireStateSnapshot(graph, reference)))}`\n : \"\";\n throw new MigrationError(\n `reanchor found no state of this history that the live schema matches.${differences}`,\n VibORMErrorCode.MIGRATION_DRIFT\n );\n }\n if (matches.length > 1) {\n throw new MigrationError(\n `Several states of this history match the live schema (${matches.join(\", \")}), and equal schemas never say which data the database holds: name one with reanchor({ to }).`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const target = matches[0]!;\n if (marker.path.some((edge) => edge.stateId === target)) {\n throw new MigrationError(\n `reanchor refuses ${target}: the marker passed through it, so the transitions lost after it changed no schema and may have moved data. Regenerate the lost states from the same documents instead: their ids come back identical.`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const path = selectRoute(graph, null, target, options.via);\n assertStructuralRoute(graph, path, \"reanchor\");\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, target)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await assertAdoptable(pinned, command, graph, null, path);\n await adoptRoute(pinned, command, graph, path, marker);\n return { stateId: target };\n }\n );\n}\n\n/** Baseline's proof of a root route: no manual, opaque or data-only edge. */\nfunction assertStructuralRoute(\n graph: MigrationGraph,\n path: readonly Sha256[],\n command: \"baseline\" | \"reanchor\"\n): void {\n for (const { from, transition, state } of routeEdges(graph, null, path)) {\n const parentSnapshot =\n from === null\n ? graph.emptySnapshotHash\n : graph.states.get(from)?.snapshotHash;\n if (\n transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" || operation.risk === \"opaque\"\n ) ||\n parentSnapshot === state.snapshotHash\n ) {\n throw new MigrationError(\n `${command} refuses a path containing manual, opaque, or data-only transitions`,\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n }\n}\n\n/**\n * Publishes the marker re-rooted on `path`, its first edge a baseline\n * boundary, in place of `current` (compare-and-swap), with the event that\n * says so: `baselined` without a marker before, `reanchored` with one. In one\n * transaction when the producer can.\n */\nasync function adoptRoute(\n pinned: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n path: readonly Sha256[],\n current: MigrationMarkerV1 | null\n): Promise<void> {\n const edges = routeEdges(graph, null, path).map(\n ({ to, transition }, index) => ({\n stateId: to,\n transitionHash: transition.transitionHash,\n baselineBoundary: index === 0,\n })\n );\n const target = path.at(-1)!;\n const publish = async (producer: AnyDriver) => {\n const next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n edges,\n graph.states.get(target)!.snapshotHash\n );\n await appendLedger(\n producer,\n command,\n ledgerEvent({\n attemptId: next.pathHash,\n kind: current ? \"reanchored\" : \"baselined\",\n estateHash: graph.estateHash,\n snapshotHash: next.snapshotHash,\n sqlHash: null,\n fromState: current?.stateId ?? null,\n toState: target,\n transitionHash: null,\n direction: \"baseline\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n })\n );\n };\n if (pinned.supportsTransactions) {\n await pinned.withTransaction((transaction) => publish(transaction));\n } else {\n await publish(pinned);\n }\n}\n\nexport interface PruneOptions {\n /** The authored checkpoint (`generate({ from: null })`) to keep history from. */\n readonly checkpoint: StateSelector;\n /** A fresh history: the source is never changed. */\n readonly into: MigrationStorageWriter;\n}\n\nexport interface PruneResult {\n /** The states `into` now holds from this history. */\n readonly states: readonly Sha256[];\n}\n\n/**\n * Plan T4: copies the checkpoint and the states `statesFrom` keeps after it\n * into a fresh history. Storage stays append-only, so pruning is a copy: what\n * it leaves out is what `check()` would report as orphaned, once the earlier\n * manifests were gone. A marker on a dropped state is moved by `reanchor()`.\n */\nexport async function pruneV1(\n storage: MigrationStorageReader,\n options: PruneOptions\n): Promise<PruneResult> {\n const graph = await loadMigrationGraph(storage);\n const kept = statesFrom(\n graph,\n resolveStateSelector(graph, options.checkpoint)\n );\n const { into } = options;\n await into.publishEstate(\n await present(\n storage.readEstate(),\n \"estate.json\",\n canonicalizeJson(graph.descriptor)\n )\n );\n const copiedSnapshots = new Set<Sha256>();\n for (const id of kept) {\n const { snapshotHash, snapshotArtifactHash, sqlHash } =\n graph.states.get(id)!;\n const dependencies: Sha256[] = [];\n let hash: Sha256 | undefined = snapshotArtifactHash ?? snapshotHash;\n while (hash !== undefined && !copiedSnapshots.has(hash)) {\n dependencies.push(hash);\n hash = graph.snapshotArtifacts.get(hash)?.baseArtifactHash;\n }\n for (const dependency of dependencies.reverse()) {\n const artifact = graph.snapshotArtifacts.get(dependency);\n const expected =\n artifact?.bytes ??\n encodeSnapshot(requireStateSnapshot(graph, null)).bytes;\n // Only the implicit empty schema needs no stored object. An explicit\n // reference, including an empty delta base, must still remain present.\n const bytes =\n !artifact && dependency === graph.emptySnapshotHash\n ? ((await storage.readSnapshot(dependency)) ?? expected)\n : await present(storage.readSnapshot(dependency), dependency);\n if (!bytesEqual(bytes, expected)) {\n throw new MigrationError(\n `Snapshot ${dependency} changed while prune copied it`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n await into.publishSnapshot(dependency, expected.slice());\n copiedSnapshots.add(dependency);\n }\n await into.publishSql(sqlHash, graph.sql.get(sqlHash)!);\n await into.publishState(\n id,\n await present(\n storage.readState(id),\n id,\n canonicalizeJson(graph.states.get(id)!)\n )\n );\n }\n return { states: [...kept] };\n}\n\n/** Refuse missing objects and revalidate fresh manifest/descriptor reads. */\nasync function present(\n read: Promise<Uint8Array | null>,\n artifact: string,\n expected?: Uint8Array\n): Promise<Uint8Array> {\n const bytes = await read;\n if (!bytes) {\n throw new MigrationError(\n `${artifact} vanished from the history while prune copied it`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (expected && !bytesEqual(bytes, expected)) {\n throw new MigrationError(\n `${artifact} changed while prune copied it`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return expected ?? bytes;\n}\n\nexport async function downV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: DownV1Options = {}\n): Promise<DownV1Result> {\n const request = normalizeDownOptions(options);\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(\n client,\n graph,\n request.dryRun ? \"read-only\" : \"effectful\",\n \"down()\"\n );\n if (request.dryRun) {\n const producer = client.$driver;\n const command = await resolveCommandDriver(producer, driver);\n const { close, removed, refusal } = await planRollback(\n producer,\n command,\n graph,\n await readCommandControl(producer, command),\n request,\n true\n );\n return {\n path: close\n ? [close.item.edge.stateId]\n : removed.map((edge) => edge.stateId),\n preview: true,\n edges: [...removed]\n .reverse()\n .map((edge) => previewRollbackEdge(graph, edge)),\n refusal,\n };\n }\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const control = await readCommandControl(pinned, command);\n const { close, removed, run } = await planRollback(\n pinned,\n command,\n graph,\n control,\n request,\n false\n );\n if (close) {\n await command.preflightSchemaRequirements(\n [requireStateSnapshot(graph, close.item.nextState)],\n (sql, params) => pinned._executeRaw(sql, params),\n []\n );\n await runProgram(pinned, command, undefined, (producer) =>\n closeCompletedRollback(\n producer,\n command,\n graph,\n close.item,\n close.attempt,\n control.ledger,\n control.marker\n )\n );\n return { path: [close.item.edge.stateId], preview: false };\n }\n if (!run) return { path: [], preview: false };\n const { prepared, attempt } = run;\n const statementsOf = (item: PreparedRollback) =>\n stepStatements(item.blob, item.rollback.operations);\n let current = run.marker;\n for (const group of groupContiguousAtomicity(prepared, statementsOf)) {\n await runProgram(\n pinned,\n command,\n {\n transactional: group.boundary === \"transactional\",\n statements: group.items.flatMap(statementsOf),\n },\n async (producer) => {\n // Only the attempt `down` resumes is its own: any other one open\n // now was opened while the lock was let go.\n await assertLockedSinceDecision(\n pinned,\n producer,\n command,\n current,\n group.items[0] === prepared[0] && attempt !== undefined\n );\n for (const item of group.items) {\n current = await executeRollbackEdge(\n producer,\n command,\n graph,\n item,\n current,\n item === prepared[0] ? attempt : undefined,\n control.ledger,\n client.$schema\n );\n }\n }\n );\n }\n return { path: removed.map((edge) => edge.stateId), preview: false };\n }\n );\n}\n\ntype PreparedRollback = ReturnType<typeof prepareRollbackEdge>;\n\ninterface RollbackPlan {\n /** The first refusal of a preview; `down` throws it instead. */\n readonly refusal: { code: string; message: string } | null;\n /** A rollback that finished before it was recorded: `down` closes it. */\n readonly close?: {\n readonly item: PreparedRollback;\n readonly attempt: LedgerEventV1;\n };\n /** The marker edges `down` removes. */\n readonly removed: MigrationMarkerV1[\"path\"];\n /** Present when `down` reverses `removed`, newest edge first. */\n readonly run?: {\n readonly marker: MigrationMarkerV1;\n readonly prepared: readonly PreparedRollback[];\n readonly attempt: LedgerEventV1 | undefined;\n };\n}\n\n/**\n * What `down` decides before its first effect, read-only and in its order, so\n * the preview refuses where `down` refuses. `previewing` returns a refusal of\n * the attempt or of the checks as data (`down` throws it); without one, a\n * preview still names the edges.\n */\nasync function planRollback(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n { marker, ledger }: MigrationControlRead,\n request: NormalizedDownOptions,\n previewing: boolean\n): Promise<RollbackPlan> {\n assertExpectedRevision(marker, request);\n let refusal: RollbackPlan[\"refusal\"] = null;\n let attempt: LedgerEventV1 | undefined;\n try {\n attempt = admitRollbackAttempt(ledger);\n } catch (error) {\n if (!previewing) throw error;\n refusal = refusalOf(error);\n }\n const { supportsTransactions } = producer;\n if (attempt && attempt.toState === (marker?.stateId ?? null)) {\n const item = prepareRollbackAttempt(\n graph,\n command,\n supportsTransactions,\n attempt\n );\n return { refusal, close: { item, attempt }, removed: [] };\n }\n if (!marker) {\n // `down` refuses the attempt before it finds nothing to roll back.\n if (refusal) return { refusal, removed: [] };\n throw new MigrationError(\n \"Nothing to roll back\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const removed = rollbackSlice(graph, marker, request);\n // `down` checks nothing more when it has nothing to roll back.\n if (refusal || removed.length === 0) return { refusal, removed };\n try {\n const reverse = [...removed].reverse();\n for (const edge of reverse) assertReversibleEdge(graph, edge);\n const prepared = reverse.map((edge) =>\n prepareRollbackEdge(graph, command, supportsTransactions, edge)\n );\n await command.preflightSchemaRequirements(\n [\n requireStateSnapshot(graph, marker.stateId),\n ...prepared.map((item) => requireStateSnapshot(graph, item.nextState)),\n ],\n (sql, params) => producer._executeRaw(sql, params),\n prepared.flatMap((item) =>\n stepStatements(item.blob, item.rollback.operations)\n ),\n // On Neki each statement commits alone: only one dispatch's own\n // statements cannot be divided.\n true\n );\n if (attempt) {\n assertResumesSelectedPath(\n graph,\n command,\n supportsTransactions,\n attempt,\n prepared[0]!\n );\n } else {\n await assertNoDrift(\n producer,\n managedAt(command, graph, marker.stateId, prepared[0]!.nextState),\n graph,\n marker\n );\n }\n await approveRollbackLosses(\n producer,\n command,\n graph,\n prepared,\n request.resolve\n );\n return { refusal, removed, run: { marker, prepared, attempt } };\n } catch (error) {\n if (!previewing) throw error;\n return { refusal: refusalOf(error), removed };\n }\n}\n\nexport async function resolveV1(\n client: MigrationClient,\n storage: MigrationStorageReader,\n options: ResolveV1Options\n): Promise<{ readonly outcome: ResolveV1Options[\"outcome\"] }> {\n const graph = await loadMigrationGraph(storage);\n const driver = openCommand(client, graph, \"effectful\", \"resolve()\");\n return withLockedMigrationProducer(\n client.$driver,\n driver,\n async (pinned, command) => {\n const { ledger } = await readCommandControl(pinned, command);\n const open = unfinishedAttempts(ledger);\n if (open.length !== 1) {\n throw new MigrationError(\n open.length === 0\n ? \"resolve requires an unfinished attempt\"\n : \"resolve requires exactly one unfinished attempt\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const attempt = open[0]!;\n if (attempt.kind === \"reset-started\") {\n throw new MigrationError(\n \"An unfinished reset can only be resumed by reset()\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (attempt.direction === \"rollback\") {\n throw new MigrationError(\n \"An unfinished rollback can only be resumed by down()\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n const to = attempt.toState;\n const from = attempt.fromState;\n if (!to) {\n throw new MigrationError(\n \"Unfinished attempt is missing its target state\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const state = graph.states.get(to);\n if (!state) {\n throw new MigrationError(\n \"Unfinished attempt target is absent from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const blob = graph.sql.get(state.sqlHash)!;\n const transition = parentTransition(graph, from, to);\n const destSnapshot = requireStateSnapshot(graph, to);\n const originSnapshot = requireStateSnapshot(graph, from);\n const statements = stepStatements(blob, transition.operations);\n // Only a retry runs the transition: its program is refused as apply's.\n await command.preflightSchemaRequirements(\n [originSnapshot, destSnapshot],\n (sql, params) => pinned._executeRaw(sql, params),\n options.outcome === \"retry\" ? statements : [],\n // On Neki each statement commits alone.\n true\n );\n // Completing or retrying lands on the destination, which manages a\n // table the edge adopts; rolling back leaves it outside.\n if (options.outcome !== \"rolled-back\") {\n await assertAdoptable(pinned, command, graph, from, [to]);\n }\n // Both ends of the edge, read once: the destination manages a table\n // the edge adopts, the origin does not.\n const across = managedAt(command, graph, to, from);\n if (options.outcome !== \"retry\") {\n await repairInvalidIndexes(\n pinned,\n across,\n statements,\n options.outcome === \"complete\" ? destSnapshot : originSnapshot\n );\n }\n const read = await introspectManaged(pinned, across);\n const destHolds =\n (await fingerprintLive(read, command, pinned)) ===\n (await fingerprintLive(destSnapshot, command, pinned)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n state.destinationChecks,\n command.namespace\n ));\n const originHolds =\n (await fingerprintLive(\n selectManagedSnapshot(\n read,\n managedAt(command, graph, from, to).target\n ),\n command,\n pinned\n )) === (await fingerprintLive(originSnapshot, command, pinned)) &&\n (await evaluateAllChecks(\n pinned,\n blob,\n transition.originChecks,\n command.namespace\n ));\n const manualOpaque = transition.operations.some(\n (operation) =>\n operation.origin === \"manual\" &&\n operation.steps.some((step) => step.retry === \"opaque\")\n );\n // Marking an outcome is one transaction where the producer has one.\n const record = { transactional: true, statements: [] };\n if (options.outcome === \"complete\") {\n if (\n !destHolds ||\n (manualOpaque && state.destinationChecks.length === 0)\n ) {\n throw new MigrationError(\n \"resolve cannot mark complete without destination proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n await runProgram(pinned, command, record, async (producer) => {\n // Completing manual SQL canonicalizes what it stored, as apply does.\n await canonicalizeSqliteStorage(\n producer,\n transition.operations,\n client.$schema,\n destSnapshot\n );\n await finishResolve(producer, command, graph, attempt, \"applied\", to);\n });\n return { outcome: \"complete\" };\n }\n if (options.outcome === \"rolled-back\") {\n refuseOpaqueEffect(transition, blob, attempt, ledger);\n if (\n !originHolds ||\n (manualOpaque && transition.originChecks.length === 0)\n ) {\n throw new MigrationError(\n \"resolve cannot mark rolled back without origin proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n await runProgram(pinned, command, record, (producer) =>\n finishResolve(producer, command, graph, attempt, \"rolled-back\", from)\n );\n return { outcome: \"rolled-back\" };\n }\n if (manualOpaque) {\n throw new MigrationError(\n \"resolve cannot retry an opaque dispatch without origin or destination proof\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n if (\n transition.operations.some((operation) =>\n operation.steps.some((step) => step.retry === \"opaque\")\n ) &&\n !originHolds\n ) {\n throw new MigrationError(\n \"resolve cannot retry a generated structural transition except from the origin\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n assertTransactionalBoundaryHonored(\n pinned.supportsTransactions,\n transition.requestedForwardBoundary\n );\n const boundary = classifyStoredAtomicity(\n command,\n transition.requestedForwardBoundary,\n transition.operations,\n blob\n );\n // A recreation is refused without a transaction: its lift is unproven.\n await runProgram(\n pinned,\n command,\n { transactional: boundary === \"transactional\", statements },\n async (producer) => {\n await executeOperations(\n producer,\n blob,\n transition.operations,\n boundary,\n undefined,\n command.namespace,\n { fromState: from, toState: to, step: \"resolve\" }\n );\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Retry did not reach the destination\"\n );\n await proveLive(\n producer,\n across,\n graph,\n state.snapshotHash,\n () => \"Retry did not reach the destination\"\n );\n await finishResolve(producer, command, graph, attempt, \"applied\", to);\n }\n );\n return { outcome: \"retry\" };\n }\n );\n}\n\n/**\n * The index a `CREATE`/`DROP`/`REINDEX INDEX CONCURRENTLY` statement names,\n * schema prefix dropped. An unnamed `CREATE INDEX CONCURRENTLY ON t` is never\n * matched; its PG-chosen name is left to the V11023 refusal. (DROP INDEX\n * CONCURRENTLY takes one name only.)\n */\nconst CONCURRENT_INDEX_NAME =\n /\\bINDEX\\s+CONCURRENTLY\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(?!ON\\b)(?:(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)\\s*\\.\\s*)?(\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)/gi;\n/** The suffix of the `_ccnew`/`_ccold` copy an interrupted `REINDEX CONCURRENTLY` leaves INVALID. */\nconst REINDEX_REMNANT = /^_cc(?:new|old)\\d*$/;\n\n/**\n * Repairs the INVALID indexes the unfinished attempt's own CONCURRENTLY\n * statements left behind — the index each names, and the `<name>_ccnew` /\n * `<name>_ccold` remnant of an interrupted `REINDEX CONCURRENTLY` — towards the snapshot the\n * requested outcome asserts: an index that snapshot declares is rebuilt, any\n * other is dropped, both CONCURRENTLY so writes keep flowing. An invalid index\n * the attempt never named (another session's build, still running perhaps) is\n * left alone, and the proof that follows refuses on it with V11023. An invalid\n * index belongs to neither state, so the repair cannot turn a false proof true.\n */\nasync function repairInvalidIndexes(\n pinned: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n statements: readonly string[],\n expected: SchemaSnapshot\n): Promise<void> {\n const named = statements.flatMap(concurrentIndexNames);\n if (named.length === 0) return;\n for (const { table, index } of await readInvalidIndexes(pinned, command)) {\n if (\n !named.some(\n (name) =>\n index === name ||\n (index.startsWith(name) &&\n REINDEX_REMNANT.test(index.slice(name.length)))\n )\n )\n continue;\n const rebuild = expected.tables.some(\n (declared) =>\n declared.name === table &&\n declared.indexes.some((item) => item.name === index)\n );\n await pinned._executeRaw(\n `${rebuild ? \"REINDEX INDEX\" : \"DROP INDEX\"} CONCURRENTLY ${qualifiedName(command, index)}`\n );\n }\n}\n\n/** The indexes a statement's `INDEX CONCURRENTLY` clauses name. */\nfunction concurrentIndexNames(text: string): string[] {\n return [...text.matchAll(CONCURRENT_INDEX_NAME)].map(([, name = \"\"]) =>\n name.startsWith('\"')\n ? name.slice(1, -1).replaceAll('\"\"', '\"')\n : name.toLowerCase()\n );\n}\n\nasync function finishResolve(\n pinned: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n attempt: LedgerEventV1,\n kind: \"applied\" | \"rolled-back\",\n to: Sha256 | null\n): Promise<void> {\n const { marker } = await readCommandControl(pinned, command);\n if (kind === \"applied\" && to && marker?.stateId !== to) {\n const transition = parentTransition(graph, attempt.fromState, to);\n await advanceMarker(\n pinned,\n command,\n graph.estateHash,\n marker,\n [\n ...(marker?.path ?? []),\n {\n stateId: to,\n transitionHash: attempt.transitionHash ?? transition.transitionHash,\n baselineBoundary: false,\n },\n ],\n graph.states.get(to)!.snapshotHash\n );\n }\n if (kind === \"rolled-back\" && marker && marker.stateId === attempt.toState) {\n const nextPath = marker.path.slice(0, -1);\n await advanceMarker(\n pinned,\n command,\n graph.estateHash,\n marker,\n nextPath,\n snapshotHashOf(graph, nextPath.at(-1)?.stateId ?? null)\n );\n }\n await appendLedger(\n pinned,\n command,\n ledgerEvent({\n attemptId: attempt.attemptId,\n kind: \"resolved\",\n estateHash: graph.estateHash,\n snapshotHash: snapshotHashOf(graph, to),\n sqlHash: attempt.sqlHash,\n fromState: attempt.fromState,\n toState: to,\n transitionHash: attempt.transitionHash,\n direction: \"resolve\",\n operationId: null,\n dispatchId: null,\n effectState: \"none\",\n })\n );\n}\n\n/** The snapshot a state, or the empty origin, authenticates. */\nfunction snapshotHashOf(graph: MigrationGraph, stateId: Sha256 | null): Sha256 {\n return stateId\n ? graph.states.get(stateId)!.snapshotHash\n : graph.emptySnapshotHash;\n}\n\nfunction prepareRollbackEdge(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n edge: MarkerPathEdgeV1\n) {\n const state = graph.states.get(edge.stateId)!;\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n )!;\n const blob = graph.sql.get(state.sqlHash)!;\n const rollback = parent.rollback;\n if (rollback.kind === \"irreversible\") {\n throw new MigrationError(\n rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n const requested =\n rollback.kind === \"manual\" ? rollback.requestedBoundary : null;\n assertTransactionalBoundaryHonored(supportsTransactions, requested);\n refuseSqliteStepwise(command, requested, edge.stateId);\n return {\n edge,\n state,\n parent,\n blob,\n rollback,\n boundary: classifyStoredAtomicity(\n command,\n requested,\n rollback.operations,\n blob\n ),\n nextState: parent.fromState,\n };\n}\n\n/**\n * One edge of a down preview: its rollback rendered as `show --sql` renders\n * it, without the forward half or its forward approvals.\n */\nfunction previewRollbackEdge(\n graph: MigrationGraph,\n edge: MarkerPathEdgeV1\n): DownPreviewEdgeV1 {\n const state = graph.states.get(edge.stateId);\n const parent = state?.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n );\n const blob = state && graph.sql.get(state.sqlHash);\n if (!(parent && blob)) {\n throw new MigrationError(\n \"Rollback cannot find the arrival transition or its SQL\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const { approvals: _forward, ...transition } = parent;\n return {\n stateId: edge.stateId,\n toState: parent.fromState,\n sql: renderMigrationReview(\n [{ ...transition, originChecks: [], operations: [] }],\n [],\n blob\n ),\n };\n}\n\n/** A migration refusal as plain data; any other error is rethrown. */\nfunction refusalOf(error: unknown): { code: string; message: string } {\n if (!(error instanceof MigrationError)) throw error;\n return { code: error.code, message: error.message };\n}\n\n/**\n * The one unfinished attempt `down` may resume: none, or a started rollback.\n * Anything else needs repair first.\n */\nfunction admitRollbackAttempt(\n ledger: readonly LedgerEventV1[]\n): LedgerEventV1 | undefined {\n const open = unfinishedAttempts(ledger);\n if (open.length > 1) {\n throw new MigrationError(\n \"Multiple unfinished migration attempts require manual repair\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n const attempt = open[0];\n if (\n attempt &&\n (attempt.kind !== \"started\" || attempt.direction !== \"rollback\")\n ) {\n throw new MigrationError(\n \"An unfinished migration attempt is blocking ordinary work\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n return attempt;\n}\n\n/** An unfinished rollback resumes only as the first edge `down` selected. */\nfunction assertResumesSelectedPath(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n attempt: LedgerEventV1,\n first: PreparedRollback\n): void {\n const resumed = prepareRollbackAttempt(\n graph,\n command,\n supportsTransactions,\n attempt\n );\n if (\n resumed.edge.stateId !== first.edge.stateId ||\n resumed.nextState !== first.nextState ||\n resumed.edge.transitionHash !== first.edge.transitionHash\n ) {\n throw new MigrationError(\n \"An unfinished rollback does not match the selected reverse path\",\n VibORMErrorCode.MIGRATION_UNFINISHED_ATTEMPT\n );\n }\n}\n\nfunction prepareRollbackAttempt(\n graph: MigrationGraph,\n command: Parameters<typeof appendLedger>[1],\n supportsTransactions: boolean,\n attempt: LedgerEventV1\n): PreparedRollback {\n if (!(attempt.fromState && attempt.transitionHash)) {\n throw new MigrationError(\n \"Unfinished rollback is missing its authenticated edge identity\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const item = prepareRollbackEdge(graph, command, supportsTransactions, {\n stateId: attempt.fromState,\n transitionHash: attempt.transitionHash,\n baselineBoundary: false,\n });\n if (\n attempt.toState !== item.nextState ||\n attempt.estateHash !== graph.estateHash ||\n attempt.snapshotHash !== item.state.snapshotHash ||\n attempt.sqlHash !== item.state.sqlHash\n ) {\n throw new MigrationError(\n \"Unfinished rollback does not match an authenticated estate edge\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return item;\n}\n\nasync function executeRollbackEdge(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n current: MigrationMarkerV1,\n resume: LedgerEventV1 | undefined,\n ledger: readonly LedgerEventV1[],\n models: MigrationClient[\"$schema\"]\n): Promise<MigrationMarkerV1> {\n const { edge, state, blob, rollback, boundary, nextState } = item;\n if (\n current.stateId !== edge.stateId ||\n current.path.at(-1)?.stateId !== edge.stateId ||\n current.path.at(-1)?.transitionHash !== edge.transitionHash\n ) {\n throw new MigrationError(\n \"Rollback marker does not name the authenticated edge being reversed\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n if (!resume) {\n await assertAllChecks(\n producer,\n blob,\n state.destinationChecks,\n command.namespace,\n \"Destination checks failed before rollback\"\n );\n }\n const events = attemptEvents(\n rollbackEventSeed(graph, item),\n resume?.attemptId\n );\n if (!resume) {\n await appendLedger(producer, command, events.event(\"started\", \"none\"));\n }\n await executeOperations(\n producer,\n blob,\n resume\n ? remainingRollbackOperations(graph, item, resume, ledger)\n : rollback.operations,\n boundary,\n (progress, effect, failure) =>\n appendLedger(\n producer,\n command,\n events.event(\"step-confirmed\", effect, progress, failure)\n ),\n command.namespace,\n { fromState: edge.stateId, toState: nextState, step: \"down\" }\n );\n // Manual rollback SQL may store text typed queries cannot compare.\n await canonicalizeSqliteStorage(\n producer,\n rollback.operations,\n models,\n requireStateSnapshot(graph, nextState)\n );\n const snapshotHash = await proveRolledBack(producer, command, graph, item);\n const next = await advanceMarker(\n producer,\n command,\n graph.estateHash,\n current,\n current.path.slice(0, -1),\n snapshotHash\n );\n await appendRolledBackEvent(producer, command, graph, item, events.attemptId);\n return next;\n}\n\nasync function closeCompletedRollback(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[],\n marker: MigrationMarkerV1 | null\n): Promise<void> {\n remainingRollbackOperations(graph, item, attempt, ledger);\n if (marker ? marker.stateId !== item.nextState : item.nextState !== null) {\n throw new MigrationError(\n \"Rollback marker is neither before nor after the unfinished edge\",\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n }\n await proveRolledBack(producer, command, graph, item);\n await appendRolledBackEvent(\n producer,\n command,\n graph,\n item,\n attempt.attemptId\n );\n}\n\n/**\n * Proves a reversed edge reached its parent: the origin checks hold and the\n * live schema is the parent's snapshot, whose hash it returns.\n */\nasync function proveRolledBack(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n { parent, blob, nextState, edge }: PreparedRollback\n): Promise<Sha256> {\n await assertAllChecks(\n producer,\n blob,\n parent.originChecks,\n command.namespace,\n \"Origin checks failed after rollback\"\n );\n const snapshotHash = snapshotHashOf(graph, nextState);\n // On the parent's side: a table the edge adopted is released, rows kept.\n await proveLive(\n producer,\n managedAt(command, graph, nextState, edge.stateId),\n graph,\n snapshotHash,\n () => \"Rollback did not reach the parent snapshot\"\n );\n return snapshotHash;\n}\n\n/** The fields every event of one reversed edge carries. */\nfunction rollbackEventSeed(\n graph: MigrationGraph,\n { edge, state, nextState }: PreparedRollback\n) {\n return {\n estateHash: graph.estateHash,\n snapshotHash: state.snapshotHash,\n sqlHash: state.sqlHash,\n fromState: edge.stateId,\n toState: nextState,\n transitionHash: edge.transitionHash,\n direction: \"rollback\",\n } as const;\n}\n\nasync function appendRolledBackEvent(\n producer: AnyDriver,\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n item: PreparedRollback,\n attemptId: Sha256\n): Promise<void> {\n const arrived = {\n ...rollbackEventSeed(graph, item),\n snapshotHash: snapshotHashOf(graph, item.nextState),\n };\n await appendLedger(\n producer,\n command,\n attemptEvents(arrived, attemptId).event(\"rolled-back\", \"committed\")\n );\n}\n\nfunction remainingRollbackOperations(\n graph: MigrationGraph,\n item: PreparedRollback,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): PreparedRollback[\"rollback\"][\"operations\"] {\n return remainingSteps(\n ledger,\n attempt,\n {\n direction: \"rollback\",\n estateHash: graph.estateHash,\n fromState: item.edge.stateId,\n toState: item.nextState,\n transitionHash: item.edge.transitionHash,\n sqlHash: item.state.sqlHash,\n operations: item.rollback.operations,\n boundary: item.boundary,\n },\n \"Rollback\"\n ).operations;\n}\n\nfunction assertReversibleEdge(\n graph: MigrationGraph,\n edge: MarkerPathEdgeV1\n): void {\n const state = graph.states.get(edge.stateId);\n if (!state) {\n throw new MigrationError(\n \"Rollback target is missing from the estate\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n const parent = state.parents.find(\n (item) => item.transitionHash === edge.transitionHash\n );\n if (!parent) {\n throw new MigrationError(\n \"Rollback cannot find the arrival transition\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (parent.rollback.kind === \"irreversible\") {\n throw new MigrationError(\n parent.rollback.reason,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n}\n\n/** `down({ expectRevision })`: the marker must still be the one the caller read. */\nfunction assertExpectedRevision(\n marker: MigrationMarkerV1 | null,\n request: NormalizedDownOptions\n): void {\n if (\n request.expectRevision === undefined ||\n marker?.revision === request.expectRevision\n ) {\n return;\n }\n throw new MigrationError(\n `down expected marker revision ${request.expectRevision}, but the marker is at revision ${marker?.revision ?? \"none\"}: another command moved it`,\n VibORMErrorCode.MIGRATION_MARKER_CONFLICT\n );\n}\n\n/**\n * Puts each destructive change the rollback makes to a table holding rows to\n * `resolve`, as generate and push ask (plan S4): a retried or mistaken `down`\n * cannot drop data unasked. Only edges whose stored rollback is destructive\n * are diffed: a manual rollback is SQL its author wrote and published, often\n * to move the rows back before a drop, so it is not asked again. An ambiguous\n * change counts as the drop it may be. A table an earlier edge of the path\n * recreates is absent live, and holds no rows. A table the edge adopts is\n * not dropped at all.\n */\nasync function approveRollbackLosses(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n graph: MigrationGraph,\n prepared: readonly PreparedRollback[],\n resolve: ResolveCallback | undefined\n): Promise<void> {\n const losses: DiffOperation[] = [];\n for (const item of prepared) {\n if (!item.rollback.operations.some((op) => op.risk === \"destructive\")) {\n continue;\n }\n const { operations, ambiguousChanges } = await diff(\n requireStateSnapshot(graph, item.edge.stateId),\n requireStateSnapshot(graph, item.nextState)\n );\n for (const change of [...operations, ...ambiguousChanges.map(asDrop)]) {\n if (\n \"tableName\" in change &&\n // An adopted table is released with no DDL: its rows stay.\n !item.parent.adopts?.includes(change.tableName) &&\n isDestructiveOperation(change) &&\n (await holdsRows(producer, command, change.tableName))\n ) {\n losses.push(change);\n }\n }\n }\n // The callback is the caller's work: no locked transaction waits on it.\n // Each group of `down` re-reads the marker under the lock it takes again.\n if (losses.length > 0 && resolve) await letLockGo(producer);\n await approveDestructiveOperations(losses, resolve, false);\n}\n\nfunction asDrop(change: AmbiguousChange): DiffOperation {\n return change.type === \"ambiguousTable\"\n ? { type: \"dropTable\", tableName: change.droppedTable }\n : {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n };\n}\n\n/**\n * The absent-and-empty-table probe: an absent table (a later state dropped it,\n * or a resumed rollback already did) holds no rows.\n */\nasync function holdsRows(\n producer: Parameters<typeof appendLedger>[0],\n command: Parameters<typeof appendLedger>[1],\n table: string\n): Promise<boolean> {\n if (await isTableMissing(producer, command, table)) return false;\n const result = await producer._executeRaw(\n `SELECT 1 AS populated FROM ${qualifiedName(command, table)} LIMIT 1`\n );\n return result.rows.length > 0;\n}\n\n/**\n * A rolled-back attempt must have left nothing behind. A manual opaque step of\n * it that committed, or was announced and never answered (it may have\n * committed), is an effect no fingerprint shows and that no rollback undid: a\n * forward attempt runs none. Marking it rolled back would let `apply` run the\n * step again — the double credit (plan S4). A step the server refused whole is\n * answered with its `failure`: nothing of it committed. Each announcement is\n * answered on its own (`countUnanswered`, as resume counts them): a resumed\n * retry of a refused step whose reply was lost may have committed. Generated\n * steps are structural, and so is a CONCURRENTLY index statement, whose index\n * resolve repairs before the origin proof (plan S7): the fingerprint proves\n * those undone.\n */\nfunction refuseOpaqueEffect(\n transition: ReturnType<typeof parentTransition>,\n blob: Uint8Array,\n attempt: LedgerEventV1,\n ledger: readonly LedgerEventV1[]\n): void {\n const opaque = new Set(\n transition.operations.flatMap((operation) =>\n operation.steps.flatMap((step) =>\n operation.origin === \"manual\" &&\n step.retry === \"opaque\" &&\n concurrentIndexNames(sliceDispatch(blob, step.execute)).length === 0\n ? [step.execute.dispatchId]\n : []\n )\n )\n );\n const effects = ledger.filter(\n (event) =>\n event.attemptId === attempt.attemptId &&\n event.kind === \"step-confirmed\" &&\n opaque.has(event.dispatchId ?? \"\")\n );\n const unanswered = new Map<LedgerEventV1[\"dispatchId\"], number>();\n for (const event of effects) {\n countUnanswered(unanswered, event.dispatchId, event);\n }\n const effect =\n effects.find((event) => event.effectState === \"committed\") ??\n effects.find((event) => (unanswered.get(event.dispatchId) ?? 0) > 0);\n if (effect === undefined) return;\n const committed = effect.effectState === \"committed\";\n throw new MigrationError(\n `resolve cannot mark this attempt rolled back: its opaque dispatch ${effect.dispatchId} ${committed ? \"committed\" : \"may have committed\"} and nothing undid it. Finish the transition by hand and resolve({ outcome: \"complete\" }).`,\n committed\n ? VibORMErrorCode.MIGRATION_PARTIAL_EFFECT\n : VibORMErrorCode.MIGRATION_AMBIGUOUS_COMMIT,\n {\n meta: {\n ...(attempt.fromState ? { fromState: attempt.fromState } : {}),\n ...(attempt.toState ? { toState: attempt.toState } : {}),\n operationId: effect.operationId ?? undefined,\n dispatchId: effect.dispatchId ?? undefined,\n lastConfirmedStep: effect.dispatchId ?? undefined,\n effectState: committed ? \"committed\" : \"may-have-committed\",\n partial: true,\n },\n }\n );\n}\n\nfunction rollbackSlice(\n graph: MigrationGraph,\n marker: MigrationMarkerV1,\n options: NormalizedDownOptions\n): MigrationMarkerV1[\"path\"] {\n if (marker.path.length === 0) {\n throw new MigrationError(\n \"Nothing to roll back\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n const steps = options.to\n ? distanceTo(\n marker.path.map((edge) => edge.stateId),\n resolveStateSelector(graph, options.to)\n )\n : options.steps;\n const removed = steps === 0 ? [] : marker.path.slice(-steps);\n if (removed.some((edge) => edge.baselineBoundary)) {\n throw new MigrationError(\n \"down cannot cross a baseline boundary\",\n VibORMErrorCode.MIGRATION_INVALID_STATE\n );\n }\n return removed;\n}\n\nfunction distanceTo(path: readonly Sha256[], target: Sha256): number {\n const index = path.lastIndexOf(target);\n if (index < 0) {\n throw new MigrationError(\n \"down target is not on the arrival path\",\n VibORMErrorCode.MIGRATION_NOT_FOUND\n );\n }\n return path.length - 1 - index;\n}\n","/**\n * Semantic migration storage. Path-level get/put/delete is gone.\n *\n * Readers return raw bytes. Parsers, not drivers, turn those bytes into\n * trusted domain values. Writers promise strongly consistent listing and\n * conditional create.\n */\n\nimport type { Sha256 } from \"../identity\";\n\nexport interface PublishResult {\n readonly outcome: \"created\" | \"identical\";\n}\n\nexport interface MigrationStorageReader {\n readEstate(): Promise<Uint8Array | null>;\n listStates(): Promise<readonly Sha256[]>;\n listSnapshots(): Promise<readonly Sha256[]>;\n listSql(): Promise<readonly Sha256[]>;\n readState(id: Sha256): Promise<Uint8Array | null>;\n readSnapshot(hash: Sha256): Promise<Uint8Array | null>;\n readSql(hash: Sha256): Promise<Uint8Array | null>;\n}\n\nexport interface MigrationStorageWriter extends MigrationStorageReader {\n publishEstate(bytes: Uint8Array): Promise<PublishResult>;\n publishSnapshot(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult>;\n}\n\nconst READER_METHODS = [\n \"readEstate\",\n \"listStates\",\n \"listSnapshots\",\n \"listSql\",\n \"readState\",\n \"readSnapshot\",\n \"readSql\",\n] as const;\n\nconst WRITER_METHODS = [\n \"publishEstate\",\n \"publishSnapshot\",\n \"publishSql\",\n \"publishState\",\n] as const;\n\nexport function isMigrationStorageReader(\n value: unknown\n): value is MigrationStorageReader {\n return hasStorageMethods(value, READER_METHODS);\n}\n\nexport function isMigrationStorageWriter(\n value: MigrationStorageReader\n): value is MigrationStorageWriter {\n return hasStorageMethods(value, WRITER_METHODS);\n}\n\nfunction hasStorageMethods(\n value: unknown,\n methods: readonly string[]\n): boolean {\n if (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n ) {\n return false;\n }\n return methods.every(\n (method) => typeof Reflect.get(value, method) === \"function\"\n );\n}\n","/** One capability-sensitive migration client composition root. */\n\nimport { CLIENT_DIAGNOSTICS } from \"../drivers/execution-context\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport { type ApplyV1Result, applyV1 } from \"./apply-v1\";\nimport { type CheckResult, checkEstate } from \"./check\";\nimport { annotateMigrationFailure } from \"./execute-dispatch\";\nimport { type GenerateV1Result, generateV1 } from \"./generate-v1\";\nimport { loadMigrationGraph, resolveStateSelector } from \"./graph\";\nimport { snapshotExactRecord } from \"./input-boundary\";\nimport { type MigrationLimits, resolveMigrationLimits } from \"./limits\";\nimport {\n baselineV1,\n downV1,\n logV1,\n type PruneOptions,\n type PruneResult,\n pruneV1,\n reanchorV1,\n resetV1,\n resolveV1,\n type StatusV1Result,\n statusV1,\n type VerifyV1Result,\n verifyV1,\n} from \"./operators\";\nimport {\n type GraphResult,\n type ListResult,\n listMigrationStates,\n migrationGraphResult,\n type ShowResult,\n showMigrationState,\n} from \"./public-view\";\nimport type { MigrationClient } from \"./push/planner\";\nimport { type PushResultFor, pushV1 } from \"./push-v1\";\nimport type {\n MigrationStorageReader,\n MigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n isMigrationStorageReader,\n isMigrationStorageWriter,\n} from \"./storage/contract\";\nimport {\n MANAGED_TABLES,\n MIGRATION_LIMITS,\n normalizeManagedTables,\n} from \"./target\";\nimport type {\n ApplyV1Options,\n BaselineOptions,\n DownV1Options,\n DownV1Result,\n ExactPushOptions,\n GenerateV1Options,\n LedgerEventV1,\n PushOptionsV1,\n ReanchorOptions,\n ResetV1Options,\n ResolveV1Options,\n StateSelector,\n} from \"./v1-types\";\n\nexport interface MigrationClientOptions<\n S extends MigrationStorageReader = MigrationStorageReader,\n> {\n readonly storage: S;\n readonly tables?: readonly string[];\n /**\n * PostgreSQL session limits and VibORM's own waits, in milliseconds, and\n * `largeTableRows`, the estimated table size above which a rewrite or scan\n * is refused in-request.\n */\n readonly limits?: MigrationLimits;\n}\n\n/** A storage-less client's options: managed tables, limits, or both. */\ntype LiveMigrationClientOptions =\n | {\n readonly tables: readonly string[];\n readonly limits?: MigrationLimits;\n }\n | {\n readonly tables?: readonly string[];\n readonly limits: MigrationLimits;\n };\n\ntype NoExtraMigrationClientOptionKeys<Given> = Record<\n Exclude<keyof Given, \"storage\" | \"tables\" | \"limits\">,\n never\n>;\n\nexport type GenerateResult = GenerateV1Result;\nexport type StatusResult = StatusV1Result;\nexport type VerifyResult = VerifyV1Result;\nexport type LogResult = readonly LedgerEventV1[];\nexport type ApplyResult = ApplyV1Result;\nexport type DownResult = DownV1Result;\nexport interface BaselineResult {\n readonly stateId: string;\n}\nexport interface ReanchorResult {\n readonly stateId: string;\n}\nexport interface ResolveResult {\n readonly outcome: ResolveV1Options[\"outcome\"];\n}\nexport interface ResetResult {\n /** Physical tables selected for a read-only reset preview. */\n readonly tables?: readonly string[];\n readonly preview: boolean;\n readonly path: readonly string[];\n}\nexport interface LiveMigrations {\n log(): Promise<LogResult>;\n push<O extends PushOptionsV1>(\n options?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>>;\n}\n\nexport interface ReadableMigrations extends LiveMigrations {\n check(): Promise<CheckResult>;\n list(): Promise<ListResult>;\n show(selector: StateSelector): Promise<ShowResult>;\n graph(): Promise<GraphResult>;\n status(): Promise<StatusResult>;\n verify(): Promise<VerifyResult>;\n apply(options?: ApplyV1Options): Promise<ApplyResult>;\n down(options?: DownV1Options): Promise<DownResult>;\n baseline(options: BaselineOptions): Promise<BaselineResult>;\n reanchor(options?: ReanchorOptions): Promise<ReanchorResult>;\n prune(options: PruneOptions): Promise<PruneResult>;\n resolve(options: ResolveV1Options): Promise<ResolveResult>;\n}\n\nexport interface WritableMigrations extends ReadableMigrations {\n generate(options?: GenerateV1Options): Promise<GenerateResult>;\n reset(options?: ResetV1Options): Promise<ResetResult>;\n}\n\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageWriter>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): WritableMigrations;\nexport function createMigrationClient<\n Options extends MigrationClientOptions<MigrationStorageReader>,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): ReadableMigrations;\nexport function createMigrationClient<\n Options extends LiveMigrationClientOptions,\n>(\n client: MigrationClient,\n options: Options & NoExtraMigrationClientOptionKeys<Options>\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: undefined\n): LiveMigrations;\nexport function createMigrationClient(\n client: MigrationClient,\n options?: MigrationClientOptions | LiveMigrationClientOptions\n): LiveMigrations | ReadableMigrations | WritableMigrations {\n // VibORM only reads Snowflake: no estate, no control table, no DDL. Every\n // command is refused here, before it reads storage or sends a statement.\n if (client.$driver.dialect === \"snowflake\")\n throw new MigrationError(\n // Short: this text ships in every migrations bundle. The Snowflake page\n // says why.\n \"Snowflake has no migrations: VibORM only reads it (introspectSchema() reads its schema).\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED,\n { meta: { dialect: \"snowflake\" } }\n );\n const record =\n options === undefined\n ? undefined\n : snapshotExactRecord(\n options,\n [\"storage\", \"tables\", \"limits\"],\n \"migration client options\",\n refuseClientOptions\n );\n const tables = normalizeManagedTables(record?.tables);\n const limits =\n record?.limits === undefined\n ? undefined\n : resolveMigrationLimits(record.limits);\n const executionClient: MigrationClient =\n tables === undefined && limits === undefined\n ? client\n : {\n $driver: client.$driver,\n $schema: client.$schema,\n [MANAGED_TABLES]: tables,\n [MIGRATION_LIMITS]: limits,\n [CLIENT_DIAGNOSTICS]: client[CLIENT_DIAGNOSTICS],\n };\n const live: LiveMigrations = Object.freeze({\n log: () => logV1(executionClient),\n push<O extends PushOptionsV1>(\n pushOptions?: ExactPushOptions<O>\n ): Promise<PushResultFor<O>> {\n return pushV1(executionClient, pushOptions);\n },\n });\n if (record === undefined) return live;\n const storage = record.storage;\n if (storage === undefined) {\n if (tables !== undefined || limits !== undefined) return live;\n return refuseClientOptions(\n \"migration client options must include storage, tables or limits when supplied\"\n );\n }\n let readableStorage: MigrationStorageReader;\n try {\n if (!isMigrationStorageReader(storage)) {\n return refuseClientOptions(\n \"migration client storage must implement MigrationStorageReader\"\n );\n }\n readableStorage = storage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n const readable: ReadableMigrations = Object.freeze({\n ...live,\n check: () => checkEstate(readableStorage),\n list: async () =>\n listMigrationStates(await loadMigrationGraph(readableStorage)),\n show: async (selector) => {\n const graph = await loadMigrationGraph(readableStorage);\n return showMigrationState(graph, resolveStateSelector(graph, selector));\n },\n graph: async () =>\n migrationGraphResult(await loadMigrationGraph(readableStorage)),\n status: () => statusV1(executionClient, readableStorage),\n verify: () => verifyV1(executionClient, readableStorage),\n apply: (applyOptions) =>\n named(\"apply\", applyV1(executionClient, readableStorage, applyOptions)),\n down: (downOptions) =>\n named(\"down\", downV1(executionClient, readableStorage, downOptions)),\n baseline: (baselineOptions) =>\n named(\n \"baseline\",\n baselineV1(executionClient, readableStorage, baselineOptions)\n ),\n reanchor: (reanchorOptions) =>\n named(\n \"reanchor\",\n reanchorV1(executionClient, readableStorage, reanchorOptions)\n ),\n prune: (pruneOptions) => pruneV1(readableStorage, pruneOptions),\n resolve: (resolveOptions) =>\n named(\n \"resolve\",\n resolveV1(executionClient, readableStorage, resolveOptions)\n ),\n });\n let writableStorage: MigrationStorageWriter;\n try {\n if (!isMigrationStorageWriter(readableStorage)) return readable;\n writableStorage = readableStorage;\n } catch (failure) {\n return refuseClientOptions(\n \"migration client storage could not be inspected\",\n errorCause(failure)\n );\n }\n\n return Object.freeze({\n ...readable,\n generate: (generateOptions) =>\n generateV1(executionClient, writableStorage, generateOptions),\n reset: (resetOptions) =>\n named(\"reset\", resetV1(executionClient, writableStorage, resetOptions)),\n });\n}\n\n/**\n * The command's result, its failure naming the step it failed in when no\n * statement or boundary inside it did: a lock wait, a marker write.\n */\nfunction named<T>(step: string, running: Promise<T>): Promise<T> {\n return running.catch((failure: unknown) => {\n throw annotateMigrationFailure(failure, { step });\n });\n}\n\nfunction refuseClientOptions(message: string, cause?: Error): never {\n throw new MigrationError(message, VibORMErrorCode.INVALID_INPUT, { cause });\n}\n"],"mappings":"4uDAmEA,MAAM,GAAQ,EAAuB,IAAI,CAGzC,SAAS,eAAe,EAAmD,CACzE,IAAM,EAA2B,EAAE,CACnC,IAAK,GAAM,CAAC,EAAM,KAAU,OAAO,QAAQ,EAAO,CAAE,CAClD,IAAM,EAAQ,EAAa,EAAO,EAAK,CACjC,EAAoB,EAAM,KAAK,MACrC,IAAK,GAAM,CAAC,EAAO,KAAW,OAAO,QAAQ,EAAM,QAAQ,CAAE,CAC3D,IAAM,EAAa,EAAO,KAAK,MACzB,EAAO,EAAW,QAAU,GAC5B,EAAS,EAAM,KAAK,aAAa,EAAM,CAAC,IAC1C,EAAW,OAAS,UACtB,EAAQ,KAAK,CACX,QACA,SACA,OACA,KAAM,UACN,Q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