@dbsp/cli 3.0.0 → 3.0.1

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/commands/apply.ts","../src/utils/output.ts","../src/commands/generator-execution.ts","../src/commands/generator-plan.ts","../src/commands/plan.ts","../src/commands/refusal-output.ts","../src/commands/generate.ts","../src/commands/inspect.ts","../src/commands/introspect.ts","../src/commands/preflight.ts","../src/commands/reconcile.ts","../src/commands/recover.ts","../src/commands/release.ts","../src/commands/repl.ts","../src/commands/verify.ts","../src/verifier.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * ARCH-002 Block 3: CLI Scaffold\n *\n * dbsp CLI - Schema-first code generation for db-semantic-planner.\n */\n\nimport { createRequire } from 'node:module';\nimport { Command, CommanderError } from 'commander';\nimport { applyCommand } from './commands/apply.js';\nimport { generateCommand } from './commands/generate.js';\nimport { inspectCommand } from './commands/inspect.js';\nimport { introspectCommand } from './commands/introspect.js';\nimport { planCommand } from './commands/plan.js';\nimport { preflightCommand } from './commands/preflight.js';\nimport { reconcileCommand } from './commands/reconcile.js';\nimport { recoverCommand } from './commands/recover.js';\n\nimport { releaseCommand } from './commands/release.js';\nimport { replCommand } from './commands/repl.js';\nimport { verifyCommand } from './commands/verify.js';\nimport { printCliJson } from './utils/output.js';\n\nconst program = new Command();\nconst packageJson = createRequire(import.meta.url)('../package.json') as {\n\treadonly version: string;\n};\n\nconst jsonFormatCommands = new Set([\n\t'apply',\n\t'inspect',\n\t'plan',\n\t'recover',\n\t'reconcile',\n\t'release',\n]);\n\nfunction requestsJson(argv: readonly string[]): boolean {\n\t// The initial positional token is the command Commander will try to run.\n\t// Do not let a typo such as `plna --format json` opt into a JSON envelope.\n\tlet command: string | undefined;\n\tfor (const argument of argv) {\n\t\tif (argument === '--') break;\n\t\tif (!argument.startsWith('-')) {\n\t\t\tcommand = argument;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (command === undefined || !jsonFormatCommands.has(command)) return false;\n\n\tfor (let index = 0; index < argv.length; index += 1) {\n\t\tconst argument = argv[index];\n\t\tif (argument === '--') break;\n\t\tif (\n\t\t\t(argument === '--format' && argv[index + 1] === 'json') ||\n\t\t\targument === '--format=json' ||\n\t\t\targument === '--json'\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nprogram\n\t.name('dbsp')\n\t.description('Schema-first code generation for db-semantic-planner')\n\t.version(packageJson.version);\n\n// Register commands\nprogram.addCommand(generateCommand);\nprogram.addCommand(introspectCommand);\nprogram.addCommand(planCommand);\nprogram.addCommand(preflightCommand);\nprogram.addCommand(applyCommand);\nprogram.addCommand(inspectCommand);\nprogram.addCommand(recoverCommand);\nprogram.addCommand(releaseCommand);\nprogram.addCommand(reconcileCommand);\nprogram.addCommand(replCommand);\nprogram.addCommand(verifyCommand);\n\nconst jsonRequested = requestsJson(process.argv.slice(2));\n\n// Commander validates options before transferring control to a subcommand.\n// Suppress its eager plaintext diagnostic whenever the request chose JSON.\nif (jsonRequested) {\n\tfor (const command of [program, ...program.commands])\n\t\tcommand.configureOutput({ writeErr: () => {} });\n}\n\n// CC-15: Intercept parse errors so recognized JSON-capable commands receive a\n// JSON error object on stdout instead of a plain-text usage message.\nfor (const command of [program, ...program.commands]) command.exitOverride();\n\ntry {\n\tprogram.parse();\n} catch (err) {\n\t// Commander throws CommanderError for --help, --version, and parse errors.\n\t// Exit 0 for informational outputs (help/version); only exit 1 for real errors.\n\tif (err instanceof CommanderError && err.exitCode === 0) {\n\t\tprocess.exit(0);\n\t}\n\tconst message = err instanceof Error ? err.message : 'Command parse error';\n\tif (jsonRequested) {\n\t\tprintCliJson({ status: 'error', error: message });\n\t} else {\n\t\tconsole.error(`❌ ${message}`);\n\t}\n\tprocess.exit(1);\n}\n","/** Execute exactly one reviewed durable transition run; never re-plan. */\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { createInterface } from 'node:readline/promises';\nimport {\n\tappendIntentJournal,\n\tappendTransitionAuthorization,\n\tcreatePgTransitionLessor,\n\tcreatePgTransitionPack,\n\tescapeDiagnosticText,\n\tpreparePgExecutionSession,\n\treadTransitionJournal,\n\tTransitionRunIdentityMismatchError,\n\tvalidatePgManagedLedgerCurrency,\n\twithPgTransitionRunLock,\n} from '@dbsp/adapter-pgsql';\nimport { lockPgJournalRun } from '@dbsp/adapter-pgsql/internal';\nimport {\n\tacquireExclusiveTransitionLease,\n\tacquireTransitionLease,\n\tcreateApplier,\n\tcreatePackRegistry,\n\ttype PackRegistry,\n\tselectorMatchesResource,\n\ttransitionPlanDigest,\n\tvalidateNormalizedManagedStepManifest,\n} from '@dbsp/core';\nimport { mintDurablyLoadedRun } from '@dbsp/core/internal';\nimport type {\n\tApplyPolicy,\n\tApplyResult,\n\tAssumptionAcceptance,\n\tLedgerAddress,\n\tNormalizedManagedStep,\n\tPhysicalOperation,\n\tResourceAddress,\n\tResourceSelector,\n\tTransitionRunAuthorization,\n\tTransitionRunJournal,\n\tTrustRoot,\n} from '@dbsp/types';\nimport { REFUSAL_VOCABULARY } from '@dbsp/types';\nimport { Command } from 'commander';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport {\n\texecuteGeneratorPlan,\n\ttype GeneratorExecutionResult,\n} from './generator-execution.js';\nimport type { GeneratorDurablePlan } from './generator-plan.js';\nimport {\n\tpersistedLifecycleDirectiveError,\n\trunGeneratorPlan,\n} from './generator-plan.js';\nimport {\n\texitCodeForPlanResult,\n\tformatPlanHuman,\n\tformatPlanJson,\n\ttype PlanResult,\n\trunPlan,\n} from './plan.js';\nimport {\n\tformatPreAppendRefusalHuman,\n\ttype PreAppendRefusal,\n\tpreAppendRefusalFor,\n} from './refusal-output.js';\n\nexport type ApplyFormat = 'text' | 'json';\nexport interface ApplyOptions {\n\treadonly db: string;\n\treadonly planDigest?: string;\n\treadonly accept?: readonly string[];\n\treadonly acceptPolicy?: string;\n\treadonly format?: ApplyFormat;\n\t/** The no-argument form's authored declaration. */\n\treadonly schemaFile?: string;\n\treadonly schema?: string;\n\treadonly yes?: boolean;\n\treadonly dryRun?: boolean;\n\t/** Reviewed replacement selector(s) for the no-argument generator path. */\n\treadonly replace?: readonly string[];\n}\n\n/**\n * Recovery is keyed to the loaded durable run. Ledger address history belongs\n * to every run that touched the address and must not make a fresh run stale.\n */\nexport function generatorRunHasPriorStepEvents(\n\tloaded: Pick<TransitionRunJournal, 'events'>,\n): boolean {\n\treturn loaded.events.some((event) => {\n\t\tconst executionId =\n\t\t\tevent.event === 'intent' && 'executionId' in event.record\n\t\t\t\t? event.record.executionId\n\t\t\t\t: undefined;\n\t\treturn !(\n\t\t\ttypeof executionId === 'string' &&\n\t\t\tevent.stepId === `dbsp.generator.attempt:${executionId}` &&\n\t\t\tevent.operationRef === 'dbsp.generator.attempt'\n\t\t);\n\t});\n}\n\nconst GENERATOR_ATTEMPT_OPERATION: Omit<PhysicalOperation, 'payload'> = {\n\tref: 'dbsp.generator.attempt',\n\toperationKind: {\n\t\tartifact: {\n\t\t\tid: 'dbsp.postgresql.generator' as PhysicalOperation['operationKind']['artifact']['id'],\n\t\t\tversion: '1',\n\t\t},\n\t\tname: 'GeneratorAttempt',\n\t},\n};\n\n/**\n * The just-persisted generator-removal exception is an in-module capability,\n * not an ApplyOptions field. A public caller can neither name its type nor\n * manufacture a value accepted by the WeakSet check below.\n */\ninterface JustPersistedGeneratorRemovalCapability {\n\treadonly runId: string;\n}\n\nconst justPersistedGeneratorRemovalCapabilities = new WeakSet<object>();\nconst justPersistedGeneratorRemovalContext =\n\tnew AsyncLocalStorage<JustPersistedGeneratorRemovalCapability>();\n\nfunction mintJustPersistedGeneratorRemovalCapability(\n\trunId: string,\n): JustPersistedGeneratorRemovalCapability {\n\tconst capability = Object.freeze({ runId });\n\tjustPersistedGeneratorRemovalCapabilities.add(capability);\n\treturn capability;\n}\n\nfunction permitsJustPersistedGeneratorRemoval(runId: string): boolean {\n\tconst capability = justPersistedGeneratorRemovalContext.getStore();\n\treturn (\n\t\tcapability !== undefined &&\n\t\tcapability.runId === runId &&\n\t\tjustPersistedGeneratorRemovalCapabilities.has(capability)\n\t);\n}\n\nfunction errorDetail(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Apply maps only the two non-resumable persisted-plan failure contracts. */\nfunction isInvalidNonResumablePersistedRunError(\n\terror: unknown,\n\trunId: string,\n): error is Error {\n\treturn (\n\t\terror instanceof Error &&\n\t\t(error.message ===\n\t\t\t'dbsp transition run plan row is invalid and non-resumable' ||\n\t\t\terror.message ===\n\t\t\t\t`dbsp transition run ${runId} has no persisted proven plan and is non-resumable`)\n\t);\n}\n\nclass RecordedPlanDigestMismatchError extends Error {\n\tconstructor(\n\t\tdetail = 'persisted generator plan digest does not match the recorded review',\n\t) {\n\t\tsuper(detail);\n\t\tthis.name = 'RecordedPlanDigestMismatchError';\n\t}\n}\n\n/** A failed owned-pool cleanup supplements a computed command result. */\nexport async function withPoolCleanupReported<T extends object>(\n\tresult: T,\n\tclose: () => Promise<void>,\n): Promise<T & { readonly cleanupError?: string }> {\n\ttry {\n\t\tawait close();\n\t\treturn result;\n\t} catch (error) {\n\t\treturn {\n\t\t\t...result,\n\t\t\tcleanupError: `database pool cleanup failed: ${errorDetail(error)}`,\n\t\t};\n\t}\n}\n\nfunction compareCodeUnits(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\n/** Stable JSON encoding: object keys sort lexically and arrays retain their supplied order. */\nexport function canonicalJson(value: unknown): string {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === 'string' ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'number'\n\t) {\n\t\tif (typeof value === 'number' && !Number.isFinite(value))\n\t\t\tthrow new Error('policy values must be finite JSON values');\n\t\treturn JSON.stringify(value);\n\t}\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n\tif (typeof value !== 'object')\n\t\tthrow new Error(\n\t\t\t'policy values must be JSON values (undefined is not allowed)',\n\t\t);\n\tconst record = value as Record<string, unknown>;\n\treturn `{${Object.keys(record)\n\t\t.sort()\n\t\t.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)\n\t\t.join(',')}}`;\n}\n\nfunction nonEmptyString(value: unknown, path: string): asserts value is string {\n\tif (typeof value !== 'string' || value.length === 0 || value.trim() !== value)\n\t\tthrow new Error(`${path} must be a non-empty, unpadded string`);\n}\n\nfunction exactKeys(\n\trecord: Record<string, unknown>,\n\tallowed: readonly string[],\n\tpath: string,\n\tsubject = 'AssumptionAcceptance',\n): void {\n\tfor (const key of Object.keys(record)) {\n\t\tif (!allowed.includes(key))\n\t\t\tthrow new Error(`${path}.${key} is not a valid ${subject} field`);\n\t}\n}\n\nfunction record(value: unknown, path: string): Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value))\n\t\tthrow new Error(`${path} must be an object`);\n\treturn value as Record<string, unknown>;\n}\n\nfunction validateResourceAddress(\n\tvalue: unknown,\n\tpath: string,\n): ResourceAddress {\n\tconst candidate = record(value, path);\n\texactKeys(\n\t\tcandidate,\n\t\t[\n\t\t\t'engine',\n\t\t\t'database',\n\t\t\t'schema',\n\t\t\t'parent',\n\t\t\t'kind',\n\t\t\t'name',\n\t\t\t'catalogueIdentity',\n\t\t\t'qualifiedBy',\n\t\t],\n\t\tpath,\n\t);\n\tfor (const key of ['engine', 'database', 'kind', 'name'] as const)\n\t\tnonEmptyString(candidate[key], `${path}.${key}`);\n\tif (candidate.schema !== undefined)\n\t\tnonEmptyString(candidate.schema, `${path}.schema`);\n\tif (candidate.parent !== undefined)\n\t\tvalidateResourceAddress(candidate.parent, `${path}.parent`);\n\tif (candidate.catalogueIdentity !== undefined) {\n\t\tconst identity = record(\n\t\t\tcandidate.catalogueIdentity,\n\t\t\t`${path}.catalogueIdentity`,\n\t\t);\n\t\texactKeys(\n\t\t\tidentity,\n\t\t\t['engine', 'format', 'value'],\n\t\t\t`${path}.catalogueIdentity`,\n\t\t\t'catalogue identity',\n\t\t);\n\t\tnonEmptyString(identity.engine, `${path}.catalogueIdentity.engine`);\n\t\tif (\n\t\t\ttypeof identity.format !== 'number' ||\n\t\t\t!Number.isInteger(identity.format) ||\n\t\t\tidentity.format <= 0\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t`${path}.catalogueIdentity.format must be a positive integer`,\n\t\t\t);\n\t\tconst identityValue = record(\n\t\t\tidentity.value,\n\t\t\t`${path}.catalogueIdentity.value`,\n\t\t);\n\t\ttry {\n\t\t\tcanonicalJson(identityValue);\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`${path}.catalogueIdentity.value must be a canonicalizable JSON object: ${errorDetail(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\tif (candidate.qualifiedBy !== undefined) {\n\t\tif (!Array.isArray(candidate.qualifiedBy))\n\t\t\tthrow new Error(`${path}.qualifiedBy must be an array of strings`);\n\t\tcandidate.qualifiedBy.forEach((part, index) => {\n\t\t\tnonEmptyString(part, `${path}.qualifiedBy[${index}]`);\n\t\t});\n\t}\n\treturn candidate as unknown as ResourceAddress;\n}\n\nfunction validateSelector(value: unknown, path: string): ResourceSelector {\n\tconst candidate = record(value, path);\n\texactKeys(candidate, ['kind', 'schema', 'name', 'within'], path);\n\tfor (const key of ['kind', 'schema', 'name'] as const) {\n\t\tif (candidate[key] !== undefined)\n\t\t\tnonEmptyString(candidate[key], `${path}.${key}`);\n\t}\n\tif (candidate.within !== undefined)\n\t\tvalidateResourceAddress(candidate.within, `${path}.within`);\n\treturn candidate as ResourceSelector;\n}\n\nfunction validateTrustRoot(value: unknown, path: string): TrustRoot {\n\tconst candidate = record(value, path);\n\tnonEmptyString(candidate.kind, `${path}.kind`);\n\tswitch (candidate.kind) {\n\t\tcase 'pack': {\n\t\t\texactKeys(candidate, ['kind', 'artifact'], path);\n\t\t\tconst artifact = record(candidate.artifact, `${path}.artifact`);\n\t\t\texactKeys(artifact, ['id', 'version'], `${path}.artifact`);\n\t\t\tnonEmptyString(artifact.id, `${path}.artifact.id`);\n\t\t\tnonEmptyString(artifact.version, `${path}.artifact.version`);\n\t\t\treturn candidate as TrustRoot;\n\t\t}\n\t\tcase 'human':\n\t\t\texactKeys(candidate, ['kind', 'identity'], path);\n\t\t\tnonEmptyString(candidate.identity, `${path}.identity`);\n\t\t\treturn candidate as TrustRoot;\n\t\tcase 'policy':\n\t\t\texactKeys(candidate, ['kind', 'policyId'], path);\n\t\t\tnonEmptyString(candidate.policyId, `${path}.policyId`);\n\t\t\treturn candidate as TrustRoot;\n\t\tdefault:\n\t\t\tthrow new Error(`${path}.kind must be pack, human, or policy`);\n\t}\n}\n\n/** Reject malformed policy input before it can be mistaken for a non-matching grant. */\nexport function validateAssumptionAcceptance(\n\tvalue: unknown,\n\tpath = 'acceptance',\n): AssumptionAcceptance {\n\tconst candidate = record(value, path);\n\texactKeys(candidate, ['class', 'fromTrustRoot', 'withinScope'], path);\n\tnonEmptyString(candidate.class, `${path}.class`);\n\tif (candidate.fromTrustRoot !== undefined)\n\t\tvalidateTrustRoot(candidate.fromTrustRoot, `${path}.fromTrustRoot`);\n\tif (candidate.withinScope !== undefined) {\n\t\tif (!Array.isArray(candidate.withinScope))\n\t\t\tthrow new Error(`${path}.withinScope must be an array of selectors`);\n\t\tcandidate.withinScope.forEach((selector, index) => {\n\t\t\tvalidateSelector(selector, `${path}.withinScope[${index}]`);\n\t\t});\n\t}\n\treturn candidate as unknown as AssumptionAcceptance;\n}\n\nfunction normaliseAcceptance(\n\tacceptance: AssumptionAcceptance,\n): AssumptionAcceptance {\n\tconst validated = validateAssumptionAcceptance(acceptance);\n\tconst withinScope = validated.withinScope\n\t\t? [\n\t\t\t\t...new Map(\n\t\t\t\t\tvalidated.withinScope.map((item) => [canonicalJson(item), item]),\n\t\t\t\t),\n\t\t\t]\n\t\t\t\t.sort(([left], [right]) => compareCodeUnits(left, right))\n\t\t\t\t.map(([, item]) => JSON.parse(canonicalJson(item)) as ResourceSelector)\n\t\t: undefined;\n\treturn JSON.parse(\n\t\tcanonicalJson({\n\t\t\tclass: validated.class,\n\t\t\t...(validated.fromTrustRoot\n\t\t\t\t? { fromTrustRoot: validated.fromTrustRoot }\n\t\t\t\t: {}),\n\t\t\t...(withinScope === undefined ? {} : { withinScope }),\n\t\t}),\n\t) as AssumptionAcceptance;\n}\n\n/**\n * Canonical policy representation used for both the authorization record and\n * its SHA-256 digest. File and repeated --accept grants form a set union:\n * exact duplicates are retained once, and selector order is normalized.\n */\nexport function canonicalApplyPolicy(\n\tacceptances: readonly AssumptionAcceptance[],\n): readonly AssumptionAcceptance[] {\n\treturn [\n\t\t...new Map(\n\t\t\tacceptances.map((item) => {\n\t\t\t\tconst normalized = normaliseAcceptance(item);\n\t\t\t\treturn [canonicalJson(normalized), normalized] as const;\n\t\t\t}),\n\t\t),\n\t]\n\t\t.sort(([left], [right]) => compareCodeUnits(left, right))\n\t\t.map(([, item]) => item);\n}\n\nexport function policyDigest(policy: readonly AssumptionAcceptance[]): string {\n\treturn createHash('sha256')\n\t\t.update(canonicalJson(canonicalApplyPolicy(policy)))\n\t\t.digest('hex');\n}\n\n/**\n * Hash the exact durable approval, not merely its policy. Run id prevents an\n * approval from replaying onto another run; plan digest pins its reviewed\n * content; grants record which policy entry accepted each assumption.\n */\nexport function authorizationDigest(\n\trunId: string,\n\tplanDigest: string,\n\tpolicy: readonly AssumptionAcceptance[],\n\tgrants: TransitionRunAuthorization['grants'],\n\tactor: string,\n\tauthorizedAt: string,\n): string {\n\tconst authorizedInstant = new Date(authorizedAt);\n\tif (Number.isNaN(authorizedInstant.getTime()))\n\t\tthrow new Error('authorization timestamp must be a valid instant');\n\treturn createHash('sha256')\n\t\t.update(\n\t\t\tcanonicalJson({\n\t\t\t\trunId,\n\t\t\t\tplanDigest,\n\t\t\t\tpolicy: canonicalApplyPolicy(policy),\n\t\t\t\tgrants,\n\t\t\t\tactor,\n\t\t\t\t// PostgreSQL drivers may spell the same timestamptz instant differently.\n\t\t\t\tauthorizedAt: authorizedInstant.toISOString(),\n\t\t\t}),\n\t\t)\n\t\t.digest('hex');\n}\n\n/** A prior authorization is reusable only when every authorization input matches. */\nexport function hasReusableAuthorization(\n\tauthorizations:\n\t\t| readonly Pick<\n\t\t\t\tTransitionRunAuthorization,\n\t\t\t\t'digest' | 'actor' | 'authorizedAt' | 'policy' | 'grants'\n\t\t >[]\n\t\t| undefined,\n\trunId: string,\n\tplanDigest: string,\n\tpolicy: readonly AssumptionAcceptance[],\n\tgrants: TransitionRunAuthorization['grants'],\n): boolean {\n\treturn (\n\t\tauthorizations?.some(\n\t\t\t(item) =>\n\t\t\t\tcanonicalJson(item.policy) === canonicalJson(policy) &&\n\t\t\t\tcanonicalJson(item.grants) === canonicalJson(grants) &&\n\t\t\t\titem.digest ===\n\t\t\t\t\tauthorizationDigest(\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tplanDigest,\n\t\t\t\t\t\tpolicy,\n\t\t\t\t\t\tgrants,\n\t\t\t\t\t\titem.actor,\n\t\t\t\t\t\titem.authorizedAt,\n\t\t\t\t\t),\n\t\t) ?? false\n\t);\n}\n\n/** Policy files are UTF-8 JSON arrays of strictly validated AssumptionAcceptance objects. */\nexport async function effectiveApplyPolicy(\n\toptions: ApplyOptions,\n): Promise<ApplyPolicy> {\n\tlet fromFile: unknown[] = [];\n\tif (options.acceptPolicy) {\n\t\tconst parsed: unknown = JSON.parse(\n\t\t\tawait readFile(options.acceptPolicy, 'utf8'),\n\t\t);\n\t\tif (!Array.isArray(parsed))\n\t\t\tthrow new Error('--accept-policy must contain a JSON array');\n\t\tfromFile = parsed;\n\t}\n\tconst merged = [\n\t\t...fromFile,\n\t\t...(options.accept ?? []).map((classification) => ({\n\t\t\tclass: classification,\n\t\t})),\n\t];\n\treturn {\n\t\taccepts: canonicalApplyPolicy(\n\t\t\tmerged.map((grant, index) =>\n\t\t\t\tvalidateAssumptionAcceptance(grant, `acceptance[${index}]`),\n\t\t\t),\n\t\t),\n\t};\n}\n\nfunction registry(): PackRegistry {\n\treturn createPackRegistry([createPgTransitionPack({})]);\n}\n\n/**\n * `dbsp apply`'s public result contract. `outcome` is always present in\n * `--format json`; it is the stable machine-readable name and `exitCode` is\n * its exact process status. Core step outcomes retain their core names.\n */\nexport const APPLY_OUTCOME_CONTRACT = [\n\t['completed', 0, 'all planned steps completed'],\n\t['operation-failed-not-applied', 10, 'operation failed before application'],\n\t['partially-applied', 11, 'some target effects may be durable'],\n\t['unknown-step-result', 12, 'a step result could not be determined'],\n\t['outcome-unknown', 13, 'run lifecycle is indeterminate'],\n\t['guard-failed', 14, 'a guard rejected the target'],\n\t['guard-timeout', 15, 'a guard timed out'],\n\t['context-mismatch', 16, 'target no longer matches the run context'],\n\t[\n\t\t'transactional-only-refusal',\n\t\t17,\n\t\t\"durable apply executes segments that forbid a transaction block only when the plan's non-transactional-segment assumption is accepted\",\n\t],\n\t['digest-mismatch', 18, 'persisted plan does not match its recorded digest'],\n\t[\n\t\t'plan-digest-required',\n\t\t32,\n\t\t'apply requires the plan digest printed by dbsp plan',\n\t],\n\t[\n\t\t'plan-digest-mismatch',\n\t\t33,\n\t\t'operator-reviewed plan digest does not match the stored plan',\n\t],\n\t[\n\t\t'non-replayable-generator-run',\n\t\t35,\n\t\t'generator removal runs require a fresh no-argument apply against live state',\n\t],\n\t[\n\t\t'selection-incomplete',\n\t\t63,\n\t\t'reviewed optional actions were not selected exactly before execution',\n\t],\n\t[\n\t\t'prior-step-events-refusal',\n\t\t19,\n\t\t'attempted runs must be classified by recover',\n\t],\n\t[\n\t\t'compatibility-refusal',\n\t\t20,\n\t\t'run execution compatibility epoch is unsupported',\n\t],\n\t['run-busy', 21, 'another database session holds this run lock'],\n\t[\n\t\t'assumption-not-accepted',\n\t\t22,\n\t\t'policy does not accept a required assumption',\n\t],\n\t['authorization-write-failed', 23, 'authorization was not durably committed'],\n\t[\n\t\t'execution-contract-refused',\n\t\t31,\n\t\t'execution contract clause was refused; re-plan for a different target or correct access',\n\t],\n\t[\n\t\t'execution-preflight-failed',\n\t\t30,\n\t\t'execution preflight query failed; retry after transport or read access is restored',\n\t],\n\t[\n\t\t'execution-failed',\n\t\t56,\n\t\t'execution phase failed after preflight; inspect the run with recover',\n\t],\n\t[\n\t\t'recovery-required',\n\t\t64,\n\t\t'an admitted non-transactional claim remains open; run recover with the reported claim reference',\n\t],\n\t['database-read-only', 34, 'target cannot accept managed writes'],\n\t[\n\t\t'destructive-authority-refused',\n\t\t59,\n\t\t'a live destructive authority did not permit the generated mutation',\n\t],\n\t[\n\t\t'adoption-refused',\n\t\t62,\n\t\t'a declared adoption no longer matches the live object reviewed for admission',\n\t],\n\t[\n\t\t'readdress-unsupported',\n\t\t60,\n\t\t'declared re-addressing is supported only for tables in one database; declare the move as a retirement and a creation',\n\t],\n\t[\n\t\t'readdress-refused',\n\t\t61,\n\t\t'declared re-addressing could not verify its source identity or target vacancy',\n\t],\n\t[\n\t\t'confirmation-required',\n\t\t57,\n\t\t'no-argument apply requires an interactive confirmation or --yes',\n\t],\n\t[\n\t\t'confirmation-declined',\n\t\t58,\n\t\t'operator declined the persisted plan before execution',\n\t],\n\t['operation-unavailable', 24, 'a required operation artifact is unavailable'],\n\t['plan-validation-failed', 25, 'stored run evidence is invalid'],\n\t['run-id-mismatch', 26, 'loaded run does not match the requested id'],\n\t['load-failed', 27, 'run or target context could not be loaded'],\n\t['policy-invalid', 28, 'acceptance policy input is malformed'],\n\t['apply-failed', 29, 'unexpected apply command failure'],\n] as const;\n\nexport type ApplyOutcome = (typeof APPLY_OUTCOME_CONTRACT)[number][0];\ntype ApplyExecutionOutcome = Exclude<\n\tApplyOutcome,\n\t| 'run-busy'\n\t| 'plan-digest-required'\n\t| 'non-replayable-generator-run'\n\t| 'policy-invalid'\n\t| 'apply-failed'\n>;\n\nconst applyExitCodes = new Map<ApplyOutcome, number>(\n\tAPPLY_OUTCOME_CONTRACT.map(([outcome, exitCode]) => [outcome, exitCode]),\n);\n\nfunction isApplyOutcome(value: string): value is ApplyOutcome {\n\treturn applyExitCodes.has(value as ApplyOutcome);\n}\n\nfunction isApplyExecutionOutcome(\n\tvalue: string,\n): value is ApplyExecutionOutcome {\n\treturn (\n\t\tisApplyOutcome(value) &&\n\t\tvalue !== 'run-busy' &&\n\t\tvalue !== 'policy-invalid' &&\n\t\tvalue !== 'apply-failed'\n\t);\n}\n\nexport function exitCodeForApplyOutcome(outcome: ApplyOutcome): number {\n\treturn applyExitCodes.get(outcome) as number;\n}\n\nexport function outcomeForApplyResult(\n\tresult: ApplyResult,\n): ApplyExecutionOutcome {\n\tif (result.durableOutcome && isApplyExecutionOutcome(result.durableOutcome))\n\t\treturn result.durableOutcome;\n\t// A committed earlier segment is the operator-facing fact. Do not let the\n\t// narrower reason from a later segment hide durable target effects.\n\tif (result.assessment.lifecycle === 'partially-applied')\n\t\treturn 'partially-applied';\n\tif (result.assessment.lifecycle === 'completed') return 'completed';\n\tconst reason = result.assessment.reasons[0];\n\tif (\n\t\treason?.code === 'context-mismatch' &&\n\t\t'fact' in reason &&\n\t\treason.fact?.key === 'durable-apply-outcome' &&\n\t\tisApplyExecutionOutcome(reason.fact.value)\n\t) {\n\t\treturn reason.fact.value;\n\t}\n\tif (reason?.code === 'unknown-step-result') return 'unknown-step-result';\n\tif (reason?.code === 'operation-failed-not-applied')\n\t\treturn 'operation-failed-not-applied';\n\tif (reason?.code === 'partially-applied') return 'partially-applied';\n\tif (reason?.code === 'guard-failed') return 'guard-failed';\n\tif (reason?.code === 'guard-timeout') return 'guard-timeout';\n\tif (reason?.code === 'context-mismatch') return 'context-mismatch';\n\tif (result.assessment.lifecycle === 'outcome-unknown')\n\t\treturn 'outcome-unknown';\n\treturn 'context-mismatch';\n}\n\nexport function formatApplyHuman(result: {\n\treadonly outcome: string;\n\treadonly runId: string;\n\treadonly result?: ApplyResult;\n\treadonly refusal?: PreAppendRefusal | RecordedPlanRefusal;\n}): string {\n\tconst line = `${result.outcome}: ${result.runId}`;\n\tif (result.refusal) {\n\t\tif ('address' in result.refusal)\n\t\t\treturn formatPreAppendRefusalHuman(line, result.refusal);\n\t\treturn [\n\t\t\tline,\n\t\t\t`refusal: ${escapeDiagnosticText(result.refusal.cause)}`,\n\t\t\t`state: ${escapeDiagnosticText(result.refusal.state)}`,\n\t\t\t`withheld authority: ${escapeDiagnosticText(result.refusal.withheldAuthority)}`,\n\t\t\t`resolving command: ${escapeDiagnosticText(result.refusal.resolvingCommand)}`,\n\t\t].join('\\n');\n\t}\n\tif (result.outcome !== 'plan-digest-mismatch' || !result.result) return line;\n\tconst detail = result.result.assessment.reasons[0]?.detail;\n\treturn detail ? `${line}\\n${detail}` : line;\n}\n\nfunction acceptanceMatches(\n\tassumption: {\n\t\treadonly class: string;\n\t\treadonly asserter: TrustRoot;\n\t\treadonly scope: readonly ResourceAddress[];\n\t},\n\tacceptance: AssumptionAcceptance,\n): boolean {\n\treturn (\n\t\tacceptance.class === assumption.class &&\n\t\t(!acceptance.fromTrustRoot ||\n\t\t\tcanonicalJson(acceptance.fromTrustRoot) ===\n\t\t\t\tcanonicalJson(assumption.asserter)) &&\n\t\t(assumption.scope.length === 0\n\t\t\t? !acceptance.withinScope || acceptance.withinScope.length === 0\n\t\t\t: !acceptance.withinScope ||\n\t\t\t\tacceptance.withinScope.length === 0 ||\n\t\t\t\tassumption.scope.every((resource) =>\n\t\t\t\t\tacceptance.withinScope?.some((selector) =>\n\t\t\t\t\t\tselectorMatchesResource(selector, resource),\n\t\t\t\t\t),\n\t\t\t\t))\n\t);\n}\n\ntype RecordedPlanRefusal = {\n\treadonly cause: string;\n\treadonly state: 'recorded-plan';\n\treadonly withheldAuthority: string;\n\treadonly resolvingCommand: string;\n};\n\nfunction recordedPlanRefusal(): RecordedPlanRefusal {\n\treturn { ...REFUSAL_VOCABULARY['ERR-10'], state: 'recorded-plan' };\n}\n\nexport type ApplyCommandResult = (\n\t| {\n\t\t\treadonly outcome: Exclude<\n\t\t\t\tApplyOutcome,\n\t\t\t\t| 'run-busy'\n\t\t\t\t| 'plan-digest-required'\n\t\t\t\t| 'non-replayable-generator-run'\n\t\t\t\t| 'policy-invalid'\n\t\t\t\t| 'apply-failed'\n\t\t\t>;\n\t\t\treadonly runId: string;\n\t\t\treadonly result: ApplyResult;\n\t\t\treadonly refusal?: PreAppendRefusal;\n\t }\n\t| {\n\t\t\treadonly outcome: 'run-busy' | 'plan-digest-required';\n\t\t\treadonly runId: string;\n\t }\n\t| {\n\t\t\t/** ERR-10: a removal-bearing generator run cannot be replayed by id. */\n\t\t\treadonly outcome: 'non-replayable-generator-run';\n\t\t\treadonly runId: string;\n\t\t\treadonly refusal: RecordedPlanRefusal;\n\t }\n) & { readonly cleanupError?: string };\n\nexport type NoArgumentApplyResult =\n\t| {\n\t\t\treadonly outcome:\n\t\t\t\t| 'dry-run'\n\t\t\t\t| 'not-executable'\n\t\t\t\t| 'confirmation-required'\n\t\t\t\t| 'confirmation-declined';\n\t\t\treadonly plan: PlanResult;\n\t\t\treadonly runId: string | null;\n\t\t\treadonly planDigest: string | null;\n\t }\n\t| {\n\t\t\treadonly outcome: ApplyOutcome;\n\t\t\treadonly plan: PlanResult;\n\t\t\treadonly runId: string;\n\t\t\treadonly planDigest: string;\n\t\t\treadonly result: ApplyCommandResult | GeneratorExecutionResult;\n\t };\n\nfunction isGeneratorPlan(plan: unknown): plan is GeneratorDurablePlan {\n\treturn (\n\t\tplan !== undefined &&\n\t\tplan !== null &&\n\t\ttypeof plan === 'object' &&\n\t\t'generator' in plan &&\n\t\t(plan as { generator?: { kind?: unknown } }).generator?.kind ===\n\t\t\t'schema-differ-generator'\n\t);\n}\n\n/** Every mapped command refusal needs a real plan address; never invent one. */\nfunction firstPlanAddress(plan: unknown): LedgerAddress | undefined {\n\tif (plan === null || typeof plan !== 'object' || !('steps' in plan))\n\t\treturn undefined;\n\tconst steps = (plan as { readonly steps?: unknown }).steps;\n\tif (!Array.isArray(steps)) return undefined;\n\tfor (const step of steps) {\n\t\tif (step === null || typeof step !== 'object') continue;\n\t\tconst candidate = step as {\n\t\t\treadonly managedClaim?: { readonly address?: LedgerAddress };\n\t\t\treadonly address?: LedgerAddress;\n\t\t\treadonly closure?: { readonly root?: LedgerAddress };\n\t\t};\n\t\tconst address =\n\t\t\tcandidate.managedClaim?.address ??\n\t\t\tcandidate.address ??\n\t\t\tcandidate.closure?.root;\n\t\tif (address) return address;\n\t}\n\treturn undefined;\n}\n\nfunction applyPreAppendRefusal(\n\toutcome: ApplyOutcome,\n\tplan: unknown,\n\tresult?: ApplyResult,\n): PreAppendRefusal | undefined {\n\tconst address = firstPlanAddress(plan);\n\tif (!address) return undefined;\n\tif (outcome === 'transactional-only-refusal')\n\t\treturn preAppendRefusalFor('ERR-01', { address, state: 'unknown' });\n\tif (outcome === 'database-read-only')\n\t\treturn preAppendRefusalFor('ERR-07', { address, state: 'unknown' });\n\tif (\n\t\toutcome === 'execution-contract-refused' &&\n\t\tresult?.assessment.reasons[0]?.detail?.startsWith(\n\t\t\t'managed-ledger-not-current:',\n\t\t)\n\t)\n\t\treturn preAppendRefusalFor('ERR-03', { address, state: 'unknown' });\n\tif (outcome === 'destructive-authority-refused')\n\t\treturn preAppendRefusalFor('ERR-04', { address, state: 'managed' });\n\tif (outcome === 'adoption-refused')\n\t\treturn preAppendRefusalFor('ERR-02', { address, state: 'unknown' });\n\treturn undefined;\n}\n\nexport type ApplyConfirmation = (\n\trunId: string,\n\tplanDigest: string,\n) => Promise<boolean>;\n\n/** Rendering is injected so the public pipeline can prove presentation precedes consent. */\nexport type ApplyPlanPresenter = (plan: PlanResult) => void;\n\n/** The sole interactive gate for no-argument apply. EOF and every non-y answer refuse. */\nexport async function confirmNoArgumentApply(\n\trunId: string,\n\tplanDigest: string,\n): Promise<boolean> {\n\tconst prompt = createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stderr,\n\t});\n\ttry {\n\t\tconst answer = await prompt.question(\n\t\t\t`Apply persisted run ${runId} (plan digest ${planDigest})? [y/N] `,\n\t\t);\n\t\treturn /^(?:y|yes)$/iu.test(answer.trim());\n\t} finally {\n\t\tprompt.close();\n\t}\n}\n\n/**\n * The unrecorded-plan path deliberately delegates proving and persistence to\n * runPlan. Therefore the durable row exists before this function asks a human\n * to approve it, and a decline is inspectable rather than a discarded plan.\n */\nexport async function runNoArgumentApply(\n\toptions: ApplyOptions,\n\tconfirm: ApplyConfirmation = confirmNoArgumentApply,\n\texecute: typeof runApply = runApply,\n\tpresent: ApplyPlanPresenter = () => undefined,\n): Promise<NoArgumentApplyResult> {\n\tif (!options.schemaFile)\n\t\tthrow new Error('no-argument apply requires --schema-file <path>');\n\tconst plan = await runPlan({\n\t\tdb: options.db,\n\t\tschemaFile: options.schemaFile,\n\t\t...(options.schema === undefined ? {} : { schema: options.schema }),\n\t\tdryRun: options.dryRun === true,\n\t\tformat: options.format === 'json' ? 'json' : 'sql',\n\t});\n\t// The transition planner intentionally has no removal mapping. The live\n\t// schema differ is therefore only a bridge for that exact unsupported\n\t// comparison. A capability refusal, no-drift result, or inapplicable plan\n\t// retains its own meaning and must never become generated DDL.\n\tconst isUnsupportedRemoval =\n\t\tplan.proveKind === 'blocked' &&\n\t\tplan.compareKind === 'unsupported' &&\n\t\tplan.assessment.decision === 'blocked' &&\n\t\tplan.assessment.reasons.length === 1 &&\n\t\tplan.assessment.reasons[0]?.code === 'unsupported-transition';\n\tconst effectivePlan = isUnsupportedRemoval\n\t\t? await runGeneratorPlan({\n\t\t\t\tdb: options.db,\n\t\t\t\tschemaFile: options.schemaFile,\n\t\t\t\t...(options.schema === undefined ? {} : { schema: options.schema }),\n\t\t\t\tdryRun: options.dryRun === true,\n\t\t\t})\n\t\t: plan;\n\tif (options.dryRun === true)\n\t\treturn {\n\t\t\toutcome: 'dry-run',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: null,\n\t\t\tplanDigest: null,\n\t\t};\n\tif (\n\t\teffectivePlan.proveKind !== 'proven' ||\n\t\teffectivePlan.persisted !== true ||\n\t\t!effectivePlan.runId ||\n\t\t!effectivePlan.planDigest\n\t) {\n\t\t// A blocked/no-drift plan has no executable durable record. Its existing\n\t\t// presentation is the complete result; do not invent an apply attempt.\n\t\treturn {\n\t\t\toutcome: 'not-executable',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: effectivePlan.runId,\n\t\t\tplanDigest: effectivePlan.planDigest,\n\t\t};\n\t}\n\tconst runId = effectivePlan.runId;\n\tconst planDigest = effectivePlan.planDigest;\n\t// Persisted material is shown before any confirmation requirement or prompt.\n\tpresent(effectivePlan);\n\tif (options.yes !== true && process.stdin.isTTY !== true) {\n\t\treturn {\n\t\t\toutcome: 'confirmation-required',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: effectivePlan.runId,\n\t\t\tplanDigest: effectivePlan.planDigest,\n\t\t};\n\t}\n\tif (options.yes !== true && !(await confirm(runId, planDigest))) {\n\t\treturn {\n\t\t\toutcome: 'confirmation-declined',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: effectivePlan.runId,\n\t\t\tplanDigest: effectivePlan.planDigest,\n\t\t};\n\t}\n\tconst recordedRunOptions = Object.fromEntries(\n\t\tObject.entries(options).filter(([key]) => key !== 'schema'),\n\t) as ApplyOptions;\n\tconst executeOptions = {\n\t\t...recordedRunOptions,\n\t\tplanDigest: effectivePlan.planDigest,\n\t};\n\tconst result = isUnsupportedRemoval\n\t\t? await justPersistedGeneratorRemovalContext.run(\n\t\t\t\tmintJustPersistedGeneratorRemovalCapability(runId),\n\t\t\t\t() => execute(runId, executeOptions),\n\t\t\t)\n\t\t: await execute(runId, executeOptions);\n\treturn {\n\t\toutcome: result.outcome,\n\t\tplan: effectivePlan,\n\t\trunId: effectivePlan.runId,\n\t\tplanDigest: effectivePlan.planDigest,\n\t\tresult,\n\t};\n}\n\nasync function loadOnLessor(\n\ttarget: Parameters<typeof acquireTransitionLease>[0],\n\trunId: string,\n) {\n\tconst lease = await acquireTransitionLease(target);\n\ttry {\n\t\treturn await readTransitionJournal(lease.session, runId, { ensure: false });\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nasync function loadOnTarget(\n\ttarget: Parameters<typeof acquireExclusiveTransitionLease>[0],\n\trunId: string,\n) {\n\tconst lease = await acquireExclusiveTransitionLease(target);\n\ttry {\n\t\treturn await readTransitionJournal(lease.session, runId, { ensure: false });\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nasync function runApplyInternal(\n\trunId: string,\n\toptions: ApplyOptions,\n\tpool?: Pool,\n): Promise<ApplyCommandResult> {\n\tconst expectedPlanDigest = options.planDigest;\n\tif (!expectedPlanDigest) return { outcome: 'plan-digest-required', runId };\n\tif (options.schema !== undefined)\n\t\tthrow new Error(\n\t\t\t'apply <run-id> refuses --schema: execution uses the recorded plan and context',\n\t\t);\n\tconst policy = await effectiveApplyPolicy(options);\n\tconst owned =\n\t\tpool === undefined ? (await createDbConnection(options.db)).pool : pool;\n\t// SC-52: this is deliberately before authorization, preflight, or a step\n\t// attempt. A persisted generator removal is reviewable, not replayable.\n\tlet persisted: Awaited<ReturnType<typeof loadOnTarget>>;\n\ttry {\n\t\tpersisted = await loadOnLessor(createPgTransitionLessor(owned), runId);\n\t} catch (error) {\n\t\tif (isInvalidNonResumablePersistedRunError(error, runId)) {\n\t\t\tconst refusal: ApplyCommandResult = {\n\t\t\t\toutcome: 'plan-digest-mismatch',\n\t\t\t\trunId,\n\t\t\t\tresult: {\n\t\t\t\t\tassessment: {\n\t\t\t\t\t\treasons: [{ detail: error.message }],\n\t\t\t\t\t},\n\t\t\t\t} as unknown as ApplyResult,\n\t\t\t};\n\t\t\treturn pool === undefined\n\t\t\t\t? withPoolCleanupReported(refusal, () => owned.end())\n\t\t\t\t: refusal;\n\t\t}\n\t\tif (error instanceof TransitionRunIdentityMismatchError) {\n\t\t\tconst refusal: ApplyCommandResult = {\n\t\t\t\toutcome: 'run-id-mismatch',\n\t\t\t\trunId,\n\t\t\t\tresult: {\n\t\t\t\t\tassessment: {\n\t\t\t\t\t\treasons: [{ detail: error.message }],\n\t\t\t\t\t},\n\t\t\t\t} as unknown as ApplyResult,\n\t\t\t};\n\t\t\treturn pool === undefined\n\t\t\t\t? withPoolCleanupReported(refusal, () => owned.end())\n\t\t\t\t: refusal;\n\t\t}\n\t\tif (pool === undefined) {\n\t\t\ttry {\n\t\t\t\tawait owned.end();\n\t\t\t} catch {\n\t\t\t\t// The load failure is the primary command outcome.\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t}\n\tif (\n\t\tpersisted.run.replayability === 'non-replayable-generator-removal' &&\n\t\t!permitsJustPersistedGeneratorRemoval(runId)\n\t) {\n\t\tconst refusal: ApplyCommandResult = {\n\t\t\toutcome: 'non-replayable-generator-run',\n\t\t\trunId,\n\t\t\trefusal: recordedPlanRefusal(),\n\t\t};\n\t\treturn pool === undefined\n\t\t\t? withPoolCleanupReported(refusal, () => owned.end())\n\t\t\t: refusal;\n\t}\n\tlet result: ApplyCommandResult;\n\ttry {\n\t\tif (isGeneratorPlan(persisted.plan)) {\n\t\t\tconst locked = await withPgTransitionRunLock(\n\t\t\t\towned,\n\t\t\t\trunId,\n\t\t\t\tasync (target) => {\n\t\t\t\t\tconst current = await loadOnTarget(target, runId);\n\t\t\t\t\tif (!isGeneratorPlan(current.plan))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'persisted run no longer contains a generator plan',\n\t\t\t\t\t\t);\n\t\t\t\t\tconst recordedSchema = current.plan.generator.planningSchema;\n\t\t\t\t\tif (!recordedSchema)\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'persisted generator run has no recorded planning schema and is non-resumable',\n\t\t\t\t\t\t);\n\t\t\t\t\tlet actualDigest: string;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tactualDigest = transitionPlanDigest(current.plan);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Persisted generator material is hostile input at apply. The\n\t\t\t\t\t\t// digest boundary must refuse it rather than let parser detail\n\t\t\t\t\t\t// escape as a command exception.\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError(\n\t\t\t\t\t\t\t`persisted generator manifest is invalid: ${errorDetail(error)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tactualDigest !== current.run.planDigest ||\n\t\t\t\t\t\tactualDigest !== expectedPlanDigest\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError();\n\t\t\t\t\tconst manifest = validateNormalizedManagedStepManifest(\n\t\t\t\t\t\tcurrent.plan.steps as unknown as readonly NormalizedManagedStep[],\n\t\t\t\t\t);\n\t\t\t\t\tif (!manifest.ok)\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError(\n\t\t\t\t\t\t\t`persisted generator manifest is invalid: ${manifest.detail}`,\n\t\t\t\t\t\t);\n\t\t\t\t\tconst lifecycleError = persistedLifecycleDirectiveError(\n\t\t\t\t\t\tmanifest.manifest.steps,\n\t\t\t\t\t);\n\t\t\t\t\tif (lifecycleError)\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError(\n\t\t\t\t\t\t\t`persisted generator manifest is invalid: ${lifecycleError}`,\n\t\t\t\t\t\t);\n\t\t\t\t\tif (generatorRunHasPriorStepEvents(current))\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\toutcome: 'prior-step-events-refusal' as const,\n\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t'run has prior generator step-attempt events; run dbsp recover instead',\n\t\t\t\t\t\t};\n\t\t\t\t\treturn executeGeneratorPlan({\n\t\t\t\t\t\tpool: owned,\n\t\t\t\t\t\trun: lockPgJournalRun(mintDurablyLoadedRun(current.run)),\n\t\t\t\t\t\tmanifest: manifest.manifest,\n\t\t\t\t\t\tplanDigest: actualDigest,\n\t\t\t\t\t\tschema: recordedSchema,\n\t\t\t\t\t\tapproval: { approvals: policy.accepts },\n\t\t\t\t\t\trecordAttempt: async (executionId) => {\n\t\t\t\t\t\t\tconst journalLease =\n\t\t\t\t\t\t\t\tawait acquireExclusiveTransitionLease(target);\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait appendIntentJournal(journalLease.session, {\n\t\t\t\t\t\t\t\t\trunId: current.run.runId,\n\t\t\t\t\t\t\t\t\trun: current.run,\n\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\tstepId: `dbsp.generator.attempt:${executionId}`,\n\t\t\t\t\t\t\t\t\toperation: {\n\t\t\t\t\t\t\t\t\t\t...GENERATOR_ATTEMPT_OPERATION,\n\t\t\t\t\t\t\t\t\t\tpayload: { executionId },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trecordedAt: new Date().toISOString(),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\tawait journalLease.release();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(options.replace === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { replaces: options.replace }),\n\t\t\t\t\t\trunId,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (locked.kind === 'busy') result = { outcome: 'run-busy', runId };\n\t\t\telse {\n\t\t\t\tconst execution = locked.value;\n\t\t\t\tconst defaultRefusal = applyPreAppendRefusal(\n\t\t\t\t\texecution.outcome as ApplyOutcome,\n\t\t\t\t\tpersisted.plan,\n\t\t\t\t);\n\t\t\t\tconst withheldAuthority =\n\t\t\t\t\texecution.outcome === 'destructive-authority-refused'\n\t\t\t\t\t\t? (execution.refusal?.withheldAuthority ??\n\t\t\t\t\t\t\t(execution.detail.includes('operator acceptance')\n\t\t\t\t\t\t\t\t? 'destructive operator acceptance authority'\n\t\t\t\t\t\t\t\t: execution.detail.includes('ledger lineage')\n\t\t\t\t\t\t\t\t\t? 'destructive ledger lineage authority'\n\t\t\t\t\t\t\t\t\t: undefined))\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst preAppendRefusal =\n\t\t\t\t\tdefaultRefusal === undefined || withheldAuthority === undefined\n\t\t\t\t\t\t? defaultRefusal\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t...defaultRefusal,\n\t\t\t\t\t\t\t\trefusal: {\n\t\t\t\t\t\t\t\t\t...defaultRefusal.refusal,\n\t\t\t\t\t\t\t\t\twithheldAuthority,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\tresult = {\n\t\t\t\t\toutcome: execution.outcome as ApplyOutcome,\n\t\t\t\t\trunId,\n\t\t\t\t\tresult: execution as unknown as ApplyResult,\n\t\t\t\t\t...(preAppendRefusal === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { refusal: preAppendRefusal }),\n\t\t\t\t} as ApplyCommandResult;\n\t\t\t}\n\t\t} else {\n\t\t\tconst locked = await withPgTransitionRunLock(\n\t\t\t\towned,\n\t\t\t\trunId,\n\t\t\t\tasync (target) => {\n\t\t\t\t\tconst loadCurrent = async (id: string) => {\n\t\t\t\t\t\treturn loadOnTarget(target, id);\n\t\t\t\t\t};\n\t\t\t\t\tconst applier = createApplier(registry(), {\n\t\t\t\t\t\t// A durable apply only verifies the existing immutable row. The applier\n\t\t\t\t\t\t// calls this before execution; a changed record remains a refusal.\n\t\t\t\t\t\tpersist: async () => undefined,\n\t\t\t\t\t});\n\t\t\t\t\treturn applier.applyDurable({\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\texpectedPlanDigest,\n\t\t\t\t\t\tloadCurrent,\n\t\t\t\t\t\tprepareExecutionSession: async (session, contract, plan) => {\n\t\t\t\t\t\t\tconst currency = await validatePgManagedLedgerCurrency(\n\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (currency)\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\t\t\tkind: 'refused' as const,\n\t\t\t\t\t\t\t\t\tdetail: currency,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\treturn preparePgExecutionSession(session, contract, plan);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpolicy,\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\tauthorize: async (run, plan, session) => {\n\t\t\t\t\t\t\tconst current = await loadOnTarget(target, run.runId);\n\t\t\t\t\t\t\tconst grants = plan.assumptions.map((assumption) => ({\n\t\t\t\t\t\t\t\tassumptionId: assumption.id,\n\t\t\t\t\t\t\t\tgrant: policy.accepts.findIndex((grant) =>\n\t\t\t\t\t\t\t\t\tacceptanceMatches(assumption, grant),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t// Crash after commit but before intent: reuse the exact prior approval.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\thasReusableAuthorization(\n\t\t\t\t\t\t\t\t\tcurrent.authorizations,\n\t\t\t\t\t\t\t\t\trun.runId,\n\t\t\t\t\t\t\t\t\ttransitionPlanDigest(plan),\n\t\t\t\t\t\t\t\t\tpolicy.accepts,\n\t\t\t\t\t\t\t\t\tgrants,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\tconst actor =\n\t\t\t\t\t\t\t\tprocess.env.USER ??\n\t\t\t\t\t\t\t\tprocess.env.LOGNAME ??\n\t\t\t\t\t\t\t\t'unknown-local-actor';\n\t\t\t\t\t\t\tconst authorizedAt = new Date().toISOString();\n\t\t\t\t\t\t\tconst digest = authorizationDigest(\n\t\t\t\t\t\t\t\trun.runId,\n\t\t\t\t\t\t\t\ttransitionPlanDigest(plan),\n\t\t\t\t\t\t\t\tpolicy.accepts,\n\t\t\t\t\t\t\t\tgrants,\n\t\t\t\t\t\t\t\tactor,\n\t\t\t\t\t\t\t\tauthorizedAt,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst record: TransitionRunAuthorization = {\n\t\t\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\t\t\tpolicy: policy.accepts,\n\t\t\t\t\t\t\t\tgrants,\n\t\t\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t\t\tactor,\n\t\t\t\t\t\t\t\tauthorizedAt,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tawait appendTransitionAuthorization(session, record);\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (locked.kind === 'busy') result = { outcome: 'run-busy', runId };\n\t\t\telse {\n\t\t\t\tconst outcome = outcomeForApplyResult(locked.value);\n\t\t\t\tconst preAppendRefusal = applyPreAppendRefusal(\n\t\t\t\t\toutcome,\n\t\t\t\t\tpersisted.plan,\n\t\t\t\t\tlocked.value,\n\t\t\t\t);\n\t\t\t\tresult = {\n\t\t\t\t\toutcome,\n\t\t\t\t\trunId,\n\t\t\t\t\tresult: locked.value,\n\t\t\t\t\t...(preAppendRefusal === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { refusal: preAppendRefusal }),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof RecordedPlanDigestMismatchError) {\n\t\t\tresult = {\n\t\t\t\toutcome: 'plan-digest-mismatch',\n\t\t\t\trunId,\n\t\t\t\tresult: {\n\t\t\t\t\tassessment: {\n\t\t\t\t\t\treasons: [{ detail: error.message }],\n\t\t\t\t\t},\n\t\t\t\t} as unknown as ApplyResult,\n\t\t\t};\n\t\t} else {\n\t\t\tif (pool === undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tawait owned.end();\n\t\t\t\t} catch {\n\t\t\t\t\t// The primary failure remains the command failure.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\tif (pool === undefined) {\n\t\treturn withPoolCleanupReported(result, () => owned.end());\n\t}\n\treturn result;\n}\n\n/** Public durable apply surface: it never accepts the private replay bridge. */\nexport async function runApply(\n\trunId: string,\n\toptions: ApplyOptions,\n\tpool?: Pool,\n): Promise<ApplyCommandResult> {\n\treturn runApplyInternal(runId, options, pool);\n}\n\nexport const applyCommand = new Command('apply')\n\t.description(\n\t\t'Plan, persist, present and execute a declaration, or execute one reviewed durable run',\n\t)\n\t.argument('[run-id]', 'Durable run identifier returned by dbsp plan')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option(\n\t\t'--plan-digest <sha>',\n\t\t'Plan digest printed by dbsp plan; required to anchor review outside the database',\n\t)\n\t.option('--schema-file <path>', 'Schema DSL file for no-argument apply')\n\t.option('--schema <name>', 'Database schema name for no-argument apply')\n\t.option('--yes', 'Confirm no-argument apply without an interactive prompt')\n\t.option(\n\t\t'--dry-run',\n\t\t'Present a no-argument plan without persisting or executing',\n\t)\n\t.option(\n\t\t'--accept <class>',\n\t\t'Accept an assumption class broadly; repeatable',\n\t\t(value, previous: string[] = []) => [...previous, value],\n\t)\n\t.option(\n\t\t'--replace <address>',\n\t\t'Replace exactly this address when the presented plan requested it; repeatable',\n\t\t(value, previous: string[] = []) => [...previous, value],\n\t)\n\t.option(\n\t\t'--accept-policy <file>',\n\t\t'UTF-8 JSON AssumptionAcceptance[] policy file; set-unioned with --accept and canonicalised before authorization',\n\t)\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (runId: string | undefined, options: ApplyOptions) => {\n\t\tif (runId === undefined) {\n\t\t\tlet result: NoArgumentApplyResult | { readonly error: string };\n\t\t\ttry {\n\t\t\t\tresult = await runNoArgumentApply(\n\t\t\t\t\toptions,\n\t\t\t\t\tconfirmNoArgumentApply,\n\t\t\t\t\trunApply,\n\t\t\t\t\toptions.format === 'json'\n\t\t\t\t\t\t? () => undefined\n\t\t\t\t\t\t: (plan) =>\n\t\t\t\t\t\t\t\tconsole.log(formatPlanHuman(plan, options.dryRun === true)),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tresult = {\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif ('error' in result) {\n\t\t\t\tif (options.format === 'json')\n\t\t\t\t\tprintCliJson({ outcome: 'apply-failed', ...result });\n\t\t\t\telse console.error(`❌ ${escapeDiagnosticText(result.error)}`);\n\t\t\t\tprocess.exitCode = exitCodeForApplyOutcome('apply-failed');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst exitCode =\n\t\t\t\tresult.outcome === 'dry-run' || result.outcome === 'not-executable'\n\t\t\t\t\t? exitCodeForPlanResult(result.plan)\n\t\t\t\t\t: exitCodeForApplyOutcome(result.outcome);\n\t\t\tif (options.format === 'json') {\n\t\t\t\tprintCliJson({\n\t\t\t\t\toutcome: result.outcome,\n\t\t\t\t\texitCode,\n\t\t\t\t\tplan: formatPlanJson(result.plan, options.dryRun === true),\n\t\t\t\t\t...(result.runId === null ? {} : { runId: result.runId }),\n\t\t\t\t\t...(result.planDigest === null\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { planDigest: result.planDigest }),\n\t\t\t\t\t...('result' in result ? { apply: result.result } : {}),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (result.outcome === 'dry-run' || result.outcome === 'not-executable')\n\t\t\t\t\tconsole.log(formatPlanHuman(result.plan, options.dryRun === true));\n\t\t\t\tif (result.outcome === 'confirmation-required')\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'confirmation-required: rerun with --yes or from an interactive TTY',\n\t\t\t\t\t);\n\t\t\t\telse if (result.outcome === 'confirmation-declined')\n\t\t\t\t\tconsole.log('confirmation-declined: persisted run was not executed');\n\t\t\t\telse if (result.outcome === 'not-executable') {\n\t\t\t\t\t// The planner already rendered the concrete no-drift/blocked reason.\n\t\t\t\t} else if (result.outcome !== 'dry-run' && 'result' in result)\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t'runId' in result.result\n\t\t\t\t\t\t\t? formatApplyHuman(result.result)\n\t\t\t\t\t\t\t: `${result.result.outcome}${\n\t\t\t\t\t\t\t\t\t'detail' in result.result ? `: ${result.result.detail}` : ''\n\t\t\t\t\t\t\t\t}`,\n\t\t\t\t\t);\n\t\t\t}\n\t\t\tprocess.exitCode = exitCode;\n\t\t\treturn;\n\t\t}\n\t\tlet result:\n\t\t\t| ApplyCommandResult\n\t\t\t| {\n\t\t\t\t\treadonly outcome: 'policy-invalid' | 'apply-failed';\n\t\t\t\t\treadonly runId: string;\n\t\t\t\t\treadonly error: string;\n\t\t\t };\n\t\ttry {\n\t\t\tresult = options.planDigest\n\t\t\t\t? await runApply(runId, options)\n\t\t\t\t: { outcome: 'plan-digest-required', runId };\n\t\t} catch (error) {\n\t\t\tresult = {\n\t\t\t\toutcome:\n\t\t\t\t\terror instanceof SyntaxError ? 'policy-invalid' : 'apply-failed',\n\t\t\t\trunId,\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\t// Validation errors are ordinary Errors, not necessarily SyntaxErrors.\n\t\t\tif (\n\t\t\t\tresult.outcome === 'apply-failed' &&\n\t\t\t\t/^(acceptance\\[|--accept-policy|policy )/u.test(result.error)\n\t\t\t)\n\t\t\t\tresult = { ...result, outcome: 'policy-invalid' };\n\t\t}\n\t\tconst exitCode = exitCodeForApplyOutcome(result.outcome);\n\t\tconst document = { ...result, exitCode };\n\t\tif (options.format === 'json') printCliJson(document);\n\t\telse console.log(formatApplyHuman(result));\n\t\tprocess.exitCode = exitCode;\n\t})\n\t.addHelpText(\n\t\t'after',\n\t\t`\\nJSON result contract (outcome -> exit code):\\n${APPLY_OUTCOME_CONTRACT.map(\n\t\t\t([outcome, exitCode, description]) =>\n\t\t\t\t` ${outcome} -> ${exitCode}: ${description}`,\n\t\t).join(\n\t\t\t'\\n',\n\t\t)}\\n\\nApply requires --plan-digest from dbsp plan. It recomputes the stored plan digest before authorization or planned DDL and refuses a missing or mismatched value. This detects substitution, not deletion: missing run evidence makes apply refuse. Policy files are JSON arrays. Every entry is strictly validated; file entries and repeated --accept values are set-unioned, exact duplicates are normalized, selector order is normalized, and the authorization digest is SHA-256 over canonical JSON {runId, planDigest, policy, grants}.\\n`,\n\t);\n","/** Shared CLI JSON boundary. Keep every machine-readable document here. */\nexport function serializeCliJson(value: unknown): string {\n\tconst serialized = JSON.stringify(value, null, 2);\n\tif (serialized === undefined)\n\t\tthrow new Error('CLI JSON output must be a JSON-serializable document');\n\treturn serialized;\n}\n\nexport function printCliJson(value: unknown): void {\n\tconsole.log(serializeCliJson(value));\n}\n","/** Live-only executor for the no-argument schema-differ plan. */\nimport { createHash, randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport {\n\tcompareSchemata,\n\tcreatePgsqlAdapter,\n\tdbTypesEqual,\n\texecutePgAdmittedOperation,\n\texecutePgDeclaredAdoption,\n\texecutePgPersistedTableReaddress,\n\ttype PgLockedRun,\n\ttype PgOutcomeCheckpointObserver,\n\tpreflightPgDeclaredAdoption,\n\treadPgCatalogueIdentity,\n\treadPgLedgerAddressChain,\n\treadPgLedgerScopeCurrency,\n\treadPgRemovalEffectsClosure,\n} from '@dbsp/adapter-pgsql';\nimport {\n\toutcomeClaimEventId,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\ttype ValidatedManagedStepManifest,\n\tvalidateNormalizedManagedStepManifest,\n} from '@dbsp/core';\nimport { decideDestructiveDecision } from '@dbsp/core/internal';\nimport type {\n\tCascadeCoveredOutcomeClaimPlan,\n\tContainmentClosureDestructiveOutcome,\n\tDestructiveAuthorityEvidence,\n\tLedgerAddress,\n\tLedgerChainMember,\n\tLedgerClaimKind,\n\tLedgerHome,\n\tLedgerPayload,\n\tModelIR,\n\tNormalizedManagedStep,\n\tScopedApprovalSet,\n\tTableIR,\n} from '@dbsp/types';\nimport { ledgerAddressKey } from '@dbsp/types';\nimport type { Pool } from 'pg';\n\nfunction managedSteps(manifest: ValidatedManagedStepManifest) {\n\treturn manifest.steps;\n}\n\n/**\n * A reviewed replacement selector is canonicalized as `table:<name>`, while\n * the CLI has always accepted the unqualified table name as a shorthand. Keep\n * the comparison at the reviewed manifest boundary so every subsequent\n * authority decision sees the same selected set.\n */\nfunction matchesReviewedReplacementSelector(\n\treviewed: string,\n\tprovided: string,\n): boolean {\n\treturn (\n\t\tprovided === reviewed ||\n\t\t(reviewed.startsWith('table:') &&\n\t\t\tprovided === reviewed.slice('table:'.length))\n\t);\n}\n\nexport type GeneratorExecutionResult =\n\t| { readonly outcome: 'completed' }\n\t| {\n\t\t\treadonly outcome: 'partially-applied';\n\t\t\treadonly detail: string;\n\t\t\treadonly completedStepKeys: readonly string[];\n\t\t\treadonly notStartedStepKeys: readonly string[];\n\t }\n\t| { readonly outcome: 'selection-incomplete'; readonly detail: string }\n\t| { readonly outcome: 'adoption-refused'; readonly detail: string }\n\t| {\n\t\t\treadonly outcome: 'readdress-unsupported' | 'readdress-refused';\n\t\t\treadonly detail: string;\n\t }\n\t| {\n\t\t\treadonly outcome: 'destructive-authority-refused';\n\t\t\treadonly detail: string;\n\t\t\t/** The exact live authority that remained withheld at admission. */\n\t\t\treadonly refusal?: { readonly withheldAuthority: string };\n\t }\n\t| { readonly outcome: 'prior-step-events-refusal'; readonly detail: string }\n\t| {\n\t\t\treadonly outcome: 'recovery-required';\n\t\t\treadonly claimId: string;\n\t\t\treadonly detail: string;\n\t }\n\t| { readonly outcome: 'execution-failed'; readonly detail: string };\n\nfunction modelForAdoption(table: TableIR): ModelIR {\n\tconst tables = new Map([[table.name, table]]);\n\tconst relations = new Map();\n\treturn {\n\t\ttables,\n\t\trelations,\n\t\tgetTable: (name) => tables.get(name),\n\t\tgetRelation: (name) => relations.get(name),\n\t\tgetRelationsFrom: () => [],\n\t\tgetRelationsTo: () => [],\n\t\tisAmbiguous: () => ({ ambiguous: false, options: [] }),\n\t};\n}\n\n/** Adoption uses the established schema differ; it has no bespoke comparator. */\nasync function adoptionShapeMatches(\n\tpool: Pool,\n\tschema: string,\n\tshape: TableIR,\n): Promise<boolean> {\n\tconst live = await createPgsqlAdapter(pool).introspect({ schema });\n\tconst diff = compareSchemata(modelForAdoption(shape), live);\n\treturn !diff.changes.some((change) => change.table === shape.name);\n}\n\nconst SYSTEM_LEDGER_SCHEMAS = new Set([\n\t'pg_toast',\n\t'pg_catalog',\n\t'information_schema',\n]);\n\n/** Preserves the candidate that made ledger-home evidence impossible. */\nclass SystemSchemaLedgerHomeError extends Error {\n\treadonly address: LedgerAddress;\n\n\tconstructor(address: LedgerAddress) {\n\t\tsuper(\n\t\t\t`SystemSchemaLedgerHomeError: ledger home is unavailable for system schema ${address.schema}: ${ledgerAddressKey(address)}`,\n\t\t);\n\t\tthis.name = 'SystemSchemaLedgerHomeError';\n\t\tthis.address = address;\n\t}\n}\n\nfunction home(address: LedgerAddress): LedgerHome {\n\tif (\n\t\taddress.scope !== 'database' &&\n\t\taddress.schema &&\n\t\tSYSTEM_LEDGER_SCHEMAS.has(address.schema)\n\t)\n\t\tthrow new SystemSchemaLedgerHomeError(address);\n\treturn address.scope === 'database'\n\t\t? ({ scope: 'database' } as const)\n\t\t: address.schema\n\t\t\t? ({ scope: 'schema', schema: address.schema } as const)\n\t\t\t: (() => {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`schema-scoped generated address ${address.name} has no schema ledger`,\n\t\t\t\t\t);\n\t\t\t\t})();\n}\n\nfunction acceptance(planDigest: string, approval: ScopedApprovalSet) {\n\treturn approval.approvals.some(\n\t\t(grant) => grant.class === `destructive-plan-accepted:${planDigest}`,\n\t) === true\n\t\t? 'destructive-plan-accepted'\n\t\t: 'absent';\n}\n\n/**\n * Preserve the authority axis in the public generated-removal result. The\n * interpreter still makes the decision; this is presentation metadata for a\n * refusal that has already been reached under the admission lock.\n */\nfunction withheldDestructiveAuthority(\n\tevidence: DestructiveAuthorityEvidence,\n): string | undefined {\n\tif (\n\t\tevidence.declaration !== 'requires-removal' &&\n\t\tevidence.declaration !== 'requires-lossy-change' &&\n\t\tevidence.declaration !== 'replacement-requested-by-plan'\n\t)\n\t\treturn 'destructive declaration authority';\n\tif (evidence.ownership !== 'managed-by-me')\n\t\treturn 'destructive ownership authority';\n\tif (evidence.catalogueIdentity !== 'matches-recorded')\n\t\treturn 'destructive catalogue identity authority';\n\tif (evidence.operatorAcceptance !== 'destructive-plan-accepted')\n\t\treturn 'destructive operator acceptance authority';\n\tif (\n\t\tevidence.containment !== undefined &&\n\t\tevidence.containment !== 'all-contained-or-managed'\n\t)\n\t\treturn 'destructive containment authority';\n\tif (evidence.ledgerLineage !== 'matches-database')\n\t\treturn 'destructive ledger lineage authority';\n\treturn undefined;\n}\n\n/** Admission can reject policy/currency before invoking the live callback. */\nfunction withheldDestructiveAuthorityFromReason(\n\treason: string,\n): string | undefined {\n\tif (reason.includes('operator acceptance'))\n\t\treturn 'destructive operator acceptance authority';\n\tif (reason.includes('ledger lineage'))\n\t\treturn 'destructive ledger lineage authority';\n\treturn undefined;\n}\n\nasync function databaseId(pool: Pool): Promise<string> {\n\tconst result = await pool.query('SELECT current_database() AS database_id');\n\tconst database = result.rows[0]?.database_id;\n\tif (typeof database !== 'string' || database.length === 0)\n\t\tthrow new Error(\n\t\t\t'schema-differ generator could not read current database identity',\n\t\t);\n\treturn database;\n}\n\ntype LedgerQueryable = Parameters<typeof readPgLedgerAddressChain>[0];\n\nasync function managed(\n\texecutor: LedgerQueryable,\n\taddress: LedgerAddress,\n): Promise<boolean> {\n\t// Let a ledger read failure reach readPgRemovalEffectsClosure's catch so it\n\t// remains an undecidable closure with its PostgreSQL reason, rather than\n\t// misclassifying unreadable ownership as an unmanaged dependent.\n\tconst chain = await readPgLedgerAddressChain(\n\t\texecutor,\n\t\thome(address),\n\t\taddress,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\treturn (\n\t\tprojection.kind === 'projected-ledger-chain' &&\n\t\tprojection.stableState === 'managed'\n\t);\n}\n\n/**\n * A generator document is re-evaluated against live state on every delivery.\n * Once a creation claim has already reached its managed terminal state, its\n * address being present is evidence of that earlier delivery, not permission to\n * send its fixed bundle again. An unmanaged occupant still follows the normal\n * vacancy refusal path.\n */\nasync function alreadyAppliedCreation(\n\texecutor: LedgerQueryable,\n\taddress: LedgerAddress,\n): Promise<boolean> {\n\tconst live = await readPgCatalogueIdentity(executor, address);\n\tif (!live?.catalogueIdentity) return false;\n\tconst chain = await readPgLedgerAddressChain(\n\t\texecutor,\n\t\thome(address),\n\t\taddress,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\tconst recorded = chain.terminalMember?.catalogueIdentity;\n\treturn (\n\t\tprojection.kind === 'projected-ledger-chain' &&\n\t\tprojection.stableState === 'managed' &&\n\t\trecorded !== undefined &&\n\t\tisDeepStrictEqual(recorded, live.catalogueIdentity)\n\t);\n}\n\nfunction observed(address: LedgerAddress): LedgerPayload {\n\treturn {\n\t\tvalue: { kind: address.kind, name: address.name },\n\t\tdigest: `generator:${address.kind}:${address.name}`,\n\t};\n}\n\nfunction normalizedDefinition(value: string): string {\n\treturn value\n\t\t.replaceAll('\"', '')\n\t\t.replace(/\\s+/gu, ' ')\n\t\t.replace(/;$/u, '')\n\t\t.trim()\n\t\t.toLowerCase();\n}\n\nfunction generatedPayload(value: unknown): LedgerPayload {\n\treturn {\n\t\tvalue: value as LedgerPayload['value'],\n\t\tdigest: createHash('sha256').update(JSON.stringify(value)).digest('hex'),\n\t};\n}\n\ntype GeneratedColumnPostcondition = {\n\treadonly name: string;\n\treadonly type?: string;\n\treadonly nullable?: boolean;\n\treadonly hasDefault?: boolean;\n\treadonly default?: string;\n\treadonly collation?: string | null;\n\treadonly identity?: 'always' | 'byDefault' | null;\n};\n\ntype GeneratedPostcondition =\n\t| {\n\t\t\treadonly kind: 'table';\n\t\t\treadonly columns: readonly GeneratedColumnPostcondition[];\n\t }\n\t| { readonly kind: 'column'; readonly column: GeneratedColumnPostcondition }\n\t| {\n\t\t\treadonly kind: 'constraint';\n\t\t\treadonly constraint:\n\t\t\t\t| { readonly type: 'p' | 'u'; readonly columns: readonly string[] }\n\t\t\t\t| {\n\t\t\t\t\t\treadonly type: 'f';\n\t\t\t\t\t\treadonly columns: readonly string[];\n\t\t\t\t\t\treadonly references: {\n\t\t\t\t\t\t\treadonly schema?: string;\n\t\t\t\t\t\t\treadonly table: string;\n\t\t\t\t\t\t\treadonly columns: readonly string[];\n\t\t\t\t\t\t};\n\t\t\t\t\t\treadonly onDelete: string;\n\t\t\t\t\t\treadonly onUpdate: string;\n\t\t\t\t\t\treadonly deferred: boolean;\n\t\t\t\t\t\treadonly notValid: boolean;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\treadonly type: 'c';\n\t\t\t\t\t\treadonly definition: string;\n\t\t\t\t\t\treadonly notValid: boolean;\n\t\t\t\t };\n\t }\n\t| { readonly kind: 'index'; readonly definition: string }\n\t| { readonly kind: 'enum'; readonly labels: readonly string[] }\n\t| {\n\t\t\treadonly kind: 'sequence';\n\t\t\treadonly startValue?: string;\n\t\t\treadonly incrementBy?: string;\n\t\t\treadonly minValue?: string;\n\t\t\treadonly maxValue?: string;\n\t\t\treadonly cycle?: boolean;\n\t }\n\t| { readonly kind: 'extension'; readonly version?: string }\n\t| { readonly kind: 'absent' }\n\t| { readonly kind: 'exempt'; readonly reason: string };\n\nfunction textList(value: unknown): readonly string[] {\n\treturn Array.isArray(value) ? value.map((item) => String(item)) : [];\n}\n\nfunction foreignKeyAction(code: unknown): string | undefined {\n\tswitch (code) {\n\t\tcase 'a':\n\t\t\treturn 'NO ACTION';\n\t\tcase 'r':\n\t\t\treturn 'RESTRICT';\n\t\tcase 'c':\n\t\t\treturn 'CASCADE';\n\t\tcase 'n':\n\t\t\treturn 'SET NULL';\n\t\tcase 'd':\n\t\t\treturn 'SET DEFAULT';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction generatedPostcondition(\n\tstep: NormalizedManagedStep,\n\taddress: LedgerAddress,\n): GeneratedPostcondition {\n\tconst value = step.expectedDeclaration?.value;\n\tif (!value || typeof value !== 'object' || Array.isArray(value))\n\t\tthrow new Error(\n\t\t\t`generated ${address.kind} step ${step.stepKey} has no structural postcondition`,\n\t\t);\n\tconst postcondition = value as GeneratedPostcondition;\n\treturn postcondition;\n}\n\n/**\n * Generated DDL has no operation runtime to supply an observation. Read the\n * precise catalogue fields it changes; a same-named object is never enough to\n * write an `observed` terminal.\n */\nexport async function readGeneratedPostcondition(\n\texecutor: LedgerQueryable,\n\tstep: NormalizedManagedStep,\n\taddress: LedgerAddress,\n): Promise<LedgerPayload> {\n\tconst parent = address.parent?.name;\n\tif (address.kind === 'column' && parent && address.schema) {\n\t\tconst postcondition = generatedPostcondition(step, address);\n\t\tif (postcondition.kind !== 'column')\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} has a non-column structural postcondition`,\n\t\t\t);\n\t\tconst expected = postcondition.column;\n\t\tif (expected.name !== address.name)\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} structural postcondition names another column`,\n\t\t\t);\n\t\tconst row = (\n\t\t\tawait executor.query(\n\t\t\t\t`SELECT pg_catalog.format_type(attribute.atttypid, attribute.atttypmod) AS column_type, attribute.attnotnull AS is_not_null, pg_catalog.pg_get_expr(default_value.adbin, default_value.adrelid) AS column_default, collation.collname AS collation_name, attribute.attidentity AS identity_kind FROM pg_catalog.pg_attribute attribute JOIN pg_catalog.pg_class relation ON relation.oid = attribute.attrelid JOIN pg_catalog.pg_namespace namespace ON namespace.oid = relation.relnamespace LEFT JOIN pg_catalog.pg_attrdef default_value ON default_value.adrelid = attribute.attrelid AND default_value.adnum = attribute.attnum LEFT JOIN pg_catalog.pg_collation collation ON collation.oid = attribute.attcollation WHERE namespace.nspname = $1 AND relation.relname = $2 AND attribute.attname = $3 AND attribute.attnum > 0 AND NOT attribute.attisdropped`,\n\t\t\t\t[address.schema, parent, address.name],\n\t\t\t)\n\t\t).rows[0];\n\t\tif (!row) throw new Error(`generated column ${address.name} is absent`);\n\t\tconst type = String(row.column_type ?? '');\n\t\tconst nullable =\n\t\t\trow.is_not_null === true\n\t\t\t\t? false\n\t\t\t\t: row.is_not_null === false\n\t\t\t\t\t? true\n\t\t\t\t\t: undefined;\n\t\tconst actualDefault =\n\t\t\trow.column_default == null ? undefined : String(row.column_default);\n\t\tconst actualCollation =\n\t\t\trow.collation_name == null ? null : String(row.collation_name);\n\t\tconst actualIdentity =\n\t\t\trow.identity_kind === 'a'\n\t\t\t\t? 'always'\n\t\t\t\t: row.identity_kind === 'd'\n\t\t\t\t\t? 'byDefault'\n\t\t\t\t\t: null;\n\t\tif (expected.type !== undefined && !dbTypesEqual(type, expected.type))\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} type postcondition differs`,\n\t\t\t);\n\t\tif (expected.nullable !== undefined && nullable !== expected.nullable)\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} nullability postcondition differs`,\n\t\t\t);\n\t\tif (\n\t\t\texpected.hasDefault === true &&\n\t\t\t(actualDefault === undefined ||\n\t\t\t\texpected.default === undefined ||\n\t\t\t\tactualDefault !== expected.default)\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} default postcondition differs`,\n\t\t\t);\n\t\tif (expected.hasDefault === false && actualDefault !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} default postcondition differs`,\n\t\t\t);\n\t\tif (\n\t\t\texpected.collation !== undefined &&\n\t\t\tactualCollation !== expected.collation\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} collation postcondition differs`,\n\t\t\t);\n\t\tif (expected.identity !== undefined && actualIdentity !== expected.identity)\n\t\t\tthrow new Error(\n\t\t\t\t`generated column ${address.name} identity postcondition differs`,\n\t\t\t);\n\t\treturn generatedPayload({\n\t\t\tkind: 'column',\n\t\t\ttype,\n\t\t\tnullable,\n\t\t\tdefault: actualDefault,\n\t\t});\n\t}\n\tif (address.kind === 'constraint' && parent && address.schema) {\n\t\tconst postcondition = generatedPostcondition(step, address);\n\t\tif (postcondition.kind !== 'constraint')\n\t\t\tthrow new Error(\n\t\t\t\t`generated constraint ${address.name} has a non-constraint structural postcondition`,\n\t\t\t);\n\t\tconst expected = postcondition.constraint;\n\t\tconst row = (\n\t\t\tawait executor.query(\n\t\t\t\t`SELECT constraint_item.contype AS constraint_type, pg_catalog.pg_get_constraintdef(constraint_item.oid, true) AS constraint_definition, ARRAY(SELECT attribute.attname::text FROM unnest(constraint_item.conkey) WITH ORDINALITY AS key_column(attnum, position) JOIN pg_catalog.pg_attribute attribute ON attribute.attrelid = constraint_item.conrelid AND attribute.attnum = key_column.attnum ORDER BY key_column.position) AS key_columns, referenced_namespace.nspname AS referenced_schema, referenced_relation.relname AS referenced_table, ARRAY(SELECT attribute.attname::text FROM unnest(constraint_item.confkey) WITH ORDINALITY AS key_column(attnum, position) JOIN pg_catalog.pg_attribute attribute ON attribute.attrelid = constraint_item.confrelid AND attribute.attnum = key_column.attnum ORDER BY key_column.position) AS referenced_columns, constraint_item.confdeltype AS on_delete, constraint_item.confupdtype AS on_update, constraint_item.condeferrable AS is_deferrable, constraint_item.condeferred AS is_deferred, constraint_item.convalidated AS is_validated FROM pg_catalog.pg_constraint constraint_item JOIN pg_catalog.pg_class relation ON relation.oid = constraint_item.conrelid JOIN pg_catalog.pg_namespace namespace ON namespace.oid = relation.relnamespace LEFT JOIN pg_catalog.pg_class referenced_relation ON referenced_relation.oid = constraint_item.confrelid LEFT JOIN pg_catalog.pg_namespace referenced_namespace ON referenced_namespace.oid = referenced_relation.relnamespace WHERE namespace.nspname = $1 AND relation.relname = $2 AND constraint_item.conname = $3`,\n\t\t\t\t[address.schema, parent, address.name],\n\t\t\t)\n\t\t).rows[0];\n\t\tif (!row) throw new Error(`generated constraint ${address.name} is absent`);\n\t\tconst definition = String(row.constraint_definition ?? '');\n\t\tif (String(row.constraint_type) !== expected.type)\n\t\t\tthrow new Error(\n\t\t\t\t`generated constraint ${address.name} postcondition differs`,\n\t\t\t);\n\t\tif (\n\t\t\t(expected.type === 'p' || expected.type === 'u') &&\n\t\t\tJSON.stringify(textList(row.key_columns)) !==\n\t\t\t\tJSON.stringify(expected.columns)\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t`generated constraint ${address.name} postcondition differs`,\n\t\t\t);\n\t\tif (expected.type === 'c') {\n\t\t\tif (\n\t\t\t\tnormalizedDefinition(definition) !==\n\t\t\t\t\tnormalizedDefinition(expected.definition) ||\n\t\t\t\t(row.is_validated === true) === expected.notValid\n\t\t\t)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`generated constraint ${address.name} postcondition differs`,\n\t\t\t\t);\n\t\t}\n\t\tif (expected.type === 'f') {\n\t\t\tif (\n\t\t\t\tJSON.stringify(textList(row.key_columns)) !==\n\t\t\t\t\tJSON.stringify(expected.columns) ||\n\t\t\t\tString(row.referenced_table ?? '') !== expected.references.table ||\n\t\t\t\t(expected.references.schema !== undefined &&\n\t\t\t\t\tString(row.referenced_schema ?? '') !== expected.references.schema) ||\n\t\t\t\tJSON.stringify(textList(row.referenced_columns)) !==\n\t\t\t\t\tJSON.stringify(expected.references.columns) ||\n\t\t\t\tforeignKeyAction(row.on_delete) !== expected.onDelete ||\n\t\t\t\tforeignKeyAction(row.on_update) !== expected.onUpdate ||\n\t\t\t\t(row.is_deferrable === true && row.is_deferred === true) !==\n\t\t\t\t\texpected.deferred ||\n\t\t\t\t(row.is_validated === true) === expected.notValid\n\t\t\t)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`generated constraint ${address.name} postcondition differs`,\n\t\t\t\t);\n\t\t}\n\t\treturn generatedPayload({\n\t\t\tkind: 'constraint',\n\t\t\ttype: String(row.constraint_type ?? ''),\n\t\t\tdefinition,\n\t\t});\n\t}\n\tif (address.kind === 'index' && parent && address.schema) {\n\t\tconst postcondition = generatedPostcondition(step, address);\n\t\tif (postcondition.kind !== 'index')\n\t\t\tthrow new Error(\n\t\t\t\t`generated index ${address.name} has a non-index structural postcondition`,\n\t\t\t);\n\t\tconst row = (\n\t\t\tawait executor.query(\n\t\t\t\t`SELECT index_relation.relname AS index_name, index_meta.indisunique AS is_unique, pg_catalog.pg_get_indexdef(index_meta.indexrelid, 0, true) AS index_definition FROM pg_catalog.pg_index index_meta JOIN pg_catalog.pg_class relation ON relation.oid = index_meta.indrelid JOIN pg_catalog.pg_namespace namespace ON namespace.oid = relation.relnamespace JOIN pg_catalog.pg_class index_relation ON index_relation.oid = index_meta.indexrelid WHERE namespace.nspname = $1 AND relation.relname = $2 AND index_relation.relname = $3`,\n\t\t\t\t[address.schema, parent, address.name],\n\t\t\t)\n\t\t).rows[0];\n\t\tif (!row) throw new Error(`generated index ${address.name} is absent`);\n\t\tconst definition = String(row.index_definition ?? '');\n\t\tif (\n\t\t\tnormalizedDefinition(definition) !==\n\t\t\tnormalizedDefinition(postcondition.definition)\n\t\t)\n\t\t\tthrow new Error(`generated index ${address.name} postcondition differs`);\n\t\treturn generatedPayload({\n\t\t\tkind: 'index',\n\t\t\tunique: row.is_unique === true,\n\t\t\tdefinition,\n\t\t});\n\t}\n\tif (address.kind === 'table' && address.schema) {\n\t\tconst postcondition = generatedPostcondition(step, address);\n\t\tif (postcondition.kind !== 'table')\n\t\t\tthrow new Error(\n\t\t\t\t`generated table ${address.name} has a non-table structural postcondition`,\n\t\t\t);\n\t\tconst rows = (\n\t\t\tawait executor.query(\n\t\t\t\t`SELECT attribute.attname AS column_name, pg_catalog.format_type(attribute.atttypid, attribute.atttypmod) AS column_type, attribute.attnotnull AS is_not_null, pg_catalog.pg_get_expr(default_value.adbin, default_value.adrelid) AS column_default FROM pg_catalog.pg_attribute attribute JOIN pg_catalog.pg_class relation ON relation.oid = attribute.attrelid JOIN pg_catalog.pg_namespace namespace ON namespace.oid = relation.relnamespace LEFT JOIN pg_catalog.pg_attrdef default_value ON default_value.adrelid = attribute.attrelid AND default_value.adnum = attribute.attnum WHERE namespace.nspname = $1 AND relation.relname = $2 AND attribute.attnum > 0 AND NOT attribute.attisdropped ORDER BY attribute.attnum`,\n\t\t\t\t[address.schema, address.name],\n\t\t\t)\n\t\t).rows;\n\t\tconst expected = postcondition.columns;\n\t\tif (expected.length === 0 || rows.length !== expected.length)\n\t\t\tthrow new Error(\n\t\t\t\t`generated table ${address.name} column postcondition differs: expected ${JSON.stringify(expected)}, live ${JSON.stringify(rows)}`,\n\t\t\t);\n\t\tfor (const specification of expected) {\n\t\t\tconst actual = rows.find((row) => row.column_name === specification.name);\n\t\t\tif (\n\t\t\t\t!actual ||\n\t\t\t\t(specification.type !== undefined &&\n\t\t\t\t\t!dbTypesEqual(\n\t\t\t\t\t\tString(actual.column_type ?? ''),\n\t\t\t\t\t\tspecification.type,\n\t\t\t\t\t)) ||\n\t\t\t\t(specification.nullable !== undefined &&\n\t\t\t\t\t(actual.is_not_null !== true) !== specification.nullable) ||\n\t\t\t\t(specification.hasDefault === true &&\n\t\t\t\t\t(specification.default === undefined ||\n\t\t\t\t\t\tactual.column_default == null ||\n\t\t\t\t\t\tString(actual.column_default) !== specification.default)) ||\n\t\t\t\t(specification.hasDefault === false && actual.column_default != null)\n\t\t\t)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`generated table ${address.name} column postcondition differs: expected ${JSON.stringify(specification)}, live ${JSON.stringify(actual)}`,\n\t\t\t\t);\n\t\t}\n\t\treturn generatedPayload({\n\t\t\tkind: 'table',\n\t\t\tcolumns: rows.map((row) => ({\n\t\t\t\tname: String(row.column_name),\n\t\t\t\ttype: String(row.column_type),\n\t\t\t\tnullable: row.is_not_null !== true,\n\t\t\t\tdefault:\n\t\t\t\t\trow.column_default == null ? undefined : String(row.column_default),\n\t\t\t})),\n\t\t});\n\t}\n\tif (address.kind === 'enum' && address.schema) {\n\t\tconst postcondition = generatedPostcondition(step, address);\n\t\tif (postcondition.kind !== 'enum')\n\t\t\tthrow new Error(\n\t\t\t\t`generated enum ${address.name} has a non-enum structural postcondition`,\n\t\t\t);\n\t\tconst rows = (\n\t\t\tawait executor.query(\n\t\t\t\t`SELECT enum_label.enumlabel AS label FROM pg_catalog.pg_type type JOIN pg_catalog.pg_namespace namespace ON namespace.oid = type.typnamespace JOIN pg_catalog.pg_enum enum_label ON enum_label.enumtypid = type.oid WHERE namespace.nspname = $1 AND type.typname = $2 ORDER BY enum_label.enumsortorder`,\n\t\t\t\t[address.schema, address.name],\n\t\t\t)\n\t\t).rows;\n\t\tconst labels = rows.map((row) => String(row.label));\n\t\tif (JSON.stringify(labels) !== JSON.stringify(postcondition.labels))\n\t\t\tthrow new Error(`generated enum ${address.name} postcondition differs`);\n\t\treturn generatedPayload({ kind: 'enum', labels });\n\t}\n\tif (address.kind === 'sequence' && address.schema) {\n\t\tconst postcondition = generatedPostcondition(step, address);\n\t\tif (postcondition.kind !== 'sequence')\n\t\t\tthrow new Error(\n\t\t\t\t`generated sequence ${address.name} has a non-sequence structural postcondition`,\n\t\t\t);\n\t\tconst row = (\n\t\t\tawait executor.query(\n\t\t\t\t`SELECT sequence.start_value::text AS start_value, sequence.increment_by::text AS increment_by, sequence.min_value::text AS min_value, sequence.max_value::text AS max_value, sequence.cache_size::text AS cache_size, sequence.cycle AS cycle FROM pg_catalog.pg_sequences sequence WHERE sequence.schemaname = $1 AND sequence.sequencename = $2`,\n\t\t\t\t[address.schema, address.name],\n\t\t\t)\n\t\t).rows[0];\n\t\tif (!row) throw new Error(`generated sequence ${address.name} is absent`);\n\t\tconst actual = {\n\t\t\tstartValue: String(row.start_value),\n\t\t\tincrementBy: String(row.increment_by),\n\t\t\tminValue: String(row.min_value),\n\t\t\tmaxValue: String(row.max_value),\n\t\t\tcycle: row.cycle === true,\n\t\t};\n\t\tfor (const key of [\n\t\t\t'startValue',\n\t\t\t'incrementBy',\n\t\t\t'minValue',\n\t\t\t'maxValue',\n\t\t\t'cycle',\n\t\t] as const)\n\t\t\tif (\n\t\t\t\tpostcondition[key] !== undefined &&\n\t\t\t\tpostcondition[key] !== actual[key]\n\t\t\t)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`generated sequence ${address.name} postcondition differs`,\n\t\t\t\t);\n\t\treturn generatedPayload({ kind: 'sequence', ...row });\n\t}\n\tif (address.kind === 'extension') {\n\t\tconst postcondition = generatedPostcondition(step, address);\n\t\tif (postcondition.kind !== 'extension')\n\t\t\tthrow new Error(\n\t\t\t\t`generated extension ${address.name} has a non-extension structural postcondition`,\n\t\t\t);\n\t\tconst row = (\n\t\t\tawait executor.query(\n\t\t\t\t`SELECT extension.extversion AS version FROM pg_catalog.pg_extension extension WHERE extension.extname = $1`,\n\t\t\t\t[address.name],\n\t\t\t)\n\t\t).rows[0];\n\t\tif (!row)\n\t\t\tthrow new Error(\n\t\t\t\t`generated extension ${address.name} version postcondition differs`,\n\t\t\t);\n\t\tif (\n\t\t\tpostcondition.version !== undefined &&\n\t\t\tString(row.version) !== postcondition.version\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t`generated extension ${address.name} version postcondition differs`,\n\t\t\t);\n\t\treturn generatedPayload({\n\t\t\tkind: 'extension',\n\t\t\tversion: String(row.version),\n\t\t});\n\t}\n\tthrow new Error(`generated ${address.kind} has no declarable read-back`);\n}\n\nfunction containedBy(root: LedgerAddress, candidate: LedgerAddress): boolean {\n\tfor (let parent = candidate.parent; parent; parent = parent.parent) {\n\t\tif (\n\t\t\tparent.engine === root.engine &&\n\t\t\tparent.database === root.database &&\n\t\t\tparent.schema === root.schema &&\n\t\t\tparent.kind === root.kind &&\n\t\t\tparent.name === root.name\n\t\t)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nasync function destructiveEvidence(input: {\n\treadonly executor: LedgerQueryable;\n\treadonly address: LedgerAddress;\n\treadonly classification: import('@dbsp/types').ManagedStepClassification;\n\treadonly selection?: NormalizedManagedStep['selection'];\n\treadonly planDigest: string;\n\treadonly approval: ScopedApprovalSet;\n}): Promise<{\n\treadonly evidence: DestructiveAuthorityEvidence;\n\treadonly containment?: Awaited<\n\t\tReturnType<typeof readPgRemovalEffectsClosure>\n\t>;\n}> {\n\tconst { executor, address } = input;\n\tlet ownership: DestructiveAuthorityEvidence['ownership'] = 'uncomputable';\n\tlet catalogueIdentity: DestructiveAuthorityEvidence['catalogueIdentity'] =\n\t\t'catalogue-unavailable';\n\tlet ledgerLineage: DestructiveAuthorityEvidence['ledgerLineage'] =\n\t\t'unreadable';\n\ttry {\n\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\texecutor,\n\t\t\thome(address),\n\t\t\taddress,\n\t\t);\n\t\tconst projection = projectLedgerChain(chain);\n\t\townership =\n\t\t\tprojection.kind === 'projected-ledger-chain'\n\t\t\t\t? projection.stableState === 'managed'\n\t\t\t\t\t? 'managed-by-me'\n\t\t\t\t\t: projection.stableState === 'unknown'\n\t\t\t\t\t\t? 'unknown'\n\t\t\t\t\t\t: 'blocked'\n\t\t\t\t: 'uncomputable';\n\t\tconst live = await readPgCatalogueIdentity(executor, address);\n\t\tconst recorded = chain.terminalMember?.catalogueIdentity;\n\t\tcatalogueIdentity = !live\n\t\t\t? 'object-absent'\n\t\t\t: recorded === undefined\n\t\t\t\t? 'differs'\n\t\t\t\t: isDeepStrictEqual(live.catalogueIdentity, recorded)\n\t\t\t\t\t? 'matches-recorded'\n\t\t\t\t\t: 'differs';\n\t\tconst currency = await readPgLedgerScopeCurrency(executor, home(address));\n\t\tledgerLineage =\n\t\t\tcurrency.kind === 'current' ? 'matches-database' : 'differs';\n\t} catch {\n\t\t// The authority table intentionally turns every unreadable live fact into a refusal.\n\t}\n\tlet containment:\n\t\t| Awaited<ReturnType<typeof readPgRemovalEffectsClosure>>\n\t\t| undefined;\n\tlet containmentOutcome: ContainmentClosureDestructiveOutcome | undefined;\n\tif (input.classification === 'removal') {\n\t\tcontainment = await readPgRemovalEffectsClosure({\n\t\t\texecutor,\n\t\t\troot: address,\n\t\t\tisManaged: (candidate) => managed(executor, candidate),\n\t\t});\n\t\tcontainmentOutcome = containment.kind;\n\t}\n\treturn {\n\t\tevidence: {\n\t\t\tdeclaration:\n\t\t\t\tinput.classification === 'removal'\n\t\t\t\t\t? input.selection?.kind === 'replacement'\n\t\t\t\t\t\t? 'replacement-requested-by-plan'\n\t\t\t\t\t\t: 'requires-removal'\n\t\t\t\t\t: 'requires-lossy-change',\n\t\t\t...(input.selection?.kind === 'replacement'\n\t\t\t\t? { replacementAddress: address }\n\t\t\t\t: {}),\n\t\t\townership,\n\t\t\tcatalogueIdentity,\n\t\t\toperatorAcceptance: acceptance(input.planDigest, input.approval),\n\t\t\t...(containmentOutcome === undefined\n\t\t\t\t? {}\n\t\t\t\t: { containment: containmentOutcome }),\n\t\t\t...(containment?.kind === 'reaches-unmanaged'\n\t\t\t\t? { containmentUnmanaged: containment.unmanaged }\n\t\t\t\t: {}),\n\t\t\t...(containment?.kind === 'undecidable'\n\t\t\t\t? { containmentReason: containment.reason }\n\t\t\t\t: {}),\n\t\t\tledgerLineage,\n\t\t},\n\t\t...(containment === undefined ? {} : { containment }),\n\t};\n}\n\n/**\n * Closure discovery is needed before the group can be reserved. It deliberately\n * does not decide destructive authority; the locked admission callback does.\n */\nasync function removalContainment(\n\texecutor: LedgerQueryable,\n\taddress: LedgerAddress,\n): Promise<Awaited<ReturnType<typeof readPgRemovalEffectsClosure>>> {\n\treturn readPgRemovalEffectsClosure({\n\t\texecutor,\n\t\troot: address,\n\t\tisManaged: (candidate) => managed(executor, candidate),\n\t});\n}\n\n/**\n * Executes the in-memory, just-presented generator material. It never reads\n * a generator run back by id: that persisted row remains review-only.\n */\nexport async function executeGeneratorPlan(input: {\n\treadonly pool: Pool;\n\t/** Bound by apply after validating the persisted durable manifest. */\n\treadonly manifest?: ValidatedManagedStepManifest;\n\t/** @deprecated Compatibility shim for direct fixtures; it is validated before use. */\n\treadonly plan?: { readonly steps: readonly unknown[] };\n\treadonly planDigest: string;\n\treadonly schema: string;\n\t/** Preserve scopes and trust roots until admission; never reduce to classes. */\n\treadonly approval?: ScopedApprovalSet;\n\t/** Durable witness minted while apply holds this run's journal lock. */\n\treadonly run: PgLockedRun;\n\t/** Appends the run-to-attempt mapping before any ledger claim may be opened. */\n\treadonly recordAttempt?: (executionId: string) => Promise<void>;\n\t/** Test-only admitted-path observation; absent from every CLI invocation. */\n\treadonly observer?: PgOutcomeCheckpointObserver;\n\t/** @deprecated Compatibility shim for old direct fixtures. */\n\treadonly accepts?: readonly string[];\n\treadonly replaces?: readonly string[];\n\treadonly runId: string;\n}): Promise<GeneratorExecutionResult> {\n\tconst validation = input.manifest\n\t\t? { ok: true as const, manifest: input.manifest }\n\t\t: validateNormalizedManagedStepManifest(\n\t\t\t\t(input.plan?.steps as readonly NormalizedManagedStep[]) ?? [],\n\t\t\t);\n\tif (!validation.ok)\n\t\treturn { outcome: 'execution-failed', detail: validation.detail };\n\tconst manifest = validation.manifest;\n\tconst approval: ScopedApprovalSet = input.approval ?? {\n\t\tapprovals: (input.accepts ?? []).map((value) => ({ class: value })),\n\t};\n\tconst completedStepKeys: string[] = [];\n\tlet destructiveRefusal: { readonly withheldAuthority: string } | undefined;\n\tlet destructiveClosureReplanRequired = false;\n\tconst partial = (detail: string): GeneratorExecutionResult =>\n\t\tcompletedStepKeys.length === 0\n\t\t\t? { outcome: 'execution-failed', detail }\n\t\t\t: {\n\t\t\t\t\toutcome: 'partially-applied',\n\t\t\t\t\tdetail,\n\t\t\t\t\tcompletedStepKeys,\n\t\t\t\t\tnotStartedStepKeys: managedSteps(manifest)\n\t\t\t\t\t\t.filter((step) => !completedStepKeys.includes(step.stepKey))\n\t\t\t\t\t\t.map((step) => step.stepKey),\n\t\t\t\t};\n\ttry {\n\t\tconst database = await databaseId(input.pool);\n\t\t// Reconciliation selects reservations by the persisted run identity. The\n\t\t// execution scope is deterministic for that run, never a disconnected UUID.\n\t\t// A persisted generator run identifies reviewed material, never a reusable\n\t\t// claim namespace. The caller has already refused any prior step-scoped\n\t\t// durable fact; a zero-event retry therefore gets a fresh attempt identity.\n\t\tconst executionId = `dbsp.generator.execution.${randomUUID()}`;\n\t\tawait input.recordAttempt?.(executionId);\n\t\tconst steps = managedSteps(manifest);\n\t\tfor (const step of steps) {\n\t\t\tif (step.lifecycle?.kind === 'adoption-refused')\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'adoption-refused',\n\t\t\t\t\tdetail: `declared adoption for ${step.address?.name ?? step.stepKey} refuses live shape mismatch`,\n\t\t\t\t};\n\t\t\tconst lifecycle = step.lifecycle;\n\t\t\tif (lifecycle?.kind !== 'adoption') continue;\n\t\t\tconst address = step.address;\n\t\t\tif (\n\t\t\t\t!address ||\n\t\t\t\t!step.expectedDeclaration ||\n\t\t\t\t!step.expectedCatalogueIdentity\n\t\t\t)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\tdetail: `adoption step ${step.stepKey} has incomplete normalized material`,\n\t\t\t\t};\n\t\t\tconst preflight = await preflightPgDeclaredAdoption({\n\t\t\t\texecutor: input.pool,\n\t\t\t\thome: home(address),\n\t\t\t\taddress,\n\t\t\t\tdeclaration: step.expectedDeclaration,\n\t\t\t\texpectedCatalogueIdentity: step.expectedCatalogueIdentity,\n\t\t\t\tshapeMatches: () =>\n\t\t\t\t\tadoptionShapeMatches(input.pool, input.schema, lifecycle.shape),\n\t\t\t});\n\t\t\tif (preflight.outcome !== 'ready' && preflight.outcome !== 'no-op')\n\t\t\t\treturn preflight.outcome === 'adoption-refused'\n\t\t\t\t\t? { outcome: 'adoption-refused', detail: preflight.detail }\n\t\t\t\t\t: { outcome: 'execution-failed', detail: preflight.detail };\n\t\t}\n\t\tconst replacementSelectors = steps\n\t\t\t.filter((step) => step.selection?.kind === 'replacement')\n\t\t\t.map((step) => step.selection?.selector)\n\t\t\t.filter((selector): selector is string => selector !== undefined);\n\t\tif (replacementSelectors.length > 0 && !input.replaces?.length)\n\t\t\treturn {\n\t\t\t\toutcome: 'destructive-authority-refused',\n\t\t\t\tdetail:\n\t\t\t\t\t'replacement requires a named --replace selector from the reviewed plan',\n\t\t\t\trefusal: { withheldAuthority: 'destructive declaration authority' },\n\t\t\t};\n\t\tfor (const selector of input.replaces ?? [])\n\t\t\tif (\n\t\t\t\t!replacementSelectors.some((reviewed) =>\n\t\t\t\t\tmatchesReviewedReplacementSelector(reviewed, selector),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'destructive-authority-refused',\n\t\t\t\t\tdetail: `replacement ${selector} was not requested by the reviewed plan`,\n\t\t\t\t\trefusal: { withheldAuthority: 'destructive declaration authority' },\n\t\t\t\t};\n\t\tif (\n\t\t\treplacementSelectors.some(\n\t\t\t\t(reviewed) =>\n\t\t\t\t\t!input.replaces?.some((provided) =>\n\t\t\t\t\t\tmatchesReviewedReplacementSelector(reviewed, provided),\n\t\t\t\t\t),\n\t\t\t)\n\t\t)\n\t\t\treturn {\n\t\t\t\toutcome: 'selection-incomplete',\n\t\t\t\tdetail:\n\t\t\t\t\t'replacement selection does not cover every reviewed replacement',\n\t\t\t};\n\t\tfor (const step of steps) {\n\t\t\tif (step.lifecycle?.kind === 'adoption-refused') continue;\n\t\t\tif (step.lifecycle?.kind === 'adoption') {\n\t\t\t\tconst lifecycle = step.lifecycle;\n\t\t\t\tconst address = step.address;\n\t\t\t\tif (\n\t\t\t\t\t!address ||\n\t\t\t\t\t!step.expectedDeclaration ||\n\t\t\t\t\t!step.expectedCatalogueIdentity\n\t\t\t\t)\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\t\tdetail: `adoption step ${step.stepKey} has incomplete normalized material`,\n\t\t\t\t\t};\n\t\t\t\tconst adopted = await executePgDeclaredAdoption({\n\t\t\t\t\texecutor: input.pool,\n\t\t\t\t\trun: input.run,\n\t\t\t\t\tmanifest,\n\t\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\t\tapproval,\n\t\t\t\t\tstep,\n\t\t\t\t\thome: home(address),\n\t\t\t\t\taddress,\n\t\t\t\t\tdeclaration: step.expectedDeclaration,\n\t\t\t\t\texpectedCatalogueIdentity: step.expectedCatalogueIdentity,\n\t\t\t\t\tshapeMatches: () =>\n\t\t\t\t\t\tadoptionShapeMatches(input.pool, input.schema, lifecycle.shape),\n\t\t\t\t\t...(input.observer === undefined ? {} : { observer: input.observer }),\n\t\t\t\t});\n\t\t\t\tif (adopted.outcome === 'completed' || adopted.outcome === 'no-op') {\n\t\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn adopted.outcome === 'adoption-refused'\n\t\t\t\t\t? { outcome: 'adoption-refused', detail: adopted.detail }\n\t\t\t\t\t: { outcome: 'execution-failed', detail: adopted.detail };\n\t\t\t}\n\t\t\tif (step.lifecycle?.kind === 'readdress') {\n\t\t\t\tconst result = await executePgPersistedTableReaddress({\n\t\t\t\t\texecutor: input.pool,\n\t\t\t\t\trun: input.run,\n\t\t\t\t\tmanifest,\n\t\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\t\tapproval,\n\t\t\t\t\tstep,\n\t\t\t\t\tdatabase,\n\t\t\t\t\ttargetSchema: input.schema,\n\t\t\t\t\t...(input.observer === undefined ? {} : { observer: input.observer }),\n\t\t\t\t});\n\t\t\t\tif (result.outcome === 'completed' || result.outcome === 'no-op') {\n\t\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tif (step.statementBundle.statements.length === 0) {\n\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst address = step.address ?? step.closure?.root;\n\t\t\tif (!address)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\tdetail: `managed step ${step.stepKey} has no address`,\n\t\t\t\t};\n\t\t\tconst plannedClaimKey = step.plannedClaimKeys[0];\n\t\t\tif (!plannedClaimKey)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\tdetail: `managed step ${step.stepKey} has no planned claim key`,\n\t\t\t\t};\n\t\t\tif (\n\t\t\t\tstep.classification === 'non-destructive' &&\n\t\t\t\tstep.requiresVacancy &&\n\t\t\t\t(await alreadyAppliedCreation(input.pool, address))\n\t\t\t) {\n\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst claimKind: LedgerClaimKind = step.claimKind;\n\t\t\tconst rootClaimId = outcomeClaimId(executionId, plannedClaimKey, address);\n\t\t\tconst claim = {\n\t\t\t\tclaimId: rootClaimId,\n\t\t\t\tclaimSpecies: 'sql-bearing' as const,\n\t\t\t\texecutionId,\n\t\t\t\tplannedClaimKey,\n\t\t\t\tclaimGroupId: rootClaimId,\n\t\t\t\trootClaimId,\n\t\t\t\taddress,\n\t\t\t\tclaimKind,\n\t\t\t\tstatementBundle: step.statementBundle,\n\t\t\t\trequiresVacancy: step.requiresVacancy,\n\t\t\t};\n\t\t\tconst baseReservation = {\n\t\t\t\taddress,\n\t\t\t\tclaimKind,\n\t\t\t\texecutionId,\n\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\thomeLedger: home(address),\n\t\t\t};\n\t\t\tif (step.classification === 'non-destructive') {\n\t\t\t\tconst result = await executePgAdmittedOperation(input.pool, {\n\t\t\t\t\trun: input.run,\n\t\t\t\t\tapproval,\n\t\t\t\t\tmanifest,\n\t\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\t\toperation: {\n\t\t\t\t\t\tkind: 'single-outcome',\n\t\t\t\t\t\trequest: {\n\t\t\t\t\t\t\tplan: claim,\n\t\t\t\t\t\t\treservations: [baseReservation],\n\t\t\t\t\t\t\tresolution: {\n\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(claim.claimId, 'observed'),\n\t\t\t\t\t\t\t\teventKind: 'observed',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t// Transactional DDL is visible only on the admitted session until\n\t\t\t\t\t\t\t// its terminal ledger fact commits with it.\n\t\t\t\t\t\t\treadBack: async (session) =>\n\t\t\t\t\t\t\t\treadGeneratedPostcondition(session, step, address),\n\t\t\t\t\t\t\trecordCatalogueIdentity: true,\n\t\t\t\t\t\t\t...(input.observer === undefined\n\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t: { observer: input.observer }),\n\t\t\t\t\t\t\tvacancy: async (executor: LedgerQueryable) =>\n\t\t\t\t\t\t\t\t(await readPgCatalogueIdentity(executor, address))\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tkind: 'occupied',\n\t\t\t\t\t\t\t\t\t\t\treason: `creation claim ${claim.claimId} refuses occupied live address ${address.name}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: { kind: 'vacant' },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (result.kind === 'outcome-recovery-required')\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutcome: 'recovery-required',\n\t\t\t\t\t\tclaimId: result.claimId,\n\t\t\t\t\t\tdetail: `claim ${result.claimId} remains open and requires recovery: ${result.reason}`,\n\t\t\t\t\t};\n\t\t\t\tif ('reason' in result) return partial(result.reason);\n\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst containment =\n\t\t\t\tstep.classification === 'removal'\n\t\t\t\t\t? await removalContainment(input.pool, address)\n\t\t\t\t\t: undefined;\n\t\t\tconst closureMembers = new Map<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\treadonly address: LedgerAddress;\n\t\t\t\t\treadonly plannedClaimKey: string;\n\t\t\t\t}\n\t\t\t>();\n\t\t\t// A normalized closure is digest-covered execution material. Its\n\t\t\t// members must receive their own claims and terminal `absent` facts;\n\t\t\t// PostgreSQL's single DROP statement does not make those ledger facts\n\t\t\t// optional. The live closure remains the authority-time cascade guard\n\t\t\t// and supplements legacy root-only manifests.\n\t\t\tfor (const member of step.closure?.members ?? []) {\n\t\t\t\tclosureMembers.set(ledgerAddressKey(member.address), {\n\t\t\t\t\taddress: member.address,\n\t\t\t\t\tplannedClaimKey: member.plannedClaimKey,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (containment?.kind === 'all-contained-or-managed') {\n\t\t\t\tfor (const effect of containment.effects) {\n\t\t\t\t\tif (effect.internalOwned) continue;\n\t\t\t\t\tif (!containedBy(address, effect.address)) continue;\n\t\t\t\t\tif (!(await managed(input.pool, effect.address))) continue;\n\t\t\t\t\tconst key = ledgerAddressKey(effect.address);\n\t\t\t\t\tif (closureMembers.has(key)) continue;\n\t\t\t\t\tclosureMembers.set(key, {\n\t\t\t\t\t\taddress: effect.address,\n\t\t\t\t\t\tplannedClaimKey: `closure:${effect.address.kind}:${effect.address.name}`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst containedClaims: Array<{\n\t\t\t\treadonly plan: CascadeCoveredOutcomeClaimPlan & {\n\t\t\t\t\treadonly plannedClaimKey: string;\n\t\t\t\t};\n\t\t\t\treadonly reservation: typeof baseReservation;\n\t\t\t}> = [];\n\t\t\tfor (const member of closureMembers.values()) {\n\t\t\t\tconst effect = member.address;\n\t\t\t\tconst childClaimId = outcomeClaimId(\n\t\t\t\t\texecutionId,\n\t\t\t\t\tplannedClaimKey,\n\t\t\t\t\teffect,\n\t\t\t\t\tmember.plannedClaimKey,\n\t\t\t\t);\n\t\t\t\tconst childReservation = {\n\t\t\t\t\t...baseReservation,\n\t\t\t\t\taddress: effect as typeof address,\n\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t};\n\t\t\t\tcontainedClaims.push({\n\t\t\t\t\tplan: {\n\t\t\t\t\t\t...claim,\n\t\t\t\t\t\tclaimId: childClaimId,\n\t\t\t\t\t\tclaimSpecies: 'cascade-covered',\n\t\t\t\t\t\taddress: effect as typeof address,\n\t\t\t\t\t\tplannedClaimKey: member.plannedClaimKey,\n\t\t\t\t\t\t// Each member contributes only its terminal absence fact; SQL is\n\t\t\t\t\t\t// exclusively carried by the destructive root manifest claim.\n\t\t\t\t\t\tstatementBundle: { statements: [] },\n\t\t\t\t\t},\n\t\t\t\t\treservation: childReservation,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst admitRequest = {\n\t\t\t\tplan: claim,\n\t\t\t\treservations: [baseReservation],\n\t\t\t\tmembers: containedClaims.map(({ plan, reservation }) => ({\n\t\t\t\t\tplan,\n\t\t\t\t\treservations: [reservation],\n\t\t\t\t})),\n\t\t\t\tdestructiveDecision: async (executor: LedgerQueryable) => {\n\t\t\t\t\tconst lockedAuthority = await destructiveEvidence({\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\taddress,\n\t\t\t\t\t\tclassification: step.classification,\n\t\t\t\t\t\tselection: step.selection,\n\t\t\t\t\t\tplanDigest: input.planDigest,\n\t\t\t\t\t\tapproval,\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\tstep.classification === 'removal' &&\n\t\t\t\t\t\t(containment?.kind !== 'all-contained-or-managed' ||\n\t\t\t\t\t\t\tlockedAuthority.containment?.kind !==\n\t\t\t\t\t\t\t\t'all-contained-or-managed' ||\n\t\t\t\t\t\t\tcontainment.closureDigest !==\n\t\t\t\t\t\t\t\tlockedAuthority.containment.closureDigest)\n\t\t\t\t\t) {\n\t\t\t\t\t\tdestructiveClosureReplanRequired = true;\n\t\t\t\t\t\tconst decision = decideDestructiveDecision(\n\t\t\t\t\t\t\t{ kind: 'removal', address },\n\t\t\t\t\t\t\t{ ...lockedAuthority.evidence, containment: 'undecidable' },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (decision.kind === 'destructive-decision-refused')\n\t\t\t\t\t\t\tdestructiveRefusal = {\n\t\t\t\t\t\t\t\twithheldAuthority:\n\t\t\t\t\t\t\t\t\twithheldDestructiveAuthority({\n\t\t\t\t\t\t\t\t\t\t...lockedAuthority.evidence,\n\t\t\t\t\t\t\t\t\t\tcontainment: 'undecidable',\n\t\t\t\t\t\t\t\t\t}) ?? 'destructive containment authority',\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\treturn decision;\n\t\t\t\t\t}\n\t\t\t\t\tconst decision = decideDestructiveDecision(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind:\n\t\t\t\t\t\t\t\tstep.classification === 'removal'\n\t\t\t\t\t\t\t\t\t? 'removal'\n\t\t\t\t\t\t\t\t\t: 'data-destructive',\n\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t...(step.classification === 'removal' &&\n\t\t\t\t\t\t\tlockedAuthority.containment?.kind === 'all-contained-or-managed'\n\t\t\t\t\t\t\t\t? { closureDigest: lockedAuthority.containment.closureDigest }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tlockedAuthority.evidence,\n\t\t\t\t\t);\n\t\t\t\t\tif (decision.kind === 'destructive-decision-refused')\n\t\t\t\t\t\tdestructiveRefusal = {\n\t\t\t\t\t\t\twithheldAuthority:\n\t\t\t\t\t\t\t\twithheldDestructiveAuthority(lockedAuthority.evidence) ??\n\t\t\t\t\t\t\t\t'destructive authority',\n\t\t\t\t\t\t};\n\t\t\t\t\treturn decision;\n\t\t\t\t},\n\t\t\t\t...(input.observer === undefined ? {} : { observer: input.observer }),\n\t\t\t};\n\t\t\tconst executed = (await executePgAdmittedOperation(input.pool, {\n\t\t\t\trun: input.run,\n\t\t\t\tapproval,\n\t\t\t\tmanifest,\n\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\toperation: {\n\t\t\t\t\tkind: 'destructive-outcome',\n\t\t\t\t\trequest: admitRequest,\n\t\t\t\t\treadBackAndResolve: async (session) => {\n\t\t\t\t\t\tconst live = await readPgCatalogueIdentity(session, address);\n\t\t\t\t\t\tconst survivors: LedgerAddress[] =\n\t\t\t\t\t\t\tstep.classification === 'removal' && live ? [address] : [];\n\t\t\t\t\t\tconst childLives = await Promise.all(\n\t\t\t\t\t\t\tcontainedClaims.map(async (child) => ({\n\t\t\t\t\t\t\t\tchild,\n\t\t\t\t\t\t\t\tlive: await readPgCatalogueIdentity(\n\t\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\t\tchild.plan.address,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tfor (const { child, live: childLive } of childLives)\n\t\t\t\t\t\t\tif (childLive) survivors.push(child.plan.address);\n\t\t\t\t\t\tif (survivors.length > 0) {\n\t\t\t\t\t\t\tconst survivorNames = survivors.map(\n\t\t\t\t\t\t\t\t(survivor) =>\n\t\t\t\t\t\t\t\t\t`${survivor.kind} ${survivor.schema ?? '<database>'}.${survivor.name}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst survivorObservation = {\n\t\t\t\t\t\t\t\tvalue: { survivors: survivorNames },\n\t\t\t\t\t\t\t\tdigest: createHash('sha256')\n\t\t\t\t\t\t\t\t\t.update(JSON.stringify(survivorNames))\n\t\t\t\t\t\t\t\t\t.digest('hex'),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\t\tmembers: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttarget: home(address),\n\t\t\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(\n\t\t\t\t\t\t\t\t\t\t\t\tclaim.claimId,\n\t\t\t\t\t\t\t\t\t\t\t\t'indeterminate',\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: claim.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimGroupId,\n\t\t\t\t\t\t\t\t\t\t\trootClaimId: claim.rootClaimId,\n\t\t\t\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\t\t\t\teventKind: 'indeterminate' as const,\n\t\t\t\t\t\t\t\t\t\t\tobserved: survivorObservation,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t...containedClaims.map((child) => ({\n\t\t\t\t\t\t\t\t\t\ttarget: home(child.plan.address),\n\t\t\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(\n\t\t\t\t\t\t\t\t\t\t\t\tchild.plan.claimId,\n\t\t\t\t\t\t\t\t\t\t\t\t'indeterminate',\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: child.plan.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimId,\n\t\t\t\t\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\t\t\t\t\taddress: child.plan.address,\n\t\t\t\t\t\t\t\t\t\t\teventKind: 'indeterminate' as const,\n\t\t\t\t\t\t\t\t\t\t\tobserved: survivorObservation,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\treservations: [\n\t\t\t\t\t\t\t\t\tbaseReservation,\n\t\t\t\t\t\t\t\t\t...containedClaims.map(({ reservation }) => reservation),\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst terminals: Array<{\n\t\t\t\t\t\t\treadonly target: LedgerHome;\n\t\t\t\t\t\t\treadonly member: Omit<\n\t\t\t\t\t\t\t\tLedgerChainMember,\n\t\t\t\t\t\t\t\t'controller' | 'recordedAt'\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t}> = [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttarget: home(address),\n\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(\n\t\t\t\t\t\t\t\t\t\tclaim.claimId,\n\t\t\t\t\t\t\t\t\t\tstep.classification === 'removal' ? 'absent' : 'observed',\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\tplannedClaimKey: claim.plannedClaimKey,\n\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimGroupId,\n\t\t\t\t\t\t\t\t\trootClaimId: claim.rootClaimId,\n\t\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\t\teventKind:\n\t\t\t\t\t\t\t\t\t\tstep.classification === 'removal' ? 'absent' : 'observed',\n\t\t\t\t\t\t\t\t\t// The append protocol reads this address's terminal on its\n\t\t\t\t\t\t\t\t\t// pinned transaction session after the post-DDL read-back.\n\t\t\t\t\t\t\t\t\t...(live?.catalogueIdentity\n\t\t\t\t\t\t\t\t\t\t? { catalogueIdentity: live.catalogueIdentity }\n\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t\t...(step.classification === 'removal'\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: { observed: observed(address) }),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t];\n\t\t\t\t\t\tfor (const child of containedClaims) {\n\t\t\t\t\t\t\tterminals.push({\n\t\t\t\t\t\t\t\ttarget: home(child.plan.address),\n\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(child.plan.claimId, 'absent'),\n\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\tplannedClaimKey: child.plan.plannedClaimKey,\n\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimId,\n\t\t\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\t\t\taddress: child.plan.address,\n\t\t\t\t\t\t\t\t\teventKind: 'absent' as const,\n\t\t\t\t\t\t\t\t\tpredecessor: child.plan.claimId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\tmembers: terminals,\n\t\t\t\t\t\t\treservations: [\n\t\t\t\t\t\t\t\tbaseReservation,\n\t\t\t\t\t\t\t\t...containedClaims.map(({ reservation }) => reservation),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})) as\n\t\t\t\t| { readonly kind: 'executed-destructive-outcome' }\n\t\t\t\t| { readonly kind: 'outcome-protocol-refused'; readonly reason: string }\n\t\t\t\t| { readonly kind: 'outcome-protocol-pending'; readonly reason: string }\n\t\t\t\t| {\n\t\t\t\t\t\treadonly kind: 'outcome-transport-ambiguous';\n\t\t\t\t\t\treadonly reason: string;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\treadonly kind: 'outcome-recovery-required';\n\t\t\t\t\t\treadonly claimId: string;\n\t\t\t\t\t\treadonly reason: string;\n\t\t\t\t };\n\t\t\tif (executed.kind === 'outcome-recovery-required')\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'recovery-required',\n\t\t\t\t\tclaimId: executed.claimId,\n\t\t\t\t\tdetail: `claim ${executed.claimId} remains open and requires recovery: ${executed.reason}`,\n\t\t\t\t};\n\t\t\tif (executed.kind === 'outcome-transport-ambiguous')\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\tdetail: executed.reason,\n\t\t\t\t};\n\t\t\tif (executed.kind === 'outcome-protocol-pending')\n\t\t\t\treturn partial(\n\t\t\t\t\t`destructive claim ${claim.claimId} remains pending after executing: ${executed.reason}`,\n\t\t\t\t);\n\t\t\tif (executed.kind !== 'executed-destructive-outcome')\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'destructive-authority-refused',\n\t\t\t\t\tdetail: destructiveClosureReplanRequired\n\t\t\t\t\t\t? `${executed.reason}; destructive closure changed under lock; replan required`\n\t\t\t\t\t\t: executed.reason,\n\t\t\t\t\t...(destructiveRefusal === undefined &&\n\t\t\t\t\twithheldDestructiveAuthorityFromReason(executed.reason) === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\trefusal: destructiveRefusal ?? {\n\t\t\t\t\t\t\t\t\twithheldAuthority:\n\t\t\t\t\t\t\t\t\t\twithheldDestructiveAuthorityFromReason(executed.reason) ??\n\t\t\t\t\t\t\t\t\t\t'destructive authority',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t}\n\t\treturn { outcome: 'completed' };\n\t} catch (error) {\n\t\treturn partial(error instanceof Error ? error.message : String(error));\n\t}\n}\n","/**\n * The schema-differ producer used by the no-argument apply command.\n *\n * This deliberately lives beside `apply`, rather than in the transition\n * planner: generated removals have a different replay contract. The emitted\n * document is nevertheless persisted in the same journal and digest domain so\n * that it is inspectable before an operator makes a fresh live-state decision.\n */\nimport { createHash, randomUUID } from 'node:crypto';\nimport {\n\tassertDeclarableChangeKind,\n\tclassifyGeneratedMutation,\n\tcomparePgsqlDatabaseSchema,\n\tcreatePgsqlAdapter,\n\tcreatePgsqlGeneratedManagedStep,\n\tcreatePgTransitionLessor,\n\tcreatePgTransitionRunPersister,\n\tgeneratedPostconditionForChange,\n\tgenerateMigrationSQL,\n\treadPgCatalogueIdentity,\n\trenderPgTableReaddressStatements,\n\ttype SchemaDiff,\n} from '@dbsp/adapter-pgsql';\nimport type { InProcessProvenPlan } from '@dbsp/core';\nimport {\n\tacquireTransitionLease,\n\ttransitionPlanDigest,\n\tvalidateNormalizedManagedStepManifest,\n} from '@dbsp/core';\nimport type {\n\tCatalogueIdentity,\n\tLedgerAddress,\n\tLedgerPayload,\n\tNormalizedManagedStep,\n\tPlanAssessment,\n\tTableIR,\n\tTableReaddressDeclaration,\n\tTransitionRunMetadata,\n} from '@dbsp/types';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { loadSchema } from '../utils/schema-loader.js';\nimport type { PlanResult } from './plan.js';\n\nexport interface GeneratorPlanMaterial {\n\treadonly kind: 'schema-differ-generator';\n\t/** Digest-covered execution context captured with the reviewed generator run. */\n\treadonly planningSchema?: string;\n\t/** Diagnostic provenance only. Execution reads plan.steps, never this list. */\n\treadonly changes: readonly {\n\t\treadonly kind: string;\n\t\treadonly table: string;\n\t\treadonly column?: string;\n\t\treadonly classification: ReturnType<typeof classifyGeneratedMutation>;\n\t\treadonly details: string;\n\t\t/** Exact SQL attributed to this change for its token-gated claim. */\n\t\treadonly statements: readonly string[];\n\t\t/** Present only for the paired table re-addressing executor. */\n\t\treadonly readdress?: TableReaddressDeclaration;\n\t\t/** Present only for a reviewed declaration to adopt an existing table. */\n\t\treadonly adoption?: {\n\t\t\treadonly declaration: LedgerPayload;\n\t\t\treadonly shape: TableIR;\n\t\t\t/** Physical identity observed with the reviewed live shape. */\n\t\t\treadonly catalogueIdentity: CatalogueIdentity;\n\t\t};\n\t\t/** A digest-covered replacement is executed only when --replace names it. */\n\t\treadonly replacement?: {\n\t\t\treadonly retireStatements: readonly string[];\n\t\t\treadonly createStatements: readonly string[];\n\t\t};\n\t}[];\n}\n\n/** Extra persisted material is digest-covered; the regular applier never executes it. */\nexport type GeneratorDurablePlan = InProcessProvenPlan & {\n\treadonly generator: GeneratorPlanMaterial;\n};\n\nfunction digest(value: unknown): string {\n\treturn createHash('sha256').update(JSON.stringify(value)).digest('hex');\n}\n\nfunction adoptionDeclaration(table: TableIR): LedgerPayload {\n\t// The live differ is the shape comparator. Persist the exact authored table\n\t// shape, rather than a boolean that could later be reinterpreted.\n\tconst value = JSON.parse(\n\t\tJSON.stringify({ kind: 'table', name: table.name, shape: table }),\n\t) as LedgerPayload['value'];\n\treturn { value, digest: digest(value) };\n}\n\nfunction replacementStatements(table: TableIR, schema: string) {\n\tconst quote = (value: string) => `\"${value.replaceAll('\"', '\"\"')}\"`;\n\tconst createDiff: SchemaDiff = {\n\t\tchanges: [\n\t\t\t{\n\t\t\t\tkind: 'create_table',\n\t\t\t\ttable: table.name,\n\t\t\t\tdestructive: false,\n\t\t\t\tdetails: `Create table \"${table.name}\"`,\n\t\t\t\tmeta: { table },\n\t\t\t},\n\t\t],\n\t\thasDestructive: false,\n\t\tsummary: {\n\t\t\ttables: { added: 1, dropped: 0 },\n\t\t\tcolumns: { added: 0, dropped: 0, altered: 0 },\n\t\t\tindexes: { added: 0, dropped: 0 },\n\t\t\tconstraints: { added: 0, dropped: 0, altered: 0 },\n\t\t},\n\t};\n\treturn {\n\t\tretireStatements: [`DROP TABLE ${quote(schema)}.${quote(table.name)}`],\n\t\tcreateStatements: generateMigrationSQL(createDiff, {\n\t\t\tincludeDestructive: true,\n\t\t\tschemaName: schema,\n\t\t}),\n\t};\n}\n\n/** The paired executor sends only SQL that the persisted root step carries. */\nfunction readdressStatements(\n\tdatabase: string,\n\tschema: string,\n\tdeclaration: TableReaddressDeclaration,\n): readonly string[] {\n\tconst endpoint = (\n\t\tvalue: TableReaddressDeclaration['from'],\n\t): LedgerAddress => ({\n\t\tscope: 'schema',\n\t\tengine: 'postgresql',\n\t\tdatabase: value.database ?? database,\n\t\tschema: value.schema ?? schema,\n\t\tkind: value.kind ?? 'table',\n\t\tname: value.name,\n\t});\n\treturn renderPgTableReaddressStatements(\n\t\tendpoint(declaration.from),\n\t\tendpoint(declaration.to),\n\t);\n}\n\nfunction lifecycleStep(input: {\n\treadonly stepKey: string;\n\treadonly order: number;\n\treadonly database: string;\n\treadonly schema: string;\n\treadonly table: string;\n\treadonly classification: ReturnType<typeof classifyGeneratedMutation>;\n\treadonly statements?: readonly string[];\n\treadonly selection?: NormalizedManagedStep['selection'];\n\treadonly lifecycle?: NormalizedManagedStep['lifecycle'];\n\treadonly expectedDeclaration?: LedgerPayload;\n\treadonly expectedCatalogueIdentity?: CatalogueIdentity;\n\treadonly requiresVacancy?: boolean;\n\treadonly claimKind?: NormalizedManagedStep['claimKind'];\n}): NormalizedManagedStep {\n\t// Lifecycle-only table work has no SchemaChange, but it must pass the same\n\t// sole declarable boundary as ordinary diff-produced manifest steps.\n\tassertDeclarableChangeKind('create_table');\n\tconst address = {\n\t\tscope: 'schema' as const,\n\t\tengine: 'postgresql',\n\t\tdatabase: input.database,\n\t\tschema: input.schema,\n\t\tkind: 'table' as const,\n\t\tname: input.table,\n\t};\n\treturn {\n\t\tstepKey: input.stepKey,\n\t\torder: input.order,\n\t\tsegmentId: `generator-segment-${input.order}`,\n\t\t// Dependencies are assigned once the complete manifest exists. A numeric\n\t\t// order is not itself a step key: replacement emits two differently named\n\t\t// steps at adjacent orders.\n\t\tdependencyOrder: [],\n\t\taddress,\n\t\tclaimKind:\n\t\t\tinput.claimKind ??\n\t\t\t(input.classification === 'removal'\n\t\t\t\t? 'retire-intent'\n\t\t\t\t: input.classification === 'paired-readdress'\n\t\t\t\t\t? 'readdress-intent'\n\t\t\t\t\t: 'intent'),\n\t\tplannedClaimKeys: [`${input.stepKey}:root`],\n\t\tstatementBundle: {\n\t\t\tstatements: (input.statements ?? []).map((sql, ordinal) => ({\n\t\t\t\tordinal,\n\t\t\t\tsql,\n\t\t\t})),\n\t\t},\n\t\tclassification: input.classification,\n\t\trequiresVacancy: input.requiresVacancy ?? false,\n\t\t...(input.expectedDeclaration === undefined\n\t\t\t? {}\n\t\t\t: { expectedDeclaration: input.expectedDeclaration }),\n\t\t...(input.expectedCatalogueIdentity === undefined\n\t\t\t? {}\n\t\t\t: { expectedCatalogueIdentity: input.expectedCatalogueIdentity }),\n\t\t...(input.selection === undefined ? {} : { selection: input.selection }),\n\t\t...(input.lifecycle === undefined ? {} : { lifecycle: input.lifecycle }),\n\t\treplayPolicy:\n\t\t\tinput.classification === 'removal' ? 'fresh-live-only' : 'recorded',\n\t};\n}\n\n/**\n * The differ is deliberately sequential: each emitted step follows the exact\n * previously emitted step, including both halves of a reviewed replacement.\n * Assign the graph from concrete keys only after every lifecycle expansion.\n */\nexport function linearizeGeneratedManagedStepDependencies(\n\tsteps: readonly NormalizedManagedStep[],\n): readonly NormalizedManagedStep[] {\n\tconst linearized: NormalizedManagedStep[] = [];\n\tfor (const step of steps) {\n\t\tconst previous = linearized.at(-1);\n\t\tlinearized.push({\n\t\t\t...step,\n\t\t\tdependencyOrder: previous === undefined ? [] : [previous.stepKey],\n\t\t});\n\t}\n\treturn linearized;\n}\n\n/**\n * A durable manifest is an execution boundary, so lifecycle exclusivity is\n * checked again after deserialization instead of trusting its producer.\n */\nexport function persistedLifecycleDirectiveError(\n\tsteps: readonly NormalizedManagedStep[],\n): string | undefined {\n\tconst directivesByTable = new Map<string, Set<string>>();\n\tfor (const step of steps) {\n\t\tconst directive = step.selection?.kind;\n\t\tif (\n\t\t\tdirective !== 'adoption' &&\n\t\t\tdirective !== 'replacement' &&\n\t\t\tdirective !== 'readdress'\n\t\t)\n\t\t\tcontinue;\n\t\tconst address = step.address ?? step.closure?.root;\n\t\tif (address?.kind !== 'table') continue;\n\t\tconst key = [\n\t\t\taddress.engine,\n\t\t\taddress.database,\n\t\t\taddress.schema ?? '',\n\t\t\taddress.name,\n\t\t].join('\\u0000');\n\t\tconst directives = directivesByTable.get(key) ?? new Set<string>();\n\t\tdirectives.add(directive);\n\t\tdirectivesByTable.set(key, directives);\n\t\tif (directives.size > 1)\n\t\t\treturn `persisted lifecycle for ${address.name} cannot set ${[...directives].sort().join(' and ')} together`;\n\t}\n\treturn undefined;\n}\n\nfunction declaredLifecycleDirectiveError(table: TableIR): string | undefined {\n\tconst directives = [\n\t\ttable.adopt === true ? 'adopt' : undefined,\n\t\ttable.replace === true ? 'replace' : undefined,\n\t\ttable.readdress === undefined ? undefined : 'readdress',\n\t].filter((directive): directive is string => directive !== undefined);\n\treturn directives.length > 1\n\t\t? `declared lifecycle for ${table.name} cannot set ${directives.join(' and ')} together`\n\t\t: undefined;\n}\n\nfunction assessment(): PlanAssessment {\n\treturn {\n\t\tdecision: 'applicable',\n\t\tassurance: 'established',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'none',\n\t\treasons: [],\n\t};\n}\n\n/** `SchemaChange.table` is overloaded for non-table resources; never use it alone. */\nfunction changeTargetsDeclaredTable(\n\tchange: SchemaDiff['changes'][number],\n\ttable: string,\n): boolean {\n\tif (change.table !== table) return false;\n\treturn !new Set([\n\t\t'create_extension',\n\t\t'drop_extension',\n\t\t'create_enum',\n\t\t'drop_enum',\n\t\t'alter_enum_add_value',\n\t\t'create_sequence',\n\t\t'drop_sequence',\n\t\t'alter_sequence',\n\t]).has(change.kind);\n}\n\nfunction requiredAdoptionIdentity(\n\tidentities: ReadonlyMap<string, CatalogueIdentity>,\n\ttable: string,\n): CatalogueIdentity {\n\tconst identity = identities.get(table);\n\tif (!identity)\n\t\tthrow new Error(`declared adoption for ${table} has no live identity`);\n\treturn identity;\n}\n\nfunction asDurableGeneratorPlan(\n\tmaterial: GeneratorPlanMaterial,\n\tsteps: readonly NormalizedManagedStep[],\n): GeneratorDurablePlan {\n\tconst validation = validateNormalizedManagedStepManifest(steps);\n\tif (!validation.ok)\n\t\tthrow new Error(\n\t\t\t`generator planning refuses invalid managed-step manifest: ${validation.detail}`,\n\t\t);\n\treturn {\n\t\tobservations: [],\n\t\tclaims: [],\n\t\tassumptions: [],\n\t\tpreconditions: [],\n\t\tsegments: [],\n\t\t// Persist exactly the canonical manifest that the digest covers. The brand\n\t\t// itself is in-memory only; its normalized step payload is durable JSON.\n\t\tsteps: validation.manifest.steps,\n\t\tpostconditions: [],\n\t\tgenerator: material,\n\t} as unknown as GeneratorDurablePlan;\n}\n\nfunction render(\n\tplan: { readonly steps: readonly NormalizedManagedStep[] },\n\tplanDigest: string,\n): string {\n\tconst destructive = plan.steps.filter(\n\t\t(step) => step.classification !== 'non-destructive',\n\t);\n\treturn [\n\t\t'-- dbsp schema-differ generator plan; apply by id executes this exact normalized manifest unless a removal requires fresh live planning.',\n\t\t...plan.steps.flatMap((step) => [\n\t\t\t`-- ${step.classification}: ${step.stepKey}`,\n\t\t\t...step.statementBundle.statements.map((statement) =>\n\t\t\t\tstatement.sql.endsWith(';') ? statement.sql : `${statement.sql};`,\n\t\t\t),\n\t\t]),\n\t\t...(destructive.length === 0\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`-- destructive acceptance required: --accept destructive-plan-accepted:${planDigest}`,\n\t\t\t\t]),\n\t].join('\\n');\n}\n\nasync function databaseId(pool: Pool): Promise<string> {\n\tconst result = await pool.query('SELECT current_database() AS database_id');\n\tconst value = result.rows[0]?.database_id;\n\tif (typeof value !== 'string' || value.length === 0)\n\t\tthrow new Error(\n\t\t\t'schema-differ generator could not read current database identity',\n\t\t);\n\treturn value;\n}\n\n/**\n * Produce and (unless previewing) persist the differ's full mutation set.\n * Every change is classified before it can reach the rendered statement list.\n */\nexport async function runGeneratorPlan(input: {\n\treadonly db: string;\n\treadonly schemaFile: string;\n\treadonly schema?: string;\n\treadonly dryRun?: boolean;\n}): Promise<PlanResult> {\n\tconst loaded = await loadSchema(input.schemaFile);\n\tconst { pool } = await createDbConnection(input.db);\n\ttry {\n\t\tconst schema = input.schema ?? 'public';\n\t\tconst diff = await comparePgsqlDatabaseSchema(\n\t\t\tcreatePgsqlAdapter(pool),\n\t\t\tloaded.model,\n\t\t\t{\n\t\t\t\tschema,\n\t\t\t\t// `apply --schema` owns one schema. Extensions are database-scoped,\n\t\t\t\t// so an extension not declared by this schema must not become a\n\t\t\t\t// schema-plan removal merely because it is installed in the database.\n\t\t\t\tignoreUnmanagedExtensions: true,\n\t\t\t\t...(loaded.dbCasing ? { dbCasing: loaded.dbCasing } : {}),\n\t\t\t},\n\t\t);\n\t\tconst declaredLifecycleWork = [...loaded.model.tables.values()].some(\n\t\t\t(table) =>\n\t\t\t\ttable.adopt === true ||\n\t\t\t\ttable.replace === true ||\n\t\t\t\ttable.readdress !== undefined,\n\t\t);\n\t\tconst lifecycleError = [...loaded.model.tables.values()]\n\t\t\t.map(declaredLifecycleDirectiveError)\n\t\t\t.find((detail) => detail !== undefined);\n\t\tif (lifecycleError) throw new Error(lifecycleError);\n\t\tconst readdressRefusal = diff.changes.find(\n\t\t\t(change) =>\n\t\t\t\tchange.kind === 'readdress_table' &&\n\t\t\t\t(change.meta?.readdressAssessment === 'source-missing' ||\n\t\t\t\t\tchange.meta?.readdressAssessment === 'target-occupied'),\n\t\t);\n\t\tif (readdressRefusal)\n\t\t\tthrow new Error(\n\t\t\t\t`generator planning refuses ${readdressRefusal.details}; no re-address manifest was created`,\n\t\t\t);\n\t\tif (diff.changes.length === 0 && !declaredLifecycleWork) {\n\t\t\treturn {\n\t\t\t\tcompareKind: 'no-drift',\n\t\t\t\tproveKind: 'no-drift',\n\t\t\t\tassessment: {\n\t\t\t\t\t...assessment(),\n\t\t\t\t\tdecision: 'inapplicable',\n\t\t\t\t\tlifecycle: 'completed',\n\t\t\t\t},\n\t\t\t\tpersisted: false,\n\t\t\t\trunId: null,\n\t\t\t\tplanDigest: null,\n\t\t\t};\n\t\t}\n\t\tconst adoptionMismatches = new Set(\n\t\t\t[...loaded.model.tables.values()]\n\t\t\t\t.filter(\n\t\t\t\t\t(table) =>\n\t\t\t\t\t\ttable.adopt === true &&\n\t\t\t\t\t\tdiff.changes.some((change) =>\n\t\t\t\t\t\t\tchangeTargetsDeclaredTable(change, table.name),\n\t\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.map((table) => table.name),\n\t\t);\n\t\tconst database = await databaseId(pool);\n\t\tconst adoptionIdentities = new Map<string, CatalogueIdentity>();\n\t\tfor (const table of loaded.model.tables.values()) {\n\t\t\tif (table.adopt !== true || adoptionMismatches.has(table.name)) continue;\n\t\t\tconst live = await readPgCatalogueIdentity(pool, {\n\t\t\t\tengine: 'postgresql',\n\t\t\t\tdatabase,\n\t\t\t\tschema: input.schema ?? 'public',\n\t\t\t\tkind: 'table',\n\t\t\t\tname: table.name,\n\t\t\t});\n\t\t\tif (!live?.catalogueIdentity)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`declared adoption for ${table.name} refuses absent live identity`,\n\t\t\t\t);\n\t\t\tadoptionIdentities.set(table.name, live.catalogueIdentity);\n\t\t}\n\t\t// A declared lifecycle request owns every change at that address. Adoption\n\t\t// is a refusal rather than a mutation; replacement is its own reviewed\n\t\t// retire-and-create protocol. Keep unrelated drift intact.\n\t\tconst executableDiff: SchemaDiff = {\n\t\t\t...diff,\n\t\t\tchanges: diff.changes.filter(\n\t\t\t\t(change) =>\n\t\t\t\t\t![...loaded.model.tables.values()].some(\n\t\t\t\t\t\t(table) =>\n\t\t\t\t\t\t\t(table.adopt === true || table.replace === true) &&\n\t\t\t\t\t\t\tchangeTargetsDeclaredTable(change, table.name),\n\t\t\t\t\t),\n\t\t\t),\n\t\t};\n\t\tconst ordinaryChanges = executableDiff.changes.map((change) => ({\n\t\t\tkind: change.kind,\n\t\t\ttable: change.table,\n\t\t\t...(change.column ? { column: change.column } : {}),\n\t\t\tclassification: classifyGeneratedMutation(change.kind, change),\n\t\t\tdetails: change.details,\n\t\t\tstatements:\n\t\t\t\tchange.kind === 'readdress_table' && change.meta?.readdress\n\t\t\t\t\t? readdressStatements(\n\t\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\t\tschema,\n\t\t\t\t\t\t\tchange.meta.readdress as TableReaddressDeclaration,\n\t\t\t\t\t\t)\n\t\t\t\t\t: generateMigrationSQL(\n\t\t\t\t\t\t\t{ ...executableDiff, changes: [change] },\n\t\t\t\t\t\t\t{ includeDestructive: true, schemaName: schema },\n\t\t\t\t\t\t),\n\t\t\t...(change.kind === 'readdress_table' && change.meta?.readdress\n\t\t\t\t? { readdress: change.meta.readdress as TableReaddressDeclaration }\n\t\t\t\t: {}),\n\t\t}));\n\t\tconst material: GeneratorPlanMaterial = {\n\t\t\tkind: 'schema-differ-generator',\n\t\t\tplanningSchema: schema,\n\t\t\tchanges: [\n\t\t\t\t...ordinaryChanges,\n\t\t\t\t...[...loaded.model.tables.values()]\n\t\t\t\t\t.filter((table) => adoptionMismatches.has(table.name))\n\t\t\t\t\t.map((table) => ({\n\t\t\t\t\t\tkind: 'adoption_refused',\n\t\t\t\t\t\ttable: table.name,\n\t\t\t\t\t\tclassification: 'non-destructive' as const,\n\t\t\t\t\t\tdetails: `Refuse adoption of table \"${table.name}\": live shape does not match declaration`,\n\t\t\t\t\t\tstatements: [],\n\t\t\t\t\t})),\n\t\t\t\t// `comparePgsqlDatabaseSchema` has just compared each side through\n\t\t\t\t// the established live canonicalisation path. An adopted table is\n\t\t\t\t// admitted only when that comparison has no remaining change for it.\n\t\t\t\t...[...loaded.model.tables.values()]\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(table) =>\n\t\t\t\t\t\t\ttable.adopt === true &&\n\t\t\t\t\t\t\t!diff.changes.some((change) =>\n\t\t\t\t\t\t\t\tchangeTargetsDeclaredTable(change, table.name),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.map((table) => ({\n\t\t\t\t\t\tkind: 'adopt_table',\n\t\t\t\t\t\ttable: table.name,\n\t\t\t\t\t\tclassification: 'non-destructive' as const,\n\t\t\t\t\t\tdetails: `Adopt existing table \"${table.name}\" after live shape match`,\n\t\t\t\t\t\tstatements: [],\n\t\t\t\t\t\tadoption: {\n\t\t\t\t\t\t\tdeclaration: adoptionDeclaration(table),\n\t\t\t\t\t\t\tshape: table,\n\t\t\t\t\t\t\tcatalogueIdentity: requiredAdoptionIdentity(\n\t\t\t\t\t\t\t\tadoptionIdentities,\n\t\t\t\t\t\t\t\ttable.name,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t},\n\t\t\t\t\t})),\n\t\t\t\t...[...loaded.model.tables.values()]\n\t\t\t\t\t.filter((table) => table.replace === true)\n\t\t\t\t\t.map((table) => ({\n\t\t\t\t\t\tkind: 'replace_table',\n\t\t\t\t\t\ttable: table.name,\n\t\t\t\t\t\tclassification: 'removal' as const,\n\t\t\t\t\t\tdetails: `Replace table \"${table.name}\" by reviewed retirement then creation`,\n\t\t\t\t\t\tstatements: [],\n\t\t\t\t\t\treplacement: replacementStatements(table, schema),\n\t\t\t\t\t})),\n\t\t\t],\n\t\t};\n\t\t// A foreign-key alteration is a replacement, not a removal that happens to\n\t\t// recreate something afterwards. Keep its two addresses/claim keys visible\n\t\t// in the durable manifest and let dependency linearisation order retirement\n\t\t// before the target vacancy claim.\n\t\tconst ordinaryStepSources: Array<{\n\t\t\tstep: NormalizedManagedStep;\n\t\t\tchange: SchemaDiff['changes'][number];\n\t\t}> = [];\n\t\tfor (const [changeIndex, change] of executableDiff.changes.entries()) {\n\t\t\tconst generated = ordinaryChanges[changeIndex];\n\t\t\tif (!generated)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'generator planning lost a generated statement bundle during lifecycle expansion',\n\t\t\t\t);\n\t\t\tconst order = ordinaryStepSources.length;\n\t\t\tif (change.kind === 'alter_foreign_key') {\n\t\t\t\tconst oldFk = change.meta?.oldFk;\n\t\t\t\tif (!oldFk || typeof oldFk !== 'object' || Array.isArray(oldFk))\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'generator planning refuses alter_foreign_key: missing typed old foreign key',\n\t\t\t\t\t);\n\t\t\t\tconst [retireStatement, ...createStatements] = generated.statements;\n\t\t\t\tif (!retireStatement || createStatements.length === 0)\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'generator planning refuses alter_foreign_key: expected DROP then ADD bundle',\n\t\t\t\t\t);\n\t\t\t\tordinaryStepSources.push({\n\t\t\t\t\tchange,\n\t\t\t\t\tstep: createPgsqlGeneratedManagedStep({\n\t\t\t\t\t\tchange: {\n\t\t\t\t\t\t\t...change,\n\t\t\t\t\t\t\tkind: 'drop_foreign_key',\n\t\t\t\t\t\t\tdestructive: true,\n\t\t\t\t\t\t\tmeta: { fk: oldFk },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\tstepKey: `generator:${order}:alter-foreign-key-retire`,\n\t\t\t\t\t\torder,\n\t\t\t\t\t\tdependencyOrder: [],\n\t\t\t\t\t\tstatements: [retireStatement],\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tordinaryStepSources.push({\n\t\t\t\t\tchange,\n\t\t\t\t\tstep: createPgsqlGeneratedManagedStep({\n\t\t\t\t\t\tchange: { ...change, kind: 'add_foreign_key', destructive: false },\n\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\tstepKey: `generator:${order + 1}:alter-foreign-key-create`,\n\t\t\t\t\t\torder: order + 1,\n\t\t\t\t\t\tdependencyOrder: [],\n\t\t\t\t\t\tstatements: createStatements,\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tordinaryStepSources.push({\n\t\t\t\tchange,\n\t\t\t\tstep: createPgsqlGeneratedManagedStep({\n\t\t\t\t\tchange,\n\t\t\t\t\tdatabase,\n\t\t\t\t\tschema,\n\t\t\t\t\tstepKey: `generator:${order}`,\n\t\t\t\t\torder,\n\t\t\t\t\tdependencyOrder: [],\n\t\t\t\t\tstatements: generated.statements,\n\t\t\t\t}),\n\t\t\t});\n\t\t}\n\t\tconst ordinarySteps = ordinaryStepSources.map(({ step }) => step);\n\t\tconst lifecycleSteps: NormalizedManagedStep[] = [];\n\t\tfor (const change of material.changes.slice(ordinaryChanges.length)) {\n\t\t\tconst base = {\n\t\t\t\torder: ordinarySteps.length + lifecycleSteps.length,\n\t\t\t\tdatabase,\n\t\t\t\tschema,\n\t\t\t\ttable: change.table,\n\t\t\t};\n\t\t\tif (change.kind === 'replace_table' && change.replacement) {\n\t\t\t\tconst replacementTable = [...loaded.model.tables.values()].find(\n\t\t\t\t\t(table) => table.name === change.table,\n\t\t\t\t);\n\t\t\t\tconst replacementPostcondition = generatedPostconditionForChange({\n\t\t\t\t\tchange: {\n\t\t\t\t\t\tkind: 'create_table',\n\t\t\t\t\t\ttable: change.table,\n\t\t\t\t\t\tdestructive: false,\n\t\t\t\t\t\tdetails: `Create replacement table \"${change.table}\"`,\n\t\t\t\t\t\tmeta: { table: replacementTable },\n\t\t\t\t\t},\n\t\t\t\t\tschema,\n\t\t\t\t});\n\t\t\t\tif (replacementPostcondition === undefined)\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`generator planning refuses replacement ${change.table}: missing table postcondition`,\n\t\t\t\t\t);\n\t\t\t\tconst selector = {\n\t\t\t\t\tkind: 'replacement' as const,\n\t\t\t\t\tselector: `table:${change.table}`,\n\t\t\t\t};\n\t\t\t\tlifecycleSteps.push(\n\t\t\t\t\tlifecycleStep({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tstepKey: `generator:${base.order}:replacement-retire`,\n\t\t\t\t\t\tclassification: 'removal',\n\t\t\t\t\t\tstatements: change.replacement.retireStatements,\n\t\t\t\t\t\tselection: selector,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tlifecycleSteps.push(\n\t\t\t\t\tlifecycleStep({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\torder: base.order + 1,\n\t\t\t\t\t\tstepKey: `generator:${base.order}:replacement-create`,\n\t\t\t\t\t\tclassification: 'non-destructive',\n\t\t\t\t\t\tstatements: change.replacement.createStatements,\n\t\t\t\t\t\tselection: selector,\n\t\t\t\t\t\trequiresVacancy: true,\n\t\t\t\t\t\texpectedDeclaration: replacementPostcondition,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (change.kind === 'adopt_table' && change.adoption) {\n\t\t\t\tlifecycleSteps.push(\n\t\t\t\t\tlifecycleStep({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tstepKey: `generator:${base.order}:adoption`,\n\t\t\t\t\t\tclassification: 'non-destructive',\n\t\t\t\t\t\tselection: { kind: 'adoption', selector: `table:${change.table}` },\n\t\t\t\t\t\texpectedDeclaration: change.adoption.declaration,\n\t\t\t\t\t\texpectedCatalogueIdentity: change.adoption.catalogueIdentity,\n\t\t\t\t\t\tclaimKind: 'adopt-intent',\n\t\t\t\t\t\tlifecycle: { kind: 'adoption', shape: change.adoption.shape },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlifecycleSteps.push(\n\t\t\t\tlifecycleStep({\n\t\t\t\t\t...base,\n\t\t\t\t\tstepKey: `generator:${base.order}`,\n\t\t\t\t\tclassification: change.classification,\n\t\t\t\t\t...(change.kind === 'adoption_refused'\n\t\t\t\t\t\t? { lifecycle: { kind: 'adoption-refused' as const } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tfor (const { step, change } of ordinaryStepSources) {\n\t\t\tif (step.address?.kind !== 'table') continue;\n\t\t\tif (change?.kind !== 'readdress_table' || !change.meta?.readdress)\n\t\t\t\tcontinue;\n\t\t\tObject.assign(step as object, {\n\t\t\t\tclaimKind: 'readdress-intent',\n\t\t\t\tselection: {\n\t\t\t\t\tkind: 'readdress',\n\t\t\t\t\tselector: `table:${step.address.name}`,\n\t\t\t\t},\n\t\t\t\tlifecycle: {\n\t\t\t\t\tkind: 'readdress',\n\t\t\t\t\tdeclaration: change.meta.readdress as TableReaddressDeclaration,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst steps = linearizeGeneratedManagedStepDependencies([\n\t\t\t...ordinarySteps,\n\t\t\t...lifecycleSteps,\n\t\t]);\n\t\tconst plan = asDurableGeneratorPlan(material, steps);\n\t\tconst planDigest = transitionPlanDigest(\n\t\t\tplan as unknown as InProcessProvenPlan,\n\t\t);\n\t\tconst run: TransitionRunMetadata = {\n\t\t\trunId: `dbsp-generator-${randomUUID()}`,\n\t\t\tplanDigest,\n\t\t\ttargetContextDigest: digest({ database: await databaseId(pool), schema }),\n\t\t\tdatabaseId: await databaseId(pool),\n\t\t\tcoreVersion: 'schema-differ-generator-v1',\n\t\t\tstartedAt: new Date().toISOString(),\n\t\t\treplayability: material.changes.some(\n\t\t\t\t(change) => change.classification === 'removal',\n\t\t\t)\n\t\t\t\t? 'non-replayable-generator-removal'\n\t\t\t\t: 'replayable',\n\t\t};\n\t\tif (!input.dryRun) {\n\t\t\tconst lease = await acquireTransitionLease(\n\t\t\t\tcreatePgTransitionLessor(pool),\n\t\t\t);\n\t\t\ttry {\n\t\t\t\tawait createPgTransitionRunPersister(lease.session).persist(\n\t\t\t\t\trun,\n\t\t\t\t\tplan as unknown as InProcessProvenPlan,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tawait lease.release();\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tcompareKind: 'transitions',\n\t\t\tproveKind: 'proven',\n\t\t\tassessment: assessment(),\n\t\t\tpersisted: !input.dryRun,\n\t\t\trunId: input.dryRun ? null : run.runId,\n\t\t\tplanDigest,\n\t\t\tplan: plan as unknown as InProcessProvenPlan,\n\t\t\tsql: render({ steps }, planDigest),\n\t\t};\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n","/**\n * dbsp plan — prove a transition and, unless previewing, retain it for a later\n * apply command. This command intentionally stops before execution.\n */\n\nimport {\n\tacquirePgTransitionClient,\n\tcreatePgExecutionContract,\n\tcreatePgsqlAdapter,\n\tcreatePgTransitionLessor,\n\tcreatePgTransitionPack,\n\tcreatePgTransitionRunPersister,\n\tensureTransitionJournal,\n\tescapeDiagnosticText,\n\tgetNamingPluginForDbCasing,\n\tPgExecutionContractDerivationError,\n\tpgTargetIdentityMismatch,\n\treadPgExecutionTargetFromClient,\n\treadPgObservationContextFromLessor,\n} from '@dbsp/adapter-pgsql';\nimport {\n\tacquireTransitionLease,\n\tbindDeclarationSet,\n\tbindExecutionContract,\n\tcreateComparator,\n\tcreatePackRegistry,\n\tcreateProver,\n\tcreateTransitionRunMetadata,\n\tdeclarationSetFromModel,\n\ttype InProcessProvenPlan,\n\ttype PackRegistry,\n\tvalidateDeclarationModel,\n} from '@dbsp/core';\nimport type {\n\tCompareOutcome,\n\tExecutionContract,\n\tModelIR,\n\tObservationContext,\n\tPlanAssessment,\n\tPostgreSqlObservationTargetIdentity,\n\tTransitionRunMetadata,\n\tTransitionSessionClient,\n} from '@dbsp/types';\nimport { Command } from 'commander';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { type LoadedSchema, loadSchema } from '../utils/schema-loader.js';\n\nexport type PlanFormat = 'sql' | 'json';\nexport type PlanPersistenceState = boolean | 'indeterminate';\n\nexport interface PlanOptions {\n\treadonly db: string;\n\treadonly schemaFile: string;\n\treadonly schema?: string;\n\treadonly dryRun?: boolean;\n\treadonly format?: PlanFormat;\n}\n\nexport interface PlanResult {\n\treadonly compareKind: CompareOutcome['kind'];\n\treadonly proveKind: 'proven' | 'no-drift' | 'blocked' | 'inapplicable';\n\treadonly assessment: PlanAssessment;\n\t/** true is durable, false was not attempted, and indeterminate may have committed. */\n\treadonly persisted: PlanPersistenceState;\n\treadonly runId: string | null;\n\treadonly planDigest: string | null;\n\treadonly plan?: InProcessProvenPlan;\n\treadonly sql?: string;\n}\n\nexport class PlanPersistenceIndeterminateError extends Error {\n\treadonly runId: string;\n\treadonly result: PlanResult;\n\treadonly persistenceError: unknown;\n\treadonly cleanup: CleanupFailure;\n\n\tconstructor(\n\t\tresult: PlanResult,\n\t\tpersistenceError: unknown,\n\t\tcleanup: CleanupFailure = noCleanupFailure,\n\t) {\n\t\tconst cause =\n\t\t\tcleanup.kind === 'failed'\n\t\t\t\t? new AggregateError(\n\t\t\t\t\t\t[persistenceError, cleanup.error],\n\t\t\t\t\t\t'persistence and connection release both failed',\n\t\t\t\t\t)\n\t\t\t\t: persistenceError;\n\t\tsuper(\n\t\t\t`persistence indeterminate; inspect run ${result.runId}: ${escapeDiagnosticText(describeThrown(persistenceError))}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'PlanPersistenceIndeterminateError';\n\t\tthis.runId = result.runId ?? '';\n\t\tthis.result = result;\n\t\tthis.persistenceError = persistenceError;\n\t\tthis.cleanup = cleanup;\n\t}\n}\n\n/** A completed plan outcome whose connection release failed afterwards. */\nexport class PlanCleanupError extends Error {\n\tconstructor(\n\t\treadonly result: PlanResult,\n\t\treadonly cleanupError: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`connection release failed after the plan outcome was determined: ${escapeDiagnosticText(describeThrown(cleanupError))}`,\n\t\t\t{ cause: cleanupError },\n\t\t);\n\t\tthis.name = 'PlanCleanupError';\n\t}\n}\n\n/** A planning failure whose declared connection release also failed. */\nclass PlanOperationAndCleanupError extends AggregateError {\n\tconstructor(\n\t\treadonly operationError: unknown,\n\t\treadonly cleanupError: unknown,\n\t) {\n\t\tsuper(\n\t\t\t[operationError, cleanupError],\n\t\t\t'planning and connection release both failed',\n\t\t\t{ cause: operationError },\n\t\t);\n\t\tthis.name = 'PlanOperationAndCleanupError';\n\t}\n}\n\ntype PlanPool = Pool;\n\n/** A release rejection is distinct from its rejection value, including undefined. */\ntype CleanupFailure =\n\t| { readonly kind: 'not-failed' }\n\t| { readonly kind: 'failed'; readonly error: unknown };\n\nconst noCleanupFailure: CleanupFailure = { kind: 'not-failed' };\n\n/**\n * A planning connection together with the action that returns its resource.\n *\n * The caller that supplies the pool decides whether it is owned, shared, or\n * otherwise managed; runPlan only invokes this declared release path.\n */\nexport interface PlanConnection {\n\treadonly pool: PlanPool;\n\treadonly release: () => Promise<void>;\n}\n\nexport interface PlanDeps {\n\treadonly createDbConnection: (db: string) => Promise<PlanConnection>;\n\treadonly loadSchema: (path: string) => Promise<LoadedSchema>;\n\treadonly ensureTransitionJournal: (pool: PlanPool) => Promise<void>;\n\treadonly captureTargetIdentity: (\n\t\tpool: PlanPool,\n\t\tschema: string | undefined,\n\t) => Promise<PostgreSqlObservationTargetIdentity>;\n\treadonly loadCurrent: (\n\t\tpool: PlanPool,\n\t\tschema: string | undefined,\n\t\texpectedTargetIdentity: PostgreSqlObservationTargetIdentity,\n\t) => Promise<ModelIR>;\n\treadonly readContext: (\n\t\tpool: PlanPool,\n\t\tschema?: string,\n\t\texpectedTargetIdentity?: PostgreSqlObservationTargetIdentity,\n\t) => Promise<ObservationContext>;\n\treadonly createPlanner: (loaded: LoadedSchema) => PlanPlanner;\n\treadonly persist: (\n\t\tpool: PlanPool,\n\t\trun: TransitionRunMetadata,\n\t\tplan: InProcessProvenPlan,\n\t) => Promise<void>;\n\treadonly buildExecutionContract: (\n\t\tpool: PlanPool,\n\t\tschema: string | undefined,\n\t\tplan: InProcessProvenPlan,\n\t\texpectedTargetIdentity: PostgreSqlObservationTargetIdentity,\n\t) => Promise<ExecutionContract>;\n}\n\nexport interface PlanPlanner {\n\treadonly compare: (\n\t\tdesired: ModelIR,\n\t\tcurrent: ModelIR,\n\t\tcontext: ObservationContext,\n\t) => CompareOutcome;\n\treadonly prove: (\n\t\tcompare: CompareOutcome,\n\t\tpool: PlanPool,\n\t\tcontext: ObservationContext,\n\t) => ReturnType<ReturnType<typeof createProver>['prove']>;\n\treadonly render: (\n\t\tplan: InProcessProvenPlan,\n\t\tcontext: ObservationContext,\n\t) => string;\n}\n\nfunction equivalenceContext(context: ObservationContext) {\n\treturn {\n\t\tengine: context.engine,\n\t\t...(context.databaseId ? { databaseId: context.databaseId } : {}),\n\t\t...(context.targetSchema ? { targetSchema: context.targetSchema } : {}),\n\t\t...(context.searchPath ? { searchPath: context.searchPath } : {}),\n\t\tproofObservationContext: context,\n\t};\n}\n\n/** The only planning-time namespace derivation; apply uses the stored clause. */\nexport function executionTargetNamespaces(\n\tplan: InProcessProvenPlan,\n\tfallbackSchema: string | undefined,\n): readonly string[] {\n\tconst namespaces = [\n\t\t...new Set(\n\t\t\tplan.steps.map((step) => {\n\t\t\t\tconst payload = step.operation.payload;\n\t\t\t\tif (\n\t\t\t\t\tpayload === null ||\n\t\t\t\t\ttypeof payload !== 'object' ||\n\t\t\t\t\tArray.isArray(payload) ||\n\t\t\t\t\ttypeof (payload as Record<string, unknown>).schema !== 'string'\n\t\t\t\t)\n\t\t\t\t\tthrow new PgExecutionContractDerivationError(\n\t\t\t\t\t\tstep.operation.ref,\n\t\t\t\t\t\tstep.operation.operationKind.name,\n\t\t\t\t\t\t'has no derivable target namespace',\n\t\t\t\t\t);\n\t\t\t\treturn (payload as Record<string, unknown>).schema as string;\n\t\t\t}),\n\t\t),\n\t];\n\tif (namespaces.length === 0 && fallbackSchema !== undefined)\n\t\tnamespaces.push(fallbackSchema);\n\treturn namespaces;\n}\n\n/** Build the PostgreSQL contract after resolving the plan's physical target. */\nexport async function buildPgExecutionContract(\n\tpool: PlanPool,\n\tschema: string | undefined,\n\tplan: InProcessProvenPlan,\n\texpectedTargetIdentity: PostgreSqlObservationTargetIdentity,\n): Promise<ExecutionContract> {\n\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\ttry {\n\t\tconst target = await readPgExecutionTargetFromClient(\n\t\t\tlease.session,\n\t\t\texecutionTargetNamespaces(plan, schema),\n\t\t);\n\t\tconst mismatch = pgTargetIdentityMismatch(\n\t\t\texpectedTargetIdentity,\n\t\t\ttarget.identity,\n\t\t);\n\t\tif (mismatch) {\n\t\t\tthrow new Error(\n\t\t\t\t`PostgreSQL target identity changed before plan persistence: ${mismatch}`,\n\t\t\t);\n\t\t}\n\t\treturn createPgExecutionContract(\n\t\t\tplan,\n\t\t\ttarget.identity,\n\t\t\ttarget.sessionProvenance,\n\t\t);\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nconst defaultPlanDeps: PlanDeps = {\n\tasync createDbConnection(db) {\n\t\tconst { pool } = await createDbConnection(db);\n\t\treturn { pool, release: () => pool.end() };\n\t},\n\tloadSchema,\n\tasync ensureTransitionJournal(pool) {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tawait ensureTransitionJournal(lease.session);\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t},\n\tasync captureTargetIdentity(pool, schema) {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\treturn (\n\t\t\t\tawait readPgExecutionTargetFromClient(lease.session, [\n\t\t\t\t\tschema ?? 'public',\n\t\t\t\t])\n\t\t\t).identity;\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t},\n\tasync loadCurrent(pool, schema, expectedTargetIdentity) {\n\t\tconst lease = await acquirePgTransitionClient(pool);\n\t\ttry {\n\t\t\tconst observed = await readPgExecutionTargetFromClient(\n\t\t\t\tlease.client as unknown as TransitionSessionClient,\n\t\t\t\t[schema ?? 'public'],\n\t\t\t);\n\t\t\tconst mismatch = pgTargetIdentityMismatch(\n\t\t\t\texpectedTargetIdentity,\n\t\t\t\tobserved.identity,\n\t\t\t);\n\t\t\tif (mismatch) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`PostgreSQL introspection target identity does not match the captured target: ${mismatch}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn await createPgsqlAdapter(lease.client, {\n\t\t\t\tborrowedClient: true,\n\t\t\t}).introspect(schema === undefined ? {} : { schema });\n\t\t} finally {\n\t\t\tlease.release();\n\t\t}\n\t},\n\tasync readContext(pool, schema, expectedTargetIdentity) {\n\t\treturn readPgObservationContextFromLessor(\n\t\t\tcreatePgTransitionLessor(pool),\n\t\t\tschema,\n\t\t\tundefined,\n\t\t\texpectedTargetIdentity,\n\t\t);\n\t},\n\tcreatePlanner(loaded) {\n\t\tconst registry = createPackRegistry([\n\t\t\tcreatePgTransitionPack({\n\t\t\t\t...(loaded.dbCasing ? { dbCasing: loaded.dbCasing } : {}),\n\t\t\t}),\n\t\t]);\n\t\tconst comparator = createComparator(registry);\n\t\tconst prover = createProver(registry);\n\t\treturn {\n\t\t\tcompare: (desired, current, context) =>\n\t\t\t\tcomparator.compare(desired, current, equivalenceContext(context)),\n\t\t\tprove: (compare, pool, context) =>\n\t\t\t\tprover.prove(compare, createPgTransitionLessor(pool), context),\n\t\t\trender: (plan, context) => renderProvenPlanSql(registry, plan, context),\n\t\t};\n\t},\n\tasync persist(pool, run, plan) {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tawait createPgTransitionRunPersister(lease.session).persist(run, plan);\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t},\n\tbuildExecutionContract: buildPgExecutionContract,\n};\n\nfunction resolvedDeps(overrides?: Partial<PlanDeps>): PlanDeps {\n\treturn { ...defaultPlanDeps, ...overrides };\n}\n\nfunction describeThrown(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction executionContractBlockedAssessment(\n\terror: PgExecutionContractDerivationError,\n): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'replan-required',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'unsupported-transition',\n\t\t\t\tchanges: [],\n\t\t\t\tscope: [],\n\t\t\t\tdetail: error.message,\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** Render only a complete proven plan. This is an inspection view, never apply input. */\nexport function renderProvenPlanSql(\n\tregistry: PackRegistry,\n\tplan: InProcessProvenPlan,\n\tcontext: ObservationContext,\n): string {\n\tconst statements = plan.steps.map((step) => {\n\t\tconst resolution = registry.resolveOperation(step.operation);\n\t\tif (!resolution.ok || !resolution.semantics.renderPlanSql) {\n\t\t\tthrow new Error(\n\t\t\t\t`no SQL renderer is registered for proven operation ${step.operation.operationKind.name}`,\n\t\t\t);\n\t\t}\n\t\treturn resolution.semantics.renderPlanSql(step.operation, context);\n\t});\n\treturn [\n\t\t'-- dbsp transition plan view; apply accepts a persisted run id, never this SQL.',\n\t\t...statements.map((statement) => `${statement};`),\n\t].join('\\n');\n}\n\nexport async function runPlan(\n\toptions: PlanOptions,\n\toverrides?: Partial<PlanDeps>,\n): Promise<PlanResult> {\n\tconst deps = resolvedDeps(overrides);\n\tconst format = options.format ?? 'sql';\n\tif (format !== 'sql' && format !== 'json') {\n\t\tthrow new Error(`unsupported plan format ${format}; expected sql or json`);\n\t}\n\tconst loaded = await deps.loadSchema(options.schemaFile);\n\t// This is deliberately before comparison: an unchanged/unsupported model is\n\t// still a declaration authored for durable replay and may not silently lose a\n\t// non-JSON default during a future plan.\n\tvalidateDeclarationModel(loaded.model);\n\tconst connection = await deps.createDbConnection(options.db);\n\tconst { pool } = connection;\n\tlet result: PlanResult | undefined;\n\tlet operationError: unknown;\n\tlet failed = false;\n\ttry {\n\t\t// This binding is deliberately first: every subsequent introspection and\n\t\t// proof lease must describe the same physical PostgreSQL target.\n\t\tconst targetIdentity = await deps.captureTargetIdentity(\n\t\t\tpool,\n\t\t\toptions.schema,\n\t\t);\n\t\tawait deps.ensureTransitionJournal(pool);\n\t\tconst current = await deps.loadCurrent(\n\t\t\tpool,\n\t\t\toptions.schema,\n\t\t\ttargetIdentity,\n\t\t);\n\t\tconst context = await deps.readContext(\n\t\t\tpool,\n\t\t\toptions.schema,\n\t\t\ttargetIdentity,\n\t\t);\n\t\tconst planner = deps.createPlanner(loaded);\n\t\tconst compare = planner.compare(loaded.model, current, context);\n\t\tconst prove = await planner.prove(compare, pool, context);\n\n\t\tif (prove.kind === 'proven') {\n\t\t\tlet executionContract: ExecutionContract | undefined;\n\t\t\ttry {\n\t\t\t\texecutionContract = await deps.buildExecutionContract(\n\t\t\t\t\tpool,\n\t\t\t\t\toptions.schema,\n\t\t\t\t\tprove.plan,\n\t\t\t\t\ttargetIdentity,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof PgExecutionContractDerivationError)) throw error;\n\t\t\t\tresult = {\n\t\t\t\t\tcompareKind: compare.kind,\n\t\t\t\t\tproveKind: 'blocked',\n\t\t\t\t\tassessment: executionContractBlockedAssessment(error),\n\t\t\t\t\tpersisted: false,\n\t\t\t\t\trunId: null,\n\t\t\t\t\tplanDigest: null,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (executionContract !== undefined) {\n\t\t\t\t// Order is intentional: an id exists before an indeterminate write, while\n\t\t\t\t// rendering happens before a durable record can be stranded unseen.\n\t\t\t\tconst contractedPlan = bindExecutionContract(\n\t\t\t\t\tprove.plan,\n\t\t\t\t\texecutionContract,\n\t\t\t\t);\n\t\t\t\tconst durablePlan = bindDeclarationSet(\n\t\t\t\t\tcontractedPlan,\n\t\t\t\t\tdeclarationSetFromModel(\n\t\t\t\t\t\tloaded.model,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tengine: context.engine,\n\t\t\t\t\t\t\tdatabase: context.databaseId,\n\t\t\t\t\t\t\tschema: options.schema ?? 'public',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetNamingPluginForDbCasing(loaded.dbCasing ?? 'preserve'),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst run = createTransitionRunMetadata(durablePlan);\n\t\t\t\tconst proofContext = prove.plan.observations.find(\n\t\t\t\t\t(observation) => observation.role === 'evidence',\n\t\t\t\t)?.context;\n\t\t\t\tif (!proofContext) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'internal error: minted proven plan has no evidence observation context',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst sql = planner.render(durablePlan, proofContext);\n\t\t\t\tif (!options.dryRun) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait deps.persist(pool, run, durablePlan);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthrow new PlanPersistenceIndeterminateError(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcompareKind: compare.kind,\n\t\t\t\t\t\t\t\tproveKind: prove.kind,\n\t\t\t\t\t\t\t\tassessment: prove.assessment,\n\t\t\t\t\t\t\t\tpersisted: 'indeterminate',\n\t\t\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\t\t\tplanDigest: run.planDigest,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult = {\n\t\t\t\t\tcompareKind: compare.kind,\n\t\t\t\t\tproveKind: prove.kind,\n\t\t\t\t\tassessment: prove.assessment,\n\t\t\t\t\tpersisted: !options.dryRun,\n\t\t\t\t\trunId: options.dryRun ? null : run.runId,\n\t\t\t\t\tplanDigest: run.planDigest,\n\t\t\t\t\tplan: durablePlan,\n\t\t\t\t\tsql,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tif (prove.kind === 'no-drift') {\n\t\t\tresult = {\n\t\t\t\tcompareKind: compare.kind,\n\t\t\t\tproveKind: prove.kind,\n\t\t\t\tassessment: prove.assessment,\n\t\t\t\tpersisted: false,\n\t\t\t\trunId: null,\n\t\t\t\tplanDigest: null,\n\t\t\t};\n\t\t} else if (prove.kind !== 'proven') {\n\t\t\tresult = {\n\t\t\t\tcompareKind: compare.kind,\n\t\t\t\tproveKind: prove.kind,\n\t\t\t\tassessment: prove.assessment,\n\t\t\t\tpersisted: false,\n\t\t\t\trunId: null,\n\t\t\t\tplanDigest: null,\n\t\t\t};\n\t\t}\n\t} catch (error) {\n\t\tfailed = true;\n\t\toperationError = error;\n\t}\n\n\tlet cleanup: CleanupFailure = noCleanupFailure;\n\ttry {\n\t\tawait connection.release();\n\t} catch (error) {\n\t\tcleanup = { kind: 'failed', error };\n\t}\n\n\tif (failed) {\n\t\tif (operationError instanceof PlanPersistenceIndeterminateError) {\n\t\t\tthrow new PlanPersistenceIndeterminateError(\n\t\t\t\toperationError.result,\n\t\t\t\toperationError.persistenceError,\n\t\t\t\tcleanup,\n\t\t\t);\n\t\t}\n\t\tif (cleanup.kind === 'failed') {\n\t\t\tthrow new PlanOperationAndCleanupError(operationError, cleanup.error);\n\t\t}\n\t\tthrow operationError;\n\t}\n\tif (cleanup.kind === 'failed') {\n\t\tthrow new PlanCleanupError(result as PlanResult, cleanup.error);\n\t}\n\treturn result as PlanResult;\n}\n\nexport function formatPlanJson(result: PlanResult, dryRun: boolean) {\n\treturn {\n\t\tcompareKind: result.compareKind,\n\t\tproveKind: result.proveKind,\n\t\tassessment: result.assessment,\n\t\tpersisted: result.persisted,\n\t\trunId: result.runId,\n\t\tplanDigest: result.planDigest,\n\t\t...(result.plan ? { plan: result.plan } : {}),\n\t\t...(result.sql ? { sql: result.sql } : {}),\n\t\t...(dryRun && result.proveKind === 'proven'\n\t\t\t? { preview: 'non-executable; no durable dbsp record' }\n\t\t\t: {}),\n\t};\n}\n\nexport function formatPlanHuman(result: PlanResult, dryRun: boolean): string {\n\tif (result.proveKind === 'proven') {\n\t\treturn [\n\t\t\tdryRun\n\t\t\t\t? 'Proven transition preview (non-executable; no durable dbsp record):'\n\t\t\t\t: 'Proven transition plan:',\n\t\t\t// Every operation renderer converges on result.sql before this human-only\n\t\t\t// view, so database-sourced SQL cannot bypass terminal escaping here.\n\t\t\t...(result.sql === undefined ? [] : [escapeDiagnosticText(result.sql)]),\n\t\t\t...(result.plan?.executionContract\n\t\t\t\t? [\n\t\t\t\t\t\t'Execution contract:',\n\t\t\t\t\t\t...result.plan.executionContract.requirements.map(\n\t\t\t\t\t\t\t(requirement) =>\n\t\t\t\t\t\t\t\t` ${escapeDiagnosticText(JSON.stringify(requirement))}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t\tdryRun\n\t\t\t\t? `Preview digest: ${result.planDigest}`\n\t\t\t\t: `Run id: ${result.runId}\\nPlan digest: ${result.planDigest}`,\n\t\t]\n\t\t\t.filter((line): line is string => line !== undefined)\n\t\t\t.join('\\n');\n\t}\n\tif (result.proveKind === 'no-drift') {\n\t\treturn 'Database already matches the target; nothing was persisted.';\n\t}\n\treturn `No durable plan was created.\\n${escapeDiagnosticText(JSON.stringify(result.assessment, null, 2))}`;\n}\n\nfunction preservedPlanResult(\n\terror: unknown,\n\tfallback?: PlanResult,\n): PlanResult | undefined {\n\tif (error instanceof PlanPersistenceIndeterminateError) return error.result;\n\tif (error instanceof PlanCleanupError) return error.result;\n\treturn fallback;\n}\n\nfunction primaryPlanError(error: unknown): unknown {\n\tif (error instanceof PlanPersistenceIndeterminateError) {\n\t\treturn error.persistenceError;\n\t}\n\tif (error instanceof PlanCleanupError) return error.cleanupError;\n\tif (error instanceof PlanOperationAndCleanupError) {\n\t\treturn error.operationError;\n\t}\n\treturn error;\n}\n\nfunction cleanupFailure(error: unknown): CleanupFailure {\n\tif (error instanceof PlanPersistenceIndeterminateError) {\n\t\treturn error.cleanup;\n\t}\n\tif (error instanceof PlanCleanupError) {\n\t\treturn { kind: 'failed', error: error.cleanupError };\n\t}\n\tif (error instanceof PlanOperationAndCleanupError) {\n\t\treturn { kind: 'failed', error: error.cleanupError };\n\t}\n\treturn noCleanupFailure;\n}\n\n/** The stable error contract for both planning and post-outcome failures. */\nexport function formatPlanFailureJson(error: unknown, fallback?: PlanResult) {\n\tconst result = preservedPlanResult(error, fallback);\n\tconst cleanupError = cleanupFailure(error);\n\treturn {\n\t\tcompareKind: result?.compareKind ?? null,\n\t\tproveKind: result?.proveKind ?? null,\n\t\tassessment: result?.assessment ?? null,\n\t\tpersisted: result?.persisted ?? false,\n\t\trunId: result?.runId ?? null,\n\t\tplanDigest: result?.planDigest ?? null,\n\t\terror: describeThrown(primaryPlanError(error)),\n\t\t...(cleanupError.kind === 'not-failed'\n\t\t\t? {}\n\t\t\t: { cleanupError: describeThrown(cleanupError.error) }),\n\t};\n}\n\nfunction formatPlanFailureHuman(error: unknown, fallback?: PlanResult): string {\n\tconst result = preservedPlanResult(error, fallback);\n\tconst fields = result\n\t\t? [\n\t\t\t\tresult.persisted === true\n\t\t\t\t\t? 'A durable plan was created before this failure.'\n\t\t\t\t\t: result.persisted === 'indeterminate'\n\t\t\t\t\t\t? 'Persistence is indeterminate; inspect the minted run before retrying.'\n\t\t\t\t\t\t: 'No durable plan was created.',\n\t\t\t\t...(result.runId ? [`Run id: ${result.runId}`] : []),\n\t\t\t\t...(result.planDigest ? [`Plan digest: ${result.planDigest}`] : []),\n\t\t\t]\n\t\t: [];\n\tconst cleanupError = cleanupFailure(error);\n\treturn [\n\t\t`❌ ${escapeDiagnosticText(describeThrown(primaryPlanError(error)))}`,\n\t\t...fields,\n\t\t...(cleanupError.kind === 'not-failed'\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`Connection release also failed: ${escapeDiagnosticText(describeThrown(cleanupError.error))}`,\n\t\t\t\t]),\n\t].join('\\n');\n}\n\nfunction printHumanResult(result: PlanResult, dryRun: boolean): void {\n\tconsole.log(formatPlanHuman(result, dryRun));\n}\n\nexport function exitCodeForPlanResult(result: PlanResult): 0 | 1 {\n\treturn result.proveKind === 'blocked' || result.proveKind === 'inapplicable'\n\t\t? 1\n\t\t: 0;\n}\n\nexport const planCommand = new Command('plan')\n\t.description('Prove and persist a transition plan without applying it')\n\t.argument('<schema-file>', 'Schema DSL file')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema <name>', 'Database schema name', 'public')\n\t.option('--dry-run', 'Prove and render without persisting a transition run')\n\t.option('--format <format>', 'Output format: sql or json', 'sql')\n\t.exitOverride()\n\t// The root handler owns parse-error presentation. Suppress Commander's\n\t// eager stderr write so --format json remains a single JSON document.\n\t.configureOutput({ writeErr: () => {} })\n\t.action(\n\t\tasync (\n\t\t\tschemaFile: string,\n\t\t\toptions: {\n\t\t\t\tdb: string;\n\t\t\t\tschema?: string;\n\t\t\t\tdryRun?: boolean;\n\t\t\t\tformat?: PlanFormat;\n\t\t\t},\n\t\t) => {\n\t\t\tlet result: PlanResult | undefined;\n\t\t\ttry {\n\t\t\t\tresult = await runPlan({ ...options, schemaFile });\n\t\t\t\tif (options.format === 'json') {\n\t\t\t\t\tprintCliJson(formatPlanJson(result, options.dryRun === true));\n\t\t\t\t} else {\n\t\t\t\t\tprintHumanResult(result, options.dryRun === true);\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = exitCodeForPlanResult(result);\n\t\t\t} catch (error) {\n\t\t\t\tif (options.format === 'json') {\n\t\t\t\t\tprintCliJson(formatPlanFailureJson(error, result));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(formatPlanFailureHuman(error, result));\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t},\n\t);\n","/** Shared command-output shape for refusals that do not append a ledger event. */\n\nimport { escapeDiagnosticText } from '@dbsp/adapter-pgsql';\nimport type { LedgerAddress, LedgerRefusal } from '@dbsp/types';\nimport { REFUSAL_VOCABULARY, type RefusalCode } from '@dbsp/types';\n\n/** `recorded-plan` is a command-path state, never a durable ledger state. */\nexport type PreAppendRefusalState = LedgerRefusal['state'] | 'recorded-plan';\n\n/**\n * Unlike a durable LedgerRefusal, this document also carries the target whose\n * refusal prevented an append. Keep the prose in REFUSAL_VOCABULARY.\n */\nexport interface PreAppendRefusal {\n\treadonly address: LedgerAddress;\n\treadonly refusal: {\n\t\treadonly code: RefusalCode;\n\t\treadonly cause: string;\n\t\treadonly state: PreAppendRefusalState;\n\t\treadonly withheldAuthority: string;\n\t\treadonly resolvingCommand: string;\n\t};\n}\n\nexport function preAppendRefusalFor(\n\tcode: RefusalCode,\n\tinput: {\n\t\treadonly address: LedgerAddress;\n\t\treadonly state: PreAppendRefusalState;\n\t},\n): PreAppendRefusal {\n\treturn {\n\t\taddress: input.address,\n\t\trefusal: { code, ...REFUSAL_VOCABULARY[code], state: input.state },\n\t};\n}\n\n/** Human output mirrors the JSON document's four actionable refusal facts. */\nexport function formatPreAppendRefusalHuman(\n\tline: string,\n\trefusal: PreAppendRefusal,\n): string {\n\treturn [\n\t\tline,\n\t\t`refusal: ${escapeDiagnosticText(refusal.refusal.cause)}`,\n\t\t`address: ${escapeDiagnosticText(JSON.stringify(refusal.address))}`,\n\t\t`state: ${escapeDiagnosticText(refusal.refusal.state)}`,\n\t\t`withheld authority: ${escapeDiagnosticText(refusal.refusal.withheldAuthority)}`,\n\t\t`resolving command: ${escapeDiagnosticText(refusal.refusal.resolvingCommand)}`,\n\t].join('\\n');\n}\n","/**\n * ARCH-002 Block 3+4+5: Generate Command\n * CLI-DDL: Added DDL generation target\n * ARCH-005: Migrated to schema() API, removed legacy generators\n *\n * dbsp generate <target> - Generate code from schema.\n *\n * Targets:\n * - ddl: Generate SQL DDL (CREATE TABLE statements)\n *\n * Deprecated targets (removed in ARCH-005):\n * - manifest: Removed legacy manifest generator\n * - kysely: Removed legacy Kysely generator\n */\n\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport type { DbCasing, DialectCapabilities } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { loadSchema, loadSchemaFromCwd } from '../utils/schema-loader.js';\n\nexport type GenerateCasingOption = 'snake' | 'camel' | 'none';\n\nconst POSTGRESQL_VERSION_USAGE =\n\t'expected a PostgreSQL major version or dotted release version such as 14, 14.2, or 14.2.1; PostgreSQL 10 or later is supported';\n\nexport const generateCommand = new Command('generate')\n\t.description('Generate code from schema')\n\t.argument('<target>', 'Target to generate: ddl')\n\t.option('-s, --schema <path>', 'Path to schema file (default: auto-detect)')\n\t.option('-o, --out <dir>', 'Output directory (default: ./generated/<target>)')\n\t.option('--output <dir>', 'Output directory (alias for --out)')\n\t.option('--drop', 'Include DROP TABLE IF EXISTS statements (ddl only)')\n\t.option('--schema-name <name>', 'Database schema name (ddl only)')\n\t.option(\n\t\t'--postgresql-version <version>',\n\t\t'Target PostgreSQL major or dotted release version (for example, 14 or 14.2; ddl only)',\n\t)\n\t.option(\n\t\t'--dialect <name>',\n\t\t'Database dialect: postgresql | mysql | sqlite | mssql (default: postgresql)',\n\t)\n\t.option(\n\t\t'--casing <type>',\n\t\t'Column naming: snake | camel | none (default: based on dialect)',\n\t)\n\t.action(\n\t\tasync (\n\t\t\ttarget: string,\n\t\t\toptions: {\n\t\t\t\tschema?: string;\n\t\t\t\tout?: string;\n\t\t\t\toutput?: string;\n\t\t\t\tdrop?: boolean;\n\t\t\t\tschemaName?: string;\n\t\t\t\tpostgresqlVersion?: string;\n\t\t\t\tdialect?: string;\n\t\t\t\tcasing?: GenerateCasingOption;\n\t\t\t},\n\t\t) => {\n\t\t\ttry {\n\t\t\t\t// Reject the target BEFORE loading the schema: loading it executes the\n\t\t\t\t// user's schema module, and there is no reason to run their code for a\n\t\t\t\t// target we are going to refuse anyway.\n\t\t\t\tif (target === 'manifest' || target === 'kysely') {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Target '${target}' has been removed. ` +\n\t\t\t\t\t\t\t`Use 'ddl' for SQL generation, or the 'introspect' command to generate a schema file.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (target !== 'ddl') {\n\t\t\t\t\tthrow new Error(`Unknown target: ${target}. Available targets: ddl`);\n\t\t\t\t}\n\n\t\t\t\tlet targetDialectCapabilities: DialectCapabilities | undefined;\n\t\t\t\tif (options.postgresqlVersion !== undefined) {\n\t\t\t\t\tconst { derivePostgresqlCapabilitiesForVersion } = await import(\n\t\t\t\t\t\t'@dbsp/adapter-pgsql'\n\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttargetDialectCapabilities = derivePostgresqlCapabilitiesForVersion(\n\t\t\t\t\t\t\toptions.postgresqlVersion,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst reason = error instanceof Error ? ` ${error.message}` : '';\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Invalid --postgresql-version \"${options.postgresqlVersion}\": ${POSTGRESQL_VERSION_USAGE}.${reason}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Load schema (ARCH-005: only schema() format supported)\n\t\t\t\tlet schema: Awaited<ReturnType<typeof loadSchema>>;\n\t\t\t\tlet schemaPath: string;\n\n\t\t\t\tif (options.schema) {\n\t\t\t\t\tschema = await loadSchema(options.schema);\n\t\t\t\t\tschemaPath = options.schema;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await loadSchemaFromCwd();\n\t\t\t\t\tschema = result.schema;\n\t\t\t\t\tschemaPath = result.path;\n\t\t\t\t}\n\n\t\t\t\t// For DDL without --output, we output to stdout so use stderr for info\n\t\t\t\tconst outputPath = options.out ?? options.output;\n\t\t\t\tconst useStdout = target === 'ddl' && !outputPath;\n\t\t\t\tconst log = useStdout ? console.error : console.log;\n\n\t\t\t\tlog(`📄 Loaded schema from: ${schemaPath}`);\n\n\t\t\t\t// Validate dialect option\n\t\t\t\tconst dialect = options.dialect ?? 'postgresql';\n\t\t\t\tif (!isDialectSupported(dialect)) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`⚠️ Warning: Only 'postgresql' dialect is currently supported. Using postgresql.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Generate based on target\n\t\t\t\tswitch (target) {\n\t\t\t\t\tcase 'ddl': {\n\t\t\t\t\t\t// Determine casing: explicit option > schema export > dialect default.\n\t\t\t\t\t\tconst dbCasing =\n\t\t\t\t\t\t\tmapCasingToDbCasing(options.casing) ??\n\t\t\t\t\t\t\tschema.dbCasing ??\n\t\t\t\t\t\t\t('snake_case' as const);\n\t\t\t\t\t\tconst casingLabel = formatGenerateCasingLabel(dbCasing);\n\n\t\t\t\t\t\t// Import adapter from adapter-pgsql (compile-only, no DB connection needed)\n\t\t\t\t\t\tconst { createPgsqlCompileOnlyAdapter } = await import(\n\t\t\t\t\t\t\t'@dbsp/adapter-pgsql'\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst adapter = createPgsqlCompileOnlyAdapter({\n\t\t\t\t\t\t\tdbCasing,\n\t\t\t\t\t\t\t...(options.schemaName ? { schemaName: options.schemaName } : {}),\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// ARCH-005: Use schema.model directly (already ModelIR)\n\t\t\t\t\t\t\tconst ddlStatements = adapter.generateDDL(schema.model, {\n\t\t\t\t\t\t\t\t...(options.drop !== undefined && {\n\t\t\t\t\t\t\t\t\tincludeDropStatements: options.drop,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...(targetDialectCapabilities !== undefined && {\n\t\t\t\t\t\t\t\t\tdialectCapabilities: targetDialectCapabilities,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tconst ddlContent = ddlStatements.join('\\n\\n');\n\t\t\t\t\t\t\tconst outputPath = options.out ?? options.output;\n\n\t\t\t\t\t\t\tif (outputPath) {\n\t\t\t\t\t\t\t\t// Write to file if --output is specified\n\t\t\t\t\t\t\t\tconst outPath = outputPath.endsWith('.sql')\n\t\t\t\t\t\t\t\t\t? resolve(process.cwd(), outputPath)\n\t\t\t\t\t\t\t\t\t: resolve(process.cwd(), outputPath, 'schema.sql');\n\n\t\t\t\t\t\t\t\tmkdirSync(dirname(outPath), { recursive: true });\n\t\t\t\t\t\t\t\twriteFileSync(outPath, ddlContent, 'utf-8');\n\n\t\t\t\t\t\t\t\tconsole.log(`✅ Generated DDL: ${outPath}`);\n\t\t\t\t\t\t\t\tconsole.log(` Tables: ${schema.tableNames.length}`);\n\t\t\t\t\t\t\t\tconsole.log(` Statements: ${ddlStatements.length}`);\n\t\t\t\t\t\t\t\tconsole.log(` Casing: ${casingLabel}`);\n\t\t\t\t\t\t\t\tif (options.drop) {\n\t\t\t\t\t\t\t\t\tconsole.log(` Includes DROP statements`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (options.schemaName) {\n\t\t\t\t\t\t\t\t\tconsole.log(` Schema: ${options.schemaName}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Output DDL to stdout (for piping)\n\t\t\t\t\t\t\t\t// Info messages (schema loaded) went to stderr\n\t\t\t\t\t\t\t\tconsole.log(ddlContent);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconsole.error(`❌ ${message}`);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t},\n\t);\n\nexport function isDialectSupported(dialect: string): dialect is 'postgresql' {\n\treturn dialect === 'postgresql';\n}\n\nexport function mapCasingToDbCasing(\n\tcasing: GenerateCasingOption | undefined,\n): DbCasing | undefined {\n\tswitch (casing) {\n\t\tcase 'snake':\n\t\t\treturn 'snake_case';\n\t\tcase 'camel':\n\t\t\treturn 'camelCase';\n\t\tcase 'none':\n\t\t\treturn 'preserve';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction formatGenerateCasingLabel(\n\tdbCasing: DbCasing,\n): 'snake' | 'camel' | 'none' {\n\tswitch (dbCasing) {\n\t\tcase 'snake_case':\n\t\t\treturn 'snake';\n\t\tcase 'camelCase':\n\t\t\treturn 'camel';\n\t\tcase 'preserve':\n\t\t\treturn 'none';\n\t}\n}\n","/** Read managed-ledger state without appending an event or repairing storage. */\n\nimport { isDeepStrictEqual } from 'node:util';\nimport {\n\tcreatePgTransitionLessor,\n\tDBSP_LEDGER_EVENT_TABLE,\n\tescapeDiagnosticText,\n\treadPgCatalogueIdentity,\n\treadPgLedgerAddressChain,\n\treadPgLedgerMarker,\n} from '@dbsp/adapter-pgsql';\nimport { acquireTransitionLease, projectLedgerChain } from '@dbsp/core';\nimport {\n\tcanonicalResourceParent,\n\ttype LedgerAddress,\n\ttype LedgerChainProjection,\n\ttype LedgerHome,\n\ttype LedgerStableState,\n\ttype RefusalCode,\n} from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson, serializeCliJson } from '../utils/output.js';\n\nexport interface InspectOptions {\n\treadonly db: string;\n\treadonly schema?: string;\n\treadonly kind?: string;\n\t/** Parent selector for column/index/constraint resources, e.g. table:orders. */\n\treadonly parent?: string;\n\t/** Select the database ledger (currently for database-scoped extensions). */\n\treadonly databaseLedger?: boolean;\n\treadonly format?: 'text' | 'json';\n}\n\nexport interface InspectResult {\n\treadonly address?: LedgerAddress;\n\treadonly ledger: LedgerHome;\n\treadonly marker:\n\t\t| Awaited<ReturnType<typeof readPgLedgerMarker>>\n\t\t| { readonly kind: 'unreadable'; readonly reason: string };\n\treadonly projection?: ReturnType<typeof projectLedgerChain>;\n\t/**\n\t * A terminal ledger refusal remains a diagnostic after its claim is closed.\n\t * It is deliberately derived from the immutable chain: inspect must not\n\t * append a second event merely to explain an earlier refusal.\n\t */\n\treadonly refusal?: {\n\t\treadonly code: RefusalCode;\n\t\treadonly cause: string;\n\t\treadonly address: LedgerAddress;\n\t\treadonly state: LedgerStableState;\n\t\treadonly withheldAuthority: string;\n\t\treadonly resolvingCommand: string;\n\t};\n\t/** A selected address exposes an interrupted re-address pair without repair. */\n\treadonly readdressPair?: {\n\t\treadonly pairId: string;\n\t\treadonly state: 'open';\n\t};\n\treadonly live:\n\t\t| { readonly kind: 'not-requested' }\n\t\t| { readonly kind: 'present'; readonly catalogueIdentity: unknown }\n\t\t| { readonly kind: 'absent' }\n\t\t| { readonly kind: 'catalogue-unavailable'; readonly reason: string };\n\t/** Comparison is derived from reads only; inspect never repairs drift. */\n\treadonly liveDrift?:\n\t\t| { readonly kind: 'matches-ledger' }\n\t\t| { readonly kind: 'catalogue-drift'; readonly detail: string }\n\t\t| { readonly kind: 'not-comparable'; readonly detail: string };\n\t/** Identifies the failed read path without mislabelling it as catalogue drift. */\n\treadonly failedSubsystem?:\n\t\t| { readonly subsystem: 'ledger'; readonly reason: string }\n\t\t| { readonly subsystem: 'catalogue'; readonly reason: string };\n\t/** Present for an unqualified inspect; no read path creates or repairs it. */\n\treadonly addresses?: readonly LedgerAddress[];\n}\n\n/**\n * Make a terminal `refused` event actionable without inventing mutable state.\n * A refused claim closes the chain at its prior stable state, so a fresh\n * generator-path apply is the only command that can seek new authority.\n */\nexport function inspectRefusal(\n\tprojection: LedgerChainProjection | undefined,\n): InspectResult['refusal'] | undefined {\n\tif (projection?.kind !== 'projected-ledger-chain') return undefined;\n\tconst predecessors = new Set(\n\t\tprojection.events\n\t\t\t.map((event) => event.predecessor)\n\t\t\t.filter(\n\t\t\t\t(predecessor): predecessor is string => predecessor !== undefined,\n\t\t\t),\n\t);\n\tconst terminals = projection.events.filter(\n\t\t(event) => !predecessors.has(event.eventId),\n\t);\n\tconst refused = terminals.length === 1 ? terminals[0] : undefined;\n\tif (refused?.eventKind !== 'refused' || refused.refusal === undefined)\n\t\treturn undefined;\n\treturn {\n\t\tcode: refused.refusal.code,\n\t\tcause: refused.refusal.cause,\n\t\taddress: projection.address,\n\t\tstate: refused.refusal.state,\n\t\twithheldAuthority: refused.refusal.withheldAuthority,\n\t\tresolvingCommand: refused.refusal.resolvingCommand,\n\t};\n}\n\nfunction inspectLiveDrift(\n\tprojection: InspectResult['projection'],\n\tlive: Awaited<ReturnType<typeof readPgCatalogueIdentity>>,\n): NonNullable<InspectResult['liveDrift']> {\n\tif (projection?.kind !== 'projected-ledger-chain')\n\t\treturn { kind: 'not-comparable', detail: 'ledger chain is unavailable' };\n\tconst terminalIds = new Set(\n\t\tprojection.events\n\t\t\t.map((event) => event.predecessor)\n\t\t\t.filter((value): value is string => value !== undefined),\n\t);\n\tconst terminal = projection.events.find(\n\t\t(event) => !terminalIds.has(event.eventId),\n\t);\n\tif (!terminal?.catalogueIdentity)\n\t\treturn {\n\t\t\tkind: 'not-comparable',\n\t\t\tdetail: 'ledger terminal has no catalogue identity',\n\t\t};\n\tif (!live?.catalogueIdentity)\n\t\treturn {\n\t\t\tkind: 'catalogue-drift',\n\t\t\tdetail:\n\t\t\t\t'ledger records a present catalogue identity but the object is absent',\n\t\t};\n\treturn isDeepStrictEqual(terminal.catalogueIdentity, live.catalogueIdentity)\n\t\t? { kind: 'matches-ledger' }\n\t\t: {\n\t\t\t\tkind: 'catalogue-drift',\n\t\t\t\tdetail: 'live catalogue identity differs from the ledger terminal',\n\t\t\t};\n}\n\n/** Human inspect output is intentionally the same escaped document as JSON. */\nexport function renderInspectHuman(result: InspectResult): string {\n\treturn serializeCliJson(result);\n}\n\nfunction quoteIdentifier(value: string): string {\n\treturn `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\nasync function readLedgerAddresses(\n\tlease: {\n\t\tquery(\n\t\t\tsql: string,\n\t\t\tparams?: unknown,\n\t\t): Promise<{ rows: readonly Record<string, unknown>[] }>;\n\t},\n\tledger: LedgerHome,\n): Promise<readonly LedgerAddress[]> {\n\tconst schema = ledger.scope === 'database' ? 'dbsp_meta' : ledger.schema;\n\tif (!schema) throw new Error('schema ledger target is missing its schema');\n\tconst rows = await lease.query(\n\t\t`SELECT DISTINCT address_engine, address_database, address_schema, address_parent, address_kind, address_name FROM ${quoteIdentifier(schema)}.${quoteIdentifier(DBSP_LEDGER_EVENT_TABLE)} ORDER BY address_engine, address_database, address_schema, address_kind, address_name`,\n\t);\n\treturn rows.rows.map((row) => {\n\t\tif (\n\t\t\ttypeof row.address_engine !== 'string' ||\n\t\t\ttypeof row.address_database !== 'string' ||\n\t\t\ttypeof row.address_schema !== 'string' ||\n\t\t\ttypeof row.address_kind !== 'string' ||\n\t\t\ttypeof row.address_name !== 'string'\n\t\t)\n\t\t\tthrow new Error('ledger address is unreadable');\n\t\treturn {\n\t\t\tscope: ledger.scope,\n\t\t\tengine: row.address_engine,\n\t\t\tdatabase: row.address_database,\n\t\t\t...(row.address_schema === '' ? {} : { schema: row.address_schema }),\n\t\t\t...(row.address_parent == null\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tparent:\n\t\t\t\t\t\t\ttypeof row.address_parent === 'string'\n\t\t\t\t\t\t\t\t? JSON.parse(row.address_parent)\n\t\t\t\t\t\t\t\t: (row.address_parent as LedgerAddress),\n\t\t\t\t\t}),\n\t\t\tkind: row.address_kind as LedgerAddress['kind'],\n\t\t\tname: row.address_name,\n\t\t};\n\t});\n}\n\nfunction addressParts(\n\tvalue: string,\n\tdefaultKind: string,\n): {\n\tkind: string;\n\tname: string;\n} {\n\tconst separator = value.indexOf(':');\n\tif (separator < 1) return { kind: defaultKind, name: value };\n\treturn { kind: value.slice(0, separator), name: value.slice(separator + 1) };\n}\n\n/** Parse the compact inspect selector; parents remain intentionally explicit later. */\nexport function inspectAddress(\n\tdatabase: string,\n\tschema: string,\n\tselector: string,\n\tkind = 'table',\n\tparentSelector?: string,\n\tscope: LedgerAddress['scope'] = 'schema',\n): LedgerAddress {\n\tconst parsed = addressParts(selector, kind);\n\tif (!parsed.name) throw new Error('inspect address name must not be empty');\n\tif (!parsed.kind) throw new Error('inspect address kind must not be empty');\n\tconst parent = parentSelector\n\t\t? addressParts(parentSelector, 'table')\n\t\t: undefined;\n\tif (parent && (!parent.kind || !parent.name))\n\t\tthrow new Error('inspect parent address must be kind:name');\n\tif (\n\t\t!parent &&\n\t\t['column', 'index', 'constraint', 'policy'].includes(parsed.kind)\n\t)\n\t\tthrow new Error(\n\t\t\t`inspect address ${parsed.kind}:${parsed.name} requires --parent <kind:name>`,\n\t\t);\n\treturn {\n\t\tscope,\n\t\tengine: 'postgresql',\n\t\tdatabase,\n\t\t...(scope === 'schema' ? { schema } : {}),\n\t\t...(parent\n\t\t\t? {\n\t\t\t\t\tparent: canonicalResourceParent({\n\t\t\t\t\t\tengine: 'postgresql',\n\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\t...(scope === 'schema' ? { schema } : {}),\n\t\t\t\t\t\tkind: parent.kind as LedgerAddress['kind'],\n\t\t\t\t\t\tname: parent.name,\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tkind: parsed.kind as LedgerAddress['kind'],\n\t\tname: parsed.name,\n\t};\n}\n\nexport async function runInspect(\n\tselector: string | undefined,\n\toptions: InspectOptions,\n): Promise<InspectResult> {\n\tconst { pool } = await createDbConnection(options.db);\n\tconst schema = options.schema ?? 'public';\n\tconst ledger: LedgerHome = options.databaseLedger\n\t\t? { scope: 'database' }\n\t\t: { scope: 'schema', schema };\n\ttry {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tlet marker: InspectResult['marker'];\n\t\t\ttry {\n\t\t\t\tmarker = await readPgLedgerMarker(lease.session, ledger);\n\t\t\t} catch (error) {\n\t\t\t\tmarker = {\n\t\t\t\t\tkind: 'unreadable',\n\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!selector) {\n\t\t\t\ttry {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tledger,\n\t\t\t\t\t\tmarker,\n\t\t\t\t\t\taddresses: await readLedgerAddresses(lease.session, ledger),\n\t\t\t\t\t\tlive: { kind: 'not-requested' },\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tledger,\n\t\t\t\t\t\tmarker,\n\t\t\t\t\t\taddresses: [],\n\t\t\t\t\t\tlive: {\n\t\t\t\t\t\t\tkind: 'catalogue-unavailable',\n\t\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfailedSubsystem: {\n\t\t\t\t\t\t\tsubsystem: 'ledger',\n\t\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst databaseRow = await lease.session.query(\n\t\t\t\t'SELECT pg_catalog.current_database() AS database',\n\t\t\t);\n\t\t\tconst database = databaseRow.rows[0]?.database;\n\t\t\tif (typeof database !== 'string')\n\t\t\t\tthrow new Error('PostgreSQL current_database() is unreadable');\n\t\t\tconst address = inspectAddress(\n\t\t\t\tdatabase,\n\t\t\t\tschema,\n\t\t\t\tselector,\n\t\t\t\toptions.kind,\n\t\t\t\toptions.parent,\n\t\t\t\tledger.scope,\n\t\t\t);\n\t\t\tlet projection: InspectResult['projection'];\n\t\t\ttry {\n\t\t\t\tprojection = projectLedgerChain(\n\t\t\t\t\tawait readPgLedgerAddressChain(lease.session, ledger, address),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\t// A missing/malformed ledger is a readable diagnostic, never a reason\n\t\t\t\t// for inspect to create its structures.\n\t\t\t\treturn {\n\t\t\t\t\taddress,\n\t\t\t\t\tledger,\n\t\t\t\t\tmarker,\n\t\t\t\t\tlive: { kind: 'not-requested' },\n\t\t\t\t\tliveDrift: {\n\t\t\t\t\t\tkind: 'not-comparable',\n\t\t\t\t\t\tdetail: 'ledger chain is unavailable',\n\t\t\t\t\t},\n\t\t\t\t\tfailedSubsystem: {\n\t\t\t\t\t\tsubsystem: 'ledger',\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst live = await readPgCatalogueIdentity(lease.session, address);\n\t\t\t\tconst refusal = inspectRefusal(projection);\n\t\t\t\tconst openReaddress =\n\t\t\t\t\tprojection?.kind === 'projected-ledger-chain' &&\n\t\t\t\t\tprojection.openClaim?.kind === 'readdress-intent' &&\n\t\t\t\t\tprojection.openClaim.event.pairId\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpairId: projection.openClaim.event.pairId,\n\t\t\t\t\t\t\t\tstate: 'open' as const,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\t\t\t\treturn {\n\t\t\t\t\taddress,\n\t\t\t\t\tledger,\n\t\t\t\t\tmarker,\n\t\t\t\t\tprojection,\n\t\t\t\t\t...(refusal === undefined ? {} : { refusal }),\n\t\t\t\t\t...(openReaddress === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { readdressPair: openReaddress }),\n\t\t\t\t\tliveDrift: inspectLiveDrift(projection, live),\n\t\t\t\t\tlive: live?.catalogueIdentity\n\t\t\t\t\t\t? { kind: 'present', catalogueIdentity: live.catalogueIdentity }\n\t\t\t\t\t\t: { kind: 'absent' },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\taddress,\n\t\t\t\t\tledger,\n\t\t\t\t\tmarker,\n\t\t\t\t\tprojection,\n\t\t\t\t\tlive: {\n\t\t\t\t\t\tkind: 'catalogue-unavailable',\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t\tliveDrift: {\n\t\t\t\t\t\tkind: 'not-comparable',\n\t\t\t\t\t\tdetail: 'live catalogue read is unavailable',\n\t\t\t\t\t},\n\t\t\t\t\tfailedSubsystem: {\n\t\t\t\t\t\tsubsystem: 'catalogue',\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n\nexport const inspectCommand = new Command('inspect')\n\t.description(\n\t\t'Read managed ledger state and live drift; never appends ledger events',\n\t)\n\t.argument('[address]', 'Address as name or kind:name')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema <name>', 'Schema ledger to read', 'public')\n\t.option('--kind <kind>', 'Kind for an unqualified address', 'table')\n\t.option(\n\t\t'--parent <kind:name>',\n\t\t'Required parent for column, index, constraint, or policy',\n\t)\n\t.option('--database-ledger', 'Read the database ledger (for extensions)')\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (address: string | undefined, options: InspectOptions) => {\n\t\ttry {\n\t\t\tconst result = await runInspect(address, options);\n\t\t\tif (options.format === 'json') printCliJson(result);\n\t\t\telse console.log(renderInspectHuman(result));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (options.format === 'json')\n\t\t\t\tprintCliJson({ outcome: 'inspect-failed', error: message });\n\t\t\telse console.error(`inspect-failed: ${escapeDiagnosticText(message)}`);\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t});\n","/**\n * CLI-DDL: Introspect Command\n *\n * dbsp introspect - Generate schema.ts from database introspection.\n */\n\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { Command } from 'commander';\nimport {\n\tgenerateSchemaFileWithDiagnostics,\n\ttype SchemaCodegenOptions,\n} from '../generators/schema-codegen.js';\nimport { createDbConnection, redactDbUrl } from '../utils/db-utils.js';\n\nfunction uniqueWarnings(warnings: readonly string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst unique: string[] = [];\n\tfor (const warning of warnings) {\n\t\tif (seen.has(warning)) continue;\n\t\tseen.add(warning);\n\t\tunique.push(warning);\n\t}\n\treturn unique;\n}\n\nfunction reportWarnings(warnings: readonly string[]): void {\n\tfor (const warning of warnings) {\n\t\tconsole.log(` ⚠️ ${warning}`);\n\t}\n}\n\nexport const introspectCommand = new Command('introspect')\n\t.description('Generate schema.ts from database introspection')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('-o, --out <file>', 'Output schema file', './dbsp.schema.ts')\n\t.option('--schema-name <name>', 'Database schema name', 'public')\n\t.option(\n\t\t'--exclude <patterns>',\n\t\t'Tables to exclude (comma-separated glob patterns)',\n\t\t'_migrations,_prisma*,pg_*',\n\t)\n\t.option('--include <patterns>', 'Tables to include (comma-separated)')\n\t.option('--no-db-type-comments', 'Omit original DB type comments')\n\t.option(\n\t\t'--db-casing <casing>',\n\t\t'Database column casing (snake_case → camelCase in generated code)',\n\t\t'snake_case',\n\t)\n\t.action(\n\t\tasync (options: {\n\t\t\tdb: string;\n\t\t\tout: string;\n\t\t\tschemaName: string;\n\t\t\texclude: string;\n\t\t\tinclude?: string;\n\t\t\tdbTypeComments: boolean;\n\t\t\tdbCasing: 'snake_case' | 'camelCase' | 'preserve';\n\t\t}) => {\n\t\t\tconst redactedUrl = redactDbUrl(options.db);\n\n\t\t\tconsole.log(`🔍 Introspecting database: ${redactedUrl}`);\n\t\t\tconsole.log(` Schema: ${options.schemaName}`);\n\t\t\tif (options.exclude) {\n\t\t\t\tconsole.log(` Excluding: ${options.exclude}`);\n\t\t\t}\n\t\t\tconsole.log('');\n\n\t\t\ttry {\n\t\t\t\t// Connect to database\n\t\t\t\tconst { pool } = await createDbConnection(options.db);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Import introspect from adapter-pgsql\n\t\t\t\t\tconst { introspect } = await import('@dbsp/adapter-pgsql');\n\n\t\t\t\t\t// Build introspection options from CLI flags\n\t\t\t\t\tconst excludePatterns = options.exclude\n\t\t\t\t\t\t? options.exclude.split(',').map((s) => s.trim())\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst includePatterns = options.include\n\t\t\t\t\t\t? options.include.split(',').map((s) => s.trim())\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t// Introspect the database directly (returns IntrospectedModelIR)\n\t\t\t\t\tconst model = await introspect(pool, {\n\t\t\t\t\t\tschema: options.schemaName,\n\t\t\t\t\t\t...(excludePatterns ? { exclude: excludePatterns } : {}),\n\t\t\t\t\t\t...(includePatterns ? { include: includePatterns } : {}),\n\t\t\t\t\t});\n\n\t\t\t\t\t// Report what we found\n\t\t\t\t\tconst tableCount = model.tables.size;\n\t\t\t\t\tconst relationCount = model.relations.size;\n\t\t\t\t\tconst hierarchyCount = model.hierarchies?.length ?? 0;\n\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`📊 Found ${tableCount} tables, ${relationCount} relations, ${hierarchyCount} hierarchies`,\n\t\t\t\t\t);\n\n\t\t\t\t\t// Generate schema file — pass metadata from introspection\n\t\t\t\t\tconst codegenOptions: SchemaCodegenOptions = {\n\t\t\t\t\t\tsourceUrl: options.db,\n\t\t\t\t\t\tincludeDbTypeComments: options.dbTypeComments,\n\t\t\t\t\t\tintrospectedAt: model.introspectedAt,\n\t\t\t\t\t\tdbCasing: options.dbCasing,\n\t\t\t\t\t};\n\n\t\t\t\t\tconst generated = generateSchemaFileWithDiagnostics(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tcodegenOptions,\n\t\t\t\t\t);\n\t\t\t\t\tconst warnings = uniqueWarnings(generated.warnings);\n\t\t\t\t\tif (warnings.length > 0) {\n\t\t\t\t\t\treportWarnings(warnings);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log('');\n\n\t\t\t\t\t// Write output file\n\t\t\t\t\tconst outPath = resolve(process.cwd(), options.out);\n\t\t\t\t\tmkdirSync(dirname(outPath), { recursive: true });\n\t\t\t\t\twriteFileSync(outPath, generated.code, 'utf-8');\n\n\t\t\t\t\tconsole.log(`✅ Generated schema: ${outPath}`);\n\t\t\t\t\tconsole.log(` Tables: ${tableCount}`);\n\t\t\t\t\tconsole.log(` Relations: ${relationCount}`);\n\t\t\t\t} finally {\n\t\t\t\t\t// Close database connection\n\t\t\t\t\tawait pool.end();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconsole.error(`❌ ${message}`);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t},\n\t);\n","/** Separately privileged ledger cutover; it never routes through apply. */\nimport { createHash } from 'node:crypto';\nimport { mkdtemp, open, rename, rm } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n\tescapeDiagnosticText,\n\tgetNamingPluginForDbCasing,\n\ttype PgReinitializePreflightPool,\n\trunPgReinitializePreflight,\n} from '@dbsp/adapter-pgsql';\nimport { declarationSetFromModel } from '@dbsp/core';\nimport type { DeclarationSet, ReinitializePreflightReport } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { loadSchema } from '../utils/schema-loader.js';\n\nexport interface PreflightOptions {\n\treadonly db: string;\n\treadonly schemaFile: string;\n\treadonly scopes: readonly string[];\n\treadonly reinitialize: boolean;\n\treadonly out: string;\n}\n\ninterface CommanderPreflightOptions extends Omit<PreflightOptions, 'scopes'> {\n\treadonly scope: readonly string[];\n}\n\nexport interface PreflightDeps {\n\treadonly createDbConnection: typeof createDbConnection;\n\treadonly loadSchema: typeof loadSchema;\n}\n\nconst defaultDeps: PreflightDeps = { createDbConnection, loadSchema };\n\nexport interface AdoptionFileSystem {\n\treadonly mkdtemp: (prefix: string) => Promise<string>;\n\treadonly open: (\n\t\tpath: string,\n\t\tflags: string,\n\t\tmode?: number,\n\t) => Promise<{\n\t\twriteFile(value: string, encoding: BufferEncoding): Promise<void>;\n\t\tsync(): Promise<void>;\n\t\tclose(): Promise<void>;\n\t}>;\n\treadonly rename: (from: string, to: string) => Promise<void>;\n\treadonly rm: (\n\t\tpath: string,\n\t\toptions: { recursive: boolean; force: boolean },\n\t) => Promise<void>;\n}\n\nconst nodeAdoptionFileSystem: AdoptionFileSystem = {\n\tmkdtemp,\n\topen,\n\trename,\n\trm,\n};\n\n/**\n * The only observable destination is `out`; the temporary name is never\n * published. An existing destination is deliberately replaced atomically only\n * after the complete new document is durable.\n */\nexport async function writeAdoptionFileAtomically(\n\tout: string,\n\treport: ReinitializePreflightReport,\n\tfileSystem: AdoptionFileSystem = nodeAdoptionFileSystem,\n): Promise<void> {\n\tconst tempDirectory = await fileSystem.mkdtemp(\n\t\tjoin(dirname(out), '.dbsp-reinitialize-'),\n\t);\n\tconst tempPath = join(tempDirectory, 'adoption.json');\n\ttry {\n\t\tconst file = await fileSystem.open(tempPath, 'wx', 0o600);\n\t\ttry {\n\t\t\tawait file.writeFile(\n\t\t\t\tJSON.stringify(\n\t\t\t\t\t{\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\tadoptions: report.adoptionCandidates,\n\t\t\t\t\t},\n\t\t\t\t\tnull,\n\t\t\t\t),\n\t\t\t\t'utf8',\n\t\t\t);\n\t\t\tawait file.sync();\n\t\t} finally {\n\t\t\tawait file.close();\n\t\t}\n\t\tawait fileSystem.rename(tempPath, out);\n\t\tconst parent = await fileSystem.open(dirname(out), 'r');\n\t\ttry {\n\t\t\tawait parent.sync();\n\t\t} finally {\n\t\t\tawait parent.close();\n\t\t}\n\t} finally {\n\t\tawait fileSystem.rm(tempDirectory, { recursive: true, force: true });\n\t}\n}\n\nasync function databaseName(pool: {\n\tquery(sql: string): Promise<{ rows: readonly Record<string, unknown>[] }>;\n}): Promise<string> {\n\tconst result = await pool.query(\n\t\t'SELECT pg_catalog.current_database() AS database',\n\t);\n\tconst name = result.rows[0]?.database;\n\tif (typeof name !== 'string')\n\t\tthrow new Error('current database could not be read');\n\treturn name;\n}\n\nfunction declarationsForScopes(\n\tmodel: Awaited<ReturnType<typeof loadSchema>>['model'],\n\tdatabase: string,\n\tscopes: readonly string[],\n\tnaming: Parameters<typeof declarationSetFromModel>[2],\n): DeclarationSet {\n\tconst declarations = scopes.flatMap(\n\t\t(schema) =>\n\t\t\tdeclarationSetFromModel(\n\t\t\t\tmodel,\n\t\t\t\t{ engine: 'postgresql', database, schema },\n\t\t\t\tnaming,\n\t\t\t).declarations,\n\t);\n\t// Database-scoped declarations (extensions) are shared by every tenant\n\t// model, while their home ledger is singular. Keep one exact declaration.\n\tconst seen = new Set<string>();\n\tconst uniqueDeclarations = declarations.filter((declaration) => {\n\t\tconst key = JSON.stringify([\n\t\t\tdeclaration.address.kind,\n\t\t\tdeclaration.address.schema ?? null,\n\t\t\tdeclaration.address.parent ?? null,\n\t\t\tdeclaration.address.name,\n\t\t]);\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n\tconst canonical = stableJson({\n\t\tversion: 1,\n\t\tdeclarations: uniqueDeclarations,\n\t});\n\treturn {\n\t\tversion: 1,\n\t\tdigest: createHash('sha256').update(canonical).digest('hex'),\n\t\tdeclarations: uniqueDeclarations,\n\t};\n}\n\nfunction stableJson(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value);\n\tif (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n\tconst record = value as Record<string, unknown>;\n\treturn `{${Object.keys(record)\n\t\t.sort()\n\t\t.map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)\n\t\t.join(',')}}`;\n}\n\nexport async function runPreflight(\n\toptions: PreflightOptions,\n\tdeps: PreflightDeps = defaultDeps,\n): Promise<ReinitializePreflightReport> {\n\tif (!options.reinitialize)\n\t\tthrow new Error('dbsp preflight requires --reinitialize');\n\tif (!options.out)\n\t\tthrow new Error('dbsp preflight --reinitialize requires --out <file>');\n\tif (options.scopes.length === 0)\n\t\tthrow new Error(\n\t\t\t'dbsp preflight requires at least one explicit --scope <schema>',\n\t\t);\n\tconst loaded = await deps.loadSchema(options.schemaFile);\n\tconst connection = await deps.createDbConnection(options.db);\n\ttry {\n\t\tconst database = await databaseName(connection.pool);\n\t\tconst declarations = declarationsForScopes(\n\t\t\tloaded.model,\n\t\t\tdatabase,\n\t\t\toptions.scopes,\n\t\t\tgetNamingPluginForDbCasing(loaded.dbCasing ?? 'preserve'),\n\t\t);\n\t\treturn await runPgReinitializePreflight({\n\t\t\tpool: connection.pool as unknown as PgReinitializePreflightPool,\n\t\t\tschemas: options.scopes,\n\t\t\tdeclarations,\n\t\t\twriteAdoptionFile: (report) =>\n\t\t\t\twriteAdoptionFileAtomically(options.out, report),\n\t\t});\n\t} finally {\n\t\tawait connection.pool.end();\n\t}\n}\n\nfunction formatScope(\n\tscope: ReinitializePreflightReport['scopes'][number],\n): string {\n\tconst name =\n\t\tscope.ledger.scope === 'database'\n\t\t\t? 'dbsp_meta'\n\t\t\t: (scope.ledger.schema ?? 'unknown');\n\tif (scope.outcome === 'failed')\n\t\treturn `${escapeDiagnosticText(name)}: failed (${escapeDiagnosticText(scope.reason.step)}: ${escapeDiagnosticText(scope.reason.message)})`;\n\treturn scope.refusal\n\t\t? `${escapeDiagnosticText(name)}: ${escapeDiagnosticText(scope.outcome)} (${escapeDiagnosticText(scope.refusal.code)}: ${escapeDiagnosticText(scope.refusal.detail)})`\n\t\t: `${escapeDiagnosticText(name)}: ${escapeDiagnosticText(scope.outcome)}`;\n}\n\n/**\n * A cutover spans independently committed scopes. Keep the durable split\n * visible in one line so a failed middle scope cannot be mistaken for an\n * all-or-nothing result; an empty class is explicitly reported.\n */\nexport function formatReinitializeSplit(\n\tscopes: ReinitializePreflightReport['scopes'],\n): string {\n\tconst names = (predicate: (scope: (typeof scopes)[number]) => boolean) =>\n\t\tscopes\n\t\t\t.filter(predicate)\n\t\t\t.map((scope) =>\n\t\t\t\tescapeDiagnosticText(\n\t\t\t\t\tscope.ledger.scope === 'database'\n\t\t\t\t\t\t? 'dbsp_meta'\n\t\t\t\t\t\t: (scope.ledger.schema ?? 'unknown'),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.join(',') || 'none';\n\treturn `reinitialize-split: changed=${names((scope) => scope.outcome === 'current')}; failed=${names((scope) => scope.outcome === 'failed')}; not-attempted=${names((scope) => scope.outcome === 'not-attempted')}`;\n}\n\nexport const preflightCommand = new Command('preflight')\n\t.description(\n\t\t'Run the separately privileged managed-ledger reinitialize cutover',\n\t)\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.requiredOption(\n\t\t'--reinitialize',\n\t\t'Allow only the explicit reinitialize-preflight flow',\n\t)\n\t.requiredOption(\n\t\t'--out <file>',\n\t\t'Write adoption candidates to this exact file',\n\t)\n\t.requiredOption('--schema-file <path>', 'Current Schema DSL file')\n\t.requiredOption('--scope <schema...>', 'Explicit tenant schema scope list')\n\t.action(async (options: CommanderPreflightOptions) => {\n\t\t// This instruction deliberately precedes opening the database connection.\n\t\tconsole.log(\n\t\t\t'Before continuing, take a database dump. This reinitialize-preflight changes managed-ledger structures but appends no events.',\n\t\t);\n\t\ttry {\n\t\t\tconst report = await runPreflight({ ...options, scopes: options.scope });\n\t\t\tfor (const scope of report.scopes) console.log(formatScope(scope));\n\t\t\tconsole.log(formatReinitializeSplit(report.scopes));\n\t\t\tif (report.scopes.some((scope) => scope.outcome === 'failed')) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.log(\n\t\t\t\t`Wrote ${report.adoptionCandidates.length} adoption candidate(s) to ${options.out}.`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconsole.error(\n\t\t\t\tescapeDiagnosticText(\n\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t),\n\t\t\t);\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t});\n","/** Resolve only the open managed claims durably linked to one run. */\nimport { createHash } from 'node:crypto';\nimport {\n\tassertCreateUniqueIndexConcurrentlyRecoveryNotInvalid,\n\tassertPgDatabaseWritable,\n\tescapeDiagnosticText,\n\tisPgDatabaseReadOnlyError,\n\treadPgLedgerAddressChain,\n\treadPgLedgerReservationsForExecution,\n\treadPgLedgerScopeCurrency,\n\treadTransitionJournal,\n\treadVerifiedPgLedgerReservationsForPair,\n\trecoverPgReaddressPair,\n\twithPgTransitionRunLock,\n} from '@dbsp/adapter-pgsql';\n// Recovery's raw claim primitive is intentionally internal: this command owns\n// the durable envelope reconstruction and run lock that make it admissible.\nimport { recoverPgOutcomeClaim } from '@dbsp/adapter-pgsql/internal';\nimport {\n\tacquireExclusiveTransitionLease,\n\tassumptionAccepted,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\tresourceScopeCovers,\n\ttransitionPlanDigest,\n} from '@dbsp/core';\nimport type {\n\tLedgerHome,\n\tLedgerPayload,\n\tLedgerReservationRow,\n\tOutcomeIndeterminateRecoveryEvidence,\n} from '@dbsp/types';\nimport { sameLedgerAddress } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport {\n\tformatPreAppendRefusalHuman,\n\ttype PreAppendRefusal,\n\tpreAppendRefusalFor,\n} from './refusal-output.js';\n\nexport interface ReconcileOptions {\n\treadonly db: string;\n\treadonly format?: 'text' | 'json';\n}\n\nexport interface ReconcileResult {\n\treadonly outcome:\n\t\t| 'database-read-only'\n\t\t| 'reconcile-claim-selection-unavailable'\n\t\t| 'reconcile-run-unavailable'\n\t\t| 'reconcile-unresolved'\n\t\t| 'reconcile-completed';\n\treadonly runId: string;\n\treadonly addresses: readonly unknown[];\n\treadonly detail?: string;\n\t/** A closed, machine-readable cause for a command-level recovery failure. */\n\treadonly failureCause?: ReconcileFailureCause;\n\t/** One entry per selected root claim; non-appends retain their reason. */\n\treadonly recovery?: readonly ReconcileRecoveryReport[];\n\t/** Present when recovery refused before it could append a ledger outcome. */\n\treadonly refusal?: PreAppendRefusal;\n}\n\n/** Distinguishes retryable connection failures from unsafe recovery evidence. */\nexport type ReconcileFailureCause =\n\t| 'authentication'\n\t| 'transport'\n\t| 'malformed-journal'\n\t| 'catalogue';\n\nfunction pgSqlState(error: unknown): string | undefined {\n\tif (typeof error !== 'object' || error === null || !('code' in error))\n\t\treturn undefined;\n\tconst code = error.code;\n\treturn typeof code === 'string' ? code : undefined;\n}\n\nfunction isTransportError(error: unknown): boolean {\n\tif (typeof error !== 'object' || error === null || !('code' in error))\n\t\treturn false;\n\tconst code = error.code;\n\treturn (\n\t\ttypeof code === 'string' &&\n\t\t[\n\t\t\t'ECONNREFUSED',\n\t\t\t'ECONNRESET',\n\t\t\t'EHOSTUNREACH',\n\t\t\t'ENETUNREACH',\n\t\t\t'ETIMEDOUT',\n\t\t].includes(code)\n\t);\n}\n\n/** Classify PostgreSQL failures by SQLSTATE; no server message is parsed. */\nexport function classifyReconcileFailure(\n\terror: unknown,\n\tstage: 'journal' | 'catalogue' | 'reconcile',\n): ReconcileFailureCause {\n\tconst state = pgSqlState(error);\n\tif (state === '28000' || state === '28P01') return 'authentication';\n\tif (state?.startsWith('08') || isTransportError(error)) return 'transport';\n\tif (stage === 'journal') return 'malformed-journal';\n\treturn 'catalogue';\n}\n\nexport interface ReconcileRecoveryReport {\n\treadonly address: LedgerReservationRow['address'];\n\treadonly outcome: PgRecoveryReportKind;\n\treadonly reason?: string;\n\t/** Present when the recovery row stopped on a classified evidence failure. */\n\treadonly failureCause?: ReconcileFailureCause;\n\treadonly refusal?: PreAppendRefusal;\n\t/** Re-address recovery is reported and resolved as one reserved closure. */\n\treadonly pairId?: string;\n}\n\ntype PgRecoveryReportKind =\n\t| 'appended'\n\t| 'already-appended'\n\t| 'no-open-claim'\n\t| 'pending'\n\t| 'blocked'\n\t| 'malformed-chain'\n\t| 'protocol-refused'\n\t| 'transport-ambiguous'\n\t| 'refused-pair'\n\t| 'indeterminate-pair';\n\nfunction ledgerHome(address: LedgerReservationRow['address']): LedgerHome {\n\tif (address.scope === 'database') return { scope: 'database' };\n\tif (!address.schema)\n\t\tthrow new Error(\n\t\t\t`schema-scoped managed claim ${address.name} has no schema`,\n\t\t);\n\treturn { scope: 'schema', schema: address.schema };\n}\n\nfunction recoveryPayload(\n\tidentity: Parameters<\n\t\tNonNullable<Parameters<typeof recoverPgOutcomeClaim>[1]['readBack']>\n\t>[2],\n): LedgerPayload {\n\tconst value = JSON.parse(\n\t\tJSON.stringify({ catalogueIdentity: identity }),\n\t) as LedgerPayload['value'];\n\treturn {\n\t\tvalue,\n\t\tdigest: createHash('sha256').update(JSON.stringify(value)).digest('hex'),\n\t};\n}\n\nfunction recoveryReport(\n\taddress: LedgerReservationRow['address'],\n\tresult: Awaited<ReturnType<typeof recoverPgOutcomeClaim>>,\n): ReconcileRecoveryReport {\n\tif (result.kind === 'outcome-recovery-appended') {\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome:\n\t\t\t\tresult.append.kind === 'already-appended-outcome-resolution'\n\t\t\t\t\t? 'already-appended'\n\t\t\t\t\t: 'appended',\n\t\t\treason: result.classification.resolution.reason,\n\t\t};\n\t}\n\tif (result.kind === 'outcome-recovery-no-open-claim')\n\t\treturn { address, outcome: 'no-open-claim' };\n\tif (result.kind === 'outcome-recovery-pending')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'pending',\n\t\t\treason: result.reason,\n\t\t\t...(result.reasonCode === 'catalogue-unavailable'\n\t\t\t\t? { failureCause: 'catalogue' as const }\n\t\t\t\t: {}),\n\t\t\t...(result.reasonCode === 'catalogue-unavailable'\n\t\t\t\t? {\n\t\t\t\t\t\trefusal: preAppendRefusalFor('ERR-09', {\n\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\tstate: 'unknown',\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\tif (result.kind === 'outcome-recovery-blocked')\n\t\treturn { address, outcome: 'blocked', reason: result.reason };\n\tif (result.kind === 'outcome-recovery-malformed-chain')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'malformed-chain',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'malformed-journal',\n\t\t\trefusal: preAppendRefusalFor('ERR-08', { address, state: 'unknown' }),\n\t\t};\n\tif (result.kind === 'outcome-transport-ambiguous')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t};\n\treturn { address, outcome: 'protocol-refused', reason: result.reason };\n}\n\nfunction readdressRecoveryReport(\n\treservations: readonly LedgerReservationRow[],\n\tresult: Awaited<ReturnType<typeof recoverPgReaddressPair>>,\n): ReconcileRecoveryReport {\n\tconst first = reservations[0];\n\tif (!first) throw new Error('re-address recovery has no reservation');\n\tif (result.kind === 'readdress-recovery-refused-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'refused-pair',\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-indeterminate-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'indeterminate-pair',\n\t\t\treason: result.reason,\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-transport-ambiguous-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t\tpairId: result.pairId,\n\t\t};\n\treturn {\n\t\taddress: first.address,\n\t\toutcome: 'pending',\n\t\treason: result.reason,\n\t\tpairId: result.pairId,\n\t};\n}\n\nexport function unresolvedRecoveryDetail(\n\treports: readonly ReconcileRecoveryReport[],\n): string | undefined {\n\tconst unresolved = reports.filter(\n\t\t(report) =>\n\t\t\treport.outcome === 'pending' ||\n\t\t\treport.outcome === 'blocked' ||\n\t\t\treport.outcome === 'malformed-chain' ||\n\t\t\treport.outcome === 'protocol-refused' ||\n\t\t\treport.outcome === 'transport-ambiguous' ||\n\t\t\treport.outcome === 'no-open-claim' ||\n\t\t\treport.outcome === 'indeterminate-pair',\n\t);\n\tif (unresolved.length === 0) return undefined;\n\treturn unresolved\n\t\t.map(\n\t\t\t(report) =>\n\t\t\t\t`${escapeDiagnosticText(report.address.name)}: ${escapeDiagnosticText(report.reason ?? report.outcome)}`,\n\t\t)\n\t\t.join('; ');\n}\n\nexport function formatReconcileHuman(result: ReconcileResult): string {\n\tconst line = `${escapeDiagnosticText(result.outcome)}: ${escapeDiagnosticText(result.runId)}`;\n\treturn result.refusal\n\t\t? formatPreAppendRefusalHuman(line, result.refusal)\n\t\t: line;\n}\n\n/**\n * The durable run identifies reviewed material; its intent events identify\n * actual apply attempts. Greenfield recovery never treats a run id as an\n * execution id: that legacy fallback could attach an unrelated reservation.\n */\nexport function executionIdsForRun(\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n): readonly string[] {\n\t// Attempt records are additive. Keep every documented pre-attempt scope so\n\t// interrupted executions produced before (or while persisting) an attempt\n\t// record remain recoverable, then add each durably recorded attempt.\n\tconst executionIds = new Set<string>([journal.run.runId]);\n\tfor (const event of journal.events) {\n\t\tconst record = event.record;\n\t\tif (\n\t\t\tevent.event === 'intent' &&\n\t\t\t'executionId' in record &&\n\t\t\ttypeof record.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.executionId);\n\t\tif (\n\t\t\tevent.event === 'observed' &&\n\t\t\t'intent' in record &&\n\t\t\trecord.intent &&\n\t\t\ttypeof record.intent.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.intent.executionId);\n\t}\n\tif ('generator' in journal.plan)\n\t\texecutionIds.add(`dbsp.generator.execution.${journal.run.runId}`);\n\treturn [...executionIds];\n}\n\nfunction statementBundleDigest(\n\tstatements: readonly { readonly ordinal: number; readonly sql: string }[],\n): string {\n\t// PostgreSQL jsonb may reorder object keys. Hash the ordered statement tuple\n\t// rather than a claim/step object or its serialized key order.\n\treturn createHash('sha256')\n\t\t.update(\n\t\t\tJSON.stringify(statements.map(({ ordinal, sql }) => [ordinal, sql])),\n\t\t)\n\t\t.digest('hex');\n}\n\nfunction recoveryEvidenceForClaim(input: {\n\treadonly journal: Awaited<ReturnType<typeof readTransitionJournal>>;\n\treadonly row: LedgerReservationRow;\n\treadonly plannedClaimKey: string;\n\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n}): OutcomeIndeterminateRecoveryEvidence | undefined {\n\tif (transitionPlanDigest(input.journal.plan) !== input.journal.run.planDigest)\n\t\treturn undefined;\n\tconst step = input.journal.plan.steps.find(\n\t\t(candidate) =>\n\t\t\tcandidate.managedClaim?.plannedClaimKey === input.plannedClaimKey,\n\t);\n\tconst claim = step?.managedClaim;\n\tif (\n\t\t!step ||\n\t\t!claim ||\n\t\t!sameLedgerAddress(claim.address, input.row.address) ||\n\t\toutcomeClaimId(\n\t\t\tinput.row.executionId,\n\t\t\tinput.plannedClaimKey,\n\t\t\tinput.row.address,\n\t\t) !== input.row.rootClaimId\n\t)\n\t\treturn undefined;\n\n\tconst binding = step.guards.find(\n\t\t(guard) =>\n\t\t\tguard.protocol.binding.kind === 'external-ddl-exclusion' &&\n\t\t\tresourceScopeCovers(guard.protocol.binding.scope, [input.row.address]),\n\t)?.protocol.binding;\n\tif (binding?.kind !== 'external-ddl-exclusion') return undefined;\n\tconst assumption = input.journal.plan.assumptions.find(\n\t\t(candidate) =>\n\t\t\tcandidate.id === binding.assumption &&\n\t\t\tcandidate.class === 'external-ddl-exclusion' &&\n\t\t\tstep.restsOnAssumptions.includes(candidate.id) &&\n\t\t\tresourceScopeCovers(candidate.scope, [input.row.address]),\n\t);\n\tif (!assumption) return undefined;\n\tconst accepted = input.journal.authorizations?.some((authorization) => {\n\t\tconst grant = authorization.grants.find(\n\t\t\t(candidate) => candidate.assumptionId === assumption.id,\n\t\t);\n\t\tif (!grant) return false;\n\t\tconst acceptance = authorization.policy[grant.grant];\n\t\treturn (\n\t\t\tacceptance !== undefined &&\n\t\t\tassumptionAccepted(assumption, { accepts: [acceptance] })\n\t\t);\n\t});\n\tif (!accepted) return undefined;\n\n\tconst bundleDigest = statementBundleDigest(claim.statementBundle.statements);\n\treturn {\n\t\trunId: input.journal.run.runId,\n\t\tplanDigest: input.journal.run.planDigest,\n\t\texecutionId: input.row.executionId,\n\t\tclaimId: input.row.rootClaimId,\n\t\tplannedClaimKey: input.plannedClaimKey,\n\t\tadmittedBundleDigest: bundleDigest,\n\t\tpersistedBundleDigest: bundleDigest,\n\t\trecordedPreState: input.stableStateBeforeClaim,\n\t\texternalDdlExclusion: {\n\t\t\tplanDigest: input.journal.run.planDigest,\n\t\t\taddress: input.row.address,\n\t\t\ttrustRoot: JSON.stringify(assumption.asserter),\n\t\t},\n\t};\n}\n\n/**\n * Reservations are the claim-to-run relation. The plan only provides the\n * finite ledger scopes to inspect; a claim is eligible only after its stored\n * execution_id matches a durable attempt belonging to the requested run.\n */\nexport async function runReconcile(\n\trunId: string,\n\toptions: ReconcileOptions,\n\tpool?: import('pg').Pool,\n): Promise<ReconcileResult> {\n\tlet owned: import('pg').Pool;\n\ttry {\n\t\towned = pool ?? (await createDbConnection(options.db)).pool;\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'reconcile-run-unavailable',\n\t\t\trunId,\n\t\t\taddresses: [],\n\t\t\tfailureCause: classifyReconcileFailure(error, 'reconcile'),\n\t\t};\n\t}\n\tlet stage: 'journal' | 'catalogue' | 'reconcile' = 'reconcile';\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\towned,\n\t\t\trunId,\n\t\t\tasync (target) => {\n\t\t\t\tconst lease = await acquireExclusiveTransitionLease(target);\n\t\t\t\ttry {\n\t\t\t\t\tstage = 'journal';\n\t\t\t\t\tconst journal = await readTransitionJournal(lease.session, runId, {\n\t\t\t\t\t\tensure: false,\n\t\t\t\t\t});\n\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\tconst material: Array<{\n\t\t\t\t\t\treadonly address: LedgerReservationRow['address'];\n\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t}> = journal.plan.steps\n\t\t\t\t\t\t// Generator manifests deliberately persist their authoritative\n\t\t\t\t\t\t// target at the step root, not under managedClaim. Reconcile by\n\t\t\t\t\t\t// that same durable address so an interrupted generator run is\n\t\t\t\t\t\t// recoverable by its documented run id.\n\t\t\t\t\t\t.map((step) => {\n\t\t\t\t\t\t\tconst generatedStep = step as {\n\t\t\t\t\t\t\t\treadonly address?: LedgerReservationRow['address'];\n\t\t\t\t\t\t\t\treadonly plannedClaimKeys?: readonly string[];\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst generated = generatedStep.address;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tstep.managedClaim ??\n\t\t\t\t\t\t\t\t(generated === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\taddress: generated,\n\t\t\t\t\t\t\t\t\t\t\t...(generatedStep.plannedClaimKeys?.[0] === undefined\n\t\t\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: generatedStep.plannedClaimKeys[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t(claim): claim is NonNullable<typeof claim> =>\n\t\t\t\t\t\t\t\tclaim !== undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait assertPgDatabaseWritable(lease.session);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\tdetail: error.message,\n\t\t\t\t\t\t\t\taddresses: material.map((claim) => claim.address),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (material.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\taddresses:\n\t\t\t\t\t\t\t\tjournal.plan.declarations?.declarations.map(\n\t\t\t\t\t\t\t\t\t(declaration) => declaration.address,\n\t\t\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\t};\n\t\t\t\t\tconst homes = new Map<string, LedgerHome>();\n\t\t\t\t\tfor (const claim of material) {\n\t\t\t\t\t\tconst home = ledgerHome(claim.address);\n\t\t\t\t\t\thomes.set(`${home.scope}:${home.schema ?? ''}`, home);\n\t\t\t\t\t}\n\t\t\t\t\t// Currency/refusal is a run-level safety gate, not a consequence of\n\t\t\t\t\t// successful reservation selection. Preserve its actionable preflight\n\t\t\t\t\t// evidence even if this run has no selectable open claim.\n\t\t\t\t\tfor (const home of homes.values()) {\n\t\t\t\t\t\tconst currency = await readPgLedgerScopeCurrency(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (currency.kind === 'current') continue;\n\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\tcurrency.kind === 'not-current' && currency.reason === 'lineage'\n\t\t\t\t\t\t\t\t? 'ledger lineage mismatch; run dbsp preflight --reinitialize'\n\t\t\t\t\t\t\t\t: `ledger marker ${currency.marker.kind}; run dbsp preflight --reinitialize`;\n\t\t\t\t\t\tconst affected = material.filter((claim) => {\n\t\t\t\t\t\t\tconst claimHome = ledgerHome(claim.address);\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tclaimHome.scope === home.scope &&\n\t\t\t\t\t\t\t\tclaimHome.schema === home.schema\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\taddresses: affected.map((claim) => claim.address),\n\t\t\t\t\t\t\tdetail,\n\t\t\t\t\t\t\trecovery: affected.map((claim) => ({\n\t\t\t\t\t\t\t\taddress: claim.address,\n\t\t\t\t\t\t\t\toutcome: 'blocked' as const,\n\t\t\t\t\t\t\t\treason: detail,\n\t\t\t\t\t\t\t\trefusal: preAppendRefusalFor('ERR-03', {\n\t\t\t\t\t\t\t\t\taddress: claim.address,\n\t\t\t\t\t\t\t\t\tstate: 'unknown',\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst executionIds = executionIdsForRun(journal);\n\t\t\t\t\tconst reservations = (\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\t[...homes.values()].flatMap((home) =>\n\t\t\t\t\t\t\t\texecutionIds.map((executionId) =>\n\t\t\t\t\t\t\t\t\treadPgLedgerReservationsForExecution(\n\t\t\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t).flat();\n\t\t\t\t\tif (reservations.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\taddresses: material.map((x) => x.address),\n\t\t\t\t\t\t};\n\t\t\t\t\tconst readdressPairs = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tconst byRoot = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tfor (const row of reservations) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trow.claimKind === 'readdress-intent' &&\n\t\t\t\t\t\t\trow.pairId !== undefined\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst pairKey = `${row.executionId}:${row.pairId}`;\n\t\t\t\t\t\t\treaddressPairs.set(pairKey, [\n\t\t\t\t\t\t\t\t...(readdressPairs.get(pairKey) ?? []),\n\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbyRoot.set(row.rootClaimId, [\n\t\t\t\t\t\t\t...(byRoot.get(row.rootClaimId) ?? []),\n\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t\tconst recovery: ReconcileRecoveryReport[] = [];\n\t\t\t\t\tfor (const [_pairKey, pairRows] of readdressPairs) {\n\t\t\t\t\t\tconst pairId = pairRows[0]?.pairId;\n\t\t\t\t\t\tconst executionId = pairRows[0]?.executionId;\n\t\t\t\t\t\tif (!pairId || !executionId) continue;\n\t\t\t\t\t\tconst readPairInSelectedHomes =\n\t\t\t\t\t\t\treadVerifiedPgLedgerReservationsForPair as unknown as (\n\t\t\t\t\t\t\t\texecutor: typeof lease.session,\n\t\t\t\t\t\t\t\tpair: string,\n\t\t\t\t\t\t\t\tselectedHomes: readonly LedgerHome[],\n\t\t\t\t\t\t\t) => Promise<readonly LedgerReservationRow[]>;\n\t\t\t\t\t\tconst closure = await readPairInSelectedHomes(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\t[...homes.values()],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst recovered = await recoverPgReaddressPair(lease.session, {\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\treservations: closure,\n\t\t\t\t\t\t});\n\t\t\t\t\t\trecovery.push(readdressRecoveryReport(closure, recovered));\n\t\t\t\t\t}\n\t\t\t\t\tfor (const rows of byRoot.values()) {\n\t\t\t\t\t\tconst rootClaimId = rows[0]?.rootClaimId;\n\t\t\t\t\t\tif (!rootClaimId) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trows.some(\n\t\t\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t\t\t!executionIds.includes(row.executionId) ||\n\t\t\t\t\t\t\t\t\trow.rootClaimId !== rootClaimId,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `reservation disagreement for root claim ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst rootCandidates: Array<{\n\t\t\t\t\t\t\treadonly row: LedgerReservationRow;\n\t\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t\t\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n\t\t\t\t\t\t}> = [];\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tstage = 'catalogue';\n\t\t\t\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\tledgerHome(row.address),\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tprojection.kind !== 'projected-ledger-chain' ||\n\t\t\t\t\t\t\t\tprojection.openClaim === undefined\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tconst open = projection.openClaim.event;\n\t\t\t\t\t\t\tconst openRoot = open.rootClaimId ?? open.eventId;\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\topen.executionId !== row.executionId ||\n\t\t\t\t\t\t\t\topenRoot !== rootClaimId\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\t\taddresses: rows.map((item) => item.address),\n\t\t\t\t\t\t\t\t\tdetail: `open chain member disagrees with reservation root ${rootClaimId}`,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (open.eventId === rootClaimId)\n\t\t\t\t\t\t\t\trootCandidates.push({\n\t\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t\t\tstableStateBeforeClaim:\n\t\t\t\t\t\t\t\t\t\tprojection.openClaim.stableStateBeforeClaim,\n\t\t\t\t\t\t\t\t\t...(open.plannedClaimKey === undefined\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: { plannedClaimKey: open.plannedClaimKey }),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rootCandidates.length !== 1)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `execution ${runId} has ${rootCandidates.length} open root members for ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst selected = rootCandidates[0];\n\t\t\t\t\t\tif (!selected) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!selected.plannedClaimKey ||\n\t\t\t\t\t\t\t!material.some(\n\t\t\t\t\t\t\t\t(claim) => claim.plannedClaimKey === selected.plannedClaimKey,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `open root ${rootClaimId} has no matching persisted managed step`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t// Recovery follows execution_id -> reservation root_claim_id -> the\n\t\t\t\t\t\t// single open root member. It never reuses an address-only plan id.\n\t\t\t\t\t\tconst step = journal.plan.steps.find(\n\t\t\t\t\t\t\t(candidate) =>\n\t\t\t\t\t\t\t\tcandidate.managedClaim?.plannedClaimKey ===\n\t\t\t\t\t\t\t\t\tselected.plannedClaimKey ||\n\t\t\t\t\t\t\t\t('plannedClaimKeys' in candidate &&\n\t\t\t\t\t\t\t\t\tArray.isArray(candidate.plannedClaimKeys) &&\n\t\t\t\t\t\t\t\t\tcandidate.plannedClaimKeys.includes(\n\t\t\t\t\t\t\t\t\t\tselected.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t)),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst operationReadBack =\n\t\t\t\t\t\t\tstep?.operation?.operationKind.name ===\n\t\t\t\t\t\t\t'CreateUniqueIndexConcurrently'\n\t\t\t\t\t\t\t\t? async (\n\t\t\t\t\t\t\t\t\t\texecutor: Parameters<\n\t\t\t\t\t\t\t\t\t\t\ttypeof assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid\n\t\t\t\t\t\t\t\t\t\t>[0],\n\t\t\t\t\t\t\t\t\t\t_address: LedgerReservationRow['address'],\n\t\t\t\t\t\t\t\t\t\tidentity: Parameters<typeof recoveryPayload>[0],\n\t\t\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\t\t\tawait assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid(\n\t\t\t\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\t\t\t\tstep.operation,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tobserved: recoveryPayload(identity),\n\t\t\t\t\t\t\t\t\t\t\teffect: 'unverifiable' as const,\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst indeterminateEvidence = recoveryEvidenceForClaim({\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\trow: selected.row,\n\t\t\t\t\t\t\tplannedClaimKey: selected.plannedClaimKey,\n\t\t\t\t\t\t\tstableStateBeforeClaim: selected.stableStateBeforeClaim,\n\t\t\t\t\t\t});\n\t\t\t\t\t\t// A reservation is released only with the terminal for that exact\n\t\t\t\t\t\t// member. Resolving the root must never erase the discovery record\n\t\t\t\t\t\t// for an unresolved child in the same durable closure.\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tconst isRoot = sameLedgerAddress(\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t\tselected.row.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst recovered = await recoverPgOutcomeClaim(owned, {\n\t\t\t\t\t\t\t\taddress: row.address,\n\t\t\t\t\t\t\t\treservations: [row],\n\t\t\t\t\t\t\t\tresolutionEventId: isRoot\n\t\t\t\t\t\t\t\t\t? `${rootClaimId}:reconcile:${runId}`\n\t\t\t\t\t\t\t\t\t: `${rootClaimId}:reconcile:${runId}:${row.address.kind}:${row.address.name}`,\n\t\t\t\t\t\t\t\tacceptedExternalDdlExclusion:\n\t\t\t\t\t\t\t\t\tisRoot && indeterminateEvidence !== undefined,\n\t\t\t\t\t\t\t\tresolveIndeterminate: true,\n\t\t\t\t\t\t\t\treadBack: async (_executor, _address, identity) =>\n\t\t\t\t\t\t\t\t\trecoveryPayload(identity),\n\t\t\t\t\t\t\t\t...(isRoot && indeterminateEvidence !== undefined\n\t\t\t\t\t\t\t\t\t? { indeterminateEvidence }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t...(isRoot && operationReadBack !== undefined\n\t\t\t\t\t\t\t\t\t? { operationReadBack }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\trecovery.push(recoveryReport(row.address, recovered));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst unresolved = unresolvedRecoveryDetail(recovery);\n\t\t\t\t\tif (unresolved)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\tdetail: unresolved,\n\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\trecovery,\n\t\t\t\t\t};\n\t\t\t\t} finally {\n\t\t\t\t\tawait lease.release();\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tif (locked.kind === 'busy')\n\t\t\treturn { outcome: 'reconcile-run-unavailable', runId, addresses: [] };\n\t\tif (locked.value.kind === 'selection-unavailable')\n\t\t\treturn {\n\t\t\t\toutcome: 'reconcile-claim-selection-unavailable',\n\t\t\t\trunId,\n\t\t\t\taddresses: locked.value.addresses,\n\t\t\t\t...(locked.value.detail ? { detail: locked.value.detail } : {}),\n\t\t\t};\n\t\tif (locked.value.kind === 'database-read-only') {\n\t\t\tconst address = locked.value.addresses[0];\n\t\t\treturn {\n\t\t\t\toutcome: 'database-read-only',\n\t\t\t\trunId,\n\t\t\t\taddresses: locked.value.addresses,\n\t\t\t\tdetail: locked.value.detail,\n\t\t\t\t...(address === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\trefusal: preAppendRefusalFor('ERR-07', {\n\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\tstate: 'unknown',\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\tif (locked.value.kind === 'unresolved') {\n\t\t\tconst address = locked.value.addresses[0];\n\t\t\tconst markerRefusal =\n\t\t\t\taddress !== undefined &&\n\t\t\t\tlocked.value.detail?.includes('run dbsp preflight --reinitialize')\n\t\t\t\t\t? preAppendRefusalFor('ERR-03', { address, state: 'unknown' })\n\t\t\t\t\t: undefined;\n\t\t\tconst recoveryRefusal = locked.value.recovery?.find(\n\t\t\t\t(report) => report.refusal !== undefined,\n\t\t\t)?.refusal;\n\t\t\tconst refusal = markerRefusal ?? recoveryRefusal;\n\t\t\treturn {\n\t\t\t\toutcome: 'reconcile-unresolved',\n\t\t\t\trunId,\n\t\t\t\taddresses: locked.value.addresses,\n\t\t\t\t...(locked.value.detail ? { detail: locked.value.detail } : {}),\n\t\t\t\t...(locked.value.recovery ? { recovery: locked.value.recovery } : {}),\n\t\t\t\t...(refusal === undefined ? {} : { refusal }),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\toutcome: 'reconcile-completed',\n\t\t\trunId,\n\t\t\taddresses: locked.value.addresses,\n\t\t\t...(locked.value.recovery ? { recovery: locked.value.recovery } : {}),\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'reconcile-run-unavailable',\n\t\t\trunId,\n\t\t\taddresses: [],\n\t\t\tdetail: escapeDiagnosticText(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t),\n\t\t\tfailureCause: classifyReconcileFailure(error, stage),\n\t\t};\n\t} finally {\n\t\tif (pool === undefined) await owned.end();\n\t}\n}\n\nexport const reconcileCommand = new Command('reconcile')\n\t.description('Resolve this run’s open managed claims from live evidence only')\n\t.argument('<run-id>', 'Durable run identifier')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (runId: string, options: ReconcileOptions) => {\n\t\tconst result = await runReconcile(runId, options);\n\t\tif (options.format === 'json') printCliJson(result);\n\t\telse console.log(formatReconcileHuman(result));\n\t\tprocess.exitCode = result.outcome === 'reconcile-completed' ? 0 : 1;\n\t});\n","/** Classify a previously attempted run. Recovery never executes planned DDL. */\nimport {\n\tassertPgDatabaseWritable,\n\tcreatePgTransitionPack,\n\tisPgDatabaseReadOnlyError,\n\tpreparePgRecoveryAdmission,\n\treadPgLedgerScopeCurrency,\n\treadPgObservationContextFromLessor,\n\treadTransitionJournal,\n\twithPgTransitionRunLock,\n} from '@dbsp/adapter-pgsql';\nimport {\n\tacquireTransitionTargetLease,\n\tassumptionAccepted,\n\tcreateApplier,\n\tcreatePackRegistry,\n\tloadVerifiedRecoveryJournal,\n\ttransitionPlanDigest,\n\tvalidateTransitionRelationalInvariants,\n} from '@dbsp/core';\nimport type {\n\tApplyPolicy,\n\tApplyResult,\n\tLedgerAddress,\n\tLedgerHome,\n\tTransitionRunJournal,\n} from '@dbsp/types';\nimport { Command } from 'commander';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport {\n\tauthorizationDigest,\n\tcanonicalApplyPolicy,\n\tvalidateAssumptionAcceptance,\n\twithPoolCleanupReported,\n} from './apply.js';\nimport {\n\ttype PreAppendRefusal,\n\tpreAppendRefusalFor,\n} from './refusal-output.js';\n\nexport const RECOVER_OUTCOME_CONTRACT = [\n\t['completed', 0, 'all attempted steps were durably reconciled'],\n\t['recovery-resume-required', 40, 'remaining work requires a new proof'],\n\t['recovery-partially-applied', 41, 'durable effects require recovery action'],\n\t['recovery-unknown-step-result', 42, 'a prior step could not be classified'],\n\t['recovery-guard-failed', 43, 'a prior guard rejected the target'],\n\t['recovery-guard-timeout', 44, 'a prior guard timed out'],\n\t[\n\t\t'recovery-operation-failed-not-applied',\n\t\t45,\n\t\t'a prior operation rolled back',\n\t],\n\t[\n\t\t'recovery-context-mismatch',\n\t\t46,\n\t\t'run evidence or target context is invalid',\n\t],\n\t['recovery-read-failed', 47, 'recovery could not read the target'],\n\t['recovery-load-failed', 48, 'run journal could not be loaded'],\n\t['recovery-plan-invalid', 49, 'stored plan failed validation'],\n\t[\n\t\t'recovery-authorization-missing',\n\t\t50,\n\t\t'attempted run has no durable authorization',\n\t],\n\t[\n\t\t'recovery-authorization-invalid',\n\t\t51,\n\t\t'attempted run authorization is invalid',\n\t],\n\t['plan-digest-required', 54, 'a reviewed plan digest is required'],\n\t['database-read-only', 34, 'target cannot accept managed recovery writes'],\n\t[\n\t\t'recovery-plan-digest-mismatch',\n\t\t55,\n\t\t'reviewed plan digest does not match the run',\n\t],\n\t['run-busy', 52, 'another database session holds this run lock'],\n\t['recovery-failed', 53, 'unexpected recovery command failure'],\n] as const;\n\nexport type RecoverOutcome = (typeof RECOVER_OUTCOME_CONTRACT)[number][0];\nconst recoverExitCodes = new Map<RecoverOutcome, number>(\n\tRECOVER_OUTCOME_CONTRACT.map(([outcome, exitCode]) => [outcome, exitCode]),\n);\n\nexport function exitCodeForRecoverOutcome(outcome: RecoverOutcome): number {\n\treturn recoverExitCodes.get(outcome) as number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\ntype AuthorizationValidation =\n\t| { readonly ok: true; readonly policy: ApplyPolicy }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly outcome:\n\t\t\t\t| 'recovery-authorization-missing'\n\t\t\t\t| 'recovery-authorization-invalid';\n\t };\n\n/**\n * Recovery uses a durable approval exactly as recorded; it never turns plan\n * assumptions into new broad grants. A record must bind its canonical policy,\n * digest, and one accepting grant for every plan assumption.\n */\nexport function validateRecoveryAuthorization(\n\tjournal: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n): AuthorizationValidation {\n\tconst records = journal.authorizations ?? [];\n\tif (records.length === 0)\n\t\treturn { ok: false, outcome: 'recovery-authorization-missing' };\n\tfor (const candidate of records) {\n\t\ttry {\n\t\t\tif (!isRecord(candidate) || candidate.runId !== journal.run.runId)\n\t\t\t\tcontinue;\n\t\t\tif (!Array.isArray(candidate.policy) || !Array.isArray(candidate.grants))\n\t\t\t\tcontinue;\n\t\t\tconst accepts = canonicalApplyPolicy(\n\t\t\t\tcandidate.policy.map((grant, index) =>\n\t\t\t\t\tvalidateAssumptionAcceptance(grant, `authorization.policy[${index}]`),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst grants = new Map<string, number>();\n\t\t\tfor (const grant of candidate.grants) {\n\t\t\t\tif (!isRecord(grant) || typeof grant.assumptionId !== 'string')\n\t\t\t\t\tthrow new Error('invalid authorization grant');\n\t\t\t\tif (!Number.isInteger(grant.grant))\n\t\t\t\t\tthrow new Error('invalid authorization grant index');\n\t\t\t\tif (grants.has(grant.assumptionId))\n\t\t\t\t\tthrow new Error('duplicate authorization grant');\n\t\t\t\tgrants.set(grant.assumptionId, grant.grant as number);\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttypeof candidate.digest !== 'string' ||\n\t\t\t\tcandidate.digest !==\n\t\t\t\t\tauthorizationDigest(\n\t\t\t\t\t\tjournal.run.runId,\n\t\t\t\t\t\tjournal.run.planDigest,\n\t\t\t\t\t\taccepts,\n\t\t\t\t\t\tcandidate.grants,\n\t\t\t\t\t\tcandidate.actor,\n\t\t\t\t\t\tcandidate.authorizedAt,\n\t\t\t\t\t)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tif (grants.size !== journal.plan.assumptions.length) continue;\n\t\t\tconst policy = { accepts };\n\t\t\tif (\n\t\t\t\tjournal.plan.assumptions.every((assumption) => {\n\t\t\t\t\tconst grant = grants.get(assumption.id);\n\t\t\t\t\tconst acceptedGrant =\n\t\t\t\t\t\tgrant === undefined ? undefined : accepts[grant];\n\t\t\t\t\treturn (\n\t\t\t\t\t\tgrant !== undefined &&\n\t\t\t\t\t\tgrant >= 0 &&\n\t\t\t\t\t\tgrant < accepts.length &&\n\t\t\t\t\t\tacceptedGrant !== undefined &&\n\t\t\t\t\t\tassumptionAccepted(assumption, {\n\t\t\t\t\t\t\taccepts: [acceptedGrant],\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t)\n\t\t\t\treturn { ok: true, policy };\n\t\t} catch {\n\t\t\t// A malformed durable record is not a policy input to repair here.\n\t\t}\n\t}\n\treturn { ok: false, outcome: 'recovery-authorization-invalid' };\n}\n\nexport function recoveryPolicyForJournal(\n\tloaded: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n\trunId: string,\n):\n\t| { readonly ok: true; readonly policy: ApplyPolicy }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly outcome:\n\t\t\t\t| 'recovery-plan-invalid'\n\t\t\t\t| 'recovery-authorization-missing'\n\t\t\t\t| 'recovery-authorization-invalid';\n\t } {\n\tif (\n\t\tloaded.run.runId !== runId ||\n\t\tloaded.run.planDigest !== transitionPlanDigest(loaded.plan) ||\n\t\t!validateTransitionRelationalInvariants({ kind: 'plan', plan: loaded.plan })\n\t\t\t.ok\n\t)\n\t\treturn { ok: false, outcome: 'recovery-plan-invalid' };\n\treturn validateRecoveryAuthorization(loaded);\n}\n\nexport function outcomeForRecoveryResult(\n\tresult: ApplyResult,\n): Exclude<RecoverOutcome, 'run-busy' | 'recovery-failed'> {\n\tif (result.recoveryOutcome) return result.recoveryOutcome;\n\tif (result.assessment.lifecycle === 'completed') return 'completed';\n\tif (result.assessment.lifecycle === 'partially-applied')\n\t\treturn 'recovery-partially-applied';\n\tconst reason = result.assessment.reasons[0];\n\tswitch (reason?.code) {\n\t\tcase 'resume-required':\n\t\t\treturn 'recovery-resume-required';\n\t\tcase 'unknown-step-result':\n\t\t\treturn 'recovery-unknown-step-result';\n\t\tcase 'guard-failed':\n\t\t\treturn 'recovery-guard-failed';\n\t\tcase 'guard-timeout':\n\t\t\treturn 'recovery-guard-timeout';\n\t\tcase 'operation-failed-not-applied':\n\t\t\treturn 'recovery-operation-failed-not-applied';\n\t\tdefault:\n\t\t\treturn 'recovery-context-mismatch';\n\t}\n}\n\nasync function load(\n\ttarget: Parameters<typeof acquireTransitionTargetLease>[0],\n\trunId: string,\n) {\n\tconst lease = await acquireTransitionTargetLease(target);\n\ttry {\n\t\treturn await readTransitionJournal(lease.session, runId, { ensure: false });\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nfunction ledgerHome(address: LedgerAddress): LedgerHome {\n\tif (address.scope === 'database') return { scope: 'database' };\n\tif (!address.schema)\n\t\tthrow new Error(\n\t\t\t`schema-scoped managed claim ${address.name} has no schema`,\n\t\t);\n\treturn { scope: 'schema', schema: address.schema };\n}\n\nfunction sameLedgerHome(left: LedgerHome, right: LedgerHome): boolean {\n\treturn left.scope === right.scope && left.schema === right.schema;\n}\n\nfunction recoveryAddresses(\n\tjournal: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n): readonly LedgerAddress[] {\n\treturn journal.plan.steps.flatMap((step) => {\n\t\tconst generated = step as { readonly address?: LedgerAddress };\n\t\tconst address = step.managedClaim?.address ?? generated.address;\n\t\treturn address === undefined ? [] : [address];\n\t});\n}\n\nfunction formatLedgerHome(home: LedgerHome): string {\n\treturn home.scope === 'database' ? 'database' : `schema ${home.schema}`;\n}\n\n/**\n * Recovery must not turn an ordinary command into a marker upgrade path. The\n * persisted run supplies the finite homes to inspect, but no recovery\n * selection, authorization replay, or ledger append may follow a stale marker.\n */\nasync function recoverMarkerRefusal(\n\ttarget: Parameters<typeof acquireTransitionTargetLease>[0],\n\tjournal: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n): Promise<\n\t| {\n\t\t\treadonly detail: string;\n\t\t\treadonly refusal: PreAppendRefusal;\n\t }\n\t| undefined\n> {\n\tconst addresses = recoveryAddresses(journal);\n\tconst homes: Array<{\n\t\treadonly address: LedgerAddress;\n\t\treadonly home: LedgerHome;\n\t}> = [];\n\tfor (const address of addresses) {\n\t\tconst home = ledgerHome(address);\n\t\tif (homes.some((candidate) => sameLedgerHome(candidate.home, home)))\n\t\t\tcontinue;\n\t\thomes.push({ address, home });\n\t}\n\tconst lease = await acquireTransitionTargetLease(target);\n\ttry {\n\t\tfor (const { address, home } of homes) {\n\t\t\tconst currency = await readPgLedgerScopeCurrency(lease.session, home);\n\t\t\tif (currency.kind === 'current') continue;\n\t\t\tconst detail =\n\t\t\t\tcurrency.kind === 'not-current' && currency.reason === 'lineage'\n\t\t\t\t\t? `ledger lineage mismatch in ${formatLedgerHome(home)}; run dbsp preflight --reinitialize`\n\t\t\t\t\t: `ledger marker ${currency.marker.kind} in ${formatLedgerHome(home)}; run dbsp preflight --reinitialize`;\n\t\t\treturn {\n\t\t\t\tdetail,\n\t\t\t\trefusal: preAppendRefusalFor('ERR-03', {\n\t\t\t\t\taddress,\n\t\t\t\t\tstate: 'unknown',\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t} finally {\n\t\tawait lease.release();\n\t}\n\treturn undefined;\n}\n\nexport type RecoverCommandResult = (\n\t| {\n\t\t\treadonly outcome: Exclude<RecoverOutcome, 'run-busy' | 'recovery-failed'>;\n\t\t\treadonly runId: string;\n\t\t\treadonly result?: ApplyResult;\n\t\t\treadonly detail?: string;\n\t\t\treadonly refusal?: PreAppendRefusal;\n\t }\n\t| { readonly outcome: 'run-busy'; readonly runId: string }\n) & {\n\treadonly cleanupError?: string;\n};\n\ntype RecoverRunResult =\n\t| RecoverCommandResult\n\t| {\n\t\t\treadonly outcome:\n\t\t\t\t| 'plan-digest-required'\n\t\t\t\t| 'recovery-plan-digest-mismatch';\n\t\t\treadonly runId: string;\n\t\t\treadonly cleanupError?: string;\n\t };\n\nexport async function runRecover(\n\trunId: string,\n\toptions: { readonly db: string; readonly planDigest?: string },\n\tpool?: Pool,\n): Promise<RecoverRunResult> {\n\tif (!options.planDigest) return { outcome: 'plan-digest-required', runId };\n\tconst expectedPlanDigest = options.planDigest;\n\tconst owned =\n\t\tpool === undefined ? (await createDbConnection(options.db)).pool : pool;\n\tlet result: RecoverRunResult;\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\towned,\n\t\t\trunId,\n\t\t\tasync (target) => {\n\t\t\t\tconst loaded = await loadVerifiedRecoveryJournal(\n\t\t\t\t\trunId,\n\t\t\t\t\texpectedPlanDigest,\n\t\t\t\t\t(id) => load(target, id),\n\t\t\t\t);\n\t\t\t\tif (!loaded.ok) {\n\t\t\t\t\tswitch (loaded.code) {\n\t\t\t\t\t\tcase 'load-failed':\n\t\t\t\t\t\t\treturn { outcome: 'recovery-load-failed' as const };\n\t\t\t\t\t\tcase 'plan-digest-mismatch':\n\t\t\t\t\t\t\treturn { outcome: 'recovery-plan-digest-mismatch' as const };\n\t\t\t\t\t\tcase 'event-invalid':\n\t\t\t\t\t\t\treturn { outcome: 'recovery-context-mismatch' as const };\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn { outcome: 'recovery-plan-invalid' as const };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst writabilityLease = await acquireTransitionTargetLease(target);\n\t\t\t\ttry {\n\t\t\t\t\tawait assertPgDatabaseWritable(writabilityLease.session);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\toutcome: 'database-read-only' as const,\n\t\t\t\t\t\t\tdetail: error.message,\n\t\t\t\t\t\t};\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tawait writabilityLease.release();\n\t\t\t\t}\n\t\t\t\tconst markerRefusal = await recoverMarkerRefusal(\n\t\t\t\t\ttarget,\n\t\t\t\t\tloaded.journal,\n\t\t\t\t);\n\t\t\t\tif (markerRefusal)\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutcome: 'recovery-context-mismatch' as const,\n\t\t\t\t\t\t...markerRefusal,\n\t\t\t\t\t};\n\t\t\t\tconst authorization =\n\t\t\t\t\tloaded.journal.events.length === 0\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: recoveryPolicyForJournal(loaded.journal, runId);\n\t\t\t\tif (authorization && !authorization.ok)\n\t\t\t\t\treturn { outcome: authorization.outcome };\n\t\t\t\tconst result = await createApplier(\n\t\t\t\t\tcreatePackRegistry([createPgTransitionPack({})]),\n\t\t\t\t\t{ persist: async () => undefined },\n\t\t\t\t).resume(\n\t\t\t\t\tloaded.journal,\n\t\t\t\t\t(leasedTarget) => readPgObservationContextFromLessor(leasedTarget),\n\t\t\t\t\tauthorization?.policy,\n\t\t\t\t\ttarget,\n\t\t\t\t\tasync (leasedTarget, contract) => {\n\t\t\t\t\t\tconst lease = await acquireTransitionTargetLease(leasedTarget);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await preparePgRecoveryAdmission(lease.session, contract);\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait lease.release();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\treturn { outcome: outcomeForRecoveryResult(result), result };\n\t\t\t},\n\t\t);\n\t\tresult =\n\t\t\tlocked.kind === 'busy'\n\t\t\t\t? { outcome: 'run-busy', runId }\n\t\t\t\t: { ...locked.value, runId };\n\t} catch (error) {\n\t\tif (pool === undefined) {\n\t\t\ttry {\n\t\t\t\tawait owned.end();\n\t\t\t} catch {\n\t\t\t\t// Preserve the primary recovery error for the CLI boundary.\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t}\n\tif (pool === undefined) {\n\t\treturn withPoolCleanupReported(result, () => owned.end());\n\t}\n\treturn result;\n}\n\nexport const recoverCommand = new Command('recover')\n\t.description(\n\t\t'Observe and classify an attempted durable run; performs no planned target DDL and does not re-authorize assumptions',\n\t)\n\t.argument('<run-id>', 'Durable run identifier')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.requiredOption(\n\t\t'--plan-digest <sha>',\n\t\t'Plan digest printed by dbsp plan; required to anchor recovery outside the database',\n\t)\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(\n\t\tasync (\n\t\t\trunId: string,\n\t\t\toptions: { db: string; planDigest: string; format?: 'text' | 'json' },\n\t\t) => {\n\t\t\tlet result:\n\t\t\t\t| RecoverCommandResult\n\t\t\t\t| {\n\t\t\t\t\t\treadonly outcome: 'recovery-failed';\n\t\t\t\t\t\treadonly runId: string;\n\t\t\t\t\t\treadonly error: string;\n\t\t\t\t };\n\t\t\ttry {\n\t\t\t\tresult = await runRecover(runId, options);\n\t\t\t} catch (error) {\n\t\t\t\tresult = {\n\t\t\t\t\toutcome: 'recovery-failed',\n\t\t\t\t\trunId,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst document = {\n\t\t\t\t...result,\n\t\t\t\texitCode: exitCodeForRecoverOutcome(result.outcome),\n\t\t\t};\n\t\t\tif (options.format === 'json') printCliJson(document);\n\t\t\telse console.log(`${result.outcome}: ${runId}`);\n\t\t\tprocess.exitCode = document.exitCode;\n\t\t},\n\t)\n\t.addHelpText(\n\t\t'after',\n\t\t`\\nJSON result contract (outcome -> exit code):\\n${RECOVER_OUTCOME_CONTRACT.map(([outcome, code, description]) => ` ${outcome} -> ${code}: ${description}`).join('\\n')}\\n`,\n\t);\n","/** `dbsp release` stops managing one address and deliberately emits no DDL. */\nimport {\n\tcreatePgTransitionLessor,\n\tescapeDiagnosticText,\n\treleasePgManagedAddress,\n} from '@dbsp/adapter-pgsql';\nimport { acquireTransitionLease } from '@dbsp/core';\nimport type { LedgerAddress, LedgerRefusal } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { inspectAddress } from './inspect.js';\n\nexport interface ReleaseOptions {\n\treadonly db: string;\n\treadonly schema?: string;\n\treadonly kind?: string;\n\treadonly parent?: string;\n\treadonly databaseLedger?: boolean;\n\treadonly format?: 'text' | 'json';\n}\n\nexport type ReleaseCommandResult =\n\t| { readonly outcome: 'released' }\n\t| {\n\t\t\treadonly outcome: 'database-read-only';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| { readonly outcome: 'release-unavailable'; readonly detail: string }\n\t| {\n\t\t\treadonly outcome: 'release-refused';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t\t\treadonly refusal: LedgerRefusal;\n\t };\n\nexport async function runRelease(\n\tselector: string,\n\toptions: ReleaseOptions,\n): Promise<ReleaseCommandResult> {\n\tconst { pool } = await createDbConnection(options.db);\n\tconst schema = options.schema ?? 'public';\n\ttry {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tconst databaseRow = await lease.session.query(\n\t\t\t\t'SELECT current_database() AS database',\n\t\t\t);\n\t\t\tconst database = databaseRow.rows[0]?.database;\n\t\t\tif (typeof database !== 'string')\n\t\t\t\tthrow new Error('PostgreSQL current_database() is unreadable');\n\t\t\t// Keep the leased session alive until the release preflight/transaction has\n\t\t\t// settled. A bare promise return would enter the finally blocks below\n\t\t\t// immediately, ending this pool while the adapter is still reading it.\n\t\t\treturn (await releasePgManagedAddress({\n\t\t\t\texecutor: lease.session,\n\t\t\t\thome: options.databaseLedger\n\t\t\t\t\t? { scope: 'database' }\n\t\t\t\t\t: { scope: 'schema', schema },\n\t\t\t\taddress: inspectAddress(\n\t\t\t\t\tdatabase,\n\t\t\t\t\tschema,\n\t\t\t\t\tselector,\n\t\t\t\t\toptions.kind,\n\t\t\t\t\toptions.parent,\n\t\t\t\t\toptions.databaseLedger ? 'database' : 'schema',\n\t\t\t\t),\n\t\t\t})) as ReleaseCommandResult;\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n\nexport function formatReleaseHuman(result: ReleaseCommandResult): string {\n\tif (result.outcome === 'released') return 'released';\n\tif (result.outcome === 'database-read-only')\n\t\treturn `database-read-only: ${escapeDiagnosticText(result.detail)}`;\n\tif (result.outcome === 'release-unavailable')\n\t\treturn `release-unavailable: ${escapeDiagnosticText(result.detail)}`;\n\treturn [\n\t\t`release-refused: ${escapeDiagnosticText(result.detail)}`,\n\t\t`address: ${escapeDiagnosticText(JSON.stringify(result.address))}`,\n\t\t`state: ${escapeDiagnosticText(result.refusal.state)}`,\n\t\t`withheld authority: ${escapeDiagnosticText(result.refusal.withheldAuthority)}`,\n\t\t`resolving command: ${escapeDiagnosticText(result.refusal.resolvingCommand)}`,\n\t].join('\\n');\n}\n\nexport const releaseCommand = new Command('release')\n\t.description(\n\t\t'End management for one address without touching the database object',\n\t)\n\t.argument('<address>', 'Address as name or kind:name')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema <name>', 'Schema ledger containing the address', 'public')\n\t.option('--kind <kind>', 'Kind for an unqualified address', 'table')\n\t.option(\n\t\t'--parent <kind:name>',\n\t\t'Required parent for column, index, constraint, or policy',\n\t)\n\t.option(\n\t\t'--database-ledger',\n\t\t'Release from the database ledger (for extensions)',\n\t)\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (address: string, options: ReleaseOptions) => {\n\t\ttry {\n\t\t\tconst result = await runRelease(address, options);\n\t\t\tif (options.format === 'json') printCliJson(result);\n\t\t\telse console.log(formatReleaseHuman(result));\n\t\t\tprocess.exitCode = result.outcome === 'released' ? 0 : 1;\n\t\t} catch (error) {\n\t\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\t\tif (options.format === 'json')\n\t\t\t\tprintCliJson({ outcome: 'release-refused', detail });\n\t\t\telse console.error(`release-refused: ${escapeDiagnosticText(detail)}`);\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t});\n","/**\n * DX-030 Block 1: REPL Command\n *\n * dbsp repl [--schema <path>] - Launch interactive REPL.\n * CLI-022: Batch mode support with --eval and --input options.\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { DbCasing } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { config } from '../config.js';\nimport { validateIdentifier } from '../utils/identifier-validation.js';\nimport { loadSchema, loadSchemaFromCwd } from '../utils/schema-loader.js';\n\nexport interface ReplOptions {\n\tschema?: string;\n\t/** CLI-020: Database connection URL for execution mode */\n\tdb?: string;\n\t/** CLI-022: Single query to evaluate (batch mode) */\n\teval?: string;\n\t/** CLI-022: File containing queries to execute (batch mode, one per line) */\n\tinput?: string;\n\t/** CLI-022: Output format for batch mode */\n\tformat?: 'text' | 'json';\n\t/** DEMO-E2E: Assertion file for validating query output */\n\tassert?: string;\n\t/** CLI-IMPORT: SQL files to import before queries (injected as .import commands) */\n\timport?: string[];\n\t/** CLI-USE: PostgreSQL schema to use (injected as .use command) */\n\tuse?: string;\n\t/** CLI-MUT: Start REPL with parse mode enabled */\n\tparse?: boolean;\n\t/** CLI-MUT: Start REPL with exec mode enabled */\n\texec?: boolean;\n\t/** CLI-CONFIG: Custom config file path (default: ~/.dbsp/config.json) */\n\tconfig?: string;\n\t/** CLI-CASING: Column naming convention (describes DB column casing) */\n\tcasing?: 'snake' | 'camel' | 'none';\n}\n\nexport const replCommand = new Command('repl')\n\t.description('Launch interactive REPL for exploring schema and queries')\n\t.option('-s, --schema <path>', 'Path to schema file (default: auto-detect)')\n\t.option(\n\t\t'-d, --db <url>',\n\t\t'PostgreSQL connection URL for execution mode (e.g., postgres://localhost/mydb)',\n\t)\n\t.option('-e, --eval <query>', 'Execute a single query and exit (batch mode)')\n\t.option(\n\t\t'-i, --input <file>',\n\t\t'Execute queries from file, one per line (batch mode)',\n\t)\n\t.option(\n\t\t'-f, --format <format>',\n\t\t'Output format for batch mode: text (default) or json',\n\t\t'text',\n\t)\n\t.option(\n\t\t'-a, --assert <file>',\n\t\t'Assertion file to validate query output (requires --input)',\n\t)\n\t.option(\n\t\t'--import <files...>',\n\t\t'SQL files to import before queries (equivalent to .import commands)',\n\t)\n\t.option(\n\t\t'--use <schema>',\n\t\t'PostgreSQL schema to use (equivalent to .use command)',\n\t)\n\t.option('--parse', 'Start REPL with parse mode enabled (.parse toggle)')\n\t.option('--exec', 'Start REPL with exec mode enabled (.exec toggle)')\n\t.option(\n\t\t'--casing <type>',\n\t\t'Column naming convention: snake (DB uses snake_case), camel (DB uses camelCase), none (preserve as-is)',\n\t)\n\t.option(\n\t\t'-c, --config <path>',\n\t\t'Custom config file path (default: ~/.dbsp/config.json)',\n\t)\n\t.action(async (options: ReplOptions) => {\n\t\t// Set custom config path if provided\n\t\tif (options.config) {\n\t\t\tconfig.setConfigPath(options.config);\n\t\t}\n\t\t// Load config\n\t\tconfig.load();\n\t\ttry {\n\t\t\t// Load schema\n\t\t\tlet schemaPath: string;\n\t\t\tlet schema: Awaited<ReturnType<typeof loadSchema>>;\n\n\t\t\tif (options.schema) {\n\t\t\t\tschema = await loadSchema(options.schema);\n\t\t\t\tschemaPath = options.schema;\n\t\t\t} else {\n\t\t\t\tconst result = await loadSchemaFromCwd();\n\t\t\t\tschema = result.schema;\n\t\t\t\tschemaPath = result.path;\n\t\t\t}\n\n\t\t\t// DEMO-E2E: Validate --assert requires --input\n\t\t\tif (options.assert && !options.input) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'--assert requires --input (assertion files validate query output from input files)',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// CLI-IMPORT: Validate that --import requires batch mode (SQL file execution)\n\t\t\t// Note: --use, --parse, --exec work in interactive mode (REPL state setup)\n\t\t\tif (options.import && !options.eval && !options.input) {\n\t\t\t\tthrow new Error('--import requires batch mode (--eval or --input)');\n\t\t\t}\n\n\t\t\t// SEC: Validate --use schema name at the entry point so both the batch path\n\t\t\t// (which injects `.use <schema>`) and the interactive path (which passes\n\t\t\t// initialSchemaName) are protected against SQL injection.\n\t\t\tif (options.use) {\n\t\t\t\tvalidateIdentifier(options.use, 'schema');\n\t\t\t}\n\n\t\t\t// CLI-CASING: explicit flag wins; otherwise use the schema declaration.\n\t\t\tconst dbCasing = mapReplCasingOption(options.casing) ?? schema.dbCasing;\n\n\t\t\t// CLI-022: Batch mode - execute queries without interactive UI\n\t\t\tif (options.eval || options.input) {\n\t\t\t\tconst { runBatchMode } = await import('../repl/batch.js');\n\t\t\t\tconst queries: string[] = [];\n\n\t\t\t\t// CLI-USE: Inject .use command first (schema scoping)\n\t\t\t\tif (options.use) {\n\t\t\t\t\tqueries.push(`.use ${options.use}`);\n\t\t\t\t}\n\n\t\t\t\t// CLI-IMPORT: Inject .import commands for SQL files\n\t\t\t\tif (options.import) {\n\t\t\t\t\tfor (const file of options.import) {\n\t\t\t\t\t\tqueries.push(`.import ${file}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (options.eval) {\n\t\t\t\t\tqueries.push(options.eval);\n\t\t\t\t}\n\n\t\t\t\tif (options.input) {\n\t\t\t\t\t// EH-2: Map ENOENT to a friendly error instead of raw stack trace\n\t\t\t\t\tlet content: string;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontent = readFileSync(options.input, 'utf-8');\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconst isNotFound =\n\t\t\t\t\t\t\terr instanceof Error &&\n\t\t\t\t\t\t\t'code' in err &&\n\t\t\t\t\t\t\t(err as NodeJS.ErrnoException).code === 'ENOENT';\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tisNotFound\n\t\t\t\t\t\t\t\t? `Input file not found: ${options.input}`\n\t\t\t\t\t\t\t\t: `Failed to read input file: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tqueries.push(...content.split('\\n'));\n\t\t\t\t}\n\n\t\t\t\tawait runBatchMode({\n\t\t\t\t\tqueries,\n\t\t\t\t\tschema,\n\t\t\t\t\tschemaPath,\n\t\t\t\t\tformat: options.format ?? 'text',\n\t\t\t\t\t...(options.db && { databaseUrl: options.db }),\n\t\t\t\t\t...(options.assert && { assertFile: options.assert }),\n\t\t\t\t\t...(dbCasing && { dbCasing }),\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Dynamic import to avoid loading React/Ink for other commands\n\t\t\tconst { startRepl } = await import('../repl/index.js');\n\t\t\t// CLI-020: Pass database URL if provided\n\t\t\t// CLI-MUT: Pass initial REPL state options\n\t\t\tawait startRepl({\n\t\t\t\tschema,\n\t\t\t\tschemaPath,\n\t\t\t\t...(options.db && { databaseUrl: options.db }),\n\t\t\t\t...(options.use && { initialSchemaName: options.use }),\n\t\t\t\t...(options.parse && { initialParseMode: true }),\n\t\t\t\t...(options.exec && { initialExecMode: true }),\n\t\t\t\t...(dbCasing && { dbCasing }),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconsole.error(`❌ ${message}`);\n\t\t\tprocess.exit(1);\n\t\t}\n\t});\n\nfunction mapReplCasingOption(\n\tcasing: ReplOptions['casing'],\n): DbCasing | undefined {\n\tswitch (casing) {\n\t\tcase 'snake':\n\t\t\treturn 'snake_case';\n\t\tcase 'camel':\n\t\t\treturn 'camelCase';\n\t\tcase 'none':\n\t\t\treturn 'preserve';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n","/**\n * Verify Command — Schema Drift Detection\n *\n * dbsp verify - Compare schema vs real database using the comparison engine.\n * Detects drift in tables, columns, types, nullable, defaults, FKs, indexes.\n */\n\nimport {\n\tcomparePgsqlDatabaseSchema,\n\tcreatePgsqlAdapter,\n\tescapeDiagnosticText,\n} from '@dbsp/adapter-pgsql';\nimport { Command } from 'commander';\nimport { createDbConnection, redactDbUrl } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { loadSchema } from '../utils/schema-loader.js';\nimport { formatVerifyResult, verifyFromDiff } from '../verifier.js';\n\nexport const verifyCommand = new Command('verify')\n\t.description('Compare schema vs real database (drift detection)')\n\t.option(\n\t\t'-s, --schema <path>',\n\t\t'Path to schema file (default: dbsp.schema.ts)',\n\t)\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema-name <name>', 'Database schema name (default: public)')\n\t.option('--json', 'Output as JSON')\n\t.action(\n\t\tasync (options: {\n\t\t\tschema?: string;\n\t\t\tdb: string;\n\t\t\tschemaName?: string;\n\t\t\tjson?: boolean;\n\t\t}) => {\n\t\t\tconst schemaPath = options.schema ?? 'dbsp.schema.ts';\n\n\t\t\tconst redactedUrl = redactDbUrl(options.db);\n\n\t\t\tif (!options.json) {\n\t\t\t\tconsole.log(`🔍 Verifying schema: ${schemaPath}`);\n\t\t\t\tconsole.log(` Database: ${redactedUrl}`);\n\t\t\t\tif (options.schemaName) {\n\t\t\t\t\tconsole.log(` Schema: ${options.schemaName}`);\n\t\t\t\t}\n\t\t\t\tconsole.log('');\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Load schema from file → ModelIR\n\t\t\t\tconst loaded = await loadSchema(schemaPath);\n\t\t\t\tconst schemaModel = loaded.model;\n\n\t\t\t\t// Connect to database\n\t\t\t\tconst { pool } = await createDbConnection(options.db);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst adapter = createPgsqlAdapter(pool);\n\t\t\t\t\t// Live diff: introspect database and canonicalise PostgreSQL CHECK\n\t\t\t\t\t// expressions before comparing.\n\t\t\t\t\tconst diff = await comparePgsqlDatabaseSchema(adapter, schemaModel, {\n\t\t\t\t\t\t...(options.schemaName ? { schema: options.schemaName } : {}),\n\t\t\t\t\t\t...(loaded.dbCasing !== undefined\n\t\t\t\t\t\t\t? { dbCasing: loaded.dbCasing }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tonExpressionCanonicalizationWarning: (warning) =>\n\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t`⚠️ [${warning.kind} ${escapeDiagnosticText(warning.table)}.${escapeDiagnosticText(warning.name)}] ${warning.message}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t});\n\n\t\t\t\t\t// Convert to verify result\n\t\t\t\t\t// Keep the legacy reporting fields sourced from introspection so\n\t\t\t\t\t// --json consumers continue to see database table names as before.\n\t\t\t\t\tconst dbModel = await adapter.introspect({\n\t\t\t\t\t\t...(options.schemaName ? { schema: options.schemaName } : {}),\n\t\t\t\t\t});\n\t\t\t\t\tconst schemaTables = Array.from(schemaModel.tables.keys());\n\t\t\t\t\tconst dbTables = Array.from(dbModel.tables.keys());\n\t\t\t\t\tconst result = verifyFromDiff(diff, schemaTables, dbTables);\n\n\t\t\t\t\t// Output\n\t\t\t\t\tif (options.json) {\n\t\t\t\t\t\t// Exclude the full diff meta from JSON output (too verbose)\n\t\t\t\t\t\tconst { diff: _diff, ...jsonResult } = result;\n\t\t\t\t\t\tprintCliJson({\n\t\t\t\t\t\t\t...jsonResult,\n\t\t\t\t\t\t\tsummary: diff.summary,\n\t\t\t\t\t\t\thasDestructive: diff.hasDestructive,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(formatVerifyResult(result));\n\t\t\t\t\t}\n\n\t\t\t\t\t// EH-14: set exit code; let finally run pool.end() before process exits\n\t\t\t\t\tprocess.exitCode = result.valid ? 0 : 1;\n\t\t\t\t\treturn;\n\t\t\t\t} finally {\n\t\t\t\t\t// Close database connection\n\t\t\t\t\tawait pool.end();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message =\n\t\t\t\t\terror instanceof Error ? error.message : 'Unknown error occurred';\n\t\t\t\t// CC-2+EH-7: If --json, error goes to stdout as JSON; otherwise stderr\n\t\t\t\tif (options.json) {\n\t\t\t\t\tprintCliJson({ status: 'error', error: message });\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(`❌ Error: ${message}`);\n\t\t\t\t}\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t},\n\t);\n","/**\n * Schema Verifier — Drift Detection via Comparison Engine\n *\n * Compares schema definition against real database using the\n * adapter's compareSchemata engine for full drift detection.\n *\n * Detects: tables, columns, types, nullable, defaults, FKs, indexes, PKs.\n */\n\nimport type { ChangeKind, SchemaChange, SchemaDiff } from '@dbsp/adapter-pgsql';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type DriftSeverity = 'error' | 'warning' | 'info';\n\n/** The observed occupancy state of a declared paired table re-address. */\nexport type ReaddressDriftState =\n\t| 'source-only'\n\t| 'target-only'\n\t| 'target-occupied'\n\t| 'source-missing'\n\t| 'unknown';\n\nexport type DriftType =\n\t// Tables\n\t| 'missing_table_in_db'\n\t| 'missing_table_in_schema'\n\t| 'readdress_table'\n\t// Columns\n\t| 'missing_column_in_db'\n\t| 'missing_column_in_schema'\n\t| 'type_mismatch'\n\t| 'nullable_mismatch'\n\t| 'default_mismatch'\n\t| 'unique_mismatch'\n\t// Constraints\n\t| 'primary_key_mismatch'\n\t| 'missing_fk_in_db'\n\t| 'missing_fk_in_schema'\n\t| 'fk_on_delete_mismatch'\n\t// Indexes\n\t| 'missing_index_in_db'\n\t| 'missing_index_in_schema'\n\t// CHECK constraints\n\t| 'missing_check_in_db'\n\t| 'missing_check_in_schema'\n\t// ENUM types\n\t| 'missing_enum_in_db'\n\t| 'missing_enum_in_schema'\n\t| 'enum_value_mismatch'\n\t// Column enhancements\n\t| 'collation_mismatch'\n\t| 'identity_mismatch'\n\t// Comments\n\t| 'comment_mismatch'\n\t// Extensions & Sequences\n\t| 'missing_extension'\n\t| 'missing_sequence'\n\t| 'sequence_mismatch'\n\t// Constraints\n\t| 'constraint_validation_mismatch'\n\t// Row-Level Security\n\t| 'rls_enabled_mismatch'\n\t| 'missing_policy_in_db'\n\t| 'missing_policy_in_schema';\n\nexport interface DriftIssue {\n\t/** Issue severity */\n\tseverity: DriftSeverity;\n\t/** Human-readable message */\n\tmessage: string;\n\t/** Table affected (if any) */\n\ttable?: string;\n\t/** Column affected (if any) */\n\tcolumn?: string;\n\t/** Issue type for programmatic handling */\n\ttype: DriftType;\n\t/** Present for a declared re-address; describes its executable/refused state. */\n\treaddress?: {\n\t\treadonly state: ReaddressDriftState;\n\t\treadonly sourcePresent?: boolean;\n\t\treadonly targetPresent?: boolean;\n\t};\n}\n\nexport interface VerifyResult {\n\t/** Whether the schema matches the database */\n\tvalid: boolean;\n\t/** List of drift issues found */\n\tissues: DriftIssue[];\n\t/** Tables in schema */\n\tschemaTables: string[];\n\t/** Tables in database */\n\tdbTables: string[];\n\t/** Structured diff (for programmatic consumers) */\n\tdiff: SchemaDiff;\n}\n\n// ============================================================================\n// Change → Drift Mapping\n// ============================================================================\n\nconst CHANGE_TO_DRIFT: Record<\n\tChangeKind,\n\t{ type: DriftType; severity: DriftSeverity }\n> = {\n\tcreate_table: { type: 'missing_table_in_db', severity: 'error' },\n\tdrop_table: { type: 'missing_table_in_schema', severity: 'warning' },\n\treaddress_table: { type: 'readdress_table', severity: 'error' },\n\tadd_column: { type: 'missing_column_in_db', severity: 'error' },\n\tdrop_column: { type: 'missing_column_in_schema', severity: 'info' },\n\talter_column_type: { type: 'type_mismatch', severity: 'error' },\n\talter_column_nullable: { type: 'nullable_mismatch', severity: 'warning' },\n\talter_column_default: { type: 'default_mismatch', severity: 'warning' },\n\talter_column_unique: { type: 'unique_mismatch', severity: 'warning' },\n\tadd_primary_key: { type: 'primary_key_mismatch', severity: 'error' },\n\tdrop_primary_key: { type: 'primary_key_mismatch', severity: 'error' },\n\tadd_foreign_key: { type: 'missing_fk_in_db', severity: 'error' },\n\tdrop_foreign_key: { type: 'missing_fk_in_schema', severity: 'warning' },\n\talter_foreign_key: { type: 'fk_on_delete_mismatch', severity: 'warning' },\n\tcreate_index: { type: 'missing_index_in_db', severity: 'warning' },\n\tdrop_index: { type: 'missing_index_in_schema', severity: 'info' },\n\t// CHECK constraints\n\tadd_check_constraint: { type: 'missing_check_in_db', severity: 'warning' },\n\tdrop_check_constraint: { type: 'missing_check_in_schema', severity: 'info' },\n\t// ENUM types\n\tcreate_enum: { type: 'missing_enum_in_db', severity: 'error' },\n\talter_enum_add_value: { type: 'enum_value_mismatch', severity: 'warning' },\n\tdrop_enum: { type: 'missing_enum_in_schema', severity: 'warning' },\n\t// Column enhancements\n\talter_column_collation: { type: 'collation_mismatch', severity: 'warning' },\n\talter_column_identity: { type: 'identity_mismatch', severity: 'warning' },\n\t// Comments\n\tadd_comment: { type: 'comment_mismatch', severity: 'info' },\n\tdrop_comment: { type: 'comment_mismatch', severity: 'info' },\n\t// Extensions & Sequences\n\tcreate_extension: { type: 'missing_extension', severity: 'error' },\n\tdrop_extension: { type: 'missing_extension', severity: 'info' },\n\tcreate_sequence: { type: 'missing_sequence', severity: 'warning' },\n\talter_sequence: { type: 'sequence_mismatch', severity: 'warning' },\n\tdrop_sequence: { type: 'missing_sequence', severity: 'info' },\n\t// Constraints\n\tvalidate_constraint: {\n\t\ttype: 'constraint_validation_mismatch',\n\t\tseverity: 'warning',\n\t},\n\t// Row-Level Security\n\tenable_rls: { type: 'rls_enabled_mismatch', severity: 'warning' },\n\tdisable_rls: { type: 'rls_enabled_mismatch', severity: 'warning' },\n\tcreate_policy: { type: 'missing_policy_in_db', severity: 'warning' },\n\tdrop_policy: { type: 'missing_policy_in_schema', severity: 'warning' },\n};\n\nfunction changeToDriftIssue(change: SchemaChange): DriftIssue {\n\tconst mapping = CHANGE_TO_DRIFT[change.kind] ?? {\n\t\ttype: 'type_mismatch' as DriftType,\n\t\tseverity: 'warning' as DriftSeverity,\n\t};\n\tif (change.kind === 'readdress_table') {\n\t\tconst assessment = change.meta?.readdressAssessment;\n\t\tconst state: ReaddressDriftState =\n\t\t\tassessment === 'source-only' ||\n\t\t\tassessment === 'target-only' ||\n\t\t\tassessment === 'target-occupied' ||\n\t\t\tassessment === 'source-missing'\n\t\t\t\t? assessment\n\t\t\t\t: 'unknown';\n\t\tconst sourcePresent = change.meta?.sourcePresent;\n\t\tconst targetPresent = change.meta?.targetPresent;\n\t\treturn {\n\t\t\tseverity:\n\t\t\t\tstate === 'source-only' || state === 'target-only'\n\t\t\t\t\t? 'warning'\n\t\t\t\t\t: mapping.severity,\n\t\t\ttype: mapping.type,\n\t\t\ttable: change.table,\n\t\t\tmessage: change.details,\n\t\t\treaddress: {\n\t\t\t\tstate,\n\t\t\t\t...(typeof sourcePresent === 'boolean' ? { sourcePresent } : {}),\n\t\t\t\t...(typeof targetPresent === 'boolean' ? { targetPresent } : {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tseverity: mapping.severity,\n\t\ttype: mapping.type,\n\t\ttable: change.table,\n\t\t...(change.column !== undefined ? { column: change.column } : {}),\n\t\tmessage: change.details,\n\t};\n}\n\n// ============================================================================\n// Verification (from SchemaDiff)\n// ============================================================================\n\n/**\n * Convert a SchemaDiff into a VerifyResult.\n *\n * @param diff - Structured diff from compareSchemata()\n * @param schemaTables - Table names in schema (for backward compat)\n * @param dbTables - Table names in database (for backward compat)\n */\nexport function verifyFromDiff(\n\tdiff: SchemaDiff,\n\tschemaTables: string[],\n\tdbTables: string[],\n): VerifyResult {\n\tconst issues = diff.changes.map(changeToDriftIssue);\n\n\t// Sort by severity (error > warning > info)\n\tconst severityOrder: Record<DriftSeverity, number> = {\n\t\terror: 0,\n\t\twarning: 1,\n\t\tinfo: 2,\n\t};\n\tissues.sort(\n\t\t(a: DriftIssue, b: DriftIssue) =>\n\t\t\tseverityOrder[a.severity] - severityOrder[b.severity],\n\t);\n\n\tconst hasErrors = issues.some((i: DriftIssue) => i.severity === 'error');\n\n\treturn {\n\t\tvalid: !hasErrors,\n\t\tissues,\n\t\tschemaTables,\n\t\tdbTables,\n\t\tdiff,\n\t};\n}\n\n// ============================================================================\n// Format\n// ============================================================================\n\n/**\n * Format verification result for CLI output.\n */\nexport function formatVerifyResult(result: VerifyResult): string {\n\tconst lines: string[] = [];\n\n\tif (result.valid) {\n\t\tlines.push('✅ Schema matches database');\n\t} else {\n\t\tlines.push('❌ Schema drift detected');\n\t}\n\n\tlines.push('');\n\tlines.push(`Tables in schema: ${result.schemaTables.length}`);\n\tlines.push(`Tables in database: ${result.dbTables.length}`);\n\tlines.push('');\n\n\tif (result.issues.length === 0) {\n\t\tlines.push('No issues found.');\n\t} else {\n\t\tconst errors = result.issues.filter((i) => i.severity === 'error');\n\t\tconst warnings = result.issues.filter((i) => i.severity === 'warning');\n\t\tconst infos = result.issues.filter((i) => i.severity === 'info');\n\n\t\tif (errors.length > 0) {\n\t\t\tlines.push(`❌ ${errors.length} error(s):`);\n\t\t\tfor (const issue of errors) {\n\t\t\t\tlines.push(` ${issue.message}`);\n\t\t\t}\n\t\t\tlines.push('');\n\t\t}\n\n\t\tif (warnings.length > 0) {\n\t\t\tlines.push(`⚠️ ${warnings.length} warning(s):`);\n\t\t\tfor (const issue of warnings) {\n\t\t\t\tlines.push(` ${issue.message}`);\n\t\t\t}\n\t\t\tlines.push('');\n\t\t}\n\n\t\tif (infos.length > 0) {\n\t\t\tlines.push(`ℹ️ ${infos.length} info:`);\n\t\t\tfor (const issue of infos) {\n\t\t\t\tlines.push(` ${issue.message}`);\n\t\t\t}\n\t\t\tlines.push('');\n\t\t}\n\t}\n\n\treturn lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAQA,SAAS,qBAAqB;AAC9B,SAAS,WAAAA,WAAS,sBAAsB;;;ACRxC,SAAS,yBAAyB;AAClC,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAChC;AAAA,EACC;AAAA,EACA;AAAA,EACA,4BAAAC;AAAA,EACA,0BAAAC;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,wBAAwB;AACjC;AAAA,EACC;AAA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GAAG,QAAQ,QAAQ;AAClD,YAAQ,gBAAgB,EAAE,UAAU,MAAM;AAAA,IAAC,EAAE,CAAC;AAChD;AAIA,WAAW,WAAW,CAAC,SAAS,GAAG,QAAQ,QAAQ,EAAG,SAAQ,aAAa;AAE3E,IAAI;AACH,UAAQ,MAAM;AACf,SAAS,KAAK;AAGb,MAAI,eAAe,kBAAkB,IAAI,aAAa,GAAG;AACxD,YAAQ,KAAK,CAAC;AAAA,EACf;AACA,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AACrD,MAAI,eAAe;AAClB,iBAAa,EAAE,QAAQ,SAAS,OAAO,QAAQ,CAAC;AAAA,EACjD,OAAO;AACN,YAAQ,MAAM,UAAK,OAAO,EAAE;AAAA,EAC7B;AACA,UAAQ,KAAK,CAAC;AACf;","names":["Command","createHash","createPgTransitionLessor","createPgTransitionPack","escapeDiagnosticText","acquireTransitionLease","createPackRegistry","transitionPlanDigest","validateNormalizedManagedStepManifest","REFUSAL_VOCABULARY","Command","address","decision","createHash","randomUUID","createPgsqlAdapter","readPgCatalogueIdentity","validateNormalizedManagedStepManifest","createHash","validateNormalizedManagedStepManifest","databaseId","createPgsqlAdapter","readPgCatalogueIdentity","randomUUID","createPgsqlAdapter","createPgTransitionLessor","createPgTransitionRunPersister","acquireTransitionLease","acquireTransitionLease","createPgTransitionLessor","observed","createPgsqlAdapter","registry","createPgTransitionRunPersister","escapeDiagnosticText","record","acceptance","createHash","createPackRegistry","createPgTransitionPack","escapeDiagnosticText","acceptance","REFUSAL_VOCABULARY","acquireTransitionLease","createPgTransitionLessor","transitionPlanDigest","validateNormalizedManagedStepManifest","digest","record","Command","result","exitCode","Command","Command","outputPath","isDeepStrictEqual","createPgTransitionLessor","escapeDiagnosticText","readPgCatalogueIdentity","readPgLedgerAddressChain","acquireTransitionLease","projectLedgerChain","Command","isDeepStrictEqual","acquireTransitionLease","createPgTransitionLessor","projectLedgerChain","readPgLedgerAddressChain","readPgCatalogueIdentity","Command","escapeDiagnosticText","mkdirSync","writeFileSync","dirname","resolve","Command","Command","resolve","mkdirSync","dirname","writeFileSync","createHash","dirname","escapeDiagnosticText","getNamingPluginForDbCasing","declarationSetFromModel","Command","dirname","declarationSetFromModel","createHash","record","getNamingPluginForDbCasing","escapeDiagnosticText","Command","createHash","escapeDiagnosticText","readPgLedgerAddressChain","readPgLedgerScopeCurrency","readTransitionJournal","withPgTransitionRunLock","acquireExclusiveTransitionLease","outcomeClaimId","projectLedgerChain","transitionPlanDigest","Command","createHash","escapeDiagnosticText","record","transitionPlanDigest","outcomeClaimId","acceptance","withPgTransitionRunLock","acquireExclusiveTransitionLease","readTransitionJournal","home","readPgLedgerScopeCurrency","readPgLedgerAddressChain","projectLedgerChain","open","Command","assertPgDatabaseWritable","createPgTransitionPack","isPgDatabaseReadOnlyError","readPgLedgerScopeCurrency","readPgObservationContextFromLessor","readTransitionJournal","withPgTransitionRunLock","assumptionAccepted","createApplier","createPackRegistry","transitionPlanDigest","Command","assumptionAccepted","transitionPlanDigest","readTransitionJournal","ledgerHome","home","readPgLedgerScopeCurrency","withPgTransitionRunLock","assertPgDatabaseWritable","isPgDatabaseReadOnlyError","result","createApplier","createPackRegistry","createPgTransitionPack","readPgObservationContextFromLessor","Command","createPgTransitionLessor","escapeDiagnosticText","acquireTransitionLease","Command","acquireTransitionLease","createPgTransitionLessor","escapeDiagnosticText","Command","Command","Command","comparePgsqlDatabaseSchema","createPgsqlAdapter","escapeDiagnosticText","Command","assessment","Command","createPgsqlAdapter","comparePgsqlDatabaseSchema","escapeDiagnosticText","Command"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/commands/apply.ts","../src/utils/output.ts","../src/commands/execution-ids.ts","../src/commands/generator-execution.ts","../src/commands/generator-plan.ts","../src/commands/plan.ts","../src/commands/refusal-output.ts","../src/commands/generate.ts","../src/commands/inspect.ts","../src/commands/introspect.ts","../src/commands/preflight.ts","../src/commands/reconcile.ts","../src/commands/recover.ts","../src/commands/release.ts","../src/commands/repl.ts","../src/commands/verify.ts","../src/verifier.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * ARCH-002 Block 3: CLI Scaffold\n *\n * dbsp CLI - Schema-first code generation for db-semantic-planner.\n */\n\nimport { createRequire } from 'node:module';\nimport { Command, CommanderError } from 'commander';\nimport { applyCommand } from './commands/apply.js';\nimport { generateCommand } from './commands/generate.js';\nimport { inspectCommand } from './commands/inspect.js';\nimport { introspectCommand } from './commands/introspect.js';\nimport { planCommand } from './commands/plan.js';\nimport { preflightCommand } from './commands/preflight.js';\nimport { reconcileCommand } from './commands/reconcile.js';\nimport { recoverCommand } from './commands/recover.js';\n\nimport { releaseCommand } from './commands/release.js';\nimport { replCommand } from './commands/repl.js';\nimport { verifyCommand } from './commands/verify.js';\nimport { printCliJson } from './utils/output.js';\n\nconst program = new Command();\nconst packageJson = createRequire(import.meta.url)('../package.json') as {\n\treadonly version: string;\n};\n\nconst jsonFormatCommands = new Set([\n\t'apply',\n\t'inspect',\n\t'plan',\n\t'recover',\n\t'reconcile',\n\t'release',\n]);\n\nfunction requestsJson(argv: readonly string[]): boolean {\n\t// The initial positional token is the command Commander will try to run.\n\t// Do not let a typo such as `plna --format json` opt into a JSON envelope.\n\tlet command: string | undefined;\n\tfor (const argument of argv) {\n\t\tif (argument === '--') break;\n\t\tif (!argument.startsWith('-')) {\n\t\t\tcommand = argument;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (command === undefined || !jsonFormatCommands.has(command)) return false;\n\n\tfor (let index = 0; index < argv.length; index += 1) {\n\t\tconst argument = argv[index];\n\t\tif (argument === '--') break;\n\t\tif (\n\t\t\t(argument === '--format' && argv[index + 1] === 'json') ||\n\t\t\targument === '--format=json' ||\n\t\t\targument === '--json'\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nprogram\n\t.name('dbsp')\n\t.description('Schema-first code generation for db-semantic-planner')\n\t.version(packageJson.version);\n\n// Register commands\nprogram.addCommand(generateCommand);\nprogram.addCommand(introspectCommand);\nprogram.addCommand(planCommand);\nprogram.addCommand(preflightCommand);\nprogram.addCommand(applyCommand);\nprogram.addCommand(inspectCommand);\nprogram.addCommand(recoverCommand);\nprogram.addCommand(releaseCommand);\nprogram.addCommand(reconcileCommand);\nprogram.addCommand(replCommand);\nprogram.addCommand(verifyCommand);\n\nconst jsonRequested = requestsJson(process.argv.slice(2));\n\n// Commander validates options before transferring control to a subcommand.\n// Suppress its eager plaintext diagnostic whenever the request chose JSON.\nif (jsonRequested) {\n\tfor (const command of [program, ...program.commands])\n\t\tcommand.configureOutput({ writeErr: () => {} });\n}\n\n// CC-15: Intercept parse errors so recognized JSON-capable commands receive a\n// JSON error object on stdout instead of a plain-text usage message.\nfor (const command of [program, ...program.commands]) command.exitOverride();\n\ntry {\n\tprogram.parse();\n} catch (err) {\n\t// Commander throws CommanderError for --help, --version, and parse errors.\n\t// Exit 0 for informational outputs (help/version); only exit 1 for real errors.\n\tif (err instanceof CommanderError && err.exitCode === 0) {\n\t\tprocess.exit(0);\n\t}\n\tconst message = err instanceof Error ? err.message : 'Command parse error';\n\tif (jsonRequested) {\n\t\tprintCliJson({ status: 'error', error: message });\n\t} else {\n\t\tconsole.error(`❌ ${message}`);\n\t}\n\tprocess.exit(1);\n}\n","/** Execute exactly one reviewed durable transition run; never re-plan. */\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { createInterface } from 'node:readline/promises';\nimport {\n\tappendIntentJournal,\n\tappendTransitionAuthorization,\n\tcreatePgTransitionLessor,\n\tcreatePgTransitionPack,\n\tescapeDiagnosticText,\n\tpreparePgExecutionSession,\n\treadPgLedgerAddressChain,\n\treadPgLedgerReservationsForExecution,\n\treadTransitionJournal,\n\tTransitionRunIdentityMismatchError,\n\tvalidatePgManagedLedgerCurrency,\n\twithPgTransitionRunLock,\n} from '@dbsp/adapter-pgsql';\nimport { lockPgJournalRun } from '@dbsp/adapter-pgsql/internal';\nimport {\n\tacquireExclusiveTransitionLease,\n\tacquireTransitionLease,\n\tcreateApplier,\n\tcreatePackRegistry,\n\ttype PackRegistry,\n\tselectorMatchesResource,\n\ttransitionPlanDigest,\n\tvalidateNormalizedManagedStepManifest,\n} from '@dbsp/core';\nimport { mintDurablyLoadedRun } from '@dbsp/core/internal';\nimport type {\n\tApplyPolicy,\n\tApplyResult,\n\tAssumptionAcceptance,\n\tLedgerAddress,\n\tLedgerHome,\n\tNormalizedManagedStep,\n\tPhysicalOperation,\n\tResourceAddress,\n\tResourceSelector,\n\tTransitionRunAuthorization,\n\tTransitionRunJournal,\n\tTrustRoot,\n} from '@dbsp/types';\nimport { ledgerAddressKey, REFUSAL_VOCABULARY } from '@dbsp/types';\nimport { Command } from 'commander';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { executionIdsForRun } from './execution-ids.js';\nimport {\n\texecuteGeneratorPlan,\n\ttype GeneratorExecutionResult,\n} from './generator-execution.js';\nimport type { GeneratorDurablePlan } from './generator-plan.js';\nimport {\n\tpersistedLifecycleDirectiveError,\n\trunGeneratorPlan,\n} from './generator-plan.js';\nimport {\n\texitCodeForPlanResult,\n\tformatPlanHuman,\n\tformatPlanJson,\n\ttype PlanResult,\n\trunPlan,\n} from './plan.js';\nimport {\n\tformatPreAppendRefusalHuman,\n\ttype PreAppendRefusal,\n\tpreAppendRefusalFor,\n} from './refusal-output.js';\n\nexport type ApplyFormat = 'text' | 'json';\nexport interface ApplyOptions {\n\treadonly db: string;\n\treadonly planDigest?: string;\n\treadonly accept?: readonly string[];\n\treadonly acceptPolicy?: string;\n\treadonly format?: ApplyFormat;\n\t/** The no-argument form's authored declaration. */\n\treadonly schemaFile?: string;\n\treadonly schema?: string;\n\treadonly yes?: boolean;\n\treadonly dryRun?: boolean;\n\t/** Reviewed replacement selector(s) for the no-argument generator path. */\n\treadonly replace?: readonly string[];\n}\n\n/**\n * Recovery is keyed to the loaded durable run. Ledger address history belongs\n * to every run that touched the address and must not make a fresh run stale.\n */\nexport function generatorRunHasPriorStepEvents(\n\tloaded: Pick<TransitionRunJournal, 'events'>,\n): boolean {\n\treturn loaded.events.some((event) => {\n\t\tconst executionId =\n\t\t\tevent.event === 'intent' && 'executionId' in event.record\n\t\t\t\t? event.record.executionId\n\t\t\t\t: undefined;\n\t\treturn !(\n\t\t\ttypeof executionId === 'string' &&\n\t\t\tevent.stepId === `dbsp.generator.attempt:${executionId}` &&\n\t\t\tevent.operationRef === 'dbsp.generator.attempt'\n\t\t);\n\t});\n}\n\nfunction ledgerHomeForGeneratorAddress(address: LedgerAddress): LedgerHome {\n\tif (address.scope === 'database') return { scope: 'database' };\n\tif (!address.schema)\n\t\tthrow new Error(\n\t\t\t`schema-scoped generated address ${address.name} has no schema ledger`,\n\t\t);\n\treturn { scope: 'schema', schema: address.schema };\n}\n\n/** Every generated address, including each closure member, bounds replay evidence reads. */\nfunction generatorPlanLedgerAddresses(\n\tsteps: readonly NormalizedManagedStep[],\n): readonly LedgerAddress[] {\n\tconst addresses = new Map<string, LedgerAddress>();\n\tfor (const step of steps) {\n\t\tif (step.address !== undefined) {\n\t\t\taddresses.set(ledgerAddressKey(step.address), step.address);\n\t\t\tcontinue;\n\t\t}\n\t\tconst closure = step.closure;\n\t\tif (!closure)\n\t\t\tthrow new Error(`generated step ${step.stepKey} has no ledger address`);\n\t\tconst candidates = [\n\t\t\tclosure.root,\n\t\t\t...closure.members.map((member) => member.address),\n\t\t];\n\t\tfor (const address of candidates)\n\t\t\taddresses.set(ledgerAddressKey(address), address);\n\t}\n\treturn [...addresses.values()];\n}\n\n/**\n * A recorded attempt remains retryable only until the ledger contains no trace\n * of it. Reservations are queried by ledger home; chain reads stay at plan addresses.\n */\nasync function generatorRunHasLedgerEvidence(\n\tsession: Parameters<typeof readPgLedgerReservationsForExecution>[0],\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n\tsteps: readonly NormalizedManagedStep[],\n): Promise<boolean> {\n\tconst executionIds = executionIdsForRun(journal);\n\tconst executionIdSet = new Set(executionIds);\n\tconst addresses = generatorPlanLedgerAddresses(steps);\n\tconst homes = new Map<string, LedgerHome>();\n\tfor (const address of addresses) {\n\t\tconst home = ledgerHomeForGeneratorAddress(address);\n\t\thomes.set(`${home.scope}:${home.schema ?? ''}`, home);\n\t}\n\tfor (const home of homes.values()) {\n\t\tfor (const executionId of executionIds) {\n\t\t\tconst reservations = await readPgLedgerReservationsForExecution(\n\t\t\t\tsession,\n\t\t\t\thome,\n\t\t\t\texecutionId,\n\t\t\t);\n\t\t\tif (reservations.length > 0) return true;\n\t\t}\n\t}\n\tfor (const address of addresses) {\n\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\tsession,\n\t\t\tledgerHomeForGeneratorAddress(address),\n\t\t\taddress,\n\t\t);\n\t\tif (\n\t\t\tchain.events.some((event) => executionIdSet.has(event.executionId ?? ''))\n\t\t)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\n/** The generator replay gate has one decision: journal steps or attributable ledger evidence. */\nasync function generatorRunRequiresRecovery(\n\ttarget: Parameters<typeof acquireExclusiveTransitionLease>[0],\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n\tsteps: readonly NormalizedManagedStep[],\n): Promise<boolean> {\n\tif (generatorRunHasPriorStepEvents(journal)) return true;\n\tconst lease = await acquireExclusiveTransitionLease(target);\n\ttry {\n\t\treturn await generatorRunHasLedgerEvidence(lease.session, journal, steps);\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nconst GENERATOR_ATTEMPT_OPERATION: Omit<PhysicalOperation, 'payload'> = {\n\tref: 'dbsp.generator.attempt',\n\toperationKind: {\n\t\tartifact: {\n\t\t\tid: 'dbsp.postgresql.generator' as PhysicalOperation['operationKind']['artifact']['id'],\n\t\t\tversion: '1',\n\t\t},\n\t\tname: 'GeneratorAttempt',\n\t},\n};\n\n/**\n * The just-persisted generator-removal exception is an in-module capability,\n * not an ApplyOptions field. A public caller can neither name its type nor\n * manufacture a value accepted by the WeakSet check below.\n */\ninterface JustPersistedGeneratorRemovalCapability {\n\treadonly runId: string;\n}\n\nconst justPersistedGeneratorRemovalCapabilities = new WeakSet<object>();\nconst justPersistedGeneratorRemovalContext =\n\tnew AsyncLocalStorage<JustPersistedGeneratorRemovalCapability>();\n\nfunction mintJustPersistedGeneratorRemovalCapability(\n\trunId: string,\n): JustPersistedGeneratorRemovalCapability {\n\tconst capability = Object.freeze({ runId });\n\tjustPersistedGeneratorRemovalCapabilities.add(capability);\n\treturn capability;\n}\n\nfunction permitsJustPersistedGeneratorRemoval(runId: string): boolean {\n\tconst capability = justPersistedGeneratorRemovalContext.getStore();\n\treturn (\n\t\tcapability !== undefined &&\n\t\tcapability.runId === runId &&\n\t\tjustPersistedGeneratorRemovalCapabilities.has(capability)\n\t);\n}\n\nfunction errorDetail(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/** Apply maps only the two non-resumable persisted-plan failure contracts. */\nfunction isInvalidNonResumablePersistedRunError(\n\terror: unknown,\n\trunId: string,\n): error is Error {\n\treturn (\n\t\terror instanceof Error &&\n\t\t(error.message ===\n\t\t\t'dbsp transition run plan row is invalid and non-resumable' ||\n\t\t\terror.message ===\n\t\t\t\t`dbsp transition run ${runId} has no persisted proven plan and is non-resumable`)\n\t);\n}\n\nclass RecordedPlanDigestMismatchError extends Error {\n\tconstructor(\n\t\tdetail = 'persisted generator plan digest does not match the recorded review',\n\t) {\n\t\tsuper(detail);\n\t\tthis.name = 'RecordedPlanDigestMismatchError';\n\t}\n}\n\n/** A failed owned-pool cleanup supplements a computed command result. */\nexport async function withPoolCleanupReported<T extends object>(\n\tresult: T,\n\tclose: () => Promise<void>,\n): Promise<T & { readonly cleanupError?: string }> {\n\ttry {\n\t\tawait close();\n\t\treturn result;\n\t} catch (error) {\n\t\treturn {\n\t\t\t...result,\n\t\t\tcleanupError: `database pool cleanup failed: ${errorDetail(error)}`,\n\t\t};\n\t}\n}\n\nfunction compareCodeUnits(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\n/** Stable JSON encoding: object keys sort lexically and arrays retain their supplied order. */\nexport function canonicalJson(value: unknown): string {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === 'string' ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'number'\n\t) {\n\t\tif (typeof value === 'number' && !Number.isFinite(value))\n\t\t\tthrow new Error('policy values must be finite JSON values');\n\t\treturn JSON.stringify(value);\n\t}\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n\tif (typeof value !== 'object')\n\t\tthrow new Error(\n\t\t\t'policy values must be JSON values (undefined is not allowed)',\n\t\t);\n\tconst record = value as Record<string, unknown>;\n\treturn `{${Object.keys(record)\n\t\t.sort()\n\t\t.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)\n\t\t.join(',')}}`;\n}\n\nfunction nonEmptyString(value: unknown, path: string): asserts value is string {\n\tif (typeof value !== 'string' || value.length === 0 || value.trim() !== value)\n\t\tthrow new Error(`${path} must be a non-empty, unpadded string`);\n}\n\nfunction exactKeys(\n\trecord: Record<string, unknown>,\n\tallowed: readonly string[],\n\tpath: string,\n\tsubject = 'AssumptionAcceptance',\n): void {\n\tfor (const key of Object.keys(record)) {\n\t\tif (!allowed.includes(key))\n\t\t\tthrow new Error(`${path}.${key} is not a valid ${subject} field`);\n\t}\n}\n\nfunction record(value: unknown, path: string): Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value))\n\t\tthrow new Error(`${path} must be an object`);\n\treturn value as Record<string, unknown>;\n}\n\nfunction validateResourceAddress(\n\tvalue: unknown,\n\tpath: string,\n): ResourceAddress {\n\tconst candidate = record(value, path);\n\texactKeys(\n\t\tcandidate,\n\t\t[\n\t\t\t'engine',\n\t\t\t'database',\n\t\t\t'schema',\n\t\t\t'parent',\n\t\t\t'kind',\n\t\t\t'name',\n\t\t\t'catalogueIdentity',\n\t\t\t'qualifiedBy',\n\t\t],\n\t\tpath,\n\t);\n\tfor (const key of ['engine', 'database', 'kind', 'name'] as const)\n\t\tnonEmptyString(candidate[key], `${path}.${key}`);\n\tif (candidate.schema !== undefined)\n\t\tnonEmptyString(candidate.schema, `${path}.schema`);\n\tif (candidate.parent !== undefined)\n\t\tvalidateResourceAddress(candidate.parent, `${path}.parent`);\n\tif (candidate.catalogueIdentity !== undefined) {\n\t\tconst identity = record(\n\t\t\tcandidate.catalogueIdentity,\n\t\t\t`${path}.catalogueIdentity`,\n\t\t);\n\t\texactKeys(\n\t\t\tidentity,\n\t\t\t['engine', 'format', 'value'],\n\t\t\t`${path}.catalogueIdentity`,\n\t\t\t'catalogue identity',\n\t\t);\n\t\tnonEmptyString(identity.engine, `${path}.catalogueIdentity.engine`);\n\t\tif (\n\t\t\ttypeof identity.format !== 'number' ||\n\t\t\t!Number.isInteger(identity.format) ||\n\t\t\tidentity.format <= 0\n\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t`${path}.catalogueIdentity.format must be a positive integer`,\n\t\t\t);\n\t\tconst identityValue = record(\n\t\t\tidentity.value,\n\t\t\t`${path}.catalogueIdentity.value`,\n\t\t);\n\t\ttry {\n\t\t\tcanonicalJson(identityValue);\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`${path}.catalogueIdentity.value must be a canonicalizable JSON object: ${errorDetail(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\tif (candidate.qualifiedBy !== undefined) {\n\t\tif (!Array.isArray(candidate.qualifiedBy))\n\t\t\tthrow new Error(`${path}.qualifiedBy must be an array of strings`);\n\t\tcandidate.qualifiedBy.forEach((part, index) => {\n\t\t\tnonEmptyString(part, `${path}.qualifiedBy[${index}]`);\n\t\t});\n\t}\n\treturn candidate as unknown as ResourceAddress;\n}\n\nfunction validateSelector(value: unknown, path: string): ResourceSelector {\n\tconst candidate = record(value, path);\n\texactKeys(candidate, ['kind', 'schema', 'name', 'within'], path);\n\tfor (const key of ['kind', 'schema', 'name'] as const) {\n\t\tif (candidate[key] !== undefined)\n\t\t\tnonEmptyString(candidate[key], `${path}.${key}`);\n\t}\n\tif (candidate.within !== undefined)\n\t\tvalidateResourceAddress(candidate.within, `${path}.within`);\n\treturn candidate as ResourceSelector;\n}\n\nfunction validateTrustRoot(value: unknown, path: string): TrustRoot {\n\tconst candidate = record(value, path);\n\tnonEmptyString(candidate.kind, `${path}.kind`);\n\tswitch (candidate.kind) {\n\t\tcase 'pack': {\n\t\t\texactKeys(candidate, ['kind', 'artifact'], path);\n\t\t\tconst artifact = record(candidate.artifact, `${path}.artifact`);\n\t\t\texactKeys(artifact, ['id', 'version'], `${path}.artifact`);\n\t\t\tnonEmptyString(artifact.id, `${path}.artifact.id`);\n\t\t\tnonEmptyString(artifact.version, `${path}.artifact.version`);\n\t\t\treturn candidate as TrustRoot;\n\t\t}\n\t\tcase 'human':\n\t\t\texactKeys(candidate, ['kind', 'identity'], path);\n\t\t\tnonEmptyString(candidate.identity, `${path}.identity`);\n\t\t\treturn candidate as TrustRoot;\n\t\tcase 'policy':\n\t\t\texactKeys(candidate, ['kind', 'policyId'], path);\n\t\t\tnonEmptyString(candidate.policyId, `${path}.policyId`);\n\t\t\treturn candidate as TrustRoot;\n\t\tdefault:\n\t\t\tthrow new Error(`${path}.kind must be pack, human, or policy`);\n\t}\n}\n\n/** Reject malformed policy input before it can be mistaken for a non-matching grant. */\nexport function validateAssumptionAcceptance(\n\tvalue: unknown,\n\tpath = 'acceptance',\n): AssumptionAcceptance {\n\tconst candidate = record(value, path);\n\texactKeys(candidate, ['class', 'fromTrustRoot', 'withinScope'], path);\n\tnonEmptyString(candidate.class, `${path}.class`);\n\tif (candidate.fromTrustRoot !== undefined)\n\t\tvalidateTrustRoot(candidate.fromTrustRoot, `${path}.fromTrustRoot`);\n\tif (candidate.withinScope !== undefined) {\n\t\tif (!Array.isArray(candidate.withinScope))\n\t\t\tthrow new Error(`${path}.withinScope must be an array of selectors`);\n\t\tcandidate.withinScope.forEach((selector, index) => {\n\t\t\tvalidateSelector(selector, `${path}.withinScope[${index}]`);\n\t\t});\n\t}\n\treturn candidate as unknown as AssumptionAcceptance;\n}\n\nfunction normaliseAcceptance(\n\tacceptance: AssumptionAcceptance,\n): AssumptionAcceptance {\n\tconst validated = validateAssumptionAcceptance(acceptance);\n\tconst withinScope = validated.withinScope\n\t\t? [\n\t\t\t\t...new Map(\n\t\t\t\t\tvalidated.withinScope.map((item) => [canonicalJson(item), item]),\n\t\t\t\t),\n\t\t\t]\n\t\t\t\t.sort(([left], [right]) => compareCodeUnits(left, right))\n\t\t\t\t.map(([, item]) => JSON.parse(canonicalJson(item)) as ResourceSelector)\n\t\t: undefined;\n\treturn JSON.parse(\n\t\tcanonicalJson({\n\t\t\tclass: validated.class,\n\t\t\t...(validated.fromTrustRoot\n\t\t\t\t? { fromTrustRoot: validated.fromTrustRoot }\n\t\t\t\t: {}),\n\t\t\t...(withinScope === undefined ? {} : { withinScope }),\n\t\t}),\n\t) as AssumptionAcceptance;\n}\n\n/**\n * Canonical policy representation used for both the authorization record and\n * its SHA-256 digest. File and repeated --accept grants form a set union:\n * exact duplicates are retained once, and selector order is normalized.\n */\nexport function canonicalApplyPolicy(\n\tacceptances: readonly AssumptionAcceptance[],\n): readonly AssumptionAcceptance[] {\n\treturn [\n\t\t...new Map(\n\t\t\tacceptances.map((item) => {\n\t\t\t\tconst normalized = normaliseAcceptance(item);\n\t\t\t\treturn [canonicalJson(normalized), normalized] as const;\n\t\t\t}),\n\t\t),\n\t]\n\t\t.sort(([left], [right]) => compareCodeUnits(left, right))\n\t\t.map(([, item]) => item);\n}\n\nexport function policyDigest(policy: readonly AssumptionAcceptance[]): string {\n\treturn createHash('sha256')\n\t\t.update(canonicalJson(canonicalApplyPolicy(policy)))\n\t\t.digest('hex');\n}\n\n/**\n * Hash the exact durable approval, not merely its policy. Run id prevents an\n * approval from replaying onto another run; plan digest pins its reviewed\n * content; grants record which policy entry accepted each assumption.\n */\nexport function authorizationDigest(\n\trunId: string,\n\tplanDigest: string,\n\tpolicy: readonly AssumptionAcceptance[],\n\tgrants: TransitionRunAuthorization['grants'],\n\tactor: string,\n\tauthorizedAt: string,\n): string {\n\tconst authorizedInstant = new Date(authorizedAt);\n\tif (Number.isNaN(authorizedInstant.getTime()))\n\t\tthrow new Error('authorization timestamp must be a valid instant');\n\treturn createHash('sha256')\n\t\t.update(\n\t\t\tcanonicalJson({\n\t\t\t\trunId,\n\t\t\t\tplanDigest,\n\t\t\t\tpolicy: canonicalApplyPolicy(policy),\n\t\t\t\tgrants,\n\t\t\t\tactor,\n\t\t\t\t// PostgreSQL drivers may spell the same timestamptz instant differently.\n\t\t\t\tauthorizedAt: authorizedInstant.toISOString(),\n\t\t\t}),\n\t\t)\n\t\t.digest('hex');\n}\n\n/** A prior authorization is reusable only when every authorization input matches. */\nexport function hasReusableAuthorization(\n\tauthorizations:\n\t\t| readonly Pick<\n\t\t\t\tTransitionRunAuthorization,\n\t\t\t\t'digest' | 'actor' | 'authorizedAt' | 'policy' | 'grants'\n\t\t >[]\n\t\t| undefined,\n\trunId: string,\n\tplanDigest: string,\n\tpolicy: readonly AssumptionAcceptance[],\n\tgrants: TransitionRunAuthorization['grants'],\n): boolean {\n\treturn (\n\t\tauthorizations?.some(\n\t\t\t(item) =>\n\t\t\t\tcanonicalJson(item.policy) === canonicalJson(policy) &&\n\t\t\t\tcanonicalJson(item.grants) === canonicalJson(grants) &&\n\t\t\t\titem.digest ===\n\t\t\t\t\tauthorizationDigest(\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\tplanDigest,\n\t\t\t\t\t\tpolicy,\n\t\t\t\t\t\tgrants,\n\t\t\t\t\t\titem.actor,\n\t\t\t\t\t\titem.authorizedAt,\n\t\t\t\t\t),\n\t\t) ?? false\n\t);\n}\n\n/** Policy files are UTF-8 JSON arrays of strictly validated AssumptionAcceptance objects. */\nexport async function effectiveApplyPolicy(\n\toptions: ApplyOptions,\n): Promise<ApplyPolicy> {\n\tlet fromFile: unknown[] = [];\n\tif (options.acceptPolicy) {\n\t\tconst parsed: unknown = JSON.parse(\n\t\t\tawait readFile(options.acceptPolicy, 'utf8'),\n\t\t);\n\t\tif (!Array.isArray(parsed))\n\t\t\tthrow new Error('--accept-policy must contain a JSON array');\n\t\tfromFile = parsed;\n\t}\n\tconst merged = [\n\t\t...fromFile,\n\t\t...(options.accept ?? []).map((classification) => ({\n\t\t\tclass: classification,\n\t\t})),\n\t];\n\treturn {\n\t\taccepts: canonicalApplyPolicy(\n\t\t\tmerged.map((grant, index) =>\n\t\t\t\tvalidateAssumptionAcceptance(grant, `acceptance[${index}]`),\n\t\t\t),\n\t\t),\n\t};\n}\n\nfunction registry(): PackRegistry {\n\treturn createPackRegistry([createPgTransitionPack({})]);\n}\n\n/**\n * `dbsp apply`'s public result contract. `outcome` is always present in\n * `--format json`; it is the stable machine-readable name and `exitCode` is\n * its exact process status. Core step outcomes retain their core names.\n */\nexport const APPLY_OUTCOME_CONTRACT = [\n\t['completed', 0, 'all planned steps completed'],\n\t['operation-failed-not-applied', 10, 'operation failed before application'],\n\t['partially-applied', 11, 'some target effects may be durable'],\n\t['unknown-step-result', 12, 'a step result could not be determined'],\n\t['outcome-unknown', 13, 'run lifecycle is indeterminate'],\n\t['guard-failed', 14, 'a guard rejected the target'],\n\t['guard-timeout', 15, 'a guard timed out'],\n\t['context-mismatch', 16, 'target no longer matches the run context'],\n\t[\n\t\t'transactional-only-refusal',\n\t\t17,\n\t\t\"durable apply executes segments that forbid a transaction block only when the plan's non-transactional-segment assumption is accepted\",\n\t],\n\t['digest-mismatch', 18, 'persisted plan does not match its recorded digest'],\n\t[\n\t\t'plan-digest-required',\n\t\t32,\n\t\t'apply requires the plan digest printed by dbsp plan',\n\t],\n\t[\n\t\t'plan-digest-mismatch',\n\t\t33,\n\t\t'operator-reviewed plan digest does not match the stored plan',\n\t],\n\t[\n\t\t'non-replayable-generator-run',\n\t\t35,\n\t\t'generator removal runs require a fresh no-argument apply against live state',\n\t],\n\t[\n\t\t'selection-incomplete',\n\t\t63,\n\t\t'reviewed optional actions were not selected exactly before execution',\n\t],\n\t[\n\t\t'prior-step-events-refusal',\n\t\t19,\n\t\t'attempted runs with prior generator step-attempt events must be classified by dbsp reconcile --db <database> <run-id>',\n\t],\n\t[\n\t\t'compatibility-refusal',\n\t\t20,\n\t\t'run execution compatibility epoch is unsupported',\n\t],\n\t['run-busy', 21, 'another database session holds this run lock'],\n\t[\n\t\t'assumption-not-accepted',\n\t\t22,\n\t\t'policy does not accept a required assumption',\n\t],\n\t['authorization-write-failed', 23, 'authorization was not durably committed'],\n\t[\n\t\t'execution-contract-refused',\n\t\t31,\n\t\t'execution contract clause was refused; re-plan for a different target or correct access',\n\t],\n\t[\n\t\t'execution-preflight-failed',\n\t\t30,\n\t\t'execution preflight query failed; retry after transport or read access is restored',\n\t],\n\t[\n\t\t'execution-failed',\n\t\t56,\n\t\t'execution phase failed after preflight; inspect the run with recover',\n\t],\n\t[\n\t\t'recovery-required',\n\t\t64,\n\t\t'an admitted claim remains open; run dbsp reconcile --db <database> <run-id>',\n\t],\n\t[\n\t\t'transport-ambiguous',\n\t\t65,\n\t\t'an admitted operation has an ambiguous transport outcome; reconcile the run before retrying',\n\t],\n\t['database-read-only', 34, 'target cannot accept managed writes'],\n\t[\n\t\t'destructive-authority-refused',\n\t\t59,\n\t\t'a live destructive authority did not permit the generated mutation',\n\t],\n\t[\n\t\t'adoption-refused',\n\t\t62,\n\t\t'a declared adoption no longer matches the live object reviewed for admission',\n\t],\n\t[\n\t\t'readdress-unsupported',\n\t\t60,\n\t\t'declared re-addressing is supported only for tables in one database; declare the move as a retirement and a creation',\n\t],\n\t[\n\t\t'readdress-refused',\n\t\t61,\n\t\t'declared re-addressing could not verify its source identity or target vacancy',\n\t],\n\t[\n\t\t'confirmation-required',\n\t\t57,\n\t\t'no-argument apply requires an interactive confirmation or --yes',\n\t],\n\t[\n\t\t'confirmation-declined',\n\t\t58,\n\t\t'operator declined the persisted plan before execution',\n\t],\n\t['operation-unavailable', 24, 'a required operation artifact is unavailable'],\n\t['plan-validation-failed', 25, 'stored run evidence is invalid'],\n\t['run-id-mismatch', 26, 'loaded run does not match the requested id'],\n\t['load-failed', 27, 'run or target context could not be loaded'],\n\t['policy-invalid', 28, 'acceptance policy input is malformed'],\n\t['apply-failed', 29, 'unexpected apply command failure'],\n] as const;\n\nexport type ApplyOutcome = (typeof APPLY_OUTCOME_CONTRACT)[number][0];\ntype ApplyExecutionOutcome = Exclude<\n\tApplyOutcome,\n\t| 'run-busy'\n\t| 'plan-digest-required'\n\t| 'non-replayable-generator-run'\n\t| 'policy-invalid'\n\t| 'apply-failed'\n>;\n\nconst applyExitCodes = new Map<ApplyOutcome, number>(\n\tAPPLY_OUTCOME_CONTRACT.map(([outcome, exitCode]) => [outcome, exitCode]),\n);\n\nfunction isApplyOutcome(value: string): value is ApplyOutcome {\n\treturn applyExitCodes.has(value as ApplyOutcome);\n}\n\nfunction isApplyExecutionOutcome(\n\tvalue: string,\n): value is ApplyExecutionOutcome {\n\treturn (\n\t\tisApplyOutcome(value) &&\n\t\tvalue !== 'run-busy' &&\n\t\tvalue !== 'policy-invalid' &&\n\t\tvalue !== 'apply-failed'\n\t);\n}\n\nexport function exitCodeForApplyOutcome(outcome: ApplyOutcome): number {\n\treturn applyExitCodes.get(outcome) as number;\n}\n\nexport function outcomeForApplyResult(\n\tresult: ApplyResult,\n): ApplyExecutionOutcome {\n\tif (result.unresolvedOutcome) return result.unresolvedOutcome.kind;\n\tif (result.durableOutcome && isApplyExecutionOutcome(result.durableOutcome))\n\t\treturn result.durableOutcome;\n\t// A committed earlier segment is the operator-facing fact. Do not let the\n\t// narrower reason from a later segment hide durable target effects.\n\tif (result.assessment.lifecycle === 'partially-applied')\n\t\treturn 'partially-applied';\n\tif (result.assessment.lifecycle === 'completed') return 'completed';\n\tconst reason = result.assessment.reasons[0];\n\tif (\n\t\treason?.code === 'context-mismatch' &&\n\t\t'fact' in reason &&\n\t\treason.fact?.key === 'durable-apply-outcome' &&\n\t\tisApplyExecutionOutcome(reason.fact.value)\n\t) {\n\t\treturn reason.fact.value;\n\t}\n\tif (reason?.code === 'unknown-step-result') return 'unknown-step-result';\n\tif (reason?.code === 'operation-failed-not-applied')\n\t\treturn 'operation-failed-not-applied';\n\tif (reason?.code === 'partially-applied') return 'partially-applied';\n\tif (reason?.code === 'guard-failed') return 'guard-failed';\n\tif (reason?.code === 'guard-timeout') return 'guard-timeout';\n\tif (reason?.code === 'context-mismatch') return 'context-mismatch';\n\tif (result.assessment.lifecycle === 'outcome-unknown')\n\t\treturn 'outcome-unknown';\n\treturn 'context-mismatch';\n}\n\ntype CoreApplyCommandResult = {\n\treadonly outcome: Exclude<\n\t\tApplyOutcome,\n\t\t| 'run-busy'\n\t\t| 'plan-digest-required'\n\t\t| 'non-replayable-generator-run'\n\t\t| 'policy-invalid'\n\t\t| 'apply-failed'\n\t>;\n\treadonly runId: string;\n\treadonly result: ApplyResult;\n\treadonly refusal?: PreAppendRefusal;\n};\n\ntype GeneratorApplyCommandResult = {\n\treadonly [Outcome in GeneratorExecutionResult['outcome']]: {\n\t\treadonly outcome: Outcome;\n\t\treadonly runId: string;\n\t\treadonly result: Extract<\n\t\t\tGeneratorExecutionResult,\n\t\t\t{ readonly outcome: Outcome }\n\t\t>;\n\t\treadonly refusal?: PreAppendRefusal;\n\t};\n}[GeneratorExecutionResult['outcome']];\n\nfunction generatorApplyCommandResult(\n\texecution: GeneratorExecutionResult,\n\trunId: string,\n\trefusal: PreAppendRefusal | undefined,\n): GeneratorApplyCommandResult {\n\tconst fields = refusal === undefined ? {} : { refusal };\n\tswitch (execution.outcome) {\n\t\tcase 'completed':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'partially-applied':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'selection-incomplete':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'adoption-refused':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'readdress-unsupported':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'readdress-refused':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'destructive-authority-refused':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'prior-step-events-refusal':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'recovery-required':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'transport-ambiguous':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t\tcase 'execution-failed':\n\t\t\treturn {\n\t\t\t\toutcome: execution.outcome,\n\t\t\t\trunId,\n\t\t\t\tresult: execution,\n\t\t\t\t...fields,\n\t\t\t};\n\t}\n}\n\ntype ApplyHumanResult =\n\t| (ApplyCommandResult & {\n\t\t\treadonly refusal?: PreAppendRefusal | RecordedPlanRefusal;\n\t })\n\t| {\n\t\t\treadonly outcome: string;\n\t\t\treadonly runId: string;\n\t\t\treadonly refusal?: PreAppendRefusal | RecordedPlanRefusal;\n\t };\n\nexport function formatApplyHuman(result: ApplyHumanResult): string {\n\tconst line = `${escapeDiagnosticText(result.outcome)}: ${escapeDiagnosticText(result.runId)}`;\n\tif (result.refusal) {\n\t\tif ('address' in result.refusal)\n\t\t\treturn formatPreAppendRefusalHuman(line, result.refusal);\n\t\treturn [\n\t\t\tline,\n\t\t\t`refusal: ${escapeDiagnosticText(result.refusal.cause)}`,\n\t\t\t`state: ${escapeDiagnosticText(result.refusal.state)}`,\n\t\t\t`withheld authority: ${escapeDiagnosticText(result.refusal.withheldAuthority)}`,\n\t\t\t`resolving command: ${escapeDiagnosticText(result.refusal.resolvingCommand)}`,\n\t\t].join('\\n');\n\t}\n\tif (!('result' in result)) return line;\n\tif ('assessment' in result.result) {\n\t\tif (result.result.unresolvedOutcome) {\n\t\t\tconst unresolved = result.result.unresolvedOutcome;\n\t\t\treturn unresolved.kind === 'recovery-required'\n\t\t\t\t? [\n\t\t\t\t\t\tline,\n\t\t\t\t\t\t`claim: ${escapeDiagnosticText(unresolved.claimId)}`,\n\t\t\t\t\t\t`detail: ${escapeDiagnosticText(unresolved.detail)}`,\n\t\t\t\t\t\t`resolving command: dbsp reconcile --db <database> ${escapeDiagnosticText(result.runId)}`,\n\t\t\t\t\t].join('\\n')\n\t\t\t\t: [\n\t\t\t\t\t\tline,\n\t\t\t\t\t\t`detail: ${escapeDiagnosticText(unresolved.detail)}`,\n\t\t\t\t\t\t`resolving command: dbsp reconcile --db <database> ${escapeDiagnosticText(result.runId)}`,\n\t\t\t\t\t].join('\\n');\n\t\t}\n\t\tif (result.outcome !== 'plan-digest-mismatch') return line;\n\t\tconst detail = result.result.assessment.reasons[0]?.detail;\n\t\treturn detail ? `${line}\\n${escapeDiagnosticText(detail)}` : line;\n\t}\n\tconst execution = result.result;\n\tswitch (execution.outcome) {\n\t\tcase 'completed':\n\t\t\treturn line;\n\t\tcase 'recovery-required':\n\t\t\treturn [\n\t\t\t\tline,\n\t\t\t\t`claim: ${escapeDiagnosticText(execution.claimId)}`,\n\t\t\t\t`detail: ${escapeDiagnosticText(execution.detail)}`,\n\t\t\t\t`resolving command: dbsp reconcile --db <database> ${escapeDiagnosticText(result.runId)}`,\n\t\t\t].join('\\n');\n\t\tcase 'transport-ambiguous':\n\t\t\treturn [\n\t\t\t\tline,\n\t\t\t\t`detail: ${escapeDiagnosticText(execution.detail)}`,\n\t\t\t\t`resolving command: dbsp reconcile --db <database> ${escapeDiagnosticText(result.runId)}`,\n\t\t\t].join('\\n');\n\t\tcase 'partially-applied':\n\t\tcase 'selection-incomplete':\n\t\tcase 'adoption-refused':\n\t\tcase 'readdress-unsupported':\n\t\tcase 'readdress-refused':\n\t\tcase 'destructive-authority-refused':\n\t\tcase 'execution-failed':\n\t\t\treturn `${line}\\ndetail: ${escapeDiagnosticText(execution.detail)}`;\n\t\tcase 'prior-step-events-refusal':\n\t\t\treturn [\n\t\t\t\tline,\n\t\t\t\t`detail: ${escapeDiagnosticText(execution.detail)}`,\n\t\t\t\t`resolving command: dbsp reconcile --db <database> ${escapeDiagnosticText(result.runId)}`,\n\t\t\t].join('\\n');\n\t}\n}\n\nfunction acceptanceMatches(\n\tassumption: {\n\t\treadonly class: string;\n\t\treadonly asserter: TrustRoot;\n\t\treadonly scope: readonly ResourceAddress[];\n\t},\n\tacceptance: AssumptionAcceptance,\n): boolean {\n\treturn (\n\t\tacceptance.class === assumption.class &&\n\t\t(!acceptance.fromTrustRoot ||\n\t\t\tcanonicalJson(acceptance.fromTrustRoot) ===\n\t\t\t\tcanonicalJson(assumption.asserter)) &&\n\t\t(assumption.scope.length === 0\n\t\t\t? !acceptance.withinScope || acceptance.withinScope.length === 0\n\t\t\t: !acceptance.withinScope ||\n\t\t\t\tacceptance.withinScope.length === 0 ||\n\t\t\t\tassumption.scope.every((resource) =>\n\t\t\t\t\tacceptance.withinScope?.some((selector) =>\n\t\t\t\t\t\tselectorMatchesResource(selector, resource),\n\t\t\t\t\t),\n\t\t\t\t))\n\t);\n}\n\ntype RecordedPlanRefusal = {\n\treadonly cause: string;\n\treadonly state: 'recorded-plan';\n\treadonly withheldAuthority: string;\n\treadonly resolvingCommand: string;\n};\n\nfunction recordedPlanRefusal(): RecordedPlanRefusal {\n\treturn { ...REFUSAL_VOCABULARY['ERR-10'], state: 'recorded-plan' };\n}\n\nexport type ApplyCommandResult = (\n\t| CoreApplyCommandResult\n\t| GeneratorApplyCommandResult\n\t| {\n\t\t\treadonly outcome: 'run-busy' | 'plan-digest-required';\n\t\t\treadonly runId: string;\n\t }\n\t| {\n\t\t\t/** ERR-10: a removal-bearing generator run cannot be replayed by id. */\n\t\t\treadonly outcome: 'non-replayable-generator-run';\n\t\t\treadonly runId: string;\n\t\t\treadonly refusal: RecordedPlanRefusal;\n\t }\n) & { readonly cleanupError?: string };\n\nexport type NoArgumentApplyResult =\n\t| {\n\t\t\treadonly outcome:\n\t\t\t\t| 'dry-run'\n\t\t\t\t| 'not-executable'\n\t\t\t\t| 'confirmation-required'\n\t\t\t\t| 'confirmation-declined';\n\t\t\treadonly plan: PlanResult;\n\t\t\treadonly runId: string | null;\n\t\t\treadonly planDigest: string | null;\n\t }\n\t| {\n\t\t\treadonly outcome: ApplyOutcome;\n\t\t\treadonly plan: PlanResult;\n\t\t\treadonly runId: string;\n\t\t\treadonly planDigest: string;\n\t\t\treadonly result: ApplyCommandResult;\n\t };\n\nfunction isGeneratorPlan(plan: unknown): plan is GeneratorDurablePlan {\n\treturn (\n\t\tplan !== undefined &&\n\t\tplan !== null &&\n\t\ttypeof plan === 'object' &&\n\t\t'generator' in plan &&\n\t\t(plan as { generator?: { kind?: unknown } }).generator?.kind ===\n\t\t\t'schema-differ-generator'\n\t);\n}\n\n/** Every mapped command refusal needs a real plan address; never invent one. */\nfunction firstPlanAddress(plan: unknown): LedgerAddress | undefined {\n\tif (plan === null || typeof plan !== 'object' || !('steps' in plan))\n\t\treturn undefined;\n\tconst steps = (plan as { readonly steps?: unknown }).steps;\n\tif (!Array.isArray(steps)) return undefined;\n\tfor (const step of steps) {\n\t\tif (step === null || typeof step !== 'object') continue;\n\t\tconst candidate = step as {\n\t\t\treadonly managedClaim?: { readonly address?: LedgerAddress };\n\t\t\treadonly address?: LedgerAddress;\n\t\t\treadonly closure?: { readonly root?: LedgerAddress };\n\t\t};\n\t\tconst address =\n\t\t\tcandidate.managedClaim?.address ??\n\t\t\tcandidate.address ??\n\t\t\tcandidate.closure?.root;\n\t\tif (address) return address;\n\t}\n\treturn undefined;\n}\n\nfunction applyPreAppendRefusal(\n\toutcome: ApplyOutcome,\n\tplan: unknown,\n\tresult?: ApplyResult,\n): PreAppendRefusal | undefined {\n\tconst address = firstPlanAddress(plan);\n\tif (!address) return undefined;\n\tif (outcome === 'transactional-only-refusal')\n\t\treturn preAppendRefusalFor('ERR-01', { address, state: 'unknown' });\n\tif (outcome === 'database-read-only')\n\t\treturn preAppendRefusalFor('ERR-07', { address, state: 'unknown' });\n\tif (\n\t\toutcome === 'execution-contract-refused' &&\n\t\tresult?.assessment.reasons[0]?.detail?.startsWith(\n\t\t\t'managed-ledger-not-current:',\n\t\t)\n\t)\n\t\treturn preAppendRefusalFor('ERR-03', { address, state: 'unknown' });\n\tif (outcome === 'destructive-authority-refused')\n\t\treturn preAppendRefusalFor('ERR-04', { address, state: 'managed' });\n\tif (outcome === 'adoption-refused')\n\t\treturn preAppendRefusalFor('ERR-02', { address, state: 'unknown' });\n\treturn undefined;\n}\n\nexport type ApplyConfirmation = (\n\trunId: string,\n\tplanDigest: string,\n) => Promise<boolean>;\n\n/** Rendering is injected so the public pipeline can prove presentation precedes consent. */\nexport type ApplyPlanPresenter = (plan: PlanResult) => void;\n\n/** The sole interactive gate for no-argument apply. EOF and every non-y answer refuse. */\nexport async function confirmNoArgumentApply(\n\trunId: string,\n\tplanDigest: string,\n): Promise<boolean> {\n\tconst prompt = createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stderr,\n\t});\n\ttry {\n\t\tconst answer = await prompt.question(\n\t\t\t`Apply persisted run ${runId} (plan digest ${planDigest})? [y/N] `,\n\t\t);\n\t\treturn /^(?:y|yes)$/iu.test(answer.trim());\n\t} finally {\n\t\tprompt.close();\n\t}\n}\n\n/**\n * The unrecorded-plan path deliberately delegates proving and persistence to\n * runPlan. Therefore the durable row exists before this function asks a human\n * to approve it, and a decline is inspectable rather than a discarded plan.\n */\nexport async function runNoArgumentApply(\n\toptions: ApplyOptions,\n\tconfirm: ApplyConfirmation = confirmNoArgumentApply,\n\texecute: typeof runApply = runApply,\n\tpresent: ApplyPlanPresenter = () => undefined,\n): Promise<NoArgumentApplyResult> {\n\tif (!options.schemaFile)\n\t\tthrow new Error('no-argument apply requires --schema-file <path>');\n\tconst plan = await runPlan({\n\t\tdb: options.db,\n\t\tschemaFile: options.schemaFile,\n\t\t...(options.schema === undefined ? {} : { schema: options.schema }),\n\t\tdryRun: options.dryRun === true,\n\t\tformat: options.format === 'json' ? 'json' : 'sql',\n\t});\n\t// The transition planner intentionally has no removal mapping. The live\n\t// schema differ is therefore only a bridge for that exact unsupported\n\t// comparison. A capability refusal, no-drift result, or inapplicable plan\n\t// retains its own meaning and must never become generated DDL.\n\tconst isUnsupportedRemoval =\n\t\tplan.proveKind === 'blocked' &&\n\t\tplan.compareKind === 'unsupported' &&\n\t\tplan.assessment.decision === 'blocked' &&\n\t\tplan.assessment.reasons.length === 1 &&\n\t\tplan.assessment.reasons[0]?.code === 'unsupported-transition';\n\tconst effectivePlan = isUnsupportedRemoval\n\t\t? await runGeneratorPlan({\n\t\t\t\tdb: options.db,\n\t\t\t\tschemaFile: options.schemaFile,\n\t\t\t\t...(options.schema === undefined ? {} : { schema: options.schema }),\n\t\t\t\tdryRun: options.dryRun === true,\n\t\t\t})\n\t\t: plan;\n\tif (options.dryRun === true)\n\t\treturn {\n\t\t\toutcome: 'dry-run',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: null,\n\t\t\tplanDigest: null,\n\t\t};\n\tif (\n\t\teffectivePlan.proveKind !== 'proven' ||\n\t\teffectivePlan.persisted !== true ||\n\t\t!effectivePlan.runId ||\n\t\t!effectivePlan.planDigest\n\t) {\n\t\t// A blocked/no-drift plan has no executable durable record. Its existing\n\t\t// presentation is the complete result; do not invent an apply attempt.\n\t\treturn {\n\t\t\toutcome: 'not-executable',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: effectivePlan.runId,\n\t\t\tplanDigest: effectivePlan.planDigest,\n\t\t};\n\t}\n\tconst runId = effectivePlan.runId;\n\tconst planDigest = effectivePlan.planDigest;\n\t// Persisted material is shown before any confirmation requirement or prompt.\n\tpresent(effectivePlan);\n\tif (options.yes !== true && process.stdin.isTTY !== true) {\n\t\treturn {\n\t\t\toutcome: 'confirmation-required',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: effectivePlan.runId,\n\t\t\tplanDigest: effectivePlan.planDigest,\n\t\t};\n\t}\n\tif (options.yes !== true && !(await confirm(runId, planDigest))) {\n\t\treturn {\n\t\t\toutcome: 'confirmation-declined',\n\t\t\tplan: effectivePlan,\n\t\t\trunId: effectivePlan.runId,\n\t\t\tplanDigest: effectivePlan.planDigest,\n\t\t};\n\t}\n\tconst recordedRunOptions = Object.fromEntries(\n\t\tObject.entries(options).filter(([key]) => key !== 'schema'),\n\t) as ApplyOptions;\n\tconst executeOptions = {\n\t\t...recordedRunOptions,\n\t\tplanDigest: effectivePlan.planDigest,\n\t};\n\tconst result = isUnsupportedRemoval\n\t\t? await justPersistedGeneratorRemovalContext.run(\n\t\t\t\tmintJustPersistedGeneratorRemovalCapability(runId),\n\t\t\t\t() => execute(runId, executeOptions),\n\t\t\t)\n\t\t: await execute(runId, executeOptions);\n\treturn {\n\t\toutcome: result.outcome,\n\t\tplan: effectivePlan,\n\t\trunId: effectivePlan.runId,\n\t\tplanDigest: effectivePlan.planDigest,\n\t\tresult,\n\t};\n}\n\nasync function loadOnLessor(\n\ttarget: Parameters<typeof acquireTransitionLease>[0],\n\trunId: string,\n) {\n\tconst lease = await acquireTransitionLease(target);\n\ttry {\n\t\treturn await readTransitionJournal(lease.session, runId, { ensure: false });\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nasync function loadOnTarget(\n\ttarget: Parameters<typeof acquireExclusiveTransitionLease>[0],\n\trunId: string,\n) {\n\tconst lease = await acquireExclusiveTransitionLease(target);\n\ttry {\n\t\treturn await readTransitionJournal(lease.session, runId, { ensure: false });\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nasync function runApplyInternal(\n\trunId: string,\n\toptions: ApplyOptions,\n\tpool?: Pool,\n): Promise<ApplyCommandResult> {\n\tconst expectedPlanDigest = options.planDigest;\n\tif (!expectedPlanDigest) return { outcome: 'plan-digest-required', runId };\n\tif (options.schema !== undefined)\n\t\tthrow new Error(\n\t\t\t'apply <run-id> refuses --schema: execution uses the recorded plan and context',\n\t\t);\n\tconst policy = await effectiveApplyPolicy(options);\n\tconst owned =\n\t\tpool === undefined ? (await createDbConnection(options.db)).pool : pool;\n\t// SC-52: this is deliberately before authorization, preflight, or a step\n\t// attempt. A persisted generator removal is reviewable, not replayable.\n\tlet persisted: Awaited<ReturnType<typeof loadOnTarget>>;\n\ttry {\n\t\tpersisted = await loadOnLessor(createPgTransitionLessor(owned), runId);\n\t} catch (error) {\n\t\tif (isInvalidNonResumablePersistedRunError(error, runId)) {\n\t\t\tconst refusal: ApplyCommandResult = {\n\t\t\t\toutcome: 'plan-digest-mismatch',\n\t\t\t\trunId,\n\t\t\t\tresult: {\n\t\t\t\t\tassessment: {\n\t\t\t\t\t\treasons: [{ detail: error.message }],\n\t\t\t\t\t},\n\t\t\t\t} as unknown as ApplyResult,\n\t\t\t};\n\t\t\treturn pool === undefined\n\t\t\t\t? withPoolCleanupReported(refusal, () => owned.end())\n\t\t\t\t: refusal;\n\t\t}\n\t\tif (error instanceof TransitionRunIdentityMismatchError) {\n\t\t\tconst refusal: ApplyCommandResult = {\n\t\t\t\toutcome: 'run-id-mismatch',\n\t\t\t\trunId,\n\t\t\t\tresult: {\n\t\t\t\t\tassessment: {\n\t\t\t\t\t\treasons: [{ detail: error.message }],\n\t\t\t\t\t},\n\t\t\t\t} as unknown as ApplyResult,\n\t\t\t};\n\t\t\treturn pool === undefined\n\t\t\t\t? withPoolCleanupReported(refusal, () => owned.end())\n\t\t\t\t: refusal;\n\t\t}\n\t\tif (pool === undefined) {\n\t\t\ttry {\n\t\t\t\tawait owned.end();\n\t\t\t} catch {\n\t\t\t\t// The load failure is the primary command outcome.\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t}\n\tif (\n\t\tpersisted.run.replayability === 'non-replayable-generator-removal' &&\n\t\t!permitsJustPersistedGeneratorRemoval(runId)\n\t) {\n\t\tconst refusal: ApplyCommandResult = {\n\t\t\toutcome: 'non-replayable-generator-run',\n\t\t\trunId,\n\t\t\trefusal: recordedPlanRefusal(),\n\t\t};\n\t\treturn pool === undefined\n\t\t\t? withPoolCleanupReported(refusal, () => owned.end())\n\t\t\t: refusal;\n\t}\n\tlet result: ApplyCommandResult;\n\ttry {\n\t\tif (isGeneratorPlan(persisted.plan)) {\n\t\t\tconst locked = await withPgTransitionRunLock(\n\t\t\t\towned,\n\t\t\t\trunId,\n\t\t\t\tasync (target) => {\n\t\t\t\t\tconst current = await loadOnTarget(target, runId);\n\t\t\t\t\tif (!isGeneratorPlan(current.plan))\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'persisted run no longer contains a generator plan',\n\t\t\t\t\t\t);\n\t\t\t\t\tconst recordedSchema = current.plan.generator.planningSchema;\n\t\t\t\t\tif (!recordedSchema)\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'persisted generator run has no recorded planning schema and is non-resumable',\n\t\t\t\t\t\t);\n\t\t\t\t\tlet actualDigest: string;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tactualDigest = transitionPlanDigest(current.plan);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Persisted generator material is hostile input at apply. The\n\t\t\t\t\t\t// digest boundary must refuse it rather than let parser detail\n\t\t\t\t\t\t// escape as a command exception.\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError(\n\t\t\t\t\t\t\t`persisted generator manifest is invalid: ${errorDetail(error)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tactualDigest !== current.run.planDigest ||\n\t\t\t\t\t\tactualDigest !== expectedPlanDigest\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError();\n\t\t\t\t\tconst manifest = validateNormalizedManagedStepManifest(\n\t\t\t\t\t\tcurrent.plan.steps as unknown as readonly NormalizedManagedStep[],\n\t\t\t\t\t);\n\t\t\t\t\tif (!manifest.ok)\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError(\n\t\t\t\t\t\t\t`persisted generator manifest is invalid: ${manifest.detail}`,\n\t\t\t\t\t\t);\n\t\t\t\t\tconst lifecycleError = persistedLifecycleDirectiveError(\n\t\t\t\t\t\tmanifest.manifest.steps,\n\t\t\t\t\t);\n\t\t\t\t\tif (lifecycleError)\n\t\t\t\t\t\tthrow new RecordedPlanDigestMismatchError(\n\t\t\t\t\t\t\t`persisted generator manifest is invalid: ${lifecycleError}`,\n\t\t\t\t\t\t);\n\t\t\t\t\tif (\n\t\t\t\t\t\tawait generatorRunRequiresRecovery(\n\t\t\t\t\t\t\ttarget,\n\t\t\t\t\t\t\tcurrent,\n\t\t\t\t\t\t\tmanifest.manifest.steps,\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\toutcome: 'prior-step-events-refusal' as const,\n\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t'run has prior generator step-attempt events; run dbsp reconcile --db <database> <run-id>',\n\t\t\t\t\t\t};\n\t\t\t\t\treturn executeGeneratorPlan({\n\t\t\t\t\t\tpool: owned,\n\t\t\t\t\t\trun: lockPgJournalRun(mintDurablyLoadedRun(current.run)),\n\t\t\t\t\t\tmanifest: manifest.manifest,\n\t\t\t\t\t\tplanDigest: actualDigest,\n\t\t\t\t\t\tschema: recordedSchema,\n\t\t\t\t\t\tapproval: { approvals: policy.accepts },\n\t\t\t\t\t\trecordAttempt: async (executionId) => {\n\t\t\t\t\t\t\tconst journalLease =\n\t\t\t\t\t\t\t\tawait acquireExclusiveTransitionLease(target);\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait appendIntentJournal(journalLease.session, {\n\t\t\t\t\t\t\t\t\trunId: current.run.runId,\n\t\t\t\t\t\t\t\t\trun: current.run,\n\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\tstepId: `dbsp.generator.attempt:${executionId}`,\n\t\t\t\t\t\t\t\t\toperation: {\n\t\t\t\t\t\t\t\t\t\t...GENERATOR_ATTEMPT_OPERATION,\n\t\t\t\t\t\t\t\t\t\tpayload: { executionId },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trecordedAt: new Date().toISOString(),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\tawait journalLease.release();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...(options.replace === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { replaces: options.replace }),\n\t\t\t\t\t\trunId,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (locked.kind === 'busy') result = { outcome: 'run-busy', runId };\n\t\t\telse {\n\t\t\t\tconst execution = locked.value;\n\t\t\t\tconst defaultRefusal = applyPreAppendRefusal(\n\t\t\t\t\texecution.outcome as ApplyOutcome,\n\t\t\t\t\tpersisted.plan,\n\t\t\t\t);\n\t\t\t\tconst withheldAuthority =\n\t\t\t\t\texecution.outcome === 'destructive-authority-refused'\n\t\t\t\t\t\t? (execution.refusal?.withheldAuthority ??\n\t\t\t\t\t\t\t(execution.detail.includes('operator acceptance')\n\t\t\t\t\t\t\t\t? 'destructive operator acceptance authority'\n\t\t\t\t\t\t\t\t: execution.detail.includes('ledger lineage')\n\t\t\t\t\t\t\t\t\t? 'destructive ledger lineage authority'\n\t\t\t\t\t\t\t\t\t: undefined))\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst preAppendRefusal =\n\t\t\t\t\tdefaultRefusal === undefined || withheldAuthority === undefined\n\t\t\t\t\t\t? defaultRefusal\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t...defaultRefusal,\n\t\t\t\t\t\t\t\trefusal: {\n\t\t\t\t\t\t\t\t\t...defaultRefusal.refusal,\n\t\t\t\t\t\t\t\t\twithheldAuthority,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\tresult = generatorApplyCommandResult(\n\t\t\t\t\texecution,\n\t\t\t\t\trunId,\n\t\t\t\t\tpreAppendRefusal,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tconst locked = await withPgTransitionRunLock(\n\t\t\t\towned,\n\t\t\t\trunId,\n\t\t\t\tasync (target) => {\n\t\t\t\t\tconst loadCurrent = async (id: string) => {\n\t\t\t\t\t\treturn loadOnTarget(target, id);\n\t\t\t\t\t};\n\t\t\t\t\tconst applier = createApplier(registry(), {\n\t\t\t\t\t\t// A durable apply only verifies the existing immutable row. The applier\n\t\t\t\t\t\t// calls this before execution; a changed record remains a refusal.\n\t\t\t\t\t\tpersist: async () => undefined,\n\t\t\t\t\t});\n\t\t\t\t\treturn applier.applyDurable({\n\t\t\t\t\t\trunId,\n\t\t\t\t\t\texpectedPlanDigest,\n\t\t\t\t\t\tloadCurrent,\n\t\t\t\t\t\tprepareExecutionSession: async (session, contract, plan) => {\n\t\t\t\t\t\t\tconst currency = await validatePgManagedLedgerCurrency(\n\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (currency)\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\t\t\tkind: 'refused' as const,\n\t\t\t\t\t\t\t\t\tdetail: currency,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\treturn preparePgExecutionSession(session, contract, plan);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpolicy,\n\t\t\t\t\t\ttarget,\n\t\t\t\t\t\tauthorize: async (run, plan, session) => {\n\t\t\t\t\t\t\tconst current = await loadOnTarget(target, run.runId);\n\t\t\t\t\t\t\tconst grants = plan.assumptions.map((assumption) => ({\n\t\t\t\t\t\t\t\tassumptionId: assumption.id,\n\t\t\t\t\t\t\t\tgrant: policy.accepts.findIndex((grant) =>\n\t\t\t\t\t\t\t\t\tacceptanceMatches(assumption, grant),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t// Crash after commit but before intent: reuse the exact prior approval.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\thasReusableAuthorization(\n\t\t\t\t\t\t\t\t\tcurrent.authorizations,\n\t\t\t\t\t\t\t\t\trun.runId,\n\t\t\t\t\t\t\t\t\ttransitionPlanDigest(plan),\n\t\t\t\t\t\t\t\t\tpolicy.accepts,\n\t\t\t\t\t\t\t\t\tgrants,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\tconst actor =\n\t\t\t\t\t\t\t\tprocess.env.USER ??\n\t\t\t\t\t\t\t\tprocess.env.LOGNAME ??\n\t\t\t\t\t\t\t\t'unknown-local-actor';\n\t\t\t\t\t\t\tconst authorizedAt = new Date().toISOString();\n\t\t\t\t\t\t\tconst digest = authorizationDigest(\n\t\t\t\t\t\t\t\trun.runId,\n\t\t\t\t\t\t\t\ttransitionPlanDigest(plan),\n\t\t\t\t\t\t\t\tpolicy.accepts,\n\t\t\t\t\t\t\t\tgrants,\n\t\t\t\t\t\t\t\tactor,\n\t\t\t\t\t\t\t\tauthorizedAt,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst record: TransitionRunAuthorization = {\n\t\t\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\t\t\tpolicy: policy.accepts,\n\t\t\t\t\t\t\t\tgrants,\n\t\t\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t\t\tactor,\n\t\t\t\t\t\t\t\tauthorizedAt,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tawait appendTransitionAuthorization(session, record);\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (locked.kind === 'busy') result = { outcome: 'run-busy', runId };\n\t\t\telse {\n\t\t\t\tconst outcome = outcomeForApplyResult(locked.value);\n\t\t\t\tconst preAppendRefusal = applyPreAppendRefusal(\n\t\t\t\t\toutcome,\n\t\t\t\t\tpersisted.plan,\n\t\t\t\t\tlocked.value,\n\t\t\t\t);\n\t\t\t\tresult = {\n\t\t\t\t\toutcome,\n\t\t\t\t\trunId,\n\t\t\t\t\tresult: locked.value,\n\t\t\t\t\t...(preAppendRefusal === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { refusal: preAppendRefusal }),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof RecordedPlanDigestMismatchError) {\n\t\t\tresult = {\n\t\t\t\toutcome: 'plan-digest-mismatch',\n\t\t\t\trunId,\n\t\t\t\tresult: {\n\t\t\t\t\tassessment: {\n\t\t\t\t\t\treasons: [{ detail: error.message }],\n\t\t\t\t\t},\n\t\t\t\t} as unknown as ApplyResult,\n\t\t\t};\n\t\t} else {\n\t\t\tif (pool === undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tawait owned.end();\n\t\t\t\t} catch {\n\t\t\t\t\t// The primary failure remains the command failure.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\tif (pool === undefined) {\n\t\treturn withPoolCleanupReported(result, () => owned.end());\n\t}\n\treturn result;\n}\n\n/** Public durable apply surface: it never accepts the private replay bridge. */\nexport async function runApply(\n\trunId: string,\n\toptions: ApplyOptions,\n\tpool?: Pool,\n): Promise<ApplyCommandResult> {\n\treturn runApplyInternal(runId, options, pool);\n}\n\nexport const applyCommand = new Command('apply')\n\t.description(\n\t\t'Plan, persist, present and execute a declaration, or execute one reviewed durable run',\n\t)\n\t.argument('[run-id]', 'Durable run identifier returned by dbsp plan')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option(\n\t\t'--plan-digest <sha>',\n\t\t'Plan digest printed by dbsp plan; required to anchor review outside the database',\n\t)\n\t.option('--schema-file <path>', 'Schema DSL file for no-argument apply')\n\t.option('--schema <name>', 'Database schema name for no-argument apply')\n\t.option('--yes', 'Confirm no-argument apply without an interactive prompt')\n\t.option(\n\t\t'--dry-run',\n\t\t'Present a no-argument plan without persisting or executing',\n\t)\n\t.option(\n\t\t'--accept <class>',\n\t\t'Accept an assumption class broadly; repeatable',\n\t\t(value, previous: string[] = []) => [...previous, value],\n\t)\n\t.option(\n\t\t'--replace <address>',\n\t\t'Replace exactly this address when the presented plan requested it; repeatable',\n\t\t(value, previous: string[] = []) => [...previous, value],\n\t)\n\t.option(\n\t\t'--accept-policy <file>',\n\t\t'UTF-8 JSON AssumptionAcceptance[] policy file; set-unioned with --accept and canonicalised before authorization',\n\t)\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (runId: string | undefined, options: ApplyOptions) => {\n\t\tif (runId === undefined) {\n\t\t\tlet result: NoArgumentApplyResult | { readonly error: string };\n\t\t\ttry {\n\t\t\t\tresult = await runNoArgumentApply(\n\t\t\t\t\toptions,\n\t\t\t\t\tconfirmNoArgumentApply,\n\t\t\t\t\trunApply,\n\t\t\t\t\toptions.format === 'json'\n\t\t\t\t\t\t? () => undefined\n\t\t\t\t\t\t: (plan) =>\n\t\t\t\t\t\t\t\tconsole.log(formatPlanHuman(plan, options.dryRun === true)),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tresult = {\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif ('error' in result) {\n\t\t\t\tif (options.format === 'json')\n\t\t\t\t\tprintCliJson({ outcome: 'apply-failed', ...result });\n\t\t\t\telse console.error(`❌ ${escapeDiagnosticText(result.error)}`);\n\t\t\t\tprocess.exitCode = exitCodeForApplyOutcome('apply-failed');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst exitCode =\n\t\t\t\tresult.outcome === 'dry-run' || result.outcome === 'not-executable'\n\t\t\t\t\t? exitCodeForPlanResult(result.plan)\n\t\t\t\t\t: exitCodeForApplyOutcome(result.outcome);\n\t\t\tif (options.format === 'json') {\n\t\t\t\tprintCliJson({\n\t\t\t\t\toutcome: result.outcome,\n\t\t\t\t\texitCode,\n\t\t\t\t\tplan: formatPlanJson(result.plan, options.dryRun === true),\n\t\t\t\t\t...(result.runId === null ? {} : { runId: result.runId }),\n\t\t\t\t\t...(result.planDigest === null\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { planDigest: result.planDigest }),\n\t\t\t\t\t...('result' in result ? { apply: result.result } : {}),\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (result.outcome === 'dry-run' || result.outcome === 'not-executable')\n\t\t\t\t\tconsole.log(formatPlanHuman(result.plan, options.dryRun === true));\n\t\t\t\tif (result.outcome === 'confirmation-required')\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'confirmation-required: rerun with --yes or from an interactive TTY',\n\t\t\t\t\t);\n\t\t\t\telse if (result.outcome === 'confirmation-declined')\n\t\t\t\t\tconsole.log('confirmation-declined: persisted run was not executed');\n\t\t\t\telse if (result.outcome === 'not-executable') {\n\t\t\t\t\t// The planner already rendered the concrete no-drift/blocked reason.\n\t\t\t\t} else if (result.outcome !== 'dry-run' && 'result' in result)\n\t\t\t\t\tconsole.log(formatApplyHuman(result.result));\n\t\t\t}\n\t\t\tprocess.exitCode = exitCode;\n\t\t\treturn;\n\t\t}\n\t\tlet result:\n\t\t\t| ApplyCommandResult\n\t\t\t| {\n\t\t\t\t\treadonly outcome: 'policy-invalid' | 'apply-failed';\n\t\t\t\t\treadonly runId: string;\n\t\t\t\t\treadonly error: string;\n\t\t\t };\n\t\ttry {\n\t\t\tresult = options.planDigest\n\t\t\t\t? await runApply(runId, options)\n\t\t\t\t: { outcome: 'plan-digest-required', runId };\n\t\t} catch (error) {\n\t\t\tresult = {\n\t\t\t\toutcome:\n\t\t\t\t\terror instanceof SyntaxError ? 'policy-invalid' : 'apply-failed',\n\t\t\t\trunId,\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\t// Validation errors are ordinary Errors, not necessarily SyntaxErrors.\n\t\t\tif (\n\t\t\t\tresult.outcome === 'apply-failed' &&\n\t\t\t\t/^(acceptance\\[|--accept-policy|policy )/u.test(result.error)\n\t\t\t)\n\t\t\t\tresult = { ...result, outcome: 'policy-invalid' };\n\t\t}\n\t\tconst exitCode = exitCodeForApplyOutcome(result.outcome);\n\t\tconst document = { ...result, exitCode };\n\t\tif (options.format === 'json') printCliJson(document);\n\t\telse console.log(formatApplyHuman(result));\n\t\tprocess.exitCode = exitCode;\n\t})\n\t.addHelpText(\n\t\t'after',\n\t\t`\\nJSON result contract (outcome -> exit code):\\n${APPLY_OUTCOME_CONTRACT.map(\n\t\t\t([outcome, exitCode, description]) =>\n\t\t\t\t` ${outcome} -> ${exitCode}: ${description}`,\n\t\t).join(\n\t\t\t'\\n',\n\t\t)}\\n\\nApply requires --plan-digest from dbsp plan. It recomputes the stored plan digest before authorization or planned DDL and refuses a missing or mismatched value. This detects substitution, not deletion: missing run evidence makes apply refuse. Policy files are JSON arrays. Every entry is strictly validated; file entries and repeated --accept values are set-unioned, exact duplicates are normalized, selector order is normalized, and the authorization digest is SHA-256 over canonical JSON {runId, planDigest, policy, grants}.\\n`,\n\t);\n","/** Shared CLI JSON boundary. Keep every machine-readable document here. */\nexport function serializeCliJson(value: unknown): string {\n\tconst serialized = JSON.stringify(value, null, 2);\n\tif (serialized === undefined)\n\t\tthrow new Error('CLI JSON output must be a JSON-serializable document');\n\treturn serialized;\n}\n\nexport function printCliJson(value: unknown): void {\n\tconsole.log(serializeCliJson(value));\n}\n","import type { readTransitionJournal } from '@dbsp/adapter-pgsql';\n\n/**\n * The durable run identifies reviewed material; its intent events identify\n * actual apply attempts. Greenfield recovery never treats a run id as an\n * execution id: that legacy fallback could attach an unrelated reservation.\n */\nexport function executionIdsForRun(\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n): readonly string[] {\n\t// Attempt records are additive. Keep every documented pre-attempt scope so\n\t// interrupted executions produced before (or while persisting) an attempt\n\t// record remain recoverable, then add each durably recorded attempt.\n\tconst executionIds = new Set<string>([journal.run.runId]);\n\tfor (const event of journal.events) {\n\t\tconst record = event.record;\n\t\tif (\n\t\t\tevent.event === 'intent' &&\n\t\t\t'executionId' in record &&\n\t\t\ttypeof record.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.executionId);\n\t\tif (\n\t\t\tevent.event === 'observed' &&\n\t\t\t'intent' in record &&\n\t\t\trecord.intent &&\n\t\t\ttypeof record.intent.executionId === 'string'\n\t\t)\n\t\t\texecutionIds.add(record.intent.executionId);\n\t}\n\t// Read-side compatibility for reservations persisted before attempt records.\n\tif ('generator' in journal.plan)\n\t\texecutionIds.add(`dbsp.generator.execution.${journal.run.runId}`);\n\treturn [...executionIds];\n}\n","/** Live-only executor for the no-argument schema-differ plan. */\nimport { randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport {\n\tassertGeneratedPostconditionSession,\n\tcompareSchemata,\n\tcreatePgsqlAdapter,\n\tdecodeGeneratedPostconditionPayload,\n\texecutePgAdmittedOperation,\n\texecutePgDeclaredAdoption,\n\texecutePgPersistedTableReaddress,\n\ttype GeneratedPostcondition,\n\ttype GeneratedPostconditionBindingAddress,\n\ttype GeneratedPostconditionSession,\n\ttype PgLockedRun,\n\ttype PgOutcomeCheckpointObserver,\n\tpreflightPgDeclaredAdoption,\n\treadPgCatalogueIdentity,\n\treadPgLedgerAddressChain,\n\treadPgLedgerScopeCurrency,\n\treadPgRemovalEffectsClosure,\n\ttoGeneratedPostconditionBindingAddress,\n\tverifyGeneratedCheckPostcondition,\n\tverifyGeneratedColumnPostcondition,\n\tverifyGeneratedIdentityPostcondition,\n\tverifyGeneratedIndexPostcondition,\n\tverifyGeneratedTablePostcondition,\n\twithGeneratedPostconditionSession,\n} from '@dbsp/adapter-pgsql';\nimport {\n\tcanonicalJson,\n\tcanonicalJsonDigest,\n\toutcomeClaimEventId,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\ttype ValidatedManagedStepManifest,\n\tvalidateNormalizedManagedStepManifest,\n} from '@dbsp/core';\nimport { decideDestructiveDecision } from '@dbsp/core/internal';\nimport type {\n\tCascadeCoveredOutcomeClaimPlan,\n\tContainmentClosureDestructiveOutcome,\n\tDestructiveAuthorityEvidence,\n\tLedgerAddress,\n\tLedgerChainMember,\n\tLedgerClaimKind,\n\tLedgerHome,\n\tLedgerPayload,\n\tModelIR,\n\tNormalizedManagedStep,\n\tScopedApprovalSet,\n\tTableIR,\n} from '@dbsp/types';\nimport { ledgerAddressKey } from '@dbsp/types';\nimport type { Pool } from 'pg';\n\nfunction managedSteps(manifest: ValidatedManagedStepManifest) {\n\treturn manifest.steps;\n}\n\n/**\n * A reviewed replacement selector is canonicalized as `table:<name>`, while\n * the CLI has always accepted the unqualified table name as a shorthand. Keep\n * the comparison at the reviewed manifest boundary so every subsequent\n * authority decision sees the same selected set.\n */\nfunction matchesReviewedReplacementSelector(\n\treviewed: string,\n\tprovided: string,\n): boolean {\n\treturn (\n\t\tprovided === reviewed ||\n\t\t(reviewed.startsWith('table:') &&\n\t\t\tprovided === reviewed.slice('table:'.length))\n\t);\n}\n\nexport type GeneratorExecutionResult =\n\t| { readonly outcome: 'completed' }\n\t| {\n\t\t\treadonly outcome: 'partially-applied';\n\t\t\treadonly detail: string;\n\t\t\treadonly completedStepKeys: readonly string[];\n\t\t\treadonly notStartedStepKeys: readonly string[];\n\t }\n\t| { readonly outcome: 'selection-incomplete'; readonly detail: string }\n\t| { readonly outcome: 'adoption-refused'; readonly detail: string }\n\t| { readonly outcome: 'readdress-unsupported'; readonly detail: string }\n\t| { readonly outcome: 'readdress-refused'; readonly detail: string }\n\t| {\n\t\t\treadonly outcome: 'destructive-authority-refused';\n\t\t\treadonly detail: string;\n\t\t\t/** The exact live authority that remained withheld at admission. */\n\t\t\treadonly refusal?: { readonly withheldAuthority: string };\n\t }\n\t| { readonly outcome: 'prior-step-events-refusal'; readonly detail: string }\n\t| {\n\t\t\treadonly outcome: 'recovery-required';\n\t\t\treadonly claimId: string;\n\t\t\treadonly detail: string;\n\t }\n\t| { readonly outcome: 'transport-ambiguous'; readonly detail: string }\n\t| { readonly outcome: 'execution-failed'; readonly detail: string };\n\nfunction modelForAdoption(table: TableIR): ModelIR {\n\tconst tables = new Map([[table.name, table]]);\n\tconst relations = new Map();\n\treturn {\n\t\ttables,\n\t\trelations,\n\t\tgetTable: (name) => tables.get(name),\n\t\tgetRelation: (name) => relations.get(name),\n\t\tgetRelationsFrom: () => [],\n\t\tgetRelationsTo: () => [],\n\t\tisAmbiguous: () => ({ ambiguous: false, options: [] }),\n\t};\n}\n\n/** Adoption uses the established schema differ; it has no bespoke comparator. */\nasync function adoptionShapeMatches(\n\tpool: Pool,\n\tschema: string,\n\tshape: TableIR,\n): Promise<boolean> {\n\tconst live = await createPgsqlAdapter(pool).introspect({ schema });\n\tconst diff = compareSchemata(modelForAdoption(shape), live);\n\treturn !diff.changes.some((change) => change.table === shape.name);\n}\n\nconst SYSTEM_LEDGER_SCHEMAS = new Set([\n\t'pg_toast',\n\t'pg_catalog',\n\t'information_schema',\n]);\n\n/** Preserves the candidate that made ledger-home evidence impossible. */\nclass SystemSchemaLedgerHomeError extends Error {\n\treadonly address: LedgerAddress;\n\n\tconstructor(address: LedgerAddress) {\n\t\tsuper(\n\t\t\t`SystemSchemaLedgerHomeError: ledger home is unavailable for system schema ${address.schema}: ${ledgerAddressKey(address)}`,\n\t\t);\n\t\tthis.name = 'SystemSchemaLedgerHomeError';\n\t\tthis.address = address;\n\t}\n}\n\nfunction home(address: LedgerAddress): LedgerHome {\n\tif (\n\t\taddress.scope !== 'database' &&\n\t\taddress.schema &&\n\t\tSYSTEM_LEDGER_SCHEMAS.has(address.schema)\n\t)\n\t\tthrow new SystemSchemaLedgerHomeError(address);\n\treturn address.scope === 'database'\n\t\t? ({ scope: 'database' } as const)\n\t\t: address.schema\n\t\t\t? ({ scope: 'schema', schema: address.schema } as const)\n\t\t\t: (() => {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`schema-scoped generated address ${address.name} has no schema ledger`,\n\t\t\t\t\t);\n\t\t\t\t})();\n}\n\nfunction acceptance(planDigest: string, approval: ScopedApprovalSet) {\n\treturn approval.approvals.some(\n\t\t(grant) => grant.class === `destructive-plan-accepted:${planDigest}`,\n\t) === true\n\t\t? 'destructive-plan-accepted'\n\t\t: 'absent';\n}\n\n/**\n * Preserve the authority axis in the public generated-removal result. The\n * interpreter still makes the decision; this is presentation metadata for a\n * refusal that has already been reached under the admission lock.\n */\nfunction withheldDestructiveAuthority(\n\tevidence: DestructiveAuthorityEvidence,\n): string | undefined {\n\tif (\n\t\tevidence.declaration !== 'requires-removal' &&\n\t\tevidence.declaration !== 'requires-lossy-change' &&\n\t\tevidence.declaration !== 'replacement-requested-by-plan'\n\t)\n\t\treturn 'destructive declaration authority';\n\tif (evidence.ownership !== 'managed-by-me')\n\t\treturn 'destructive ownership authority';\n\tif (evidence.catalogueIdentity !== 'matches-recorded')\n\t\treturn 'destructive catalogue identity authority';\n\tif (evidence.operatorAcceptance !== 'destructive-plan-accepted')\n\t\treturn 'destructive operator acceptance authority';\n\tif (\n\t\tevidence.containment !== undefined &&\n\t\tevidence.containment !== 'all-contained-or-managed'\n\t)\n\t\treturn 'destructive containment authority';\n\tif (evidence.ledgerLineage !== 'matches-database')\n\t\treturn 'destructive ledger lineage authority';\n\treturn undefined;\n}\n\n/** Admission can reject policy/currency before invoking the live callback. */\nfunction withheldDestructiveAuthorityFromReason(\n\treason: string,\n): string | undefined {\n\tif (reason.includes('operator acceptance'))\n\t\treturn 'destructive operator acceptance authority';\n\tif (reason.includes('ledger lineage'))\n\t\treturn 'destructive ledger lineage authority';\n\treturn undefined;\n}\n\nasync function databaseId(pool: Pool): Promise<string> {\n\tconst result = await pool.query('SELECT current_database() AS database_id');\n\tconst database = result.rows[0]?.database_id;\n\tif (typeof database !== 'string' || database.length === 0)\n\t\tthrow new Error(\n\t\t\t'schema-differ generator could not read current database identity',\n\t\t);\n\treturn database;\n}\n\ntype LedgerQueryable = Parameters<typeof readPgLedgerAddressChain>[0];\n\nasync function managed(\n\texecutor: LedgerQueryable,\n\taddress: LedgerAddress,\n): Promise<boolean> {\n\t// Let a ledger read failure reach readPgRemovalEffectsClosure's catch so it\n\t// remains an undecidable closure with its PostgreSQL reason, rather than\n\t// misclassifying unreadable ownership as an unmanaged dependent.\n\tconst chain = await readPgLedgerAddressChain(\n\t\texecutor,\n\t\thome(address),\n\t\taddress,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\treturn (\n\t\tprojection.kind === 'projected-ledger-chain' &&\n\t\tprojection.stableState === 'managed'\n\t);\n}\n\n/**\n * A generator document is re-evaluated against live state on every delivery.\n * Once a creation claim has already reached its managed terminal state, its\n * address being present is evidence of that earlier delivery, not permission to\n * send its fixed bundle again. An unmanaged occupant still follows the normal\n * vacancy refusal path.\n */\nasync function alreadyAppliedCreation(\n\texecutor: LedgerQueryable,\n\taddress: LedgerAddress,\n): Promise<boolean> {\n\tconst live = await readPgCatalogueIdentity(executor, address);\n\tif (!live?.catalogueIdentity) return false;\n\tconst chain = await readPgLedgerAddressChain(\n\t\texecutor,\n\t\thome(address),\n\t\taddress,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\tconst recorded = chain.terminalMember?.catalogueIdentity;\n\treturn (\n\t\tprojection.kind === 'projected-ledger-chain' &&\n\t\tprojection.stableState === 'managed' &&\n\t\trecorded !== undefined &&\n\t\tisDeepStrictEqual(recorded, live.catalogueIdentity)\n\t);\n}\n\nfunction observed(address: LedgerAddress): LedgerPayload {\n\treturn {\n\t\tvalue: { kind: address.kind, name: address.name },\n\t\tdigest: `generator:${address.kind}:${address.name}`,\n\t};\n}\n\n/** Durable payload roles are disjoint before the outcome protocol serializes them. */\nexport type GeneratedIdentityObservation = LedgerPayload & {\n\treadonly payloadKind: 'generated-identity-observation';\n};\nexport type GeneratedStructuralObservation = LedgerPayload & {\n\treadonly payloadKind: 'generated-structural-observation';\n};\ntype GeneratedPostconditionObservation =\n\t| GeneratedIdentityObservation\n\t| GeneratedStructuralObservation;\n\nfunction generatedPayload(value: unknown): GeneratedStructuralObservation {\n\tconst encoded = canonicalJson(value);\n\tconst normalized = JSON.parse(encoded) as LedgerPayload['value'];\n\treturn {\n\t\tvalue: normalized,\n\t\tdigest: canonicalJsonDigest(normalized),\n\t\tpayloadKind: 'generated-structural-observation',\n\t} satisfies GeneratedStructuralObservation;\n}\n\n/** An identity-only existence and catalogue-identity read-back for the four #597 kinds. */\nasync function identityObserved(\n\texecutor: GeneratedPostconditionSession,\n\tpostcondition: GeneratedPostcondition,\n\taddress: GeneratedPostconditionBindingAddress,\n\tkind: 'constraint' | 'enum' | 'sequence' | 'extension',\n): Promise<{\n\treadonly observed: GeneratedIdentityObservation;\n\treadonly catalogueIdentity: NonNullable<LedgerAddress['catalogueIdentity']>;\n}> {\n\tconst verified = await verifyGeneratedIdentityPostcondition({\n\t\tsession: executor,\n\t\tpostcondition,\n\t\taddress,\n\t\tkind,\n\t});\n\tconst value = JSON.parse(\n\t\tcanonicalJson({\n\t\t\tkind: 'identity-observed',\n\t\t\tobservedKind: verified.kind,\n\t\t\taddress: {\n\t\t\t\tscope: address.scope,\n\t\t\t\t...(address.schema === undefined ? {} : { schema: address.schema }),\n\t\t\t\tname: address.name,\n\t\t\t},\n\t\t\tidentity: verified.identity,\n\t\t\tstructuralSemantics: 'unverified',\n\t\t}),\n\t) as LedgerPayload['value'];\n\treturn {\n\t\tcatalogueIdentity: verified.catalogueIdentity,\n\t\tobserved: {\n\t\t\tvalue,\n\t\t\tdigest: canonicalJsonDigest(value),\n\t\t\tpayloadKind: 'generated-identity-observation',\n\t\t} satisfies GeneratedIdentityObservation,\n\t};\n}\n\nfunction generatedPostcondition(\n\tstep: NormalizedManagedStep,\n\taddress: LedgerAddress,\n): GeneratedPostcondition {\n\tconst declaration = step.expectedDeclaration;\n\tif (\n\t\t!declaration?.value ||\n\t\ttypeof declaration.value !== 'object' ||\n\t\tArray.isArray(declaration.value)\n\t)\n\t\tthrow new Error(\n\t\t\t`generated ${address.kind} step ${step.stepKey} has no decodable generated declaration`,\n\t\t);\n\treturn decodeGeneratedPostconditionPayload(declaration, step.stepKey);\n}\n\n/**\n * Version 3 binds its address separately from its structural declaration. The\n * adapter owns both binding resolution and structural proof, so the CLI only\n * dispatches from the decoded declaration kind and carries the step address.\n */\nasync function readGeneratedV3Postcondition(\n\texecutor: GeneratedPostconditionSession,\n\tpostcondition: Extract<\n\t\tGeneratedPostcondition,\n\t\t{ readonly postconditionVersion: 3 }\n\t>,\n\taddress: LedgerAddress,\n): Promise<{\n\treadonly observed: GeneratedPostconditionObservation;\n\treadonly catalogueIdentity?: NonNullable<LedgerAddress['catalogueIdentity']>;\n}> {\n\tconst bindingAddress = toGeneratedPostconditionBindingAddress(address);\n\tswitch (postcondition.declaration.kind) {\n\t\tcase 'column': {\n\t\t\tconst verified = await verifyGeneratedColumnPostcondition({\n\t\t\t\tsession: executor,\n\t\t\t\tpostcondition,\n\t\t\t\taddress: bindingAddress,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcatalogueIdentity: verified.catalogueIdentity,\n\t\t\t\tobserved: generatedPayload({\n\t\t\t\t\tkind: 'column',\n\t\t\t\t\ttype: verified.projection.type,\n\t\t\t\t\tnullable: verified.projection.nullable,\n\t\t\t\t\t...(verified.projection.default === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { default: verified.projection.default }),\n\t\t\t\t\t...(verified.projection.collation === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { collation: verified.projection.collation }),\n\t\t\t\t\t...(verified.projection.identity === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { identity: verified.projection.identity }),\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\tcase 'check': {\n\t\t\tconst verified = await verifyGeneratedCheckPostcondition({\n\t\t\t\tsession: executor,\n\t\t\t\tpostcondition,\n\t\t\t\taddress: bindingAddress,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcatalogueIdentity: verified.catalogueIdentity,\n\t\t\t\tobserved: generatedPayload({\n\t\t\t\t\tkind: verified.kind,\n\t\t\t\t\ttype: 'c',\n\t\t\t\t\texpression: verified.projection.expression,\n\t\t\t\t\tvalidated: verified.projection.validated,\n\t\t\t\t\tnoInherit: verified.projection.noInherit,\n\t\t\t\t\tenforced: verified.projection.enforced,\n\t\t\t\t\tisLocal: verified.projection.isLocal,\n\t\t\t\t\tinheritanceCount: verified.projection.inheritanceCount,\n\t\t\t\t\tparentId: verified.projection.parentId,\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\tcase 'constraint': {\n\t\t\treturn identityObserved(\n\t\t\t\texecutor,\n\t\t\t\tpostcondition,\n\t\t\t\tbindingAddress,\n\t\t\t\t'constraint',\n\t\t\t);\n\t\t}\n\t\tcase 'index': {\n\t\t\tconst verified = await verifyGeneratedIndexPostcondition({\n\t\t\t\tsession: executor,\n\t\t\t\tpostcondition,\n\t\t\t\taddress: bindingAddress,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcatalogueIdentity: verified.catalogueIdentity,\n\t\t\t\tobserved: generatedPayload({\n\t\t\t\t\tkind: verified.kind,\n\t\t\t\t\tprojection: verified.projection,\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\tcase 'table': {\n\t\t\tconst verified = await verifyGeneratedTablePostcondition({\n\t\t\t\tsession: executor,\n\t\t\t\tpostcondition,\n\t\t\t\taddress: bindingAddress,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcatalogueIdentity: verified.catalogueIdentity,\n\t\t\t\tobserved: generatedPayload({\n\t\t\t\t\tkind: verified.kind,\n\t\t\t\t\tcolumns: verified.projection.columns.map((column) => ({\n\t\t\t\t\t\tname: column.name,\n\t\t\t\t\t\ttype: column.type,\n\t\t\t\t\t\tnullable: column.nullable,\n\t\t\t\t\t\t...(column.default === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { default: column.default }),\n\t\t\t\t\t\t...(column.collation === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { collation: column.collation }),\n\t\t\t\t\t\t...(column.identity === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { identity: column.identity }),\n\t\t\t\t\t})),\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\tcase 'enum': {\n\t\t\treturn identityObserved(executor, postcondition, bindingAddress, 'enum');\n\t\t}\n\t\tcase 'sequence': {\n\t\t\treturn identityObserved(\n\t\t\t\texecutor,\n\t\t\t\tpostcondition,\n\t\t\t\tbindingAddress,\n\t\t\t\t'sequence',\n\t\t\t);\n\t\t}\n\t\tcase 'extension': {\n\t\t\treturn identityObserved(\n\t\t\t\texecutor,\n\t\t\t\tpostcondition,\n\t\t\t\tbindingAddress,\n\t\t\t\t'extension',\n\t\t\t);\n\t\t}\n\t\tcase 'absent': {\n\t\t\t// Removal admission owns the destructive absence read-back. Consume it\n\t\t\t// explicitly if this dispatcher is used for a terminal absence fact.\n\t\t\tconst live = await readPgCatalogueIdentity(executor, address);\n\t\t\tif (live)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`generated ${address.kind} absence postcondition differs: ${address.name} is still present`,\n\t\t\t\t);\n\t\t\treturn { observed: generatedPayload({ kind: 'absent' }) };\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error('generated v3 postcondition has no declarable read-back');\n\t}\n}\n\n/**\n * Generated DDL has no operation runtime to supply an observation. Structural\n * declarations read the precise catalogue fields they change; the four #597\n * identity-only declarations prove existence and catalogue identity, not shape.\n * A same-named object is never enough to write an `observed` terminal.\n */\nexport async function readGeneratedPostcondition(\n\texecutor: GeneratedPostconditionSession,\n\tstep: NormalizedManagedStep,\n\taddress: LedgerAddress,\n): Promise<GeneratedPostconditionObservation> {\n\texecutor = assertGeneratedPostconditionSession(executor);\n\tconst decodedPostcondition = generatedPostcondition(step, address);\n\tif (decodedPostcondition.postconditionVersion === 3)\n\t\treturn (\n\t\t\tawait readGeneratedV3Postcondition(\n\t\t\t\texecutor,\n\t\t\t\tdecodedPostcondition,\n\t\t\t\taddress,\n\t\t\t)\n\t\t).observed;\n\tthrow new Error(\n\t\t'generated postcondition decoder returned no supported version',\n\t);\n}\n\nfunction containedBy(root: LedgerAddress, candidate: LedgerAddress): boolean {\n\tfor (let parent = candidate.parent; parent; parent = parent.parent) {\n\t\tif (\n\t\t\tparent.engine === root.engine &&\n\t\t\tparent.database === root.database &&\n\t\t\tparent.schema === root.schema &&\n\t\t\tparent.kind === root.kind &&\n\t\t\tparent.name === root.name\n\t\t)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nasync function destructiveEvidence(input: {\n\treadonly executor: LedgerQueryable;\n\treadonly address: LedgerAddress;\n\treadonly classification: import('@dbsp/types').ManagedStepClassification;\n\treadonly selection?: NormalizedManagedStep['selection'];\n\treadonly planDigest: string;\n\treadonly approval: ScopedApprovalSet;\n}): Promise<{\n\treadonly evidence: DestructiveAuthorityEvidence;\n\treadonly containment?: Awaited<\n\t\tReturnType<typeof readPgRemovalEffectsClosure>\n\t>;\n}> {\n\tconst { executor, address } = input;\n\tlet ownership: DestructiveAuthorityEvidence['ownership'] = 'uncomputable';\n\tlet catalogueIdentity: DestructiveAuthorityEvidence['catalogueIdentity'] =\n\t\t'catalogue-unavailable';\n\tlet ledgerLineage: DestructiveAuthorityEvidence['ledgerLineage'] =\n\t\t'unreadable';\n\ttry {\n\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\texecutor,\n\t\t\thome(address),\n\t\t\taddress,\n\t\t);\n\t\tconst projection = projectLedgerChain(chain);\n\t\townership =\n\t\t\tprojection.kind === 'projected-ledger-chain'\n\t\t\t\t? projection.stableState === 'managed'\n\t\t\t\t\t? 'managed-by-me'\n\t\t\t\t\t: projection.stableState === 'unknown'\n\t\t\t\t\t\t? 'unknown'\n\t\t\t\t\t\t: 'blocked'\n\t\t\t\t: 'uncomputable';\n\t\tconst live = await readPgCatalogueIdentity(executor, address);\n\t\tconst recorded = chain.terminalMember?.catalogueIdentity;\n\t\tcatalogueIdentity = !live\n\t\t\t? 'object-absent'\n\t\t\t: recorded === undefined\n\t\t\t\t? 'differs'\n\t\t\t\t: isDeepStrictEqual(live.catalogueIdentity, recorded)\n\t\t\t\t\t? 'matches-recorded'\n\t\t\t\t\t: 'differs';\n\t\tconst currency = await readPgLedgerScopeCurrency(executor, home(address));\n\t\tledgerLineage =\n\t\t\tcurrency.kind === 'current' ? 'matches-database' : 'differs';\n\t} catch {\n\t\t// The authority table intentionally turns every unreadable live fact into a refusal.\n\t}\n\tlet containment:\n\t\t| Awaited<ReturnType<typeof readPgRemovalEffectsClosure>>\n\t\t| undefined;\n\tlet containmentOutcome: ContainmentClosureDestructiveOutcome | undefined;\n\tif (input.classification === 'removal') {\n\t\tcontainment = await readPgRemovalEffectsClosure({\n\t\t\texecutor,\n\t\t\troot: address,\n\t\t\tisManaged: (candidate) => managed(executor, candidate),\n\t\t});\n\t\tcontainmentOutcome = containment.kind;\n\t}\n\treturn {\n\t\tevidence: {\n\t\t\tdeclaration:\n\t\t\t\tinput.classification === 'removal'\n\t\t\t\t\t? input.selection?.kind === 'replacement'\n\t\t\t\t\t\t? 'replacement-requested-by-plan'\n\t\t\t\t\t\t: 'requires-removal'\n\t\t\t\t\t: 'requires-lossy-change',\n\t\t\t...(input.selection?.kind === 'replacement'\n\t\t\t\t? { replacementAddress: address }\n\t\t\t\t: {}),\n\t\t\townership,\n\t\t\tcatalogueIdentity,\n\t\t\toperatorAcceptance: acceptance(input.planDigest, input.approval),\n\t\t\t...(containmentOutcome === undefined\n\t\t\t\t? {}\n\t\t\t\t: { containment: containmentOutcome }),\n\t\t\t...(containment?.kind === 'reaches-unmanaged'\n\t\t\t\t? { containmentUnmanaged: containment.unmanaged }\n\t\t\t\t: {}),\n\t\t\t...(containment?.kind === 'undecidable'\n\t\t\t\t? { containmentReason: containment.reason }\n\t\t\t\t: {}),\n\t\t\tledgerLineage,\n\t\t},\n\t\t...(containment === undefined ? {} : { containment }),\n\t};\n}\n\n/**\n * Closure discovery is needed before the group can be reserved. It deliberately\n * does not decide destructive authority; the locked admission callback does.\n */\nasync function removalContainment(\n\texecutor: LedgerQueryable,\n\taddress: LedgerAddress,\n): Promise<Awaited<ReturnType<typeof readPgRemovalEffectsClosure>>> {\n\treturn readPgRemovalEffectsClosure({\n\t\texecutor,\n\t\troot: address,\n\t\tisManaged: (candidate) => managed(executor, candidate),\n\t});\n}\n\n/**\n * Executes the in-memory, just-presented generator material. It never reads\n * a generator run back by id: that persisted row remains review-only.\n */\nexport async function executeGeneratorPlan(input: {\n\treadonly pool: Pool;\n\t/** Bound by apply after validating the persisted durable manifest. */\n\treadonly manifest?: ValidatedManagedStepManifest;\n\t/** @deprecated Compatibility shim for direct fixtures; it is validated before use. */\n\treadonly plan?: { readonly steps: readonly unknown[] };\n\treadonly planDigest: string;\n\treadonly schema: string;\n\t/** Preserve scopes and trust roots until admission; never reduce to classes. */\n\treadonly approval?: ScopedApprovalSet;\n\t/** Durable witness minted while apply holds this run's journal lock. */\n\treadonly run: PgLockedRun;\n\t/** Appends the run-to-attempt mapping before any ledger claim may be opened. */\n\treadonly recordAttempt: (executionId: string) => Promise<void>;\n\t/** Test-only admitted-path observation; absent from every CLI invocation. */\n\treadonly observer?: PgOutcomeCheckpointObserver;\n\t/** @deprecated Compatibility shim for old direct fixtures. */\n\treadonly accepts?: readonly string[];\n\treadonly replaces?: readonly string[];\n\treadonly runId: string;\n}): Promise<GeneratorExecutionResult> {\n\tconst validation = input.manifest\n\t\t? { ok: true as const, manifest: input.manifest }\n\t\t: validateNormalizedManagedStepManifest(\n\t\t\t\t(input.plan?.steps as readonly NormalizedManagedStep[]) ?? [],\n\t\t\t);\n\tif (!validation.ok)\n\t\treturn { outcome: 'execution-failed', detail: validation.detail };\n\tconst manifest = validation.manifest;\n\tconst approval: ScopedApprovalSet = input.approval ?? {\n\t\tapprovals: (input.accepts ?? []).map((value) => ({ class: value })),\n\t};\n\tconst completedStepKeys: string[] = [];\n\tlet destructiveRefusal: { readonly withheldAuthority: string } | undefined;\n\tlet destructiveClosureReplanRequired = false;\n\tconst partial = (detail: string): GeneratorExecutionResult =>\n\t\tcompletedStepKeys.length === 0\n\t\t\t? { outcome: 'execution-failed', detail }\n\t\t\t: {\n\t\t\t\t\toutcome: 'partially-applied',\n\t\t\t\t\tdetail,\n\t\t\t\t\tcompletedStepKeys,\n\t\t\t\t\tnotStartedStepKeys: managedSteps(manifest)\n\t\t\t\t\t\t.filter((step) => !completedStepKeys.includes(step.stepKey))\n\t\t\t\t\t\t.map((step) => step.stepKey),\n\t\t\t\t};\n\ttry {\n\t\tconst database = await databaseId(input.pool);\n\t\t// The attempt id is random, journaled before any step, and is the namespace\n\t\t// claims bind to. Reconciliation discovers it from the journal.\n\t\tconst executionId = `dbsp.generator.execution.${randomUUID()}`;\n\t\tawait input.recordAttempt(executionId);\n\t\tconst steps = managedSteps(manifest);\n\t\tfor (const step of steps) {\n\t\t\tif (step.lifecycle?.kind === 'adoption-refused')\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'adoption-refused',\n\t\t\t\t\tdetail: `declared adoption for ${step.address?.name ?? step.stepKey} refuses live shape mismatch`,\n\t\t\t\t};\n\t\t\tconst lifecycle = step.lifecycle;\n\t\t\tif (lifecycle?.kind !== 'adoption') continue;\n\t\t\tconst address = step.address;\n\t\t\tif (\n\t\t\t\t!address ||\n\t\t\t\t!step.expectedDeclaration ||\n\t\t\t\t!step.expectedCatalogueIdentity\n\t\t\t)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\tdetail: `adoption step ${step.stepKey} has incomplete normalized material`,\n\t\t\t\t};\n\t\t\tconst preflight = await preflightPgDeclaredAdoption({\n\t\t\t\texecutor: input.pool,\n\t\t\t\thome: home(address),\n\t\t\t\taddress,\n\t\t\t\tdeclaration: step.expectedDeclaration,\n\t\t\t\texpectedCatalogueIdentity: step.expectedCatalogueIdentity,\n\t\t\t\tshapeMatches: () =>\n\t\t\t\t\tadoptionShapeMatches(input.pool, input.schema, lifecycle.shape),\n\t\t\t});\n\t\t\tif (preflight.outcome !== 'ready' && preflight.outcome !== 'no-op')\n\t\t\t\treturn preflight.outcome === 'adoption-refused'\n\t\t\t\t\t? { outcome: 'adoption-refused', detail: preflight.detail }\n\t\t\t\t\t: { outcome: 'execution-failed', detail: preflight.detail };\n\t\t}\n\t\tconst replacementSelectors = steps\n\t\t\t.filter((step) => step.selection?.kind === 'replacement')\n\t\t\t.map((step) => step.selection?.selector)\n\t\t\t.filter((selector): selector is string => selector !== undefined);\n\t\tif (replacementSelectors.length > 0 && !input.replaces?.length)\n\t\t\treturn {\n\t\t\t\toutcome: 'destructive-authority-refused',\n\t\t\t\tdetail:\n\t\t\t\t\t'replacement requires a named --replace selector from the reviewed plan',\n\t\t\t\trefusal: { withheldAuthority: 'destructive declaration authority' },\n\t\t\t};\n\t\tfor (const selector of input.replaces ?? [])\n\t\t\tif (\n\t\t\t\t!replacementSelectors.some((reviewed) =>\n\t\t\t\t\tmatchesReviewedReplacementSelector(reviewed, selector),\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'destructive-authority-refused',\n\t\t\t\t\tdetail: `replacement ${selector} was not requested by the reviewed plan`,\n\t\t\t\t\trefusal: { withheldAuthority: 'destructive declaration authority' },\n\t\t\t\t};\n\t\tif (\n\t\t\treplacementSelectors.some(\n\t\t\t\t(reviewed) =>\n\t\t\t\t\t!input.replaces?.some((provided) =>\n\t\t\t\t\t\tmatchesReviewedReplacementSelector(reviewed, provided),\n\t\t\t\t\t),\n\t\t\t)\n\t\t)\n\t\t\treturn {\n\t\t\t\toutcome: 'selection-incomplete',\n\t\t\t\tdetail:\n\t\t\t\t\t'replacement selection does not cover every reviewed replacement',\n\t\t\t};\n\t\tfor (const step of steps) {\n\t\t\tif (step.lifecycle?.kind === 'adoption-refused') continue;\n\t\t\tif (step.lifecycle?.kind === 'adoption') {\n\t\t\t\tconst lifecycle = step.lifecycle;\n\t\t\t\tconst address = step.address;\n\t\t\t\tif (\n\t\t\t\t\t!address ||\n\t\t\t\t\t!step.expectedDeclaration ||\n\t\t\t\t\t!step.expectedCatalogueIdentity\n\t\t\t\t)\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\t\tdetail: `adoption step ${step.stepKey} has incomplete normalized material`,\n\t\t\t\t\t};\n\t\t\t\tconst adopted = await executePgDeclaredAdoption({\n\t\t\t\t\texecutor: input.pool,\n\t\t\t\t\trun: input.run,\n\t\t\t\t\tmanifest,\n\t\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\t\tapproval,\n\t\t\t\t\texecutionId,\n\t\t\t\t\tstep,\n\t\t\t\t\thome: home(address),\n\t\t\t\t\taddress,\n\t\t\t\t\tdeclaration: step.expectedDeclaration,\n\t\t\t\t\texpectedCatalogueIdentity: step.expectedCatalogueIdentity,\n\t\t\t\t\tshapeMatches: () =>\n\t\t\t\t\t\tadoptionShapeMatches(input.pool, input.schema, lifecycle.shape),\n\t\t\t\t\t...(input.observer === undefined ? {} : { observer: input.observer }),\n\t\t\t\t});\n\t\t\t\tif (adopted.outcome === 'completed' || adopted.outcome === 'no-op') {\n\t\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (adopted.outcome === 'adoption-refused')\n\t\t\t\t\treturn { outcome: 'adoption-refused', detail: adopted.detail };\n\t\t\t\tif (adopted.outcome === 'recovery-required') return adopted;\n\t\t\t\tif (adopted.outcome === 'transport-ambiguous') return adopted;\n\t\t\t\treturn { outcome: 'execution-failed', detail: adopted.detail };\n\t\t\t}\n\t\t\tif (step.lifecycle?.kind === 'readdress') {\n\t\t\t\tconst result = await executePgPersistedTableReaddress({\n\t\t\t\t\texecutor: input.pool,\n\t\t\t\t\trun: input.run,\n\t\t\t\t\tmanifest,\n\t\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\t\tapproval,\n\t\t\t\t\texecutionId,\n\t\t\t\t\tstep,\n\t\t\t\t\tdatabase,\n\t\t\t\t\ttargetSchema: input.schema,\n\t\t\t\t\t...(input.observer === undefined ? {} : { observer: input.observer }),\n\t\t\t\t});\n\t\t\t\tif (result.outcome === 'completed' || result.outcome === 'no-op') {\n\t\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tif (step.statementBundle.statements.length === 0) {\n\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst address = step.address ?? step.closure?.root;\n\t\t\tif (!address)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\tdetail: `managed step ${step.stepKey} has no address`,\n\t\t\t\t};\n\t\t\tconst plannedClaimKey = step.plannedClaimKeys[0];\n\t\t\tif (!plannedClaimKey)\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'execution-failed',\n\t\t\t\t\tdetail: `managed step ${step.stepKey} has no planned claim key`,\n\t\t\t\t};\n\t\t\tif (\n\t\t\t\tstep.classification === 'non-destructive' &&\n\t\t\t\tstep.requiresVacancy &&\n\t\t\t\t(await alreadyAppliedCreation(input.pool, address))\n\t\t\t) {\n\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst claimKind: LedgerClaimKind = step.claimKind;\n\t\t\tconst rootClaimId = outcomeClaimId(executionId, plannedClaimKey, address);\n\t\t\tconst claim = {\n\t\t\t\tclaimId: rootClaimId,\n\t\t\t\tclaimSpecies: 'sql-bearing' as const,\n\t\t\t\texecutionId,\n\t\t\t\tplannedClaimKey,\n\t\t\t\tclaimGroupId: rootClaimId,\n\t\t\t\trootClaimId,\n\t\t\t\taddress,\n\t\t\t\tclaimKind,\n\t\t\t\tstatementBundle: step.statementBundle,\n\t\t\t\trequiresVacancy: step.requiresVacancy,\n\t\t\t};\n\t\t\tconst baseReservation = {\n\t\t\t\taddress,\n\t\t\t\tclaimKind,\n\t\t\t\texecutionId,\n\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\thomeLedger: home(address),\n\t\t\t};\n\t\t\tif (step.classification === 'non-destructive') {\n\t\t\t\tconst result = await executePgAdmittedOperation(input.pool, {\n\t\t\t\t\trun: input.run,\n\t\t\t\t\tapproval,\n\t\t\t\t\tmanifest,\n\t\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\t\toperation: {\n\t\t\t\t\t\tkind: 'single-outcome',\n\t\t\t\t\t\trequest: {\n\t\t\t\t\t\t\tplan: claim,\n\t\t\t\t\t\t\treservations: [baseReservation],\n\t\t\t\t\t\t\tresolution: {\n\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(claim.claimId, 'observed'),\n\t\t\t\t\t\t\t\teventKind: 'observed',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t// Transactional DDL is visible only on the admitted session until\n\t\t\t\t\t\t\t// its terminal ledger fact commits with it.\n\t\t\t\t\t\t\treadBack: async (session) =>\n\t\t\t\t\t\t\t\treadGeneratedPostcondition(session, step, address),\n\t\t\t\t\t\t\trecordCatalogueIdentity: true,\n\t\t\t\t\t\t\t...(input.observer === undefined\n\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t: { observer: input.observer }),\n\t\t\t\t\t\t\tvacancy: async (executor: LedgerQueryable) =>\n\t\t\t\t\t\t\t\t(await readPgCatalogueIdentity(executor, address))\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tkind: 'occupied',\n\t\t\t\t\t\t\t\t\t\t\treason: `creation claim ${claim.claimId} refuses occupied live address ${address.name}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: { kind: 'vacant' },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (result.kind === 'outcome-recovery-required')\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutcome: 'recovery-required',\n\t\t\t\t\t\tclaimId: result.claimId,\n\t\t\t\t\t\tdetail: `claim ${result.claimId} remains open and requires recovery: ${result.reason}`,\n\t\t\t\t\t};\n\t\t\t\tif (result.kind === 'outcome-transport-ambiguous')\n\t\t\t\t\treturn { outcome: 'transport-ambiguous', detail: result.reason };\n\t\t\t\tif ('reason' in result) return partial(result.reason);\n\t\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst containment =\n\t\t\t\tstep.classification === 'removal'\n\t\t\t\t\t? await removalContainment(input.pool, address)\n\t\t\t\t\t: undefined;\n\t\t\tconst closureMembers = new Map<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\treadonly address: LedgerAddress;\n\t\t\t\t\treadonly plannedClaimKey: string;\n\t\t\t\t}\n\t\t\t>();\n\t\t\t// A normalized closure is digest-covered execution material. Its\n\t\t\t// members must receive their own claims and terminal `absent` facts;\n\t\t\t// PostgreSQL's single DROP statement does not make those ledger facts\n\t\t\t// optional. The live closure remains the authority-time cascade guard\n\t\t\t// and supplements legacy root-only manifests.\n\t\t\tfor (const member of step.closure?.members ?? []) {\n\t\t\t\tclosureMembers.set(ledgerAddressKey(member.address), {\n\t\t\t\t\taddress: member.address,\n\t\t\t\t\tplannedClaimKey: member.plannedClaimKey,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (containment?.kind === 'all-contained-or-managed') {\n\t\t\t\tfor (const effect of containment.effects) {\n\t\t\t\t\tif (effect.internalOwned) continue;\n\t\t\t\t\tif (!containedBy(address, effect.address)) continue;\n\t\t\t\t\tif (!(await managed(input.pool, effect.address))) continue;\n\t\t\t\t\tconst key = ledgerAddressKey(effect.address);\n\t\t\t\t\tif (closureMembers.has(key)) continue;\n\t\t\t\t\tclosureMembers.set(key, {\n\t\t\t\t\t\taddress: effect.address,\n\t\t\t\t\t\tplannedClaimKey: `closure:${effect.address.kind}:${effect.address.name}`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst containedClaims: Array<{\n\t\t\t\treadonly plan: CascadeCoveredOutcomeClaimPlan & {\n\t\t\t\t\treadonly plannedClaimKey: string;\n\t\t\t\t};\n\t\t\t\treadonly reservation: typeof baseReservation;\n\t\t\t}> = [];\n\t\t\tfor (const member of closureMembers.values()) {\n\t\t\t\tconst effect = member.address;\n\t\t\t\tconst childClaimId = outcomeClaimId(\n\t\t\t\t\texecutionId,\n\t\t\t\t\tplannedClaimKey,\n\t\t\t\t\teffect,\n\t\t\t\t\tmember.plannedClaimKey,\n\t\t\t\t);\n\t\t\t\tconst childReservation = {\n\t\t\t\t\t...baseReservation,\n\t\t\t\t\taddress: effect as typeof address,\n\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t};\n\t\t\t\tcontainedClaims.push({\n\t\t\t\t\tplan: {\n\t\t\t\t\t\t...claim,\n\t\t\t\t\t\tclaimId: childClaimId,\n\t\t\t\t\t\tclaimSpecies: 'cascade-covered',\n\t\t\t\t\t\taddress: effect as typeof address,\n\t\t\t\t\t\tplannedClaimKey: member.plannedClaimKey,\n\t\t\t\t\t\t// Each member contributes only its terminal absence fact; SQL is\n\t\t\t\t\t\t// exclusively carried by the destructive root manifest claim.\n\t\t\t\t\t\tstatementBundle: { statements: [] },\n\t\t\t\t\t},\n\t\t\t\t\treservation: childReservation,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst admitRequest = {\n\t\t\t\tplan: claim,\n\t\t\t\treservations: [baseReservation],\n\t\t\t\tmembers: containedClaims.map(({ plan, reservation }) => ({\n\t\t\t\t\tplan,\n\t\t\t\t\treservations: [reservation],\n\t\t\t\t})),\n\t\t\t\tdestructiveDecision: async (executor: LedgerQueryable) => {\n\t\t\t\t\tconst lockedAuthority = await destructiveEvidence({\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\taddress,\n\t\t\t\t\t\tclassification: step.classification,\n\t\t\t\t\t\tselection: step.selection,\n\t\t\t\t\t\tplanDigest: input.planDigest,\n\t\t\t\t\t\tapproval,\n\t\t\t\t\t});\n\t\t\t\t\tif (\n\t\t\t\t\t\tstep.classification === 'removal' &&\n\t\t\t\t\t\t(containment?.kind !== 'all-contained-or-managed' ||\n\t\t\t\t\t\t\tlockedAuthority.containment?.kind !==\n\t\t\t\t\t\t\t\t'all-contained-or-managed' ||\n\t\t\t\t\t\t\tcontainment.closureDigest !==\n\t\t\t\t\t\t\t\tlockedAuthority.containment.closureDigest)\n\t\t\t\t\t) {\n\t\t\t\t\t\tdestructiveClosureReplanRequired = true;\n\t\t\t\t\t\tconst decision = decideDestructiveDecision(\n\t\t\t\t\t\t\t{ kind: 'removal', address },\n\t\t\t\t\t\t\t{ ...lockedAuthority.evidence, containment: 'undecidable' },\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (decision.kind === 'destructive-decision-refused')\n\t\t\t\t\t\t\tdestructiveRefusal = {\n\t\t\t\t\t\t\t\twithheldAuthority:\n\t\t\t\t\t\t\t\t\twithheldDestructiveAuthority({\n\t\t\t\t\t\t\t\t\t\t...lockedAuthority.evidence,\n\t\t\t\t\t\t\t\t\t\tcontainment: 'undecidable',\n\t\t\t\t\t\t\t\t\t}) ?? 'destructive containment authority',\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\treturn decision;\n\t\t\t\t\t}\n\t\t\t\t\tconst decision = decideDestructiveDecision(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tkind:\n\t\t\t\t\t\t\t\tstep.classification === 'removal'\n\t\t\t\t\t\t\t\t\t? 'removal'\n\t\t\t\t\t\t\t\t\t: 'data-destructive',\n\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t...(step.classification === 'removal' &&\n\t\t\t\t\t\t\tlockedAuthority.containment?.kind === 'all-contained-or-managed'\n\t\t\t\t\t\t\t\t? { closureDigest: lockedAuthority.containment.closureDigest }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tlockedAuthority.evidence,\n\t\t\t\t\t);\n\t\t\t\t\tif (decision.kind === 'destructive-decision-refused')\n\t\t\t\t\t\tdestructiveRefusal = {\n\t\t\t\t\t\t\twithheldAuthority:\n\t\t\t\t\t\t\t\twithheldDestructiveAuthority(lockedAuthority.evidence) ??\n\t\t\t\t\t\t\t\t'destructive authority',\n\t\t\t\t\t\t};\n\t\t\t\t\treturn decision;\n\t\t\t\t},\n\t\t\t\t...(input.observer === undefined ? {} : { observer: input.observer }),\n\t\t\t};\n\t\t\tconst executed = (await executePgAdmittedOperation(input.pool, {\n\t\t\t\trun: input.run,\n\t\t\t\tapproval,\n\t\t\t\tmanifest,\n\t\t\t\trecomputedPlanDigest: input.planDigest,\n\t\t\t\toperation: {\n\t\t\t\t\tkind: 'destructive-outcome',\n\t\t\t\t\trequest: admitRequest,\n\t\t\t\t\treadBackAndResolve: async (session) => {\n\t\t\t\t\t\tconst declarationReadBack =\n\t\t\t\t\t\t\tstep.classification === 'data-destructive' &&\n\t\t\t\t\t\t\tstep.expectedDeclaration !== undefined\n\t\t\t\t\t\t\t\t? await withGeneratedPostconditionSession(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tconnect: async () => ({\n\t\t\t\t\t\t\t\t\t\t\t\tquery: session.query.bind(session),\n\t\t\t\t\t\t\t\t\t\t\t\trelease: () => undefined,\n\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t(proof) => {\n\t\t\t\t\t\t\t\t\t\t\tconst postcondition = generatedPostcondition(\n\t\t\t\t\t\t\t\t\t\t\t\tstep,\n\t\t\t\t\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\tif (postcondition.postconditionVersion !== 3)\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t\t'generated postcondition decoder returned no supported version',\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\treturn readGeneratedV3Postcondition(\n\t\t\t\t\t\t\t\t\t\t\t\tproof,\n\t\t\t\t\t\t\t\t\t\t\t\tpostcondition,\n\t\t\t\t\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst live =\n\t\t\t\t\t\t\tstep.classification === 'removal'\n\t\t\t\t\t\t\t\t? await readPgCatalogueIdentity(session, address)\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst terminalCatalogueIdentity =\n\t\t\t\t\t\t\tstep.classification === 'removal'\n\t\t\t\t\t\t\t\t? live?.catalogueIdentity\n\t\t\t\t\t\t\t\t: declarationReadBack?.catalogueIdentity;\n\t\t\t\t\t\tconst survivors: LedgerAddress[] =\n\t\t\t\t\t\t\tstep.classification === 'removal' && live ? [address] : [];\n\t\t\t\t\t\tconst childLives = await Promise.all(\n\t\t\t\t\t\t\tcontainedClaims.map(async (child) => ({\n\t\t\t\t\t\t\t\tchild,\n\t\t\t\t\t\t\t\tlive: await readPgCatalogueIdentity(\n\t\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\t\tchild.plan.address,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tfor (const { child, live: childLive } of childLives)\n\t\t\t\t\t\t\tif (childLive) survivors.push(child.plan.address);\n\t\t\t\t\t\tif (survivors.length > 0) {\n\t\t\t\t\t\t\tconst survivorNames = survivors.map(\n\t\t\t\t\t\t\t\t(survivor) =>\n\t\t\t\t\t\t\t\t\t`${survivor.kind} ${survivor.schema ?? '<database>'}.${survivor.name}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst survivorValue = { survivors: survivorNames };\n\t\t\t\t\t\t\tconst survivorObservation = {\n\t\t\t\t\t\t\t\tvalue: survivorValue,\n\t\t\t\t\t\t\t\tdigest: canonicalJsonDigest(survivorValue),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\t\tmembers: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttarget: home(address),\n\t\t\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(\n\t\t\t\t\t\t\t\t\t\t\t\tclaim.claimId,\n\t\t\t\t\t\t\t\t\t\t\t\t'indeterminate',\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: claim.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimGroupId,\n\t\t\t\t\t\t\t\t\t\t\trootClaimId: claim.rootClaimId,\n\t\t\t\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\t\t\t\teventKind: 'indeterminate' as const,\n\t\t\t\t\t\t\t\t\t\t\tobserved: survivorObservation,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t...containedClaims.map((child) => ({\n\t\t\t\t\t\t\t\t\t\ttarget: home(child.plan.address),\n\t\t\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(\n\t\t\t\t\t\t\t\t\t\t\t\tchild.plan.claimId,\n\t\t\t\t\t\t\t\t\t\t\t\t'indeterminate',\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: child.plan.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimId,\n\t\t\t\t\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\t\t\t\t\taddress: child.plan.address,\n\t\t\t\t\t\t\t\t\t\t\teventKind: 'indeterminate' as const,\n\t\t\t\t\t\t\t\t\t\t\tobserved: survivorObservation,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\treservations: [\n\t\t\t\t\t\t\t\t\tbaseReservation,\n\t\t\t\t\t\t\t\t\t...containedClaims.map(({ reservation }) => reservation),\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst terminals: Array<{\n\t\t\t\t\t\t\treadonly target: LedgerHome;\n\t\t\t\t\t\t\treadonly member: Omit<\n\t\t\t\t\t\t\t\tLedgerChainMember,\n\t\t\t\t\t\t\t\t'controller' | 'recordedAt'\n\t\t\t\t\t\t\t>;\n\t\t\t\t\t\t}> = [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttarget: home(address),\n\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(\n\t\t\t\t\t\t\t\t\t\tclaim.claimId,\n\t\t\t\t\t\t\t\t\t\tstep.classification === 'removal' ? 'absent' : 'observed',\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\tplannedClaimKey: claim.plannedClaimKey,\n\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimGroupId,\n\t\t\t\t\t\t\t\t\trootClaimId: claim.rootClaimId,\n\t\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\t\teventKind:\n\t\t\t\t\t\t\t\t\t\tstep.classification === 'removal' ? 'absent' : 'observed',\n\t\t\t\t\t\t\t\t\t// The append protocol reads this address's terminal on its\n\t\t\t\t\t\t\t\t\t// pinned transaction session after the post-DDL read-back.\n\t\t\t\t\t\t\t\t\t...(terminalCatalogueIdentity === undefined\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: { catalogueIdentity: terminalCatalogueIdentity }),\n\t\t\t\t\t\t\t\t\t...(step.classification === 'removal'\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\tobserved:\n\t\t\t\t\t\t\t\t\t\t\t\t\tdeclarationReadBack?.observed ?? observed(address),\n\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t];\n\t\t\t\t\t\tfor (const child of containedClaims) {\n\t\t\t\t\t\t\tterminals.push({\n\t\t\t\t\t\t\t\ttarget: home(child.plan.address),\n\t\t\t\t\t\t\t\tmember: {\n\t\t\t\t\t\t\t\t\teventId: outcomeClaimEventId(child.plan.claimId, 'absent'),\n\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\tplannedClaimKey: child.plan.plannedClaimKey,\n\t\t\t\t\t\t\t\t\tclaimGroupId: claim.claimId,\n\t\t\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\t\t\taddress: child.plan.address,\n\t\t\t\t\t\t\t\t\teventKind: 'absent' as const,\n\t\t\t\t\t\t\t\t\tpredecessor: child.plan.claimId,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\trootClaimId: claim.claimId,\n\t\t\t\t\t\t\tmembers: terminals,\n\t\t\t\t\t\t\treservations: [\n\t\t\t\t\t\t\t\tbaseReservation,\n\t\t\t\t\t\t\t\t...containedClaims.map(({ reservation }) => reservation),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})) as\n\t\t\t\t| { readonly kind: 'executed-destructive-outcome' }\n\t\t\t\t| { readonly kind: 'outcome-protocol-refused'; readonly reason: string }\n\t\t\t\t| { readonly kind: 'outcome-protocol-pending'; readonly reason: string }\n\t\t\t\t| {\n\t\t\t\t\t\treadonly kind: 'outcome-transport-ambiguous';\n\t\t\t\t\t\treadonly reason: string;\n\t\t\t\t }\n\t\t\t\t| {\n\t\t\t\t\t\treadonly kind: 'outcome-recovery-required';\n\t\t\t\t\t\treadonly claimId: string;\n\t\t\t\t\t\treadonly reason: string;\n\t\t\t\t };\n\t\t\tif (executed.kind === 'outcome-recovery-required')\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'recovery-required',\n\t\t\t\t\tclaimId: executed.claimId,\n\t\t\t\t\tdetail: `claim ${executed.claimId} remains open and requires recovery: ${executed.reason}`,\n\t\t\t\t};\n\t\t\tif (executed.kind === 'outcome-transport-ambiguous')\n\t\t\t\treturn { outcome: 'transport-ambiguous', detail: executed.reason };\n\t\t\tif (executed.kind === 'outcome-protocol-pending')\n\t\t\t\treturn partial(\n\t\t\t\t\t`destructive claim ${claim.claimId} remains pending after executing: ${executed.reason}`,\n\t\t\t\t);\n\t\t\tif (executed.kind !== 'executed-destructive-outcome')\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'destructive-authority-refused',\n\t\t\t\t\tdetail: destructiveClosureReplanRequired\n\t\t\t\t\t\t? `${executed.reason}; destructive closure changed under lock; replan required`\n\t\t\t\t\t\t: executed.reason,\n\t\t\t\t\t...(destructiveRefusal === undefined &&\n\t\t\t\t\twithheldDestructiveAuthorityFromReason(executed.reason) === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\trefusal: destructiveRefusal ?? {\n\t\t\t\t\t\t\t\t\twithheldAuthority:\n\t\t\t\t\t\t\t\t\t\twithheldDestructiveAuthorityFromReason(executed.reason) ??\n\t\t\t\t\t\t\t\t\t\t'destructive authority',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\tcompletedStepKeys.push(step.stepKey);\n\t\t}\n\t\treturn { outcome: 'completed' };\n\t} catch (error) {\n\t\treturn partial(error instanceof Error ? error.message : String(error));\n\t}\n}\n","/**\n * The schema-differ producer used by the no-argument apply command.\n *\n * This deliberately lives beside `apply`, rather than in the transition\n * planner: generated removals have a different replay contract. The emitted\n * document is nevertheless persisted in the same journal and digest domain so\n * that it is inspectable before an operator makes a fresh live-state decision.\n */\nimport { randomUUID } from 'node:crypto';\nimport {\n\tassertDeclarableChangeKind,\n\tclassifyGeneratedMutation,\n\tcomparePgsqlDatabaseSchema,\n\tcreatePgsqlAdapter,\n\tcreatePgsqlGeneratedManagedStep,\n\tcreatePgTransitionLessor,\n\tcreatePgTransitionRunPersister,\n\tgeneratedPostconditionForChange,\n\tgenerateMigrationSQL,\n\treadPgCatalogueIdentity,\n\trenderPgTableReaddressStatements,\n\ttype SchemaDiff,\n} from '@dbsp/adapter-pgsql';\nimport type { InProcessProvenPlan } from '@dbsp/core';\nimport {\n\tacquireTransitionLease,\n\tcanonicalJson,\n\tcanonicalJsonDigest,\n\ttransitionPlanDigest,\n\tvalidateNormalizedManagedStepManifest,\n} from '@dbsp/core';\nimport type {\n\tCatalogueIdentity,\n\tLedgerAddress,\n\tLedgerPayload,\n\tNormalizedManagedStep,\n\tPlanAssessment,\n\tTableIR,\n\tTableReaddressDeclaration,\n\tTransitionRunMetadata,\n} from '@dbsp/types';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { loadSchema } from '../utils/schema-loader.js';\nimport type { PlanResult } from './plan.js';\n\nexport interface GeneratorPlanMaterial {\n\treadonly kind: 'schema-differ-generator';\n\t/** Digest-covered execution context captured with the reviewed generator run. */\n\treadonly planningSchema?: string;\n\t/** Diagnostic provenance only. Execution reads plan.steps, never this list. */\n\treadonly changes: readonly {\n\t\treadonly kind: string;\n\t\treadonly table: string;\n\t\treadonly column?: string;\n\t\treadonly classification: ReturnType<typeof classifyGeneratedMutation>;\n\t\treadonly details: string;\n\t\t/** Exact SQL attributed to this change for its token-gated claim. */\n\t\treadonly statements: readonly string[];\n\t\t/** Present only for the paired table re-addressing executor. */\n\t\treadonly readdress?: TableReaddressDeclaration;\n\t\t/** Present only for a reviewed declaration to adopt an existing table. */\n\t\treadonly adoption?: {\n\t\t\treadonly declaration: LedgerPayload;\n\t\t\treadonly shape: TableIR;\n\t\t\t/** Physical identity observed with the reviewed live shape. */\n\t\t\treadonly catalogueIdentity: CatalogueIdentity;\n\t\t};\n\t\t/** A digest-covered replacement is executed only when --replace names it. */\n\t\treadonly replacement?: {\n\t\t\treadonly retireStatements: readonly string[];\n\t\t\treadonly createStatements: readonly string[];\n\t\t};\n\t}[];\n}\n\n/** Extra persisted material is digest-covered; the regular applier never executes it. */\nexport type GeneratorDurablePlan = InProcessProvenPlan & {\n\treadonly generator: GeneratorPlanMaterial;\n};\n\nfunction adoptionDeclaration(table: TableIR): LedgerPayload {\n\t// The live differ is the shape comparator. Persist the exact authored table\n\t// shape, rather than a boolean that could later be reinterpreted.\n\tconst value = JSON.parse(\n\t\tcanonicalJson({ kind: 'table', name: table.name, shape: table }),\n\t) as LedgerPayload['value'];\n\treturn { value, digest: canonicalJsonDigest(value) };\n}\n\nfunction replacementStatements(table: TableIR, schema: string) {\n\tconst quote = (value: string) => `\"${value.replaceAll('\"', '\"\"')}\"`;\n\tconst createDiff: SchemaDiff = {\n\t\tchanges: [\n\t\t\t{\n\t\t\t\tkind: 'create_table',\n\t\t\t\ttable: table.name,\n\t\t\t\tdestructive: false,\n\t\t\t\tdetails: `Create table \"${table.name}\"`,\n\t\t\t\tmeta: { table },\n\t\t\t},\n\t\t],\n\t\thasDestructive: false,\n\t\tsummary: {\n\t\t\ttables: { added: 1, dropped: 0 },\n\t\t\tcolumns: { added: 0, dropped: 0, altered: 0 },\n\t\t\tindexes: { added: 0, dropped: 0 },\n\t\t\tconstraints: { added: 0, dropped: 0, altered: 0 },\n\t\t},\n\t};\n\treturn {\n\t\tretireStatements: [`DROP TABLE ${quote(schema)}.${quote(table.name)}`],\n\t\tcreateStatements: generateMigrationSQL(createDiff, {\n\t\t\tincludeDestructive: true,\n\t\t\tschemaName: schema,\n\t\t}),\n\t};\n}\n\n/** The paired executor sends only SQL that the persisted root step carries. */\nfunction readdressStatements(\n\tdatabase: string,\n\tschema: string,\n\tdeclaration: TableReaddressDeclaration,\n): readonly string[] {\n\tconst endpoint = (\n\t\tvalue: TableReaddressDeclaration['from'],\n\t): LedgerAddress => ({\n\t\tscope: 'schema',\n\t\tengine: 'postgresql',\n\t\tdatabase: value.database ?? database,\n\t\tschema: value.schema ?? schema,\n\t\tkind: value.kind ?? 'table',\n\t\tname: value.name,\n\t});\n\treturn renderPgTableReaddressStatements(\n\t\tendpoint(declaration.from),\n\t\tendpoint(declaration.to),\n\t);\n}\n\nfunction lifecycleStep(input: {\n\treadonly stepKey: string;\n\treadonly order: number;\n\treadonly database: string;\n\treadonly schema: string;\n\treadonly table: string;\n\treadonly classification: ReturnType<typeof classifyGeneratedMutation>;\n\treadonly statements?: readonly string[];\n\treadonly selection?: NormalizedManagedStep['selection'];\n\treadonly lifecycle?: NormalizedManagedStep['lifecycle'];\n\treadonly expectedDeclaration?: LedgerPayload;\n\treadonly expectedCatalogueIdentity?: CatalogueIdentity;\n\treadonly requiresVacancy?: boolean;\n\treadonly claimKind?: NormalizedManagedStep['claimKind'];\n}): NormalizedManagedStep {\n\t// Lifecycle-only table work has no SchemaChange, but it must pass the same\n\t// sole declarable boundary as ordinary diff-produced manifest steps.\n\tassertDeclarableChangeKind('create_table');\n\tconst address = {\n\t\tscope: 'schema' as const,\n\t\tengine: 'postgresql',\n\t\tdatabase: input.database,\n\t\tschema: input.schema,\n\t\tkind: 'table' as const,\n\t\tname: input.table,\n\t};\n\treturn {\n\t\tstepKey: input.stepKey,\n\t\torder: input.order,\n\t\tsegmentId: `generator-segment-${input.order}`,\n\t\t// Dependencies are assigned once the complete manifest exists. A numeric\n\t\t// order is not itself a step key: replacement emits two differently named\n\t\t// steps at adjacent orders.\n\t\tdependencyOrder: [],\n\t\taddress,\n\t\tclaimKind:\n\t\t\tinput.claimKind ??\n\t\t\t(input.classification === 'removal'\n\t\t\t\t? 'retire-intent'\n\t\t\t\t: input.classification === 'paired-readdress'\n\t\t\t\t\t? 'readdress-intent'\n\t\t\t\t\t: 'intent'),\n\t\tplannedClaimKeys: [`${input.stepKey}:root`],\n\t\tstatementBundle: {\n\t\t\tstatements: (input.statements ?? []).map((sql, ordinal) => ({\n\t\t\t\tordinal,\n\t\t\t\tsql,\n\t\t\t})),\n\t\t},\n\t\tclassification: input.classification,\n\t\trequiresVacancy: input.requiresVacancy ?? false,\n\t\t...(input.expectedDeclaration === undefined\n\t\t\t? {}\n\t\t\t: { expectedDeclaration: input.expectedDeclaration }),\n\t\t...(input.expectedCatalogueIdentity === undefined\n\t\t\t? {}\n\t\t\t: { expectedCatalogueIdentity: input.expectedCatalogueIdentity }),\n\t\t...(input.selection === undefined ? {} : { selection: input.selection }),\n\t\t...(input.lifecycle === undefined ? {} : { lifecycle: input.lifecycle }),\n\t\treplayPolicy:\n\t\t\tinput.classification === 'removal' ? 'fresh-live-only' : 'recorded',\n\t};\n}\n\n/**\n * The differ is deliberately sequential: each emitted step follows the exact\n * previously emitted step, including both halves of a reviewed replacement.\n * Assign the graph from concrete keys only after every lifecycle expansion.\n */\nexport function linearizeGeneratedManagedStepDependencies(\n\tsteps: readonly NormalizedManagedStep[],\n): readonly NormalizedManagedStep[] {\n\tconst linearized: NormalizedManagedStep[] = [];\n\tfor (const step of steps) {\n\t\tconst previous = linearized.at(-1);\n\t\tlinearized.push({\n\t\t\t...step,\n\t\t\tdependencyOrder: previous === undefined ? [] : [previous.stepKey],\n\t\t});\n\t}\n\treturn linearized;\n}\n\n/**\n * A durable manifest is an execution boundary, so lifecycle exclusivity is\n * checked again after deserialization instead of trusting its producer.\n */\nexport function persistedLifecycleDirectiveError(\n\tsteps: readonly NormalizedManagedStep[],\n): string | undefined {\n\tconst directivesByTable = new Map<string, Set<string>>();\n\tfor (const step of steps) {\n\t\tconst directive = step.selection?.kind;\n\t\tif (\n\t\t\tdirective !== 'adoption' &&\n\t\t\tdirective !== 'replacement' &&\n\t\t\tdirective !== 'readdress'\n\t\t)\n\t\t\tcontinue;\n\t\tconst address = step.address ?? step.closure?.root;\n\t\tif (address?.kind !== 'table') continue;\n\t\tconst key = [\n\t\t\taddress.engine,\n\t\t\taddress.database,\n\t\t\taddress.schema ?? '',\n\t\t\taddress.name,\n\t\t].join('\\u0000');\n\t\tconst directives = directivesByTable.get(key) ?? new Set<string>();\n\t\tdirectives.add(directive);\n\t\tdirectivesByTable.set(key, directives);\n\t\tif (directives.size > 1)\n\t\t\treturn `persisted lifecycle for ${address.name} cannot set ${[...directives].sort().join(' and ')} together`;\n\t}\n\treturn undefined;\n}\n\nfunction declaredLifecycleDirectiveError(table: TableIR): string | undefined {\n\tconst directives = [\n\t\ttable.adopt === true ? 'adopt' : undefined,\n\t\ttable.replace === true ? 'replace' : undefined,\n\t\ttable.readdress === undefined ? undefined : 'readdress',\n\t].filter((directive): directive is string => directive !== undefined);\n\treturn directives.length > 1\n\t\t? `declared lifecycle for ${table.name} cannot set ${directives.join(' and ')} together`\n\t\t: undefined;\n}\n\nfunction assessment(): PlanAssessment {\n\treturn {\n\t\tdecision: 'applicable',\n\t\tassurance: 'established',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'none',\n\t\treasons: [],\n\t};\n}\n\n/** `SchemaChange.table` is overloaded for non-table resources; never use it alone. */\nfunction changeTargetsDeclaredTable(\n\tchange: SchemaDiff['changes'][number],\n\ttable: string,\n): boolean {\n\tif (change.table !== table) return false;\n\treturn !new Set([\n\t\t'create_extension',\n\t\t'drop_extension',\n\t\t'create_enum',\n\t\t'drop_enum',\n\t\t'alter_enum_add_value',\n\t\t'create_sequence',\n\t\t'drop_sequence',\n\t\t'alter_sequence',\n\t]).has(change.kind);\n}\n\nfunction requiredAdoptionIdentity(\n\tidentities: ReadonlyMap<string, CatalogueIdentity>,\n\ttable: string,\n): CatalogueIdentity {\n\tconst identity = identities.get(table);\n\tif (!identity)\n\t\tthrow new Error(`declared adoption for ${table} has no live identity`);\n\treturn identity;\n}\n\nfunction asDurableGeneratorPlan(\n\tmaterial: GeneratorPlanMaterial,\n\tsteps: readonly NormalizedManagedStep[],\n): GeneratorDurablePlan {\n\tconst validation = validateNormalizedManagedStepManifest(steps);\n\tif (!validation.ok)\n\t\tthrow new Error(\n\t\t\t`generator planning refuses invalid managed-step manifest: ${validation.detail}`,\n\t\t);\n\treturn {\n\t\tobservations: [],\n\t\tclaims: [],\n\t\tassumptions: [],\n\t\tpreconditions: [],\n\t\tsegments: [],\n\t\t// Persist exactly the canonical manifest that the digest covers. The brand\n\t\t// itself is in-memory only; its normalized step payload is durable JSON.\n\t\tsteps: validation.manifest.steps,\n\t\tpostconditions: [],\n\t\tgenerator: material,\n\t} as unknown as GeneratorDurablePlan;\n}\n\nfunction render(\n\tplan: { readonly steps: readonly NormalizedManagedStep[] },\n\tplanDigest: string,\n): string {\n\tconst destructive = plan.steps.filter(\n\t\t(step) => step.classification !== 'non-destructive',\n\t);\n\treturn [\n\t\t'-- dbsp schema-differ generator plan; apply by id executes this exact normalized manifest unless a removal requires fresh live planning.',\n\t\t...plan.steps.flatMap((step) => [\n\t\t\t`-- ${step.classification}: ${step.stepKey}`,\n\t\t\t...step.statementBundle.statements.map((statement) =>\n\t\t\t\tstatement.sql.endsWith(';') ? statement.sql : `${statement.sql};`,\n\t\t\t),\n\t\t]),\n\t\t...(destructive.length === 0\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`-- destructive acceptance required: --accept destructive-plan-accepted:${planDigest}`,\n\t\t\t\t]),\n\t].join('\\n');\n}\n\nasync function databaseId(pool: Pool): Promise<string> {\n\tconst result = await pool.query('SELECT current_database() AS database_id');\n\tconst value = result.rows[0]?.database_id;\n\tif (typeof value !== 'string' || value.length === 0)\n\t\tthrow new Error(\n\t\t\t'schema-differ generator could not read current database identity',\n\t\t);\n\treturn value;\n}\n\n/**\n * Produce and (unless previewing) persist the differ's full mutation set.\n * Every change is classified before it can reach the rendered statement list.\n */\nexport async function runGeneratorPlan(input: {\n\treadonly db: string;\n\treadonly schemaFile: string;\n\treadonly schema?: string;\n\treadonly dryRun?: boolean;\n}): Promise<PlanResult> {\n\tconst loaded = await loadSchema(input.schemaFile);\n\tconst { pool } = await createDbConnection(input.db);\n\ttry {\n\t\tconst schema = input.schema ?? 'public';\n\t\tconst diff = await comparePgsqlDatabaseSchema(\n\t\t\tcreatePgsqlAdapter(pool),\n\t\t\tloaded.model,\n\t\t\t{\n\t\t\t\tschema,\n\t\t\t\t// `apply --schema` owns one schema. Extensions are database-scoped,\n\t\t\t\t// so an extension not declared by this schema must not become a\n\t\t\t\t// schema-plan removal merely because it is installed in the database.\n\t\t\t\tignoreUnmanagedExtensions: true,\n\t\t\t\t...(loaded.dbCasing ? { dbCasing: loaded.dbCasing } : {}),\n\t\t\t},\n\t\t);\n\t\tconst declaredLifecycleWork = [...loaded.model.tables.values()].some(\n\t\t\t(table) =>\n\t\t\t\ttable.adopt === true ||\n\t\t\t\ttable.replace === true ||\n\t\t\t\ttable.readdress !== undefined,\n\t\t);\n\t\tconst lifecycleError = [...loaded.model.tables.values()]\n\t\t\t.map(declaredLifecycleDirectiveError)\n\t\t\t.find((detail) => detail !== undefined);\n\t\tif (lifecycleError) throw new Error(lifecycleError);\n\t\tconst readdressRefusal = diff.changes.find(\n\t\t\t(change) =>\n\t\t\t\tchange.kind === 'readdress_table' &&\n\t\t\t\t(change.meta?.readdressAssessment === 'source-missing' ||\n\t\t\t\t\tchange.meta?.readdressAssessment === 'target-occupied'),\n\t\t);\n\t\tif (readdressRefusal)\n\t\t\tthrow new Error(\n\t\t\t\t`generator planning refuses ${readdressRefusal.details}; no re-address manifest was created`,\n\t\t\t);\n\t\tif (diff.changes.length === 0 && !declaredLifecycleWork) {\n\t\t\treturn {\n\t\t\t\tcompareKind: 'no-drift',\n\t\t\t\tproveKind: 'no-drift',\n\t\t\t\tassessment: {\n\t\t\t\t\t...assessment(),\n\t\t\t\t\tdecision: 'inapplicable',\n\t\t\t\t\tlifecycle: 'completed',\n\t\t\t\t},\n\t\t\t\tpersisted: false,\n\t\t\t\trunId: null,\n\t\t\t\tplanDigest: null,\n\t\t\t};\n\t\t}\n\t\tconst adoptionMismatches = new Set(\n\t\t\t[...loaded.model.tables.values()]\n\t\t\t\t.filter(\n\t\t\t\t\t(table) =>\n\t\t\t\t\t\ttable.adopt === true &&\n\t\t\t\t\t\tdiff.changes.some((change) =>\n\t\t\t\t\t\t\tchangeTargetsDeclaredTable(change, table.name),\n\t\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.map((table) => table.name),\n\t\t);\n\t\tconst database = await databaseId(pool);\n\t\tconst adoptionIdentities = new Map<string, CatalogueIdentity>();\n\t\tfor (const table of loaded.model.tables.values()) {\n\t\t\tif (table.adopt !== true || adoptionMismatches.has(table.name)) continue;\n\t\t\tconst live = await readPgCatalogueIdentity(pool, {\n\t\t\t\tengine: 'postgresql',\n\t\t\t\tdatabase,\n\t\t\t\tschema: input.schema ?? 'public',\n\t\t\t\tkind: 'table',\n\t\t\t\tname: table.name,\n\t\t\t});\n\t\t\tif (!live?.catalogueIdentity)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`declared adoption for ${table.name} refuses absent live identity`,\n\t\t\t\t);\n\t\t\tadoptionIdentities.set(table.name, live.catalogueIdentity);\n\t\t}\n\t\t// A declared lifecycle request owns every change at that address. Adoption\n\t\t// is a refusal rather than a mutation; replacement is its own reviewed\n\t\t// retire-and-create protocol. Keep unrelated drift intact.\n\t\tconst executableDiff: SchemaDiff = {\n\t\t\t...diff,\n\t\t\tchanges: diff.changes.filter(\n\t\t\t\t(change) =>\n\t\t\t\t\t![...loaded.model.tables.values()].some(\n\t\t\t\t\t\t(table) =>\n\t\t\t\t\t\t\t(table.adopt === true || table.replace === true) &&\n\t\t\t\t\t\t\tchangeTargetsDeclaredTable(change, table.name),\n\t\t\t\t\t),\n\t\t\t),\n\t\t};\n\t\tconst ordinaryChanges = executableDiff.changes.map((change) => ({\n\t\t\tkind: change.kind,\n\t\t\ttable: change.table,\n\t\t\t...(change.column ? { column: change.column } : {}),\n\t\t\tclassification: classifyGeneratedMutation(change.kind, change),\n\t\t\tdetails: change.details,\n\t\t\tstatements:\n\t\t\t\tchange.kind === 'readdress_table' && change.meta?.readdress\n\t\t\t\t\t? readdressStatements(\n\t\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\t\tschema,\n\t\t\t\t\t\t\tchange.meta.readdress as TableReaddressDeclaration,\n\t\t\t\t\t\t)\n\t\t\t\t\t: generateMigrationSQL(\n\t\t\t\t\t\t\t{ ...executableDiff, changes: [change] },\n\t\t\t\t\t\t\t{ includeDestructive: true, schemaName: schema },\n\t\t\t\t\t\t),\n\t\t\t...(change.kind === 'readdress_table' && change.meta?.readdress\n\t\t\t\t? { readdress: change.meta.readdress as TableReaddressDeclaration }\n\t\t\t\t: {}),\n\t\t}));\n\t\tconst material: GeneratorPlanMaterial = {\n\t\t\tkind: 'schema-differ-generator',\n\t\t\tplanningSchema: schema,\n\t\t\tchanges: [\n\t\t\t\t...ordinaryChanges,\n\t\t\t\t...[...loaded.model.tables.values()]\n\t\t\t\t\t.filter((table) => adoptionMismatches.has(table.name))\n\t\t\t\t\t.map((table) => ({\n\t\t\t\t\t\tkind: 'adoption_refused',\n\t\t\t\t\t\ttable: table.name,\n\t\t\t\t\t\tclassification: 'non-destructive' as const,\n\t\t\t\t\t\tdetails: `Refuse adoption of table \"${table.name}\": live shape does not match declaration`,\n\t\t\t\t\t\tstatements: [],\n\t\t\t\t\t})),\n\t\t\t\t// `comparePgsqlDatabaseSchema` has just compared each side through\n\t\t\t\t// the established live canonicalisation path. An adopted table is\n\t\t\t\t// admitted only when that comparison has no remaining change for it.\n\t\t\t\t...[...loaded.model.tables.values()]\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(table) =>\n\t\t\t\t\t\t\ttable.adopt === true &&\n\t\t\t\t\t\t\t!diff.changes.some((change) =>\n\t\t\t\t\t\t\t\tchangeTargetsDeclaredTable(change, table.name),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.map((table) => ({\n\t\t\t\t\t\tkind: 'adopt_table',\n\t\t\t\t\t\ttable: table.name,\n\t\t\t\t\t\tclassification: 'non-destructive' as const,\n\t\t\t\t\t\tdetails: `Adopt existing table \"${table.name}\" after live shape match`,\n\t\t\t\t\t\tstatements: [],\n\t\t\t\t\t\tadoption: {\n\t\t\t\t\t\t\tdeclaration: adoptionDeclaration(table),\n\t\t\t\t\t\t\tshape: table,\n\t\t\t\t\t\t\tcatalogueIdentity: requiredAdoptionIdentity(\n\t\t\t\t\t\t\t\tadoptionIdentities,\n\t\t\t\t\t\t\t\ttable.name,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t},\n\t\t\t\t\t})),\n\t\t\t\t...[...loaded.model.tables.values()]\n\t\t\t\t\t.filter((table) => table.replace === true)\n\t\t\t\t\t.map((table) => ({\n\t\t\t\t\t\tkind: 'replace_table',\n\t\t\t\t\t\ttable: table.name,\n\t\t\t\t\t\tclassification: 'removal' as const,\n\t\t\t\t\t\tdetails: `Replace table \"${table.name}\" by reviewed retirement then creation`,\n\t\t\t\t\t\tstatements: [],\n\t\t\t\t\t\treplacement: replacementStatements(table, schema),\n\t\t\t\t\t})),\n\t\t\t],\n\t\t};\n\t\t// A foreign-key alteration is a replacement, not a removal that happens to\n\t\t// recreate something afterwards. Keep its two addresses/claim keys visible\n\t\t// in the durable manifest and let dependency linearisation order retirement\n\t\t// before the target vacancy claim.\n\t\tconst ordinaryStepSources: Array<{\n\t\t\tstep: NormalizedManagedStep;\n\t\t\tchange: SchemaDiff['changes'][number];\n\t\t}> = [];\n\t\tfor (const [changeIndex, change] of executableDiff.changes.entries()) {\n\t\t\tconst generated = ordinaryChanges[changeIndex];\n\t\t\tif (!generated)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'generator planning lost a generated statement bundle during lifecycle expansion',\n\t\t\t\t);\n\t\t\tconst order = ordinaryStepSources.length;\n\t\t\tif (change.kind === 'alter_foreign_key') {\n\t\t\t\tconst oldFk = change.meta?.oldFk;\n\t\t\t\tif (!oldFk || typeof oldFk !== 'object' || Array.isArray(oldFk))\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'generator planning refuses alter_foreign_key: missing typed old foreign key',\n\t\t\t\t\t);\n\t\t\t\tconst [retireStatement, ...createStatements] = generated.statements;\n\t\t\t\tif (!retireStatement || createStatements.length === 0)\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'generator planning refuses alter_foreign_key: expected DROP then ADD bundle',\n\t\t\t\t\t);\n\t\t\t\tordinaryStepSources.push({\n\t\t\t\t\tchange,\n\t\t\t\t\tstep: createPgsqlGeneratedManagedStep({\n\t\t\t\t\t\tchange: {\n\t\t\t\t\t\t\t...change,\n\t\t\t\t\t\t\tkind: 'drop_foreign_key',\n\t\t\t\t\t\t\tdestructive: true,\n\t\t\t\t\t\t\tmeta: { fk: oldFk },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\tstepKey: `generator:${order}:alter-foreign-key-retire`,\n\t\t\t\t\t\torder,\n\t\t\t\t\t\tdependencyOrder: [],\n\t\t\t\t\t\tstatements: [retireStatement],\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tordinaryStepSources.push({\n\t\t\t\t\tchange,\n\t\t\t\t\tstep: createPgsqlGeneratedManagedStep({\n\t\t\t\t\t\tchange: { ...change, kind: 'add_foreign_key', destructive: false },\n\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\tstepKey: `generator:${order + 1}:alter-foreign-key-create`,\n\t\t\t\t\t\torder: order + 1,\n\t\t\t\t\t\tdependencyOrder: [],\n\t\t\t\t\t\tstatements: createStatements,\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tordinaryStepSources.push({\n\t\t\t\tchange,\n\t\t\t\tstep: createPgsqlGeneratedManagedStep({\n\t\t\t\t\tchange,\n\t\t\t\t\tdatabase,\n\t\t\t\t\tschema,\n\t\t\t\t\tstepKey: `generator:${order}`,\n\t\t\t\t\torder,\n\t\t\t\t\tdependencyOrder: [],\n\t\t\t\t\tstatements: generated.statements,\n\t\t\t\t}),\n\t\t\t});\n\t\t}\n\t\tconst ordinarySteps = ordinaryStepSources.map(({ step }) => step);\n\t\tconst lifecycleSteps: NormalizedManagedStep[] = [];\n\t\tfor (const change of material.changes.slice(ordinaryChanges.length)) {\n\t\t\tconst base = {\n\t\t\t\torder: ordinarySteps.length + lifecycleSteps.length,\n\t\t\t\tdatabase,\n\t\t\t\tschema,\n\t\t\t\ttable: change.table,\n\t\t\t};\n\t\t\tif (change.kind === 'replace_table' && change.replacement) {\n\t\t\t\tconst replacementTable = [...loaded.model.tables.values()].find(\n\t\t\t\t\t(table) => table.name === change.table,\n\t\t\t\t);\n\t\t\t\tconst replacementPostcondition = generatedPostconditionForChange({\n\t\t\t\t\tchange: {\n\t\t\t\t\t\tkind: 'create_table',\n\t\t\t\t\t\ttable: change.table,\n\t\t\t\t\t\tdestructive: false,\n\t\t\t\t\t\tdetails: `Create replacement table \"${change.table}\"`,\n\t\t\t\t\t\tmeta: { table: replacementTable },\n\t\t\t\t\t},\n\t\t\t\t\tschema,\n\t\t\t\t});\n\t\t\t\tif (replacementPostcondition === undefined)\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`generator planning refuses replacement ${change.table}: missing table postcondition`,\n\t\t\t\t\t);\n\t\t\t\tconst selector = {\n\t\t\t\t\tkind: 'replacement' as const,\n\t\t\t\t\tselector: `table:${change.table}`,\n\t\t\t\t};\n\t\t\t\tlifecycleSteps.push(\n\t\t\t\t\tlifecycleStep({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tstepKey: `generator:${base.order}:replacement-retire`,\n\t\t\t\t\t\tclassification: 'removal',\n\t\t\t\t\t\tstatements: change.replacement.retireStatements,\n\t\t\t\t\t\tselection: selector,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tlifecycleSteps.push(\n\t\t\t\t\tlifecycleStep({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\torder: base.order + 1,\n\t\t\t\t\t\tstepKey: `generator:${base.order}:replacement-create`,\n\t\t\t\t\t\tclassification: 'non-destructive',\n\t\t\t\t\t\tstatements: change.replacement.createStatements,\n\t\t\t\t\t\tselection: selector,\n\t\t\t\t\t\trequiresVacancy: true,\n\t\t\t\t\t\texpectedDeclaration: replacementPostcondition,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (change.kind === 'adopt_table' && change.adoption) {\n\t\t\t\tlifecycleSteps.push(\n\t\t\t\t\tlifecycleStep({\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tstepKey: `generator:${base.order}:adoption`,\n\t\t\t\t\t\tclassification: 'non-destructive',\n\t\t\t\t\t\tselection: { kind: 'adoption', selector: `table:${change.table}` },\n\t\t\t\t\t\texpectedDeclaration: change.adoption.declaration,\n\t\t\t\t\t\texpectedCatalogueIdentity: change.adoption.catalogueIdentity,\n\t\t\t\t\t\tclaimKind: 'adopt-intent',\n\t\t\t\t\t\tlifecycle: { kind: 'adoption', shape: change.adoption.shape },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlifecycleSteps.push(\n\t\t\t\tlifecycleStep({\n\t\t\t\t\t...base,\n\t\t\t\t\tstepKey: `generator:${base.order}`,\n\t\t\t\t\tclassification: change.classification,\n\t\t\t\t\t...(change.kind === 'adoption_refused'\n\t\t\t\t\t\t? { lifecycle: { kind: 'adoption-refused' as const } }\n\t\t\t\t\t\t: {}),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tfor (const { step, change } of ordinaryStepSources) {\n\t\t\tif (step.address?.kind !== 'table') continue;\n\t\t\tif (change?.kind !== 'readdress_table' || !change.meta?.readdress)\n\t\t\t\tcontinue;\n\t\t\tObject.assign(step as object, {\n\t\t\t\tclaimKind: 'readdress-intent',\n\t\t\t\tselection: {\n\t\t\t\t\tkind: 'readdress',\n\t\t\t\t\tselector: `table:${step.address.name}`,\n\t\t\t\t},\n\t\t\t\tlifecycle: {\n\t\t\t\t\tkind: 'readdress',\n\t\t\t\t\tdeclaration: change.meta.readdress as TableReaddressDeclaration,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst steps = linearizeGeneratedManagedStepDependencies([\n\t\t\t...ordinarySteps,\n\t\t\t...lifecycleSteps,\n\t\t]);\n\t\tconst plan = asDurableGeneratorPlan(material, steps);\n\t\tconst planDigest = transitionPlanDigest(\n\t\t\tplan as unknown as InProcessProvenPlan,\n\t\t);\n\t\tconst run: TransitionRunMetadata = {\n\t\t\trunId: `dbsp-generator-${randomUUID()}`,\n\t\t\tplanDigest,\n\t\t\ttargetContextDigest: canonicalJsonDigest({\n\t\t\t\tdatabase: await databaseId(pool),\n\t\t\t\tschema,\n\t\t\t}),\n\t\t\tdatabaseId: await databaseId(pool),\n\t\t\tcoreVersion: 'schema-differ-generator-v1',\n\t\t\tstartedAt: new Date().toISOString(),\n\t\t\treplayability: material.changes.some(\n\t\t\t\t(change) => change.classification === 'removal',\n\t\t\t)\n\t\t\t\t? 'non-replayable-generator-removal'\n\t\t\t\t: 'replayable',\n\t\t};\n\t\tif (!input.dryRun) {\n\t\t\tconst lease = await acquireTransitionLease(\n\t\t\t\tcreatePgTransitionLessor(pool),\n\t\t\t);\n\t\t\ttry {\n\t\t\t\tawait createPgTransitionRunPersister(lease.session).persist(\n\t\t\t\t\trun,\n\t\t\t\t\tplan as unknown as InProcessProvenPlan,\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tawait lease.release();\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tcompareKind: 'transitions',\n\t\t\tproveKind: 'proven',\n\t\t\tassessment: assessment(),\n\t\t\tpersisted: !input.dryRun,\n\t\t\trunId: input.dryRun ? null : run.runId,\n\t\t\tplanDigest,\n\t\t\tplan: plan as unknown as InProcessProvenPlan,\n\t\t\tsql: render({ steps }, planDigest),\n\t\t};\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n","/**\n * dbsp plan — prove a transition and, unless previewing, retain it for a later\n * apply command. This command intentionally stops before execution.\n */\n\nimport {\n\tacquirePgTransitionClient,\n\tcreatePgExecutionContract,\n\tcreatePgsqlAdapter,\n\tcreatePgTransitionLessor,\n\tcreatePgTransitionPack,\n\tcreatePgTransitionRunPersister,\n\tensureTransitionJournal,\n\tescapeDiagnosticText,\n\tgetNamingPluginForDbCasing,\n\tPgExecutionContractDerivationError,\n\tpgTargetIdentityMismatch,\n\treadPgExecutionTargetFromClient,\n\treadPgObservationContextFromLessor,\n} from '@dbsp/adapter-pgsql';\nimport {\n\tacquireTransitionLease,\n\tbindDeclarationSet,\n\tbindExecutionContract,\n\tcreateComparator,\n\tcreatePackRegistry,\n\tcreateProver,\n\tcreateTransitionRunMetadata,\n\tdeclarationSetFromModel,\n\ttype InProcessProvenPlan,\n\ttype PackRegistry,\n\tvalidateDeclarationModel,\n} from '@dbsp/core';\nimport type {\n\tCompareOutcome,\n\tExecutionContract,\n\tModelIR,\n\tObservationContext,\n\tPlanAssessment,\n\tPostgreSqlObservationTargetIdentity,\n\tTransitionRunMetadata,\n\tTransitionSessionClient,\n} from '@dbsp/types';\nimport { Command } from 'commander';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { type LoadedSchema, loadSchema } from '../utils/schema-loader.js';\n\nexport type PlanFormat = 'sql' | 'json';\nexport type PlanPersistenceState = boolean | 'indeterminate';\n\nexport interface PlanOptions {\n\treadonly db: string;\n\treadonly schemaFile: string;\n\treadonly schema?: string;\n\treadonly dryRun?: boolean;\n\treadonly format?: PlanFormat;\n}\n\nexport interface PlanResult {\n\treadonly compareKind: CompareOutcome['kind'];\n\treadonly proveKind: 'proven' | 'no-drift' | 'blocked' | 'inapplicable';\n\treadonly assessment: PlanAssessment;\n\t/** true is durable, false was not attempted, and indeterminate may have committed. */\n\treadonly persisted: PlanPersistenceState;\n\treadonly runId: string | null;\n\treadonly planDigest: string | null;\n\treadonly plan?: InProcessProvenPlan;\n\treadonly sql?: string;\n}\n\nexport class PlanPersistenceIndeterminateError extends Error {\n\treadonly runId: string;\n\treadonly result: PlanResult;\n\treadonly persistenceError: unknown;\n\treadonly cleanup: CleanupFailure;\n\n\tconstructor(\n\t\tresult: PlanResult,\n\t\tpersistenceError: unknown,\n\t\tcleanup: CleanupFailure = noCleanupFailure,\n\t) {\n\t\tconst cause =\n\t\t\tcleanup.kind === 'failed'\n\t\t\t\t? new AggregateError(\n\t\t\t\t\t\t[persistenceError, cleanup.error],\n\t\t\t\t\t\t'persistence and connection release both failed',\n\t\t\t\t\t)\n\t\t\t\t: persistenceError;\n\t\tsuper(\n\t\t\t`persistence indeterminate; inspect run ${result.runId}: ${escapeDiagnosticText(describeThrown(persistenceError))}`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'PlanPersistenceIndeterminateError';\n\t\tthis.runId = result.runId ?? '';\n\t\tthis.result = result;\n\t\tthis.persistenceError = persistenceError;\n\t\tthis.cleanup = cleanup;\n\t}\n}\n\n/** A completed plan outcome whose connection release failed afterwards. */\nexport class PlanCleanupError extends Error {\n\tconstructor(\n\t\treadonly result: PlanResult,\n\t\treadonly cleanupError: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`connection release failed after the plan outcome was determined: ${escapeDiagnosticText(describeThrown(cleanupError))}`,\n\t\t\t{ cause: cleanupError },\n\t\t);\n\t\tthis.name = 'PlanCleanupError';\n\t}\n}\n\n/** A planning failure whose declared connection release also failed. */\nclass PlanOperationAndCleanupError extends AggregateError {\n\tconstructor(\n\t\treadonly operationError: unknown,\n\t\treadonly cleanupError: unknown,\n\t) {\n\t\tsuper(\n\t\t\t[operationError, cleanupError],\n\t\t\t'planning and connection release both failed',\n\t\t\t{ cause: operationError },\n\t\t);\n\t\tthis.name = 'PlanOperationAndCleanupError';\n\t}\n}\n\ntype PlanPool = Pool;\n\n/** A release rejection is distinct from its rejection value, including undefined. */\ntype CleanupFailure =\n\t| { readonly kind: 'not-failed' }\n\t| { readonly kind: 'failed'; readonly error: unknown };\n\nconst noCleanupFailure: CleanupFailure = { kind: 'not-failed' };\n\n/**\n * A planning connection together with the action that returns its resource.\n *\n * The caller that supplies the pool decides whether it is owned, shared, or\n * otherwise managed; runPlan only invokes this declared release path.\n */\nexport interface PlanConnection {\n\treadonly pool: PlanPool;\n\treadonly release: () => Promise<void>;\n}\n\nexport interface PlanDeps {\n\treadonly createDbConnection: (db: string) => Promise<PlanConnection>;\n\treadonly loadSchema: (path: string) => Promise<LoadedSchema>;\n\treadonly ensureTransitionJournal: (pool: PlanPool) => Promise<void>;\n\treadonly captureTargetIdentity: (\n\t\tpool: PlanPool,\n\t\tschema: string | undefined,\n\t) => Promise<PostgreSqlObservationTargetIdentity>;\n\treadonly loadCurrent: (\n\t\tpool: PlanPool,\n\t\tschema: string | undefined,\n\t\texpectedTargetIdentity: PostgreSqlObservationTargetIdentity,\n\t) => Promise<ModelIR>;\n\treadonly readContext: (\n\t\tpool: PlanPool,\n\t\tschema?: string,\n\t\texpectedTargetIdentity?: PostgreSqlObservationTargetIdentity,\n\t) => Promise<ObservationContext>;\n\treadonly createPlanner: (loaded: LoadedSchema) => PlanPlanner;\n\treadonly persist: (\n\t\tpool: PlanPool,\n\t\trun: TransitionRunMetadata,\n\t\tplan: InProcessProvenPlan,\n\t) => Promise<void>;\n\treadonly buildExecutionContract: (\n\t\tpool: PlanPool,\n\t\tschema: string | undefined,\n\t\tplan: InProcessProvenPlan,\n\t\texpectedTargetIdentity: PostgreSqlObservationTargetIdentity,\n\t) => Promise<ExecutionContract>;\n}\n\nexport interface PlanPlanner {\n\treadonly compare: (\n\t\tdesired: ModelIR,\n\t\tcurrent: ModelIR,\n\t\tcontext: ObservationContext,\n\t) => CompareOutcome;\n\treadonly prove: (\n\t\tcompare: CompareOutcome,\n\t\tpool: PlanPool,\n\t\tcontext: ObservationContext,\n\t) => ReturnType<ReturnType<typeof createProver>['prove']>;\n\treadonly render: (\n\t\tplan: InProcessProvenPlan,\n\t\tcontext: ObservationContext,\n\t) => string;\n}\n\nfunction equivalenceContext(context: ObservationContext) {\n\treturn {\n\t\tengine: context.engine,\n\t\t...(context.databaseId ? { databaseId: context.databaseId } : {}),\n\t\t...(context.targetSchema ? { targetSchema: context.targetSchema } : {}),\n\t\t...(context.searchPath ? { searchPath: context.searchPath } : {}),\n\t\tproofObservationContext: context,\n\t};\n}\n\n/** The only planning-time namespace derivation; apply uses the stored clause. */\nexport function executionTargetNamespaces(\n\tplan: InProcessProvenPlan,\n\tfallbackSchema: string | undefined,\n): readonly string[] {\n\tconst namespaces = [\n\t\t...new Set(\n\t\t\tplan.steps.map((step) => {\n\t\t\t\tconst payload = step.operation.payload;\n\t\t\t\tif (\n\t\t\t\t\tpayload === null ||\n\t\t\t\t\ttypeof payload !== 'object' ||\n\t\t\t\t\tArray.isArray(payload) ||\n\t\t\t\t\ttypeof (payload as Record<string, unknown>).schema !== 'string'\n\t\t\t\t)\n\t\t\t\t\tthrow new PgExecutionContractDerivationError(\n\t\t\t\t\t\tstep.operation.ref,\n\t\t\t\t\t\tstep.operation.operationKind.name,\n\t\t\t\t\t\t'has no derivable target namespace',\n\t\t\t\t\t);\n\t\t\t\treturn (payload as Record<string, unknown>).schema as string;\n\t\t\t}),\n\t\t),\n\t];\n\tif (namespaces.length === 0 && fallbackSchema !== undefined)\n\t\tnamespaces.push(fallbackSchema);\n\treturn namespaces;\n}\n\n/** Build the PostgreSQL contract after resolving the plan's physical target. */\nexport async function buildPgExecutionContract(\n\tpool: PlanPool,\n\tschema: string | undefined,\n\tplan: InProcessProvenPlan,\n\texpectedTargetIdentity: PostgreSqlObservationTargetIdentity,\n): Promise<ExecutionContract> {\n\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\ttry {\n\t\tconst target = await readPgExecutionTargetFromClient(\n\t\t\tlease.session,\n\t\t\texecutionTargetNamespaces(plan, schema),\n\t\t);\n\t\tconst mismatch = pgTargetIdentityMismatch(\n\t\t\texpectedTargetIdentity,\n\t\t\ttarget.identity,\n\t\t);\n\t\tif (mismatch) {\n\t\t\tthrow new Error(\n\t\t\t\t`PostgreSQL target identity changed before plan persistence: ${mismatch}`,\n\t\t\t);\n\t\t}\n\t\treturn createPgExecutionContract(\n\t\t\tplan,\n\t\t\ttarget.identity,\n\t\t\ttarget.sessionProvenance,\n\t\t);\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nconst defaultPlanDeps: PlanDeps = {\n\tasync createDbConnection(db) {\n\t\tconst { pool } = await createDbConnection(db);\n\t\treturn { pool, release: () => pool.end() };\n\t},\n\tloadSchema,\n\tasync ensureTransitionJournal(pool) {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tawait ensureTransitionJournal(lease.session);\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t},\n\tasync captureTargetIdentity(pool, schema) {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\treturn (\n\t\t\t\tawait readPgExecutionTargetFromClient(lease.session, [\n\t\t\t\t\tschema ?? 'public',\n\t\t\t\t])\n\t\t\t).identity;\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t},\n\tasync loadCurrent(pool, schema, expectedTargetIdentity) {\n\t\tconst lease = await acquirePgTransitionClient(pool);\n\t\ttry {\n\t\t\tconst observed = await readPgExecutionTargetFromClient(\n\t\t\t\tlease.client as unknown as TransitionSessionClient,\n\t\t\t\t[schema ?? 'public'],\n\t\t\t);\n\t\t\tconst mismatch = pgTargetIdentityMismatch(\n\t\t\t\texpectedTargetIdentity,\n\t\t\t\tobserved.identity,\n\t\t\t);\n\t\t\tif (mismatch) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`PostgreSQL introspection target identity does not match the captured target: ${mismatch}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn await createPgsqlAdapter(lease.client, {\n\t\t\t\tborrowedClient: true,\n\t\t\t}).introspect(schema === undefined ? {} : { schema });\n\t\t} finally {\n\t\t\tlease.release();\n\t\t}\n\t},\n\tasync readContext(pool, schema, expectedTargetIdentity) {\n\t\treturn readPgObservationContextFromLessor(\n\t\t\tcreatePgTransitionLessor(pool),\n\t\t\tschema,\n\t\t\tundefined,\n\t\t\texpectedTargetIdentity,\n\t\t);\n\t},\n\tcreatePlanner(loaded) {\n\t\tconst registry = createPackRegistry([\n\t\t\tcreatePgTransitionPack({\n\t\t\t\t...(loaded.dbCasing ? { dbCasing: loaded.dbCasing } : {}),\n\t\t\t}),\n\t\t]);\n\t\tconst comparator = createComparator(registry);\n\t\tconst prover = createProver(registry);\n\t\treturn {\n\t\t\tcompare: (desired, current, context) =>\n\t\t\t\tcomparator.compare(desired, current, equivalenceContext(context)),\n\t\t\tprove: (compare, pool, context) =>\n\t\t\t\tprover.prove(compare, createPgTransitionLessor(pool), context),\n\t\t\trender: (plan, context) => renderProvenPlanSql(registry, plan, context),\n\t\t};\n\t},\n\tasync persist(pool, run, plan) {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tawait createPgTransitionRunPersister(lease.session).persist(run, plan);\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t},\n\tbuildExecutionContract: buildPgExecutionContract,\n};\n\nfunction resolvedDeps(overrides?: Partial<PlanDeps>): PlanDeps {\n\treturn { ...defaultPlanDeps, ...overrides };\n}\n\nfunction describeThrown(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction executionContractBlockedAssessment(\n\terror: PgExecutionContractDerivationError,\n): PlanAssessment {\n\treturn {\n\t\tdecision: 'blocked',\n\t\tassurance: 'unproven',\n\t\tlifecycle: 'planned',\n\t\tcontinuation: 'replan-required',\n\t\treasons: [\n\t\t\t{\n\t\t\t\tcode: 'unsupported-transition',\n\t\t\t\tchanges: [],\n\t\t\t\tscope: [],\n\t\t\t\tdetail: error.message,\n\t\t\t},\n\t\t],\n\t};\n}\n\n/** Render only a complete proven plan. This is an inspection view, never apply input. */\nexport function renderProvenPlanSql(\n\tregistry: PackRegistry,\n\tplan: InProcessProvenPlan,\n\tcontext: ObservationContext,\n): string {\n\tconst statements = plan.steps.map((step) => {\n\t\tconst resolution = registry.resolveOperation(step.operation);\n\t\tif (!resolution.ok || !resolution.semantics.renderPlanSql) {\n\t\t\tthrow new Error(\n\t\t\t\t`no SQL renderer is registered for proven operation ${step.operation.operationKind.name}`,\n\t\t\t);\n\t\t}\n\t\treturn resolution.semantics.renderPlanSql(step.operation, context);\n\t});\n\treturn [\n\t\t'-- dbsp transition plan view; apply accepts a persisted run id, never this SQL.',\n\t\t...statements.map((statement) => `${statement};`),\n\t].join('\\n');\n}\n\nexport async function runPlan(\n\toptions: PlanOptions,\n\toverrides?: Partial<PlanDeps>,\n): Promise<PlanResult> {\n\tconst deps = resolvedDeps(overrides);\n\tconst format = options.format ?? 'sql';\n\tif (format !== 'sql' && format !== 'json') {\n\t\tthrow new Error(`unsupported plan format ${format}; expected sql or json`);\n\t}\n\tconst loaded = await deps.loadSchema(options.schemaFile);\n\t// This is deliberately before comparison: an unchanged/unsupported model is\n\t// still a declaration authored for durable replay and may not silently lose a\n\t// non-JSON default during a future plan.\n\tvalidateDeclarationModel(loaded.model);\n\tconst connection = await deps.createDbConnection(options.db);\n\tconst { pool } = connection;\n\tlet result: PlanResult | undefined;\n\tlet operationError: unknown;\n\tlet failed = false;\n\ttry {\n\t\t// This binding is deliberately first: every subsequent introspection and\n\t\t// proof lease must describe the same physical PostgreSQL target.\n\t\tconst targetIdentity = await deps.captureTargetIdentity(\n\t\t\tpool,\n\t\t\toptions.schema,\n\t\t);\n\t\tawait deps.ensureTransitionJournal(pool);\n\t\tconst current = await deps.loadCurrent(\n\t\t\tpool,\n\t\t\toptions.schema,\n\t\t\ttargetIdentity,\n\t\t);\n\t\tconst context = await deps.readContext(\n\t\t\tpool,\n\t\t\toptions.schema,\n\t\t\ttargetIdentity,\n\t\t);\n\t\tconst planner = deps.createPlanner(loaded);\n\t\tconst compare = planner.compare(loaded.model, current, context);\n\t\tconst prove = await planner.prove(compare, pool, context);\n\n\t\tif (prove.kind === 'proven') {\n\t\t\tlet executionContract: ExecutionContract | undefined;\n\t\t\ttry {\n\t\t\t\texecutionContract = await deps.buildExecutionContract(\n\t\t\t\t\tpool,\n\t\t\t\t\toptions.schema,\n\t\t\t\t\tprove.plan,\n\t\t\t\t\ttargetIdentity,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof PgExecutionContractDerivationError)) throw error;\n\t\t\t\tresult = {\n\t\t\t\t\tcompareKind: compare.kind,\n\t\t\t\t\tproveKind: 'blocked',\n\t\t\t\t\tassessment: executionContractBlockedAssessment(error),\n\t\t\t\t\tpersisted: false,\n\t\t\t\t\trunId: null,\n\t\t\t\t\tplanDigest: null,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (executionContract !== undefined) {\n\t\t\t\t// Order is intentional: an id exists before an indeterminate write, while\n\t\t\t\t// rendering happens before a durable record can be stranded unseen.\n\t\t\t\tconst contractedPlan = bindExecutionContract(\n\t\t\t\t\tprove.plan,\n\t\t\t\t\texecutionContract,\n\t\t\t\t);\n\t\t\t\tconst durablePlan = bindDeclarationSet(\n\t\t\t\t\tcontractedPlan,\n\t\t\t\t\tdeclarationSetFromModel(\n\t\t\t\t\t\tloaded.model,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tengine: context.engine,\n\t\t\t\t\t\t\tdatabase: context.databaseId,\n\t\t\t\t\t\t\tschema: options.schema ?? 'public',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgetNamingPluginForDbCasing(loaded.dbCasing ?? 'preserve'),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst run = createTransitionRunMetadata(durablePlan);\n\t\t\t\tconst proofContext = prove.plan.observations.find(\n\t\t\t\t\t(observation) => observation.role === 'evidence',\n\t\t\t\t)?.context;\n\t\t\t\tif (!proofContext) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'internal error: minted proven plan has no evidence observation context',\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst sql = planner.render(durablePlan, proofContext);\n\t\t\t\tif (!options.dryRun) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait deps.persist(pool, run, durablePlan);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthrow new PlanPersistenceIndeterminateError(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcompareKind: compare.kind,\n\t\t\t\t\t\t\t\tproveKind: prove.kind,\n\t\t\t\t\t\t\t\tassessment: prove.assessment,\n\t\t\t\t\t\t\t\tpersisted: 'indeterminate',\n\t\t\t\t\t\t\t\trunId: run.runId,\n\t\t\t\t\t\t\t\tplanDigest: run.planDigest,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult = {\n\t\t\t\t\tcompareKind: compare.kind,\n\t\t\t\t\tproveKind: prove.kind,\n\t\t\t\t\tassessment: prove.assessment,\n\t\t\t\t\tpersisted: !options.dryRun,\n\t\t\t\t\trunId: options.dryRun ? null : run.runId,\n\t\t\t\t\tplanDigest: run.planDigest,\n\t\t\t\t\tplan: durablePlan,\n\t\t\t\t\tsql,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tif (prove.kind === 'no-drift') {\n\t\t\tresult = {\n\t\t\t\tcompareKind: compare.kind,\n\t\t\t\tproveKind: prove.kind,\n\t\t\t\tassessment: prove.assessment,\n\t\t\t\tpersisted: false,\n\t\t\t\trunId: null,\n\t\t\t\tplanDigest: null,\n\t\t\t};\n\t\t} else if (prove.kind !== 'proven') {\n\t\t\tresult = {\n\t\t\t\tcompareKind: compare.kind,\n\t\t\t\tproveKind: prove.kind,\n\t\t\t\tassessment: prove.assessment,\n\t\t\t\tpersisted: false,\n\t\t\t\trunId: null,\n\t\t\t\tplanDigest: null,\n\t\t\t};\n\t\t}\n\t} catch (error) {\n\t\tfailed = true;\n\t\toperationError = error;\n\t}\n\n\tlet cleanup: CleanupFailure = noCleanupFailure;\n\ttry {\n\t\tawait connection.release();\n\t} catch (error) {\n\t\tcleanup = { kind: 'failed', error };\n\t}\n\n\tif (failed) {\n\t\tif (operationError instanceof PlanPersistenceIndeterminateError) {\n\t\t\tthrow new PlanPersistenceIndeterminateError(\n\t\t\t\toperationError.result,\n\t\t\t\toperationError.persistenceError,\n\t\t\t\tcleanup,\n\t\t\t);\n\t\t}\n\t\tif (cleanup.kind === 'failed') {\n\t\t\tthrow new PlanOperationAndCleanupError(operationError, cleanup.error);\n\t\t}\n\t\tthrow operationError;\n\t}\n\tif (cleanup.kind === 'failed') {\n\t\tthrow new PlanCleanupError(result as PlanResult, cleanup.error);\n\t}\n\treturn result as PlanResult;\n}\n\nexport function formatPlanJson(result: PlanResult, dryRun: boolean) {\n\treturn {\n\t\tcompareKind: result.compareKind,\n\t\tproveKind: result.proveKind,\n\t\tassessment: result.assessment,\n\t\tpersisted: result.persisted,\n\t\trunId: result.runId,\n\t\tplanDigest: result.planDigest,\n\t\t...(result.plan ? { plan: result.plan } : {}),\n\t\t...(result.sql ? { sql: result.sql } : {}),\n\t\t...(dryRun && result.proveKind === 'proven'\n\t\t\t? { preview: 'non-executable; no durable dbsp record' }\n\t\t\t: {}),\n\t};\n}\n\nexport function formatPlanHuman(result: PlanResult, dryRun: boolean): string {\n\tif (result.proveKind === 'proven') {\n\t\treturn [\n\t\t\tdryRun\n\t\t\t\t? 'Proven transition preview (non-executable; no durable dbsp record):'\n\t\t\t\t: 'Proven transition plan:',\n\t\t\t// Every operation renderer converges on result.sql before this human-only\n\t\t\t// view, so database-sourced SQL cannot bypass terminal escaping here.\n\t\t\t...(result.sql === undefined ? [] : [escapeDiagnosticText(result.sql)]),\n\t\t\t...(result.plan?.executionContract\n\t\t\t\t? [\n\t\t\t\t\t\t'Execution contract:',\n\t\t\t\t\t\t...result.plan.executionContract.requirements.map(\n\t\t\t\t\t\t\t(requirement) =>\n\t\t\t\t\t\t\t\t` ${escapeDiagnosticText(JSON.stringify(requirement))}`,\n\t\t\t\t\t\t),\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t\tdryRun\n\t\t\t\t? `Preview digest: ${result.planDigest}`\n\t\t\t\t: `Run id: ${result.runId}\\nPlan digest: ${result.planDigest}`,\n\t\t]\n\t\t\t.filter((line): line is string => line !== undefined)\n\t\t\t.join('\\n');\n\t}\n\tif (result.proveKind === 'no-drift') {\n\t\treturn 'Database already matches the target; nothing was persisted.';\n\t}\n\treturn `No durable plan was created.\\n${escapeDiagnosticText(JSON.stringify(result.assessment, null, 2))}`;\n}\n\nfunction preservedPlanResult(\n\terror: unknown,\n\tfallback?: PlanResult,\n): PlanResult | undefined {\n\tif (error instanceof PlanPersistenceIndeterminateError) return error.result;\n\tif (error instanceof PlanCleanupError) return error.result;\n\treturn fallback;\n}\n\nfunction primaryPlanError(error: unknown): unknown {\n\tif (error instanceof PlanPersistenceIndeterminateError) {\n\t\treturn error.persistenceError;\n\t}\n\tif (error instanceof PlanCleanupError) return error.cleanupError;\n\tif (error instanceof PlanOperationAndCleanupError) {\n\t\treturn error.operationError;\n\t}\n\treturn error;\n}\n\nfunction cleanupFailure(error: unknown): CleanupFailure {\n\tif (error instanceof PlanPersistenceIndeterminateError) {\n\t\treturn error.cleanup;\n\t}\n\tif (error instanceof PlanCleanupError) {\n\t\treturn { kind: 'failed', error: error.cleanupError };\n\t}\n\tif (error instanceof PlanOperationAndCleanupError) {\n\t\treturn { kind: 'failed', error: error.cleanupError };\n\t}\n\treturn noCleanupFailure;\n}\n\n/** The stable error contract for both planning and post-outcome failures. */\nexport function formatPlanFailureJson(error: unknown, fallback?: PlanResult) {\n\tconst result = preservedPlanResult(error, fallback);\n\tconst cleanupError = cleanupFailure(error);\n\treturn {\n\t\tcompareKind: result?.compareKind ?? null,\n\t\tproveKind: result?.proveKind ?? null,\n\t\tassessment: result?.assessment ?? null,\n\t\tpersisted: result?.persisted ?? false,\n\t\trunId: result?.runId ?? null,\n\t\tplanDigest: result?.planDigest ?? null,\n\t\terror: describeThrown(primaryPlanError(error)),\n\t\t...(cleanupError.kind === 'not-failed'\n\t\t\t? {}\n\t\t\t: { cleanupError: describeThrown(cleanupError.error) }),\n\t};\n}\n\nfunction formatPlanFailureHuman(error: unknown, fallback?: PlanResult): string {\n\tconst result = preservedPlanResult(error, fallback);\n\tconst fields = result\n\t\t? [\n\t\t\t\tresult.persisted === true\n\t\t\t\t\t? 'A durable plan was created before this failure.'\n\t\t\t\t\t: result.persisted === 'indeterminate'\n\t\t\t\t\t\t? 'Persistence is indeterminate; inspect the minted run before retrying.'\n\t\t\t\t\t\t: 'No durable plan was created.',\n\t\t\t\t...(result.runId ? [`Run id: ${result.runId}`] : []),\n\t\t\t\t...(result.planDigest ? [`Plan digest: ${result.planDigest}`] : []),\n\t\t\t]\n\t\t: [];\n\tconst cleanupError = cleanupFailure(error);\n\treturn [\n\t\t`❌ ${escapeDiagnosticText(describeThrown(primaryPlanError(error)))}`,\n\t\t...fields,\n\t\t...(cleanupError.kind === 'not-failed'\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t`Connection release also failed: ${escapeDiagnosticText(describeThrown(cleanupError.error))}`,\n\t\t\t\t]),\n\t].join('\\n');\n}\n\nfunction printHumanResult(result: PlanResult, dryRun: boolean): void {\n\tconsole.log(formatPlanHuman(result, dryRun));\n}\n\nexport function exitCodeForPlanResult(result: PlanResult): 0 | 1 {\n\treturn result.proveKind === 'blocked' || result.proveKind === 'inapplicable'\n\t\t? 1\n\t\t: 0;\n}\n\nexport const planCommand = new Command('plan')\n\t.description('Prove and persist a transition plan without applying it')\n\t.argument('<schema-file>', 'Schema DSL file')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema <name>', 'Database schema name', 'public')\n\t.option('--dry-run', 'Prove and render without persisting a transition run')\n\t.option('--format <format>', 'Output format: sql or json', 'sql')\n\t.exitOverride()\n\t// The root handler owns parse-error presentation. Suppress Commander's\n\t// eager stderr write so --format json remains a single JSON document.\n\t.configureOutput({ writeErr: () => {} })\n\t.action(\n\t\tasync (\n\t\t\tschemaFile: string,\n\t\t\toptions: {\n\t\t\t\tdb: string;\n\t\t\t\tschema?: string;\n\t\t\t\tdryRun?: boolean;\n\t\t\t\tformat?: PlanFormat;\n\t\t\t},\n\t\t) => {\n\t\t\tlet result: PlanResult | undefined;\n\t\t\ttry {\n\t\t\t\tresult = await runPlan({ ...options, schemaFile });\n\t\t\t\tif (options.format === 'json') {\n\t\t\t\t\tprintCliJson(formatPlanJson(result, options.dryRun === true));\n\t\t\t\t} else {\n\t\t\t\t\tprintHumanResult(result, options.dryRun === true);\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = exitCodeForPlanResult(result);\n\t\t\t} catch (error) {\n\t\t\t\tif (options.format === 'json') {\n\t\t\t\t\tprintCliJson(formatPlanFailureJson(error, result));\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(formatPlanFailureHuman(error, result));\n\t\t\t\t}\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}\n\t\t},\n\t);\n","/** Shared command-output shape for refusals that do not append a ledger event. */\n\nimport { escapeDiagnosticText } from '@dbsp/adapter-pgsql';\nimport type { LedgerAddress, LedgerRefusal } from '@dbsp/types';\nimport { REFUSAL_VOCABULARY, type RefusalCode } from '@dbsp/types';\n\n/** `recorded-plan` is a command-path state, never a durable ledger state. */\nexport type PreAppendRefusalState = LedgerRefusal['state'] | 'recorded-plan';\n\n/**\n * Unlike a durable LedgerRefusal, this document also carries the target whose\n * refusal prevented an append. Keep the prose in REFUSAL_VOCABULARY.\n */\nexport interface PreAppendRefusal {\n\treadonly address: LedgerAddress;\n\treadonly refusal: {\n\t\treadonly code: RefusalCode;\n\t\treadonly cause: string;\n\t\treadonly state: PreAppendRefusalState;\n\t\treadonly withheldAuthority: string;\n\t\treadonly resolvingCommand: string;\n\t};\n}\n\nexport function preAppendRefusalFor(\n\tcode: RefusalCode,\n\tinput: {\n\t\treadonly address: LedgerAddress;\n\t\treadonly state: PreAppendRefusalState;\n\t},\n): PreAppendRefusal {\n\treturn {\n\t\taddress: input.address,\n\t\trefusal: { code, ...REFUSAL_VOCABULARY[code], state: input.state },\n\t};\n}\n\n/** Human output mirrors the JSON document's four actionable refusal facts. */\nexport function formatPreAppendRefusalHuman(\n\tline: string,\n\trefusal: PreAppendRefusal,\n): string {\n\treturn [\n\t\tline,\n\t\t`refusal: ${escapeDiagnosticText(refusal.refusal.cause)}`,\n\t\t`address: ${escapeDiagnosticText(JSON.stringify(refusal.address))}`,\n\t\t`state: ${escapeDiagnosticText(refusal.refusal.state)}`,\n\t\t`withheld authority: ${escapeDiagnosticText(refusal.refusal.withheldAuthority)}`,\n\t\t`resolving command: ${escapeDiagnosticText(refusal.refusal.resolvingCommand)}`,\n\t].join('\\n');\n}\n","/**\n * ARCH-002 Block 3+4+5: Generate Command\n * CLI-DDL: Added DDL generation target\n * ARCH-005: Migrated to schema() API, removed legacy generators\n *\n * dbsp generate <target> - Generate code from schema.\n *\n * Targets:\n * - ddl: Generate SQL DDL (CREATE TABLE statements)\n *\n * Deprecated targets (removed in ARCH-005):\n * - manifest: Removed legacy manifest generator\n * - kysely: Removed legacy Kysely generator\n */\n\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport type { DbCasing, DialectCapabilities } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { loadSchema, loadSchemaFromCwd } from '../utils/schema-loader.js';\n\nexport type GenerateCasingOption = 'snake' | 'camel' | 'none';\n\nconst POSTGRESQL_VERSION_USAGE =\n\t'expected a PostgreSQL major version or dotted release version such as 14, 14.2, or 14.2.1; PostgreSQL 10 or later is supported';\n\nexport const generateCommand = new Command('generate')\n\t.description('Generate code from schema')\n\t.argument('<target>', 'Target to generate: ddl')\n\t.option('-s, --schema <path>', 'Path to schema file (default: auto-detect)')\n\t.option('-o, --out <dir>', 'Output directory (default: ./generated/<target>)')\n\t.option('--output <dir>', 'Output directory (alias for --out)')\n\t.option('--drop', 'Include DROP TABLE IF EXISTS statements (ddl only)')\n\t.option('--schema-name <name>', 'Database schema name (ddl only)')\n\t.option(\n\t\t'--postgresql-version <version>',\n\t\t'Target PostgreSQL major or dotted release version (for example, 14 or 14.2; ddl only)',\n\t)\n\t.option(\n\t\t'--dialect <name>',\n\t\t'Database dialect: postgresql | mysql | sqlite | mssql (default: postgresql)',\n\t)\n\t.option(\n\t\t'--casing <type>',\n\t\t'Column naming: snake | camel | none (default: based on dialect)',\n\t)\n\t.action(\n\t\tasync (\n\t\t\ttarget: string,\n\t\t\toptions: {\n\t\t\t\tschema?: string;\n\t\t\t\tout?: string;\n\t\t\t\toutput?: string;\n\t\t\t\tdrop?: boolean;\n\t\t\t\tschemaName?: string;\n\t\t\t\tpostgresqlVersion?: string;\n\t\t\t\tdialect?: string;\n\t\t\t\tcasing?: GenerateCasingOption;\n\t\t\t},\n\t\t) => {\n\t\t\ttry {\n\t\t\t\t// Reject the target BEFORE loading the schema: loading it executes the\n\t\t\t\t// user's schema module, and there is no reason to run their code for a\n\t\t\t\t// target we are going to refuse anyway.\n\t\t\t\tif (target === 'manifest' || target === 'kysely') {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Target '${target}' has been removed. ` +\n\t\t\t\t\t\t\t`Use 'ddl' for SQL generation, or the 'introspect' command to generate a schema file.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (target !== 'ddl') {\n\t\t\t\t\tthrow new Error(`Unknown target: ${target}. Available targets: ddl`);\n\t\t\t\t}\n\n\t\t\t\tlet targetDialectCapabilities: DialectCapabilities | undefined;\n\t\t\t\tif (options.postgresqlVersion !== undefined) {\n\t\t\t\t\tconst { derivePostgresqlCapabilitiesForVersion } = await import(\n\t\t\t\t\t\t'@dbsp/adapter-pgsql'\n\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttargetDialectCapabilities = derivePostgresqlCapabilitiesForVersion(\n\t\t\t\t\t\t\toptions.postgresqlVersion,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst reason = error instanceof Error ? ` ${error.message}` : '';\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Invalid --postgresql-version \"${options.postgresqlVersion}\": ${POSTGRESQL_VERSION_USAGE}.${reason}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Load schema (ARCH-005: only schema() format supported)\n\t\t\t\tlet schema: Awaited<ReturnType<typeof loadSchema>>;\n\t\t\t\tlet schemaPath: string;\n\n\t\t\t\tif (options.schema) {\n\t\t\t\t\tschema = await loadSchema(options.schema);\n\t\t\t\t\tschemaPath = options.schema;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await loadSchemaFromCwd();\n\t\t\t\t\tschema = result.schema;\n\t\t\t\t\tschemaPath = result.path;\n\t\t\t\t}\n\n\t\t\t\t// For DDL without --output, we output to stdout so use stderr for info\n\t\t\t\tconst outputPath = options.out ?? options.output;\n\t\t\t\tconst useStdout = target === 'ddl' && !outputPath;\n\t\t\t\tconst log = useStdout ? console.error : console.log;\n\n\t\t\t\tlog(`📄 Loaded schema from: ${schemaPath}`);\n\n\t\t\t\t// Validate dialect option\n\t\t\t\tconst dialect = options.dialect ?? 'postgresql';\n\t\t\t\tif (!isDialectSupported(dialect)) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`⚠️ Warning: Only 'postgresql' dialect is currently supported. Using postgresql.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Generate based on target\n\t\t\t\tswitch (target) {\n\t\t\t\t\tcase 'ddl': {\n\t\t\t\t\t\t// Determine casing: explicit option > schema export > dialect default.\n\t\t\t\t\t\tconst dbCasing =\n\t\t\t\t\t\t\tmapCasingToDbCasing(options.casing) ??\n\t\t\t\t\t\t\tschema.dbCasing ??\n\t\t\t\t\t\t\t('snake_case' as const);\n\t\t\t\t\t\tconst casingLabel = formatGenerateCasingLabel(dbCasing);\n\n\t\t\t\t\t\t// Import adapter from adapter-pgsql (compile-only, no DB connection needed)\n\t\t\t\t\t\tconst { createPgsqlCompileOnlyAdapter } = await import(\n\t\t\t\t\t\t\t'@dbsp/adapter-pgsql'\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst adapter = createPgsqlCompileOnlyAdapter({\n\t\t\t\t\t\t\tdbCasing,\n\t\t\t\t\t\t\t...(options.schemaName ? { schemaName: options.schemaName } : {}),\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// ARCH-005: Use schema.model directly (already ModelIR)\n\t\t\t\t\t\t\tconst ddlStatements = adapter.generateDDL(schema.model, {\n\t\t\t\t\t\t\t\t...(options.drop !== undefined && {\n\t\t\t\t\t\t\t\t\tincludeDropStatements: options.drop,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...(targetDialectCapabilities !== undefined && {\n\t\t\t\t\t\t\t\t\tdialectCapabilities: targetDialectCapabilities,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tconst ddlContent = ddlStatements.join('\\n\\n');\n\t\t\t\t\t\t\tconst outputPath = options.out ?? options.output;\n\n\t\t\t\t\t\t\tif (outputPath) {\n\t\t\t\t\t\t\t\t// Write to file if --output is specified\n\t\t\t\t\t\t\t\tconst outPath = outputPath.endsWith('.sql')\n\t\t\t\t\t\t\t\t\t? resolve(process.cwd(), outputPath)\n\t\t\t\t\t\t\t\t\t: resolve(process.cwd(), outputPath, 'schema.sql');\n\n\t\t\t\t\t\t\t\tmkdirSync(dirname(outPath), { recursive: true });\n\t\t\t\t\t\t\t\twriteFileSync(outPath, ddlContent, 'utf-8');\n\n\t\t\t\t\t\t\t\tconsole.log(`✅ Generated DDL: ${outPath}`);\n\t\t\t\t\t\t\t\tconsole.log(` Tables: ${schema.tableNames.length}`);\n\t\t\t\t\t\t\t\tconsole.log(` Statements: ${ddlStatements.length}`);\n\t\t\t\t\t\t\t\tconsole.log(` Casing: ${casingLabel}`);\n\t\t\t\t\t\t\t\tif (options.drop) {\n\t\t\t\t\t\t\t\t\tconsole.log(` Includes DROP statements`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (options.schemaName) {\n\t\t\t\t\t\t\t\t\tconsole.log(` Schema: ${options.schemaName}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Output DDL to stdout (for piping)\n\t\t\t\t\t\t\t\t// Info messages (schema loaded) went to stderr\n\t\t\t\t\t\t\t\tconsole.log(ddlContent);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconsole.error(`❌ ${message}`);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t},\n\t);\n\nexport function isDialectSupported(dialect: string): dialect is 'postgresql' {\n\treturn dialect === 'postgresql';\n}\n\nexport function mapCasingToDbCasing(\n\tcasing: GenerateCasingOption | undefined,\n): DbCasing | undefined {\n\tswitch (casing) {\n\t\tcase 'snake':\n\t\t\treturn 'snake_case';\n\t\tcase 'camel':\n\t\t\treturn 'camelCase';\n\t\tcase 'none':\n\t\t\treturn 'preserve';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction formatGenerateCasingLabel(\n\tdbCasing: DbCasing,\n): 'snake' | 'camel' | 'none' {\n\tswitch (dbCasing) {\n\t\tcase 'snake_case':\n\t\t\treturn 'snake';\n\t\tcase 'camelCase':\n\t\t\treturn 'camel';\n\t\tcase 'preserve':\n\t\t\treturn 'none';\n\t}\n}\n","/** Read managed-ledger state without appending an event or repairing storage. */\n\nimport { isDeepStrictEqual } from 'node:util';\nimport {\n\tcreatePgTransitionLessor,\n\tDBSP_LEDGER_EVENT_TABLE,\n\tescapeDiagnosticText,\n\treadPgCatalogueIdentity,\n\treadPgLedgerAddressChain,\n\treadPgLedgerMarker,\n} from '@dbsp/adapter-pgsql';\nimport { acquireTransitionLease, projectLedgerChain } from '@dbsp/core';\nimport {\n\tcanonicalResourceParent,\n\ttype LedgerAddress,\n\ttype LedgerChainProjection,\n\ttype LedgerHome,\n\ttype LedgerStableState,\n\ttype RefusalCode,\n} from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson, serializeCliJson } from '../utils/output.js';\n\nexport interface InspectOptions {\n\treadonly db: string;\n\treadonly schema?: string;\n\treadonly kind?: string;\n\t/** Parent selector for column/index/constraint resources, e.g. table:orders. */\n\treadonly parent?: string;\n\t/** Select the database ledger (currently for database-scoped extensions). */\n\treadonly databaseLedger?: boolean;\n\treadonly format?: 'text' | 'json';\n}\n\nexport interface InspectResult {\n\treadonly address?: LedgerAddress;\n\treadonly ledger: LedgerHome;\n\treadonly marker:\n\t\t| Awaited<ReturnType<typeof readPgLedgerMarker>>\n\t\t| { readonly kind: 'unreadable'; readonly reason: string };\n\treadonly projection?: ReturnType<typeof projectLedgerChain>;\n\t/**\n\t * A terminal ledger refusal remains a diagnostic after its claim is closed.\n\t * It is deliberately derived from the immutable chain: inspect must not\n\t * append a second event merely to explain an earlier refusal.\n\t */\n\treadonly refusal?: {\n\t\treadonly code: RefusalCode;\n\t\treadonly cause: string;\n\t\treadonly address: LedgerAddress;\n\t\treadonly state: LedgerStableState;\n\t\treadonly withheldAuthority: string;\n\t\treadonly resolvingCommand: string;\n\t};\n\t/** A selected address exposes an interrupted re-address pair without repair. */\n\treadonly readdressPair?: {\n\t\treadonly pairId: string;\n\t\treadonly state: 'open';\n\t};\n\treadonly live:\n\t\t| { readonly kind: 'not-requested' }\n\t\t| { readonly kind: 'present'; readonly catalogueIdentity: unknown }\n\t\t| { readonly kind: 'absent' }\n\t\t| { readonly kind: 'catalogue-unavailable'; readonly reason: string };\n\t/** Comparison is derived from reads only; inspect never repairs drift. */\n\treadonly liveDrift?:\n\t\t| { readonly kind: 'matches-ledger' }\n\t\t| { readonly kind: 'catalogue-drift'; readonly detail: string }\n\t\t| { readonly kind: 'not-comparable'; readonly detail: string };\n\t/** Identifies the failed read path without mislabelling it as catalogue drift. */\n\treadonly failedSubsystem?:\n\t\t| { readonly subsystem: 'ledger'; readonly reason: string }\n\t\t| { readonly subsystem: 'catalogue'; readonly reason: string };\n\t/** Present for an unqualified inspect; no read path creates or repairs it. */\n\treadonly addresses?: readonly LedgerAddress[];\n}\n\n/**\n * Make a terminal `refused` event actionable without inventing mutable state.\n * A refused claim closes the chain at its prior stable state, so a fresh\n * generator-path apply is the only command that can seek new authority.\n */\nexport function inspectRefusal(\n\tprojection: LedgerChainProjection | undefined,\n): InspectResult['refusal'] | undefined {\n\tif (projection?.kind !== 'projected-ledger-chain') return undefined;\n\tconst predecessors = new Set(\n\t\tprojection.events\n\t\t\t.map((event) => event.predecessor)\n\t\t\t.filter(\n\t\t\t\t(predecessor): predecessor is string => predecessor !== undefined,\n\t\t\t),\n\t);\n\tconst terminals = projection.events.filter(\n\t\t(event) => !predecessors.has(event.eventId),\n\t);\n\tconst refused = terminals.length === 1 ? terminals[0] : undefined;\n\tif (refused?.eventKind !== 'refused' || refused.refusal === undefined)\n\t\treturn undefined;\n\treturn {\n\t\tcode: refused.refusal.code,\n\t\tcause: refused.refusal.cause,\n\t\taddress: projection.address,\n\t\tstate: refused.refusal.state,\n\t\twithheldAuthority: refused.refusal.withheldAuthority,\n\t\tresolvingCommand: refused.refusal.resolvingCommand,\n\t};\n}\n\nfunction inspectLiveDrift(\n\tprojection: InspectResult['projection'],\n\tlive: Awaited<ReturnType<typeof readPgCatalogueIdentity>>,\n): NonNullable<InspectResult['liveDrift']> {\n\tif (projection?.kind !== 'projected-ledger-chain')\n\t\treturn { kind: 'not-comparable', detail: 'ledger chain is unavailable' };\n\tconst terminalIds = new Set(\n\t\tprojection.events\n\t\t\t.map((event) => event.predecessor)\n\t\t\t.filter((value): value is string => value !== undefined),\n\t);\n\tconst terminal = projection.events.find(\n\t\t(event) => !terminalIds.has(event.eventId),\n\t);\n\tif (!terminal?.catalogueIdentity)\n\t\treturn {\n\t\t\tkind: 'not-comparable',\n\t\t\tdetail: 'ledger terminal has no catalogue identity',\n\t\t};\n\tif (!live?.catalogueIdentity)\n\t\treturn {\n\t\t\tkind: 'catalogue-drift',\n\t\t\tdetail:\n\t\t\t\t'ledger records a present catalogue identity but the object is absent',\n\t\t};\n\treturn isDeepStrictEqual(terminal.catalogueIdentity, live.catalogueIdentity)\n\t\t? { kind: 'matches-ledger' }\n\t\t: {\n\t\t\t\tkind: 'catalogue-drift',\n\t\t\t\tdetail: 'live catalogue identity differs from the ledger terminal',\n\t\t\t};\n}\n\n/** Human inspect output is intentionally the same escaped document as JSON. */\nexport function renderInspectHuman(result: InspectResult): string {\n\treturn serializeCliJson(result);\n}\n\nfunction quoteIdentifier(value: string): string {\n\treturn `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\nasync function readLedgerAddresses(\n\tlease: {\n\t\tquery(\n\t\t\tsql: string,\n\t\t\tparams?: unknown,\n\t\t): Promise<{ rows: readonly Record<string, unknown>[] }>;\n\t},\n\tledger: LedgerHome,\n): Promise<readonly LedgerAddress[]> {\n\tconst schema = ledger.scope === 'database' ? 'dbsp_meta' : ledger.schema;\n\tif (!schema) throw new Error('schema ledger target is missing its schema');\n\tconst rows = await lease.query(\n\t\t`SELECT DISTINCT address_engine, address_database, address_schema, address_parent, address_kind, address_name FROM ${quoteIdentifier(schema)}.${quoteIdentifier(DBSP_LEDGER_EVENT_TABLE)} ORDER BY address_engine, address_database, address_schema, address_kind, address_name`,\n\t);\n\treturn rows.rows.map((row) => {\n\t\tif (\n\t\t\ttypeof row.address_engine !== 'string' ||\n\t\t\ttypeof row.address_database !== 'string' ||\n\t\t\ttypeof row.address_schema !== 'string' ||\n\t\t\ttypeof row.address_kind !== 'string' ||\n\t\t\ttypeof row.address_name !== 'string'\n\t\t)\n\t\t\tthrow new Error('ledger address is unreadable');\n\t\treturn {\n\t\t\tscope: ledger.scope,\n\t\t\tengine: row.address_engine,\n\t\t\tdatabase: row.address_database,\n\t\t\t...(row.address_schema === '' ? {} : { schema: row.address_schema }),\n\t\t\t...(row.address_parent == null\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tparent:\n\t\t\t\t\t\t\ttypeof row.address_parent === 'string'\n\t\t\t\t\t\t\t\t? JSON.parse(row.address_parent)\n\t\t\t\t\t\t\t\t: (row.address_parent as LedgerAddress),\n\t\t\t\t\t}),\n\t\t\tkind: row.address_kind as LedgerAddress['kind'],\n\t\t\tname: row.address_name,\n\t\t};\n\t});\n}\n\nfunction addressParts(\n\tvalue: string,\n\tdefaultKind: string,\n): {\n\tkind: string;\n\tname: string;\n} {\n\tconst separator = value.indexOf(':');\n\tif (separator < 1) return { kind: defaultKind, name: value };\n\treturn { kind: value.slice(0, separator), name: value.slice(separator + 1) };\n}\n\n/** Parse the compact inspect selector; parents remain intentionally explicit later. */\nexport function inspectAddress(\n\tdatabase: string,\n\tschema: string,\n\tselector: string,\n\tkind = 'table',\n\tparentSelector?: string,\n\tscope: LedgerAddress['scope'] = 'schema',\n): LedgerAddress {\n\tconst parsed = addressParts(selector, kind);\n\tif (!parsed.name) throw new Error('inspect address name must not be empty');\n\tif (!parsed.kind) throw new Error('inspect address kind must not be empty');\n\tconst parent = parentSelector\n\t\t? addressParts(parentSelector, 'table')\n\t\t: undefined;\n\tif (parent && (!parent.kind || !parent.name))\n\t\tthrow new Error('inspect parent address must be kind:name');\n\tif (\n\t\t!parent &&\n\t\t['column', 'index', 'constraint', 'policy'].includes(parsed.kind)\n\t)\n\t\tthrow new Error(\n\t\t\t`inspect address ${parsed.kind}:${parsed.name} requires --parent <kind:name>`,\n\t\t);\n\treturn {\n\t\tscope,\n\t\tengine: 'postgresql',\n\t\tdatabase,\n\t\t...(scope === 'schema' ? { schema } : {}),\n\t\t...(parent\n\t\t\t? {\n\t\t\t\t\tparent: canonicalResourceParent({\n\t\t\t\t\t\tengine: 'postgresql',\n\t\t\t\t\t\tdatabase,\n\t\t\t\t\t\t...(scope === 'schema' ? { schema } : {}),\n\t\t\t\t\t\tkind: parent.kind as LedgerAddress['kind'],\n\t\t\t\t\t\tname: parent.name,\n\t\t\t\t\t}),\n\t\t\t\t}\n\t\t\t: {}),\n\t\tkind: parsed.kind as LedgerAddress['kind'],\n\t\tname: parsed.name,\n\t};\n}\n\nexport async function runInspect(\n\tselector: string | undefined,\n\toptions: InspectOptions,\n): Promise<InspectResult> {\n\tconst { pool } = await createDbConnection(options.db);\n\tconst schema = options.schema ?? 'public';\n\tconst ledger: LedgerHome = options.databaseLedger\n\t\t? { scope: 'database' }\n\t\t: { scope: 'schema', schema };\n\ttry {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tlet marker: InspectResult['marker'];\n\t\t\ttry {\n\t\t\t\tmarker = await readPgLedgerMarker(lease.session, ledger);\n\t\t\t} catch (error) {\n\t\t\t\tmarker = {\n\t\t\t\t\tkind: 'unreadable',\n\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!selector) {\n\t\t\t\ttry {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tledger,\n\t\t\t\t\t\tmarker,\n\t\t\t\t\t\taddresses: await readLedgerAddresses(lease.session, ledger),\n\t\t\t\t\t\tlive: { kind: 'not-requested' },\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tledger,\n\t\t\t\t\t\tmarker,\n\t\t\t\t\t\taddresses: [],\n\t\t\t\t\t\tlive: {\n\t\t\t\t\t\t\tkind: 'catalogue-unavailable',\n\t\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfailedSubsystem: {\n\t\t\t\t\t\t\tsubsystem: 'ledger',\n\t\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst databaseRow = await lease.session.query(\n\t\t\t\t'SELECT pg_catalog.current_database() AS database',\n\t\t\t);\n\t\t\tconst database = databaseRow.rows[0]?.database;\n\t\t\tif (typeof database !== 'string')\n\t\t\t\tthrow new Error('PostgreSQL current_database() is unreadable');\n\t\t\tconst address = inspectAddress(\n\t\t\t\tdatabase,\n\t\t\t\tschema,\n\t\t\t\tselector,\n\t\t\t\toptions.kind,\n\t\t\t\toptions.parent,\n\t\t\t\tledger.scope,\n\t\t\t);\n\t\t\tlet projection: InspectResult['projection'];\n\t\t\ttry {\n\t\t\t\tprojection = projectLedgerChain(\n\t\t\t\t\tawait readPgLedgerAddressChain(lease.session, ledger, address),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\t// A missing/malformed ledger is a readable diagnostic, never a reason\n\t\t\t\t// for inspect to create its structures.\n\t\t\t\treturn {\n\t\t\t\t\taddress,\n\t\t\t\t\tledger,\n\t\t\t\t\tmarker,\n\t\t\t\t\tlive: { kind: 'not-requested' },\n\t\t\t\t\tliveDrift: {\n\t\t\t\t\t\tkind: 'not-comparable',\n\t\t\t\t\t\tdetail: 'ledger chain is unavailable',\n\t\t\t\t\t},\n\t\t\t\t\tfailedSubsystem: {\n\t\t\t\t\t\tsubsystem: 'ledger',\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst live = await readPgCatalogueIdentity(lease.session, address);\n\t\t\t\tconst refusal = inspectRefusal(projection);\n\t\t\t\tconst openReaddress =\n\t\t\t\t\tprojection?.kind === 'projected-ledger-chain' &&\n\t\t\t\t\tprojection.openClaim?.kind === 'readdress-intent' &&\n\t\t\t\t\tprojection.openClaim.event.pairId\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpairId: projection.openClaim.event.pairId,\n\t\t\t\t\t\t\t\tstate: 'open' as const,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\t\t\t\treturn {\n\t\t\t\t\taddress,\n\t\t\t\t\tledger,\n\t\t\t\t\tmarker,\n\t\t\t\t\tprojection,\n\t\t\t\t\t...(refusal === undefined ? {} : { refusal }),\n\t\t\t\t\t...(openReaddress === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { readdressPair: openReaddress }),\n\t\t\t\t\tliveDrift: inspectLiveDrift(projection, live),\n\t\t\t\t\tlive: live?.catalogueIdentity\n\t\t\t\t\t\t? { kind: 'present', catalogueIdentity: live.catalogueIdentity }\n\t\t\t\t\t\t: { kind: 'absent' },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\taddress,\n\t\t\t\t\tledger,\n\t\t\t\t\tmarker,\n\t\t\t\t\tprojection,\n\t\t\t\t\tlive: {\n\t\t\t\t\t\tkind: 'catalogue-unavailable',\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t\tliveDrift: {\n\t\t\t\t\t\tkind: 'not-comparable',\n\t\t\t\t\t\tdetail: 'live catalogue read is unavailable',\n\t\t\t\t\t},\n\t\t\t\t\tfailedSubsystem: {\n\t\t\t\t\t\tsubsystem: 'catalogue',\n\t\t\t\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n\nexport const inspectCommand = new Command('inspect')\n\t.description(\n\t\t'Read managed ledger state and live drift; never appends ledger events',\n\t)\n\t.argument('[address]', 'Address as name or kind:name')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema <name>', 'Schema ledger to read', 'public')\n\t.option('--kind <kind>', 'Kind for an unqualified address', 'table')\n\t.option(\n\t\t'--parent <kind:name>',\n\t\t'Required parent for column, index, constraint, or policy',\n\t)\n\t.option('--database-ledger', 'Read the database ledger (for extensions)')\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (address: string | undefined, options: InspectOptions) => {\n\t\ttry {\n\t\t\tconst result = await runInspect(address, options);\n\t\t\tif (options.format === 'json') printCliJson(result);\n\t\t\telse console.log(renderInspectHuman(result));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (options.format === 'json')\n\t\t\t\tprintCliJson({ outcome: 'inspect-failed', error: message });\n\t\t\telse console.error(`inspect-failed: ${escapeDiagnosticText(message)}`);\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t});\n","/**\n * CLI-DDL: Introspect Command\n *\n * dbsp introspect - Generate schema.ts from database introspection.\n */\n\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { Command } from 'commander';\nimport {\n\tgenerateSchemaFileWithDiagnostics,\n\ttype SchemaCodegenOptions,\n} from '../generators/schema-codegen.js';\nimport { createDbConnection, redactDbUrl } from '../utils/db-utils.js';\n\nfunction uniqueWarnings(warnings: readonly string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst unique: string[] = [];\n\tfor (const warning of warnings) {\n\t\tif (seen.has(warning)) continue;\n\t\tseen.add(warning);\n\t\tunique.push(warning);\n\t}\n\treturn unique;\n}\n\nfunction reportWarnings(warnings: readonly string[]): void {\n\tfor (const warning of warnings) {\n\t\tconsole.log(` ⚠️ ${warning}`);\n\t}\n}\n\nexport const introspectCommand = new Command('introspect')\n\t.description('Generate schema.ts from database introspection')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('-o, --out <file>', 'Output schema file', './dbsp.schema.ts')\n\t.option('--schema-name <name>', 'Database schema name', 'public')\n\t.option(\n\t\t'--exclude <patterns>',\n\t\t'Tables to exclude (comma-separated glob patterns)',\n\t\t'_migrations,_prisma*,pg_*',\n\t)\n\t.option('--include <patterns>', 'Tables to include (comma-separated)')\n\t.option('--no-db-type-comments', 'Omit original DB type comments')\n\t.option(\n\t\t'--db-casing <casing>',\n\t\t'Database column casing (snake_case → camelCase in generated code)',\n\t\t'snake_case',\n\t)\n\t.action(\n\t\tasync (options: {\n\t\t\tdb: string;\n\t\t\tout: string;\n\t\t\tschemaName: string;\n\t\t\texclude: string;\n\t\t\tinclude?: string;\n\t\t\tdbTypeComments: boolean;\n\t\t\tdbCasing: 'snake_case' | 'camelCase' | 'preserve';\n\t\t}) => {\n\t\t\tconst redactedUrl = redactDbUrl(options.db);\n\n\t\t\tconsole.log(`🔍 Introspecting database: ${redactedUrl}`);\n\t\t\tconsole.log(` Schema: ${options.schemaName}`);\n\t\t\tif (options.exclude) {\n\t\t\t\tconsole.log(` Excluding: ${options.exclude}`);\n\t\t\t}\n\t\t\tconsole.log('');\n\n\t\t\ttry {\n\t\t\t\t// Connect to database\n\t\t\t\tconst { pool } = await createDbConnection(options.db);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Import introspect from adapter-pgsql\n\t\t\t\t\tconst { introspect } = await import('@dbsp/adapter-pgsql');\n\n\t\t\t\t\t// Build introspection options from CLI flags\n\t\t\t\t\tconst excludePatterns = options.exclude\n\t\t\t\t\t\t? options.exclude.split(',').map((s) => s.trim())\n\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst includePatterns = options.include\n\t\t\t\t\t\t? options.include.split(',').map((s) => s.trim())\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t// Introspect the database directly (returns IntrospectedModelIR)\n\t\t\t\t\tconst model = await introspect(pool, {\n\t\t\t\t\t\tschema: options.schemaName,\n\t\t\t\t\t\t...(excludePatterns ? { exclude: excludePatterns } : {}),\n\t\t\t\t\t\t...(includePatterns ? { include: includePatterns } : {}),\n\t\t\t\t\t});\n\n\t\t\t\t\t// Report what we found\n\t\t\t\t\tconst tableCount = model.tables.size;\n\t\t\t\t\tconst relationCount = model.relations.size;\n\t\t\t\t\tconst hierarchyCount = model.hierarchies?.length ?? 0;\n\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`📊 Found ${tableCount} tables, ${relationCount} relations, ${hierarchyCount} hierarchies`,\n\t\t\t\t\t);\n\n\t\t\t\t\t// Generate schema file — pass metadata from introspection\n\t\t\t\t\tconst codegenOptions: SchemaCodegenOptions = {\n\t\t\t\t\t\tsourceUrl: options.db,\n\t\t\t\t\t\tincludeDbTypeComments: options.dbTypeComments,\n\t\t\t\t\t\tintrospectedAt: model.introspectedAt,\n\t\t\t\t\t\tdbCasing: options.dbCasing,\n\t\t\t\t\t};\n\n\t\t\t\t\tconst generated = generateSchemaFileWithDiagnostics(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tcodegenOptions,\n\t\t\t\t\t);\n\t\t\t\t\tconst warnings = uniqueWarnings(generated.warnings);\n\t\t\t\t\tif (warnings.length > 0) {\n\t\t\t\t\t\treportWarnings(warnings);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log('');\n\n\t\t\t\t\t// Write output file\n\t\t\t\t\tconst outPath = resolve(process.cwd(), options.out);\n\t\t\t\t\tmkdirSync(dirname(outPath), { recursive: true });\n\t\t\t\t\twriteFileSync(outPath, generated.code, 'utf-8');\n\n\t\t\t\t\tconsole.log(`✅ Generated schema: ${outPath}`);\n\t\t\t\t\tconsole.log(` Tables: ${tableCount}`);\n\t\t\t\t\tconsole.log(` Relations: ${relationCount}`);\n\t\t\t\t} finally {\n\t\t\t\t\t// Close database connection\n\t\t\t\t\tawait pool.end();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tconsole.error(`❌ ${message}`);\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t},\n\t);\n","/** Separately privileged ledger cutover; it never routes through apply. */\nimport { createHash } from 'node:crypto';\nimport { mkdtemp, open, rename, rm } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n\tescapeDiagnosticText,\n\tgetNamingPluginForDbCasing,\n\ttype PgReinitializePreflightPool,\n\trunPgReinitializePreflight,\n} from '@dbsp/adapter-pgsql';\nimport { declarationSetFromModel } from '@dbsp/core';\nimport type { DeclarationSet, ReinitializePreflightReport } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { loadSchema } from '../utils/schema-loader.js';\n\nexport interface PreflightOptions {\n\treadonly db: string;\n\treadonly schemaFile: string;\n\treadonly scopes: readonly string[];\n\treadonly reinitialize: boolean;\n\treadonly out: string;\n}\n\ninterface CommanderPreflightOptions extends Omit<PreflightOptions, 'scopes'> {\n\treadonly scope: readonly string[];\n}\n\nexport interface PreflightDeps {\n\treadonly createDbConnection: typeof createDbConnection;\n\treadonly loadSchema: typeof loadSchema;\n}\n\nconst defaultDeps: PreflightDeps = { createDbConnection, loadSchema };\n\nexport interface AdoptionFileSystem {\n\treadonly mkdtemp: (prefix: string) => Promise<string>;\n\treadonly open: (\n\t\tpath: string,\n\t\tflags: string,\n\t\tmode?: number,\n\t) => Promise<{\n\t\twriteFile(value: string, encoding: BufferEncoding): Promise<void>;\n\t\tsync(): Promise<void>;\n\t\tclose(): Promise<void>;\n\t}>;\n\treadonly rename: (from: string, to: string) => Promise<void>;\n\treadonly rm: (\n\t\tpath: string,\n\t\toptions: { recursive: boolean; force: boolean },\n\t) => Promise<void>;\n}\n\nconst nodeAdoptionFileSystem: AdoptionFileSystem = {\n\tmkdtemp,\n\topen,\n\trename,\n\trm,\n};\n\n/**\n * The only observable destination is `out`; the temporary name is never\n * published. An existing destination is deliberately replaced atomically only\n * after the complete new document is durable.\n */\nexport async function writeAdoptionFileAtomically(\n\tout: string,\n\treport: ReinitializePreflightReport,\n\tfileSystem: AdoptionFileSystem = nodeAdoptionFileSystem,\n): Promise<void> {\n\tconst tempDirectory = await fileSystem.mkdtemp(\n\t\tjoin(dirname(out), '.dbsp-reinitialize-'),\n\t);\n\tconst tempPath = join(tempDirectory, 'adoption.json');\n\ttry {\n\t\tconst file = await fileSystem.open(tempPath, 'wx', 0o600);\n\t\ttry {\n\t\t\tawait file.writeFile(\n\t\t\t\tJSON.stringify(\n\t\t\t\t\t{\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\tadoptions: report.adoptionCandidates,\n\t\t\t\t\t},\n\t\t\t\t\tnull,\n\t\t\t\t),\n\t\t\t\t'utf8',\n\t\t\t);\n\t\t\tawait file.sync();\n\t\t} finally {\n\t\t\tawait file.close();\n\t\t}\n\t\tawait fileSystem.rename(tempPath, out);\n\t\tconst parent = await fileSystem.open(dirname(out), 'r');\n\t\ttry {\n\t\t\tawait parent.sync();\n\t\t} finally {\n\t\t\tawait parent.close();\n\t\t}\n\t} finally {\n\t\tawait fileSystem.rm(tempDirectory, { recursive: true, force: true });\n\t}\n}\n\nasync function databaseName(pool: {\n\tquery(sql: string): Promise<{ rows: readonly Record<string, unknown>[] }>;\n}): Promise<string> {\n\tconst result = await pool.query(\n\t\t'SELECT pg_catalog.current_database() AS database',\n\t);\n\tconst name = result.rows[0]?.database;\n\tif (typeof name !== 'string')\n\t\tthrow new Error('current database could not be read');\n\treturn name;\n}\n\nfunction declarationsForScopes(\n\tmodel: Awaited<ReturnType<typeof loadSchema>>['model'],\n\tdatabase: string,\n\tscopes: readonly string[],\n\tnaming: Parameters<typeof declarationSetFromModel>[2],\n): DeclarationSet {\n\tconst declarations = scopes.flatMap(\n\t\t(schema) =>\n\t\t\tdeclarationSetFromModel(\n\t\t\t\tmodel,\n\t\t\t\t{ engine: 'postgresql', database, schema },\n\t\t\t\tnaming,\n\t\t\t).declarations,\n\t);\n\t// Database-scoped declarations (extensions) are shared by every tenant\n\t// model, while their home ledger is singular. Keep one exact declaration.\n\tconst seen = new Set<string>();\n\tconst uniqueDeclarations = declarations.filter((declaration) => {\n\t\tconst key = JSON.stringify([\n\t\t\tdeclaration.address.kind,\n\t\t\tdeclaration.address.schema ?? null,\n\t\t\tdeclaration.address.parent ?? null,\n\t\t\tdeclaration.address.name,\n\t\t]);\n\t\tif (seen.has(key)) return false;\n\t\tseen.add(key);\n\t\treturn true;\n\t});\n\tconst canonical = stableJson({\n\t\tversion: 1,\n\t\tdeclarations: uniqueDeclarations,\n\t});\n\treturn {\n\t\tversion: 1,\n\t\tdigest: createHash('sha256').update(canonical).digest('hex'),\n\t\tdeclarations: uniqueDeclarations,\n\t};\n}\n\nfunction stableJson(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value);\n\tif (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n\tconst record = value as Record<string, unknown>;\n\treturn `{${Object.keys(record)\n\t\t.sort()\n\t\t.map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)\n\t\t.join(',')}}`;\n}\n\nexport async function runPreflight(\n\toptions: PreflightOptions,\n\tdeps: PreflightDeps = defaultDeps,\n): Promise<ReinitializePreflightReport> {\n\tif (!options.reinitialize)\n\t\tthrow new Error('dbsp preflight requires --reinitialize');\n\tif (!options.out)\n\t\tthrow new Error('dbsp preflight --reinitialize requires --out <file>');\n\tif (options.scopes.length === 0)\n\t\tthrow new Error(\n\t\t\t'dbsp preflight requires at least one explicit --scope <schema>',\n\t\t);\n\tconst loaded = await deps.loadSchema(options.schemaFile);\n\tconst connection = await deps.createDbConnection(options.db);\n\ttry {\n\t\tconst database = await databaseName(connection.pool);\n\t\tconst declarations = declarationsForScopes(\n\t\t\tloaded.model,\n\t\t\tdatabase,\n\t\t\toptions.scopes,\n\t\t\tgetNamingPluginForDbCasing(loaded.dbCasing ?? 'preserve'),\n\t\t);\n\t\treturn await runPgReinitializePreflight({\n\t\t\tpool: connection.pool as unknown as PgReinitializePreflightPool,\n\t\t\tschemas: options.scopes,\n\t\t\tdeclarations,\n\t\t\twriteAdoptionFile: (report) =>\n\t\t\t\twriteAdoptionFileAtomically(options.out, report),\n\t\t});\n\t} finally {\n\t\tawait connection.pool.end();\n\t}\n}\n\nfunction formatScope(\n\tscope: ReinitializePreflightReport['scopes'][number],\n): string {\n\tconst name =\n\t\tscope.ledger.scope === 'database'\n\t\t\t? 'dbsp_meta'\n\t\t\t: (scope.ledger.schema ?? 'unknown');\n\tif (scope.outcome === 'failed')\n\t\treturn `${escapeDiagnosticText(name)}: failed (${escapeDiagnosticText(scope.reason.step)}: ${escapeDiagnosticText(scope.reason.message)})`;\n\treturn scope.refusal\n\t\t? `${escapeDiagnosticText(name)}: ${escapeDiagnosticText(scope.outcome)} (${escapeDiagnosticText(scope.refusal.code)}: ${escapeDiagnosticText(scope.refusal.detail)})`\n\t\t: `${escapeDiagnosticText(name)}: ${escapeDiagnosticText(scope.outcome)}`;\n}\n\n/**\n * A cutover spans independently committed scopes. Keep the durable split\n * visible in one line so a failed middle scope cannot be mistaken for an\n * all-or-nothing result; an empty class is explicitly reported.\n */\nexport function formatReinitializeSplit(\n\tscopes: ReinitializePreflightReport['scopes'],\n): string {\n\tconst names = (predicate: (scope: (typeof scopes)[number]) => boolean) =>\n\t\tscopes\n\t\t\t.filter(predicate)\n\t\t\t.map((scope) =>\n\t\t\t\tescapeDiagnosticText(\n\t\t\t\t\tscope.ledger.scope === 'database'\n\t\t\t\t\t\t? 'dbsp_meta'\n\t\t\t\t\t\t: (scope.ledger.schema ?? 'unknown'),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.join(',') || 'none';\n\treturn `reinitialize-split: changed=${names((scope) => scope.outcome === 'current')}; failed=${names((scope) => scope.outcome === 'failed')}; not-attempted=${names((scope) => scope.outcome === 'not-attempted')}`;\n}\n\nexport const preflightCommand = new Command('preflight')\n\t.description(\n\t\t'Run the separately privileged managed-ledger reinitialize cutover',\n\t)\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.requiredOption(\n\t\t'--reinitialize',\n\t\t'Allow only the explicit reinitialize-preflight flow',\n\t)\n\t.requiredOption(\n\t\t'--out <file>',\n\t\t'Write adoption candidates to this exact file',\n\t)\n\t.requiredOption('--schema-file <path>', 'Current Schema DSL file')\n\t.requiredOption('--scope <schema...>', 'Explicit tenant schema scope list')\n\t.action(async (options: CommanderPreflightOptions) => {\n\t\t// This instruction deliberately precedes opening the database connection.\n\t\tconsole.log(\n\t\t\t'Before continuing, take a database dump. This reinitialize-preflight changes managed-ledger structures but appends no events.',\n\t\t);\n\t\ttry {\n\t\t\tconst report = await runPreflight({ ...options, scopes: options.scope });\n\t\t\tfor (const scope of report.scopes) console.log(formatScope(scope));\n\t\t\tconsole.log(formatReinitializeSplit(report.scopes));\n\t\t\tif (report.scopes.some((scope) => scope.outcome === 'failed')) {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.log(\n\t\t\t\t`Wrote ${report.adoptionCandidates.length} adoption candidate(s) to ${options.out}.`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconsole.error(\n\t\t\t\tescapeDiagnosticText(\n\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t),\n\t\t\t);\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t});\n","/** Resolve only the open managed claims durably linked to one run. */\nimport { createHash } from 'node:crypto';\nimport {\n\tassertCreateUniqueIndexConcurrentlyRecoveryNotInvalid,\n\tassertPgDatabaseWritable,\n\tescapeDiagnosticText,\n\tisPgDatabaseReadOnlyError,\n\treadPgLedgerAddressChain,\n\treadPgLedgerReservationsForExecution,\n\treadPgLedgerScopeCurrency,\n\treadTransitionJournal,\n\treadVerifiedPgLedgerReservationsForPair,\n\trecoverPgReaddressPair,\n\twithPgTransitionRunLock,\n} from '@dbsp/adapter-pgsql';\n// Recovery's raw claim primitive is intentionally internal: this command owns\n// the durable envelope reconstruction and run lock that make it admissible.\nimport { recoverPgOutcomeClaim } from '@dbsp/adapter-pgsql/internal';\nimport {\n\tacquireExclusiveTransitionLease,\n\tassumptionAccepted,\n\tcanonicalJson,\n\tcanonicalJsonDigest,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\tresourceScopeCovers,\n\ttransitionPlanDigest,\n} from '@dbsp/core';\nimport type {\n\tLedgerHome,\n\tLedgerPayload,\n\tLedgerReservationRow,\n\tOutcomeIndeterminateRecoveryEvidence,\n} from '@dbsp/types';\nimport { sameLedgerAddress } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { executionIdsForRun } from './execution-ids.js';\nimport {\n\tformatPreAppendRefusalHuman,\n\ttype PreAppendRefusal,\n\tpreAppendRefusalFor,\n} from './refusal-output.js';\n\nexport { executionIdsForRun } from './execution-ids.js';\n\nexport interface ReconcileOptions {\n\treadonly db: string;\n\treadonly format?: 'text' | 'json';\n}\n\nexport interface ReconcileResult {\n\treadonly outcome:\n\t\t| 'database-read-only'\n\t\t| 'reconcile-claim-selection-unavailable'\n\t\t| 'reconcile-run-unavailable'\n\t\t| 'reconcile-unresolved'\n\t\t| 'reconcile-completed';\n\treadonly runId: string;\n\treadonly addresses: readonly unknown[];\n\treadonly detail?: string;\n\t/** A closed, machine-readable cause for a command-level recovery failure. */\n\treadonly failureCause?: ReconcileFailureCause;\n\t/** One entry per selected root claim; non-appends retain their reason. */\n\treadonly recovery?: readonly ReconcileRecoveryReport[];\n\t/** Present when recovery refused before it could append a ledger outcome. */\n\treadonly refusal?: PreAppendRefusal;\n}\n\n/** Distinguishes retryable connection failures from unsafe recovery evidence. */\nexport type ReconcileFailureCause =\n\t| 'authentication'\n\t| 'transport'\n\t| 'malformed-journal'\n\t| 'catalogue';\n\nfunction pgSqlState(error: unknown): string | undefined {\n\tif (typeof error !== 'object' || error === null || !('code' in error))\n\t\treturn undefined;\n\tconst code = error.code;\n\treturn typeof code === 'string' ? code : undefined;\n}\n\nfunction isTransportError(error: unknown): boolean {\n\tif (typeof error !== 'object' || error === null || !('code' in error))\n\t\treturn false;\n\tconst code = error.code;\n\treturn (\n\t\ttypeof code === 'string' &&\n\t\t[\n\t\t\t'ECONNREFUSED',\n\t\t\t'ECONNRESET',\n\t\t\t'EHOSTUNREACH',\n\t\t\t'ENETUNREACH',\n\t\t\t'ETIMEDOUT',\n\t\t].includes(code)\n\t);\n}\n\n/** Classify PostgreSQL failures by SQLSTATE; no server message is parsed. */\nexport function classifyReconcileFailure(\n\terror: unknown,\n\tstage: 'journal' | 'catalogue' | 'reconcile',\n): ReconcileFailureCause {\n\tconst state = pgSqlState(error);\n\tif (state === '28000' || state === '28P01') return 'authentication';\n\tif (state?.startsWith('08') || isTransportError(error)) return 'transport';\n\tif (stage === 'journal') return 'malformed-journal';\n\treturn 'catalogue';\n}\n\nexport interface ReconcileRecoveryReport {\n\treadonly address: LedgerReservationRow['address'];\n\treadonly outcome: PgRecoveryReportKind;\n\treadonly reason?: string;\n\t/** Present when the recovery row stopped on a classified evidence failure. */\n\treadonly failureCause?: ReconcileFailureCause;\n\treadonly refusal?: PreAppendRefusal;\n\t/** Re-address recovery is reported and resolved as one reserved closure. */\n\treadonly pairId?: string;\n}\n\ntype PgRecoveryReportKind =\n\t| 'appended'\n\t| 'already-appended'\n\t| 'indeterminate-appended'\n\t| 'no-open-claim'\n\t| 'pending'\n\t| 'blocked'\n\t| 'malformed-chain'\n\t| 'protocol-refused'\n\t| 'transport-ambiguous'\n\t| 'refused-pair'\n\t| 'indeterminate-pair';\n\nfunction isUnresolvedRecoveryOutcome(report: ReconcileRecoveryReport): boolean {\n\treturn (\n\t\treport.outcome === 'pending' ||\n\t\treport.outcome === 'blocked' ||\n\t\treport.outcome === 'malformed-chain' ||\n\t\treport.outcome === 'protocol-refused' ||\n\t\treport.outcome === 'transport-ambiguous' ||\n\t\treport.outcome === 'no-open-claim' ||\n\t\treport.outcome === 'indeterminate-appended' ||\n\t\treport.outcome === 'indeterminate-pair'\n\t);\n}\n\nfunction ledgerHome(address: LedgerReservationRow['address']): LedgerHome {\n\tif (address.scope === 'database') return { scope: 'database' };\n\tif (!address.schema)\n\t\tthrow new Error(\n\t\t\t`schema-scoped managed claim ${address.name} has no schema`,\n\t\t);\n\treturn { scope: 'schema', schema: address.schema };\n}\n\nexport function recoveryPayload(\n\tidentity: Parameters<\n\t\tNonNullable<Parameters<typeof recoverPgOutcomeClaim>[1]['readBack']>\n\t>[2],\n): LedgerPayload {\n\tconst value = JSON.parse(\n\t\tcanonicalJson({\n\t\t\t...(identity === undefined ? {} : { catalogueIdentity: identity }),\n\t\t}),\n\t) as LedgerPayload['value'];\n\treturn {\n\t\tvalue,\n\t\tdigest: canonicalJsonDigest(value),\n\t};\n}\n\nfunction recoveryReport(\n\taddress: LedgerReservationRow['address'],\n\tresult: Awaited<ReturnType<typeof recoverPgOutcomeClaim>>,\n): ReconcileRecoveryReport {\n\tif (result.kind === 'outcome-recovery-appended') {\n\t\tconst indeterminate =\n\t\t\tresult.classification.resolution.eventKind === 'indeterminate';\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: indeterminate\n\t\t\t\t? 'indeterminate-appended'\n\t\t\t\t: result.append.kind === 'already-appended-outcome-resolution'\n\t\t\t\t\t? 'already-appended'\n\t\t\t\t\t: 'appended',\n\t\t\treason: result.classification.resolution.reason,\n\t\t};\n\t}\n\tif (result.kind === 'outcome-recovery-no-open-claim')\n\t\treturn { address, outcome: 'no-open-claim' };\n\tif (result.kind === 'outcome-recovery-pending')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'pending',\n\t\t\treason: result.reason,\n\t\t\t...(result.reasonCode === 'catalogue-unavailable'\n\t\t\t\t? { failureCause: 'catalogue' as const }\n\t\t\t\t: {}),\n\t\t\t...(result.reasonCode === 'catalogue-unavailable'\n\t\t\t\t? {\n\t\t\t\t\t\trefusal: preAppendRefusalFor('ERR-09', {\n\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\tstate: 'unknown',\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\tif (result.kind === 'outcome-recovery-blocked')\n\t\treturn { address, outcome: 'blocked', reason: result.reason };\n\tif (result.kind === 'outcome-recovery-malformed-chain')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'malformed-chain',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'malformed-journal',\n\t\t\trefusal: preAppendRefusalFor('ERR-08', { address, state: 'unknown' }),\n\t\t};\n\tif (result.kind === 'outcome-transport-ambiguous')\n\t\treturn {\n\t\t\taddress,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t};\n\treturn { address, outcome: 'protocol-refused', reason: result.reason };\n}\n\nfunction readdressRecoveryReport(\n\treservations: readonly LedgerReservationRow[],\n\tresult: Awaited<ReturnType<typeof recoverPgReaddressPair>>,\n): ReconcileRecoveryReport {\n\tconst first = reservations[0];\n\tif (!first) throw new Error('re-address recovery has no reservation');\n\tif (result.kind === 'readdress-recovery-refused-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'refused-pair',\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-indeterminate-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'indeterminate-pair',\n\t\t\treason: result.reason,\n\t\t\tpairId: result.pairId,\n\t\t};\n\tif (result.kind === 'readdress-recovery-transport-ambiguous-pair')\n\t\treturn {\n\t\t\taddress: first.address,\n\t\t\toutcome: 'transport-ambiguous',\n\t\t\treason: result.reason,\n\t\t\tfailureCause: 'transport',\n\t\t\tpairId: result.pairId,\n\t\t};\n\treturn {\n\t\taddress: first.address,\n\t\toutcome: 'pending',\n\t\treason: result.reason,\n\t\tpairId: result.pairId,\n\t};\n}\n\nexport function unresolvedRecoveryDetail(\n\treports: readonly ReconcileRecoveryReport[],\n): string | undefined {\n\tconst unresolved = reports.filter(isUnresolvedRecoveryOutcome);\n\tif (unresolved.length === 0) return undefined;\n\treturn unresolved\n\t\t.map(\n\t\t\t(report) =>\n\t\t\t\t`${escapeDiagnosticText(report.address.name)}: ${escapeDiagnosticText(report.reason ?? report.outcome)}`,\n\t\t)\n\t\t.join('; ');\n}\n\nexport function formatReconcileHuman(result: ReconcileResult): string {\n\tconst line = `${escapeDiagnosticText(result.outcome)}: ${escapeDiagnosticText(result.runId)}`;\n\tconst base = result.refusal\n\t\t? formatPreAppendRefusalHuman(line, result.refusal)\n\t\t: line;\n\tif (result.outcome === 'reconcile-completed' || !result.recovery) return base;\n\tconst unresolved = result.recovery.filter(isUnresolvedRecoveryOutcome);\n\treturn unresolved.length === 0\n\t\t? base\n\t\t: [\n\t\t\t\tbase,\n\t\t\t\t...unresolved.map(\n\t\t\t\t\t(report) =>\n\t\t\t\t\t\t`${escapeDiagnosticText(report.address.name)}: ${escapeDiagnosticText(report.outcome)}${report.reason ? `: ${escapeDiagnosticText(report.reason)}` : ''}`,\n\t\t\t\t),\n\t\t\t].join('\\n');\n}\n\nfunction statementBundleDigest(\n\tstatements: readonly { readonly ordinal: number; readonly sql: string }[],\n): string {\n\t// PostgreSQL jsonb may reorder object keys. Hash the ordered statement tuple\n\t// rather than a claim/step object or its serialized key order.\n\treturn createHash('sha256')\n\t\t.update(\n\t\t\tJSON.stringify(statements.map(({ ordinal, sql }) => [ordinal, sql])),\n\t\t)\n\t\t.digest('hex');\n}\n\nfunction recoveryEvidenceForClaim(input: {\n\treadonly journal: Awaited<ReturnType<typeof readTransitionJournal>>;\n\treadonly row: LedgerReservationRow;\n\treadonly plannedClaimKey: string;\n\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n}): OutcomeIndeterminateRecoveryEvidence | undefined {\n\tif (transitionPlanDigest(input.journal.plan) !== input.journal.run.planDigest)\n\t\treturn undefined;\n\tconst step = input.journal.plan.steps.find(\n\t\t(candidate) =>\n\t\t\tcandidate.managedClaim?.plannedClaimKey === input.plannedClaimKey,\n\t);\n\tconst claim = step?.managedClaim;\n\tif (\n\t\t!step ||\n\t\t!claim ||\n\t\t!sameLedgerAddress(claim.address, input.row.address) ||\n\t\toutcomeClaimId(\n\t\t\tinput.row.executionId,\n\t\t\tinput.plannedClaimKey,\n\t\t\tinput.row.address,\n\t\t) !== input.row.rootClaimId\n\t)\n\t\treturn undefined;\n\n\tconst binding = step.guards.find(\n\t\t(guard) =>\n\t\t\tguard.protocol.binding.kind === 'external-ddl-exclusion' &&\n\t\t\tresourceScopeCovers(guard.protocol.binding.scope, [input.row.address]),\n\t)?.protocol.binding;\n\tif (binding?.kind !== 'external-ddl-exclusion') return undefined;\n\tconst assumption = input.journal.plan.assumptions.find(\n\t\t(candidate) =>\n\t\t\tcandidate.id === binding.assumption &&\n\t\t\tcandidate.class === 'external-ddl-exclusion' &&\n\t\t\tstep.restsOnAssumptions.includes(candidate.id) &&\n\t\t\tresourceScopeCovers(candidate.scope, [input.row.address]),\n\t);\n\tif (!assumption) return undefined;\n\tconst accepted = input.journal.authorizations?.some((authorization) => {\n\t\tconst grant = authorization.grants.find(\n\t\t\t(candidate) => candidate.assumptionId === assumption.id,\n\t\t);\n\t\tif (!grant) return false;\n\t\tconst acceptance = authorization.policy[grant.grant];\n\t\treturn (\n\t\t\tacceptance !== undefined &&\n\t\t\tassumptionAccepted(assumption, { accepts: [acceptance] })\n\t\t);\n\t});\n\tif (!accepted) return undefined;\n\n\tconst bundleDigest = statementBundleDigest(claim.statementBundle.statements);\n\treturn {\n\t\trunId: input.journal.run.runId,\n\t\tplanDigest: input.journal.run.planDigest,\n\t\texecutionId: input.row.executionId,\n\t\tclaimId: input.row.rootClaimId,\n\t\tplannedClaimKey: input.plannedClaimKey,\n\t\tadmittedBundleDigest: bundleDigest,\n\t\tpersistedBundleDigest: bundleDigest,\n\t\trecordedPreState: input.stableStateBeforeClaim,\n\t\texternalDdlExclusion: {\n\t\t\tplanDigest: input.journal.run.planDigest,\n\t\t\taddress: input.row.address,\n\t\t\ttrustRoot: JSON.stringify(assumption.asserter),\n\t\t},\n\t};\n}\n\n/**\n * Reservations are the claim-to-run relation. The plan only provides the\n * finite ledger scopes to inspect; a claim is eligible only after its stored\n * execution_id matches a durable attempt belonging to the requested run.\n */\nexport async function runReconcile(\n\trunId: string,\n\toptions: ReconcileOptions,\n\tpool?: import('pg').Pool,\n): Promise<ReconcileResult> {\n\tlet owned: import('pg').Pool;\n\ttry {\n\t\towned = pool ?? (await createDbConnection(options.db)).pool;\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'reconcile-run-unavailable',\n\t\t\trunId,\n\t\t\taddresses: [],\n\t\t\tfailureCause: classifyReconcileFailure(error, 'reconcile'),\n\t\t};\n\t}\n\tlet stage: 'journal' | 'catalogue' | 'reconcile' = 'reconcile';\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\towned,\n\t\t\trunId,\n\t\t\tasync (target) => {\n\t\t\t\tconst lease = await acquireExclusiveTransitionLease(target);\n\t\t\t\ttry {\n\t\t\t\t\tstage = 'journal';\n\t\t\t\t\tconst journal = await readTransitionJournal(lease.session, runId, {\n\t\t\t\t\t\tensure: false,\n\t\t\t\t\t});\n\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\tconst material: Array<{\n\t\t\t\t\t\treadonly address: LedgerReservationRow['address'];\n\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t}> = journal.plan.steps\n\t\t\t\t\t\t// Generator manifests deliberately persist their authoritative\n\t\t\t\t\t\t// target at the step root, not under managedClaim. Reconcile by\n\t\t\t\t\t\t// that same durable address so an interrupted generator run is\n\t\t\t\t\t\t// recoverable by its documented run id.\n\t\t\t\t\t\t.map((step) => {\n\t\t\t\t\t\t\tconst generatedStep = step as {\n\t\t\t\t\t\t\t\treadonly address?: LedgerReservationRow['address'];\n\t\t\t\t\t\t\t\treadonly plannedClaimKeys?: readonly string[];\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst generated = generatedStep.address;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tstep.managedClaim ??\n\t\t\t\t\t\t\t\t(generated === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\taddress: generated,\n\t\t\t\t\t\t\t\t\t\t\t...(generatedStep.plannedClaimKeys?.[0] === undefined\n\t\t\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tplannedClaimKey: generatedStep.plannedClaimKeys[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t(claim): claim is NonNullable<typeof claim> =>\n\t\t\t\t\t\t\t\tclaim !== undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait assertPgDatabaseWritable(lease.session);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\tdetail: error.message,\n\t\t\t\t\t\t\t\taddresses: material.map((claim) => claim.address),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (material.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\taddresses:\n\t\t\t\t\t\t\t\tjournal.plan.declarations?.declarations.map(\n\t\t\t\t\t\t\t\t\t(declaration) => declaration.address,\n\t\t\t\t\t\t\t\t) ?? [],\n\t\t\t\t\t\t};\n\t\t\t\t\tconst homes = new Map<string, LedgerHome>();\n\t\t\t\t\tfor (const claim of material) {\n\t\t\t\t\t\tconst home = ledgerHome(claim.address);\n\t\t\t\t\t\thomes.set(`${home.scope}:${home.schema ?? ''}`, home);\n\t\t\t\t\t}\n\t\t\t\t\t// Currency/refusal is a run-level safety gate, not a consequence of\n\t\t\t\t\t// successful reservation selection. Preserve its actionable preflight\n\t\t\t\t\t// evidence even if this run has no selectable open claim.\n\t\t\t\t\tfor (const home of homes.values()) {\n\t\t\t\t\t\tconst currency = await readPgLedgerScopeCurrency(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (currency.kind === 'current') continue;\n\t\t\t\t\t\tconst detail =\n\t\t\t\t\t\t\tcurrency.kind === 'not-current' && currency.reason === 'lineage'\n\t\t\t\t\t\t\t\t? 'ledger lineage mismatch; run dbsp preflight --reinitialize'\n\t\t\t\t\t\t\t\t: `ledger marker ${currency.marker.kind}; run dbsp preflight --reinitialize`;\n\t\t\t\t\t\tconst affected = material.filter((claim) => {\n\t\t\t\t\t\t\tconst claimHome = ledgerHome(claim.address);\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tclaimHome.scope === home.scope &&\n\t\t\t\t\t\t\t\tclaimHome.schema === home.schema\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\taddresses: affected.map((claim) => claim.address),\n\t\t\t\t\t\t\tdetail,\n\t\t\t\t\t\t\trecovery: affected.map((claim) => ({\n\t\t\t\t\t\t\t\taddress: claim.address,\n\t\t\t\t\t\t\t\toutcome: 'blocked' as const,\n\t\t\t\t\t\t\t\treason: detail,\n\t\t\t\t\t\t\t\trefusal: preAppendRefusalFor('ERR-03', {\n\t\t\t\t\t\t\t\t\taddress: claim.address,\n\t\t\t\t\t\t\t\t\tstate: 'unknown',\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst executionIds = executionIdsForRun(journal);\n\t\t\t\t\tconst reservations = (\n\t\t\t\t\t\tawait Promise.all(\n\t\t\t\t\t\t\t[...homes.values()].flatMap((home) =>\n\t\t\t\t\t\t\t\texecutionIds.map((executionId) =>\n\t\t\t\t\t\t\t\t\treadPgLedgerReservationsForExecution(\n\t\t\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\t\t\thome,\n\t\t\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t).flat();\n\t\t\t\t\tif (reservations.length === 0)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\taddresses: material.map((x) => x.address),\n\t\t\t\t\t\t};\n\t\t\t\t\tconst readdressPairs = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tconst byRoot = new Map<string, LedgerReservationRow[]>();\n\t\t\t\t\tfor (const row of reservations) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trow.claimKind === 'readdress-intent' &&\n\t\t\t\t\t\t\trow.pairId !== undefined\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst pairKey = `${row.executionId}:${row.pairId}`;\n\t\t\t\t\t\t\treaddressPairs.set(pairKey, [\n\t\t\t\t\t\t\t\t...(readdressPairs.get(pairKey) ?? []),\n\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbyRoot.set(row.rootClaimId, [\n\t\t\t\t\t\t\t...(byRoot.get(row.rootClaimId) ?? []),\n\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t]);\n\t\t\t\t\t}\n\t\t\t\t\tconst recovery: ReconcileRecoveryReport[] = [];\n\t\t\t\t\tfor (const [_pairKey, pairRows] of readdressPairs) {\n\t\t\t\t\t\tconst pairId = pairRows[0]?.pairId;\n\t\t\t\t\t\tconst executionId = pairRows[0]?.executionId;\n\t\t\t\t\t\tif (!pairId || !executionId) continue;\n\t\t\t\t\t\tconst readPairInSelectedHomes =\n\t\t\t\t\t\t\treadVerifiedPgLedgerReservationsForPair as unknown as (\n\t\t\t\t\t\t\t\texecutor: typeof lease.session,\n\t\t\t\t\t\t\t\tpair: string,\n\t\t\t\t\t\t\t\tselectedHomes: readonly LedgerHome[],\n\t\t\t\t\t\t\t) => Promise<readonly LedgerReservationRow[]>;\n\t\t\t\t\t\tconst closure = await readPairInSelectedHomes(\n\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\t[...homes.values()],\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst recovered = await recoverPgReaddressPair(lease.session, {\n\t\t\t\t\t\t\tpairId,\n\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\treservations: closure,\n\t\t\t\t\t\t});\n\t\t\t\t\t\trecovery.push(readdressRecoveryReport(closure, recovered));\n\t\t\t\t\t}\n\t\t\t\t\tfor (const rows of byRoot.values()) {\n\t\t\t\t\t\tconst rootClaimId = rows[0]?.rootClaimId;\n\t\t\t\t\t\tif (!rootClaimId) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\trows.some(\n\t\t\t\t\t\t\t\t(row) =>\n\t\t\t\t\t\t\t\t\t!executionIds.includes(row.executionId) ||\n\t\t\t\t\t\t\t\t\trow.rootClaimId !== rootClaimId,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `reservation disagreement for root claim ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst rootCandidates: Array<{\n\t\t\t\t\t\t\treadonly row: LedgerReservationRow;\n\t\t\t\t\t\t\treadonly plannedClaimKey?: string;\n\t\t\t\t\t\t\treadonly stableStateBeforeClaim: 'unknown' | 'managed' | 'absent';\n\t\t\t\t\t\t}> = [];\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tstage = 'catalogue';\n\t\t\t\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\t\t\t\tlease.session,\n\t\t\t\t\t\t\t\tledgerHome(row.address),\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tstage = 'reconcile';\n\t\t\t\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tprojection.kind !== 'projected-ledger-chain' ||\n\t\t\t\t\t\t\t\tprojection.openClaim === undefined\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tconst open = projection.openClaim.event;\n\t\t\t\t\t\t\tconst openRoot = open.rootClaimId ?? open.eventId;\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\topen.executionId !== row.executionId ||\n\t\t\t\t\t\t\t\topenRoot !== rootClaimId\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\t\taddresses: rows.map((item) => item.address),\n\t\t\t\t\t\t\t\t\tdetail: `open chain member disagrees with reservation root ${rootClaimId}`,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (open.eventId === rootClaimId)\n\t\t\t\t\t\t\t\trootCandidates.push({\n\t\t\t\t\t\t\t\t\trow,\n\t\t\t\t\t\t\t\t\tstableStateBeforeClaim:\n\t\t\t\t\t\t\t\t\t\tprojection.openClaim.stableStateBeforeClaim,\n\t\t\t\t\t\t\t\t\t...(open.plannedClaimKey === undefined\n\t\t\t\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t\t\t\t: { plannedClaimKey: open.plannedClaimKey }),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (rootCandidates.length !== 1)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `execution ${runId} has ${rootCandidates.length} open root members for ${rootClaimId}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tconst selected = rootCandidates[0];\n\t\t\t\t\t\tif (!selected) continue;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!selected.plannedClaimKey ||\n\t\t\t\t\t\t\t!material.some(\n\t\t\t\t\t\t\t\t(claim) => claim.plannedClaimKey === selected.plannedClaimKey,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tkind: 'selection-unavailable' as const,\n\t\t\t\t\t\t\t\taddresses: rows.map((row) => row.address),\n\t\t\t\t\t\t\t\tdetail: `open root ${rootClaimId} has no matching persisted managed step`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t// Recovery follows execution_id -> reservation root_claim_id -> the\n\t\t\t\t\t\t// single open root member. It never reuses an address-only plan id.\n\t\t\t\t\t\tconst step = journal.plan.steps.find(\n\t\t\t\t\t\t\t(candidate) =>\n\t\t\t\t\t\t\t\tcandidate.managedClaim?.plannedClaimKey ===\n\t\t\t\t\t\t\t\t\tselected.plannedClaimKey ||\n\t\t\t\t\t\t\t\t('plannedClaimKeys' in candidate &&\n\t\t\t\t\t\t\t\t\tArray.isArray(candidate.plannedClaimKeys) &&\n\t\t\t\t\t\t\t\t\tcandidate.plannedClaimKeys.includes(\n\t\t\t\t\t\t\t\t\t\tselected.plannedClaimKey,\n\t\t\t\t\t\t\t\t\t)),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst operationReadBack =\n\t\t\t\t\t\t\tstep?.operation?.operationKind.name ===\n\t\t\t\t\t\t\t'CreateUniqueIndexConcurrently'\n\t\t\t\t\t\t\t\t? async (\n\t\t\t\t\t\t\t\t\t\texecutor: Parameters<\n\t\t\t\t\t\t\t\t\t\t\ttypeof assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid\n\t\t\t\t\t\t\t\t\t\t>[0],\n\t\t\t\t\t\t\t\t\t\t_address: LedgerReservationRow['address'],\n\t\t\t\t\t\t\t\t\t\tidentity: Parameters<typeof recoveryPayload>[0],\n\t\t\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\t\t\tawait assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid(\n\t\t\t\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\t\t\t\tstep.operation,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tobserved: recoveryPayload(identity),\n\t\t\t\t\t\t\t\t\t\t\teffect: 'unverifiable' as const,\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\tconst indeterminateEvidence = recoveryEvidenceForClaim({\n\t\t\t\t\t\t\tjournal,\n\t\t\t\t\t\t\trow: selected.row,\n\t\t\t\t\t\t\tplannedClaimKey: selected.plannedClaimKey,\n\t\t\t\t\t\t\tstableStateBeforeClaim: selected.stableStateBeforeClaim,\n\t\t\t\t\t\t});\n\t\t\t\t\t\t// A reservation is released only with the terminal for that exact\n\t\t\t\t\t\t// member. Resolving the root must never erase the discovery record\n\t\t\t\t\t\t// for an unresolved child in the same durable closure.\n\t\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\t\tconst isRoot = sameLedgerAddress(\n\t\t\t\t\t\t\t\trow.address,\n\t\t\t\t\t\t\t\tselected.row.address,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst recovered = await recoverPgOutcomeClaim(owned, {\n\t\t\t\t\t\t\t\taddress: row.address,\n\t\t\t\t\t\t\t\treservations: [row],\n\t\t\t\t\t\t\t\tresolutionEventId: isRoot\n\t\t\t\t\t\t\t\t\t? `${rootClaimId}:reconcile:${runId}`\n\t\t\t\t\t\t\t\t\t: `${rootClaimId}:reconcile:${runId}:${row.address.kind}:${row.address.name}`,\n\t\t\t\t\t\t\t\tacceptedExternalDdlExclusion:\n\t\t\t\t\t\t\t\t\tisRoot && indeterminateEvidence !== undefined,\n\t\t\t\t\t\t\t\tresolveIndeterminate: true,\n\t\t\t\t\t\t\t\treadBack: async (_executor, _address, identity) =>\n\t\t\t\t\t\t\t\t\trecoveryPayload(identity),\n\t\t\t\t\t\t\t\t...(isRoot && indeterminateEvidence !== undefined\n\t\t\t\t\t\t\t\t\t? { indeterminateEvidence }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t...(isRoot && operationReadBack !== undefined\n\t\t\t\t\t\t\t\t\t? { operationReadBack }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\trecovery.push(recoveryReport(row.address, recovered));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst unresolved = unresolvedRecoveryDetail(recovery);\n\t\t\t\t\tif (unresolved)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\tdetail: unresolved,\n\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\trecovery,\n\t\t\t\t\t};\n\t\t\t\t} finally {\n\t\t\t\t\tawait lease.release();\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t\tif (locked.kind === 'busy')\n\t\t\treturn { outcome: 'reconcile-run-unavailable', runId, addresses: [] };\n\t\tif (locked.value.kind === 'selection-unavailable')\n\t\t\treturn {\n\t\t\t\toutcome: 'reconcile-claim-selection-unavailable',\n\t\t\t\trunId,\n\t\t\t\taddresses: locked.value.addresses,\n\t\t\t\t...(locked.value.detail ? { detail: locked.value.detail } : {}),\n\t\t\t};\n\t\tif (locked.value.kind === 'database-read-only') {\n\t\t\tconst address = locked.value.addresses[0];\n\t\t\treturn {\n\t\t\t\toutcome: 'database-read-only',\n\t\t\t\trunId,\n\t\t\t\taddresses: locked.value.addresses,\n\t\t\t\tdetail: locked.value.detail,\n\t\t\t\t...(address === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\trefusal: preAppendRefusalFor('ERR-07', {\n\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\tstate: 'unknown',\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t\tif (locked.value.kind === 'unresolved') {\n\t\t\tconst address = locked.value.addresses[0];\n\t\t\tconst markerRefusal =\n\t\t\t\taddress !== undefined &&\n\t\t\t\tlocked.value.detail?.includes('run dbsp preflight --reinitialize')\n\t\t\t\t\t? preAppendRefusalFor('ERR-03', { address, state: 'unknown' })\n\t\t\t\t\t: undefined;\n\t\t\tconst recoveryRefusal = locked.value.recovery?.find(\n\t\t\t\t(report) => report.refusal !== undefined,\n\t\t\t)?.refusal;\n\t\t\tconst refusal = markerRefusal ?? recoveryRefusal;\n\t\t\treturn {\n\t\t\t\toutcome: 'reconcile-unresolved',\n\t\t\t\trunId,\n\t\t\t\taddresses: locked.value.addresses,\n\t\t\t\t...(locked.value.detail ? { detail: locked.value.detail } : {}),\n\t\t\t\t...(locked.value.recovery ? { recovery: locked.value.recovery } : {}),\n\t\t\t\t...(refusal === undefined ? {} : { refusal }),\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\toutcome: 'reconcile-completed',\n\t\t\trunId,\n\t\t\taddresses: locked.value.addresses,\n\t\t\t...(locked.value.recovery ? { recovery: locked.value.recovery } : {}),\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'reconcile-run-unavailable',\n\t\t\trunId,\n\t\t\taddresses: [],\n\t\t\tdetail: escapeDiagnosticText(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t),\n\t\t\tfailureCause: classifyReconcileFailure(error, stage),\n\t\t};\n\t} finally {\n\t\tif (pool === undefined) await owned.end();\n\t}\n}\n\nexport const reconcileCommand = new Command('reconcile')\n\t.description('Resolve this run’s open managed claims from live evidence only')\n\t.argument('<run-id>', 'Durable run identifier')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (runId: string, options: ReconcileOptions) => {\n\t\tconst result = await runReconcile(runId, options);\n\t\tif (options.format === 'json') printCliJson(result);\n\t\telse console.log(formatReconcileHuman(result));\n\t\tprocess.exitCode = result.outcome === 'reconcile-completed' ? 0 : 1;\n\t});\n","/** Classify a previously attempted run. Recovery never executes planned DDL. */\nimport {\n\tassertPgDatabaseWritable,\n\tcreatePgTransitionPack,\n\tisPgDatabaseReadOnlyError,\n\tpreparePgRecoveryAdmission,\n\treadPgLedgerScopeCurrency,\n\treadPgObservationContextFromLessor,\n\treadTransitionJournal,\n\twithPgTransitionRunLock,\n} from '@dbsp/adapter-pgsql';\nimport {\n\tacquireTransitionTargetLease,\n\tassumptionAccepted,\n\tcreateApplier,\n\tcreatePackRegistry,\n\tloadVerifiedRecoveryJournal,\n\ttransitionPlanDigest,\n\tvalidateTransitionRelationalInvariants,\n} from '@dbsp/core';\nimport type {\n\tApplyPolicy,\n\tApplyResult,\n\tLedgerAddress,\n\tLedgerHome,\n\tTransitionRunJournal,\n} from '@dbsp/types';\nimport { Command } from 'commander';\nimport type { Pool } from 'pg';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport {\n\tauthorizationDigest,\n\tcanonicalApplyPolicy,\n\tvalidateAssumptionAcceptance,\n\twithPoolCleanupReported,\n} from './apply.js';\nimport {\n\ttype PreAppendRefusal,\n\tpreAppendRefusalFor,\n} from './refusal-output.js';\n\nexport const RECOVER_OUTCOME_CONTRACT = [\n\t['completed', 0, 'all attempted steps were durably reconciled'],\n\t['recovery-resume-required', 40, 'remaining work requires a new proof'],\n\t['recovery-partially-applied', 41, 'durable effects require recovery action'],\n\t['recovery-unknown-step-result', 42, 'a prior step could not be classified'],\n\t['recovery-guard-failed', 43, 'a prior guard rejected the target'],\n\t['recovery-guard-timeout', 44, 'a prior guard timed out'],\n\t[\n\t\t'recovery-operation-failed-not-applied',\n\t\t45,\n\t\t'a prior operation rolled back',\n\t],\n\t[\n\t\t'recovery-context-mismatch',\n\t\t46,\n\t\t'run evidence or target context is invalid',\n\t],\n\t['recovery-read-failed', 47, 'recovery could not read the target'],\n\t['recovery-load-failed', 48, 'run journal could not be loaded'],\n\t['recovery-plan-invalid', 49, 'stored plan failed validation'],\n\t[\n\t\t'recovery-authorization-missing',\n\t\t50,\n\t\t'attempted run has no durable authorization',\n\t],\n\t[\n\t\t'recovery-authorization-invalid',\n\t\t51,\n\t\t'attempted run authorization is invalid',\n\t],\n\t['plan-digest-required', 54, 'a reviewed plan digest is required'],\n\t['database-read-only', 34, 'target cannot accept managed recovery writes'],\n\t[\n\t\t'recovery-plan-digest-mismatch',\n\t\t55,\n\t\t'reviewed plan digest does not match the run',\n\t],\n\t['run-busy', 52, 'another database session holds this run lock'],\n\t['recovery-failed', 53, 'unexpected recovery command failure'],\n] as const;\n\nexport type RecoverOutcome = (typeof RECOVER_OUTCOME_CONTRACT)[number][0];\nconst recoverExitCodes = new Map<RecoverOutcome, number>(\n\tRECOVER_OUTCOME_CONTRACT.map(([outcome, exitCode]) => [outcome, exitCode]),\n);\n\nexport function exitCodeForRecoverOutcome(outcome: RecoverOutcome): number {\n\treturn recoverExitCodes.get(outcome) as number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\ntype AuthorizationValidation =\n\t| { readonly ok: true; readonly policy: ApplyPolicy }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly outcome:\n\t\t\t\t| 'recovery-authorization-missing'\n\t\t\t\t| 'recovery-authorization-invalid';\n\t };\n\n/**\n * Recovery uses a durable approval exactly as recorded; it never turns plan\n * assumptions into new broad grants. A record must bind its canonical policy,\n * digest, and one accepting grant for every plan assumption.\n */\nexport function validateRecoveryAuthorization(\n\tjournal: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n): AuthorizationValidation {\n\tconst records = journal.authorizations ?? [];\n\tif (records.length === 0)\n\t\treturn { ok: false, outcome: 'recovery-authorization-missing' };\n\tfor (const candidate of records) {\n\t\ttry {\n\t\t\tif (!isRecord(candidate) || candidate.runId !== journal.run.runId)\n\t\t\t\tcontinue;\n\t\t\tif (!Array.isArray(candidate.policy) || !Array.isArray(candidate.grants))\n\t\t\t\tcontinue;\n\t\t\tconst accepts = canonicalApplyPolicy(\n\t\t\t\tcandidate.policy.map((grant, index) =>\n\t\t\t\t\tvalidateAssumptionAcceptance(grant, `authorization.policy[${index}]`),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst grants = new Map<string, number>();\n\t\t\tfor (const grant of candidate.grants) {\n\t\t\t\tif (!isRecord(grant) || typeof grant.assumptionId !== 'string')\n\t\t\t\t\tthrow new Error('invalid authorization grant');\n\t\t\t\tif (!Number.isInteger(grant.grant))\n\t\t\t\t\tthrow new Error('invalid authorization grant index');\n\t\t\t\tif (grants.has(grant.assumptionId))\n\t\t\t\t\tthrow new Error('duplicate authorization grant');\n\t\t\t\tgrants.set(grant.assumptionId, grant.grant as number);\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttypeof candidate.digest !== 'string' ||\n\t\t\t\tcandidate.digest !==\n\t\t\t\t\tauthorizationDigest(\n\t\t\t\t\t\tjournal.run.runId,\n\t\t\t\t\t\tjournal.run.planDigest,\n\t\t\t\t\t\taccepts,\n\t\t\t\t\t\tcandidate.grants,\n\t\t\t\t\t\tcandidate.actor,\n\t\t\t\t\t\tcandidate.authorizedAt,\n\t\t\t\t\t)\n\t\t\t)\n\t\t\t\tcontinue;\n\t\t\tif (grants.size !== journal.plan.assumptions.length) continue;\n\t\t\tconst policy = { accepts };\n\t\t\tif (\n\t\t\t\tjournal.plan.assumptions.every((assumption) => {\n\t\t\t\t\tconst grant = grants.get(assumption.id);\n\t\t\t\t\tconst acceptedGrant =\n\t\t\t\t\t\tgrant === undefined ? undefined : accepts[grant];\n\t\t\t\t\treturn (\n\t\t\t\t\t\tgrant !== undefined &&\n\t\t\t\t\t\tgrant >= 0 &&\n\t\t\t\t\t\tgrant < accepts.length &&\n\t\t\t\t\t\tacceptedGrant !== undefined &&\n\t\t\t\t\t\tassumptionAccepted(assumption, {\n\t\t\t\t\t\t\taccepts: [acceptedGrant],\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t)\n\t\t\t\treturn { ok: true, policy };\n\t\t} catch {\n\t\t\t// A malformed durable record is not a policy input to repair here.\n\t\t}\n\t}\n\treturn { ok: false, outcome: 'recovery-authorization-invalid' };\n}\n\nexport function recoveryPolicyForJournal(\n\tloaded: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n\trunId: string,\n):\n\t| { readonly ok: true; readonly policy: ApplyPolicy }\n\t| {\n\t\t\treadonly ok: false;\n\t\t\treadonly outcome:\n\t\t\t\t| 'recovery-plan-invalid'\n\t\t\t\t| 'recovery-authorization-missing'\n\t\t\t\t| 'recovery-authorization-invalid';\n\t } {\n\tif (\n\t\tloaded.run.runId !== runId ||\n\t\tloaded.run.planDigest !== transitionPlanDigest(loaded.plan) ||\n\t\t!validateTransitionRelationalInvariants({ kind: 'plan', plan: loaded.plan })\n\t\t\t.ok\n\t)\n\t\treturn { ok: false, outcome: 'recovery-plan-invalid' };\n\treturn validateRecoveryAuthorization(loaded);\n}\n\nexport function outcomeForRecoveryResult(\n\tresult: ApplyResult,\n): Exclude<RecoverOutcome, 'run-busy' | 'recovery-failed'> {\n\tif (result.recoveryOutcome) return result.recoveryOutcome;\n\tif (result.assessment.lifecycle === 'completed') return 'completed';\n\tif (result.assessment.lifecycle === 'partially-applied')\n\t\treturn 'recovery-partially-applied';\n\tconst reason = result.assessment.reasons[0];\n\tswitch (reason?.code) {\n\t\tcase 'resume-required':\n\t\t\treturn 'recovery-resume-required';\n\t\tcase 'unknown-step-result':\n\t\t\treturn 'recovery-unknown-step-result';\n\t\tcase 'guard-failed':\n\t\t\treturn 'recovery-guard-failed';\n\t\tcase 'guard-timeout':\n\t\t\treturn 'recovery-guard-timeout';\n\t\tcase 'operation-failed-not-applied':\n\t\t\treturn 'recovery-operation-failed-not-applied';\n\t\tdefault:\n\t\t\treturn 'recovery-context-mismatch';\n\t}\n}\n\nasync function load(\n\ttarget: Parameters<typeof acquireTransitionTargetLease>[0],\n\trunId: string,\n) {\n\tconst lease = await acquireTransitionTargetLease(target);\n\ttry {\n\t\treturn await readTransitionJournal(lease.session, runId, { ensure: false });\n\t} finally {\n\t\tawait lease.release();\n\t}\n}\n\nfunction ledgerHome(address: LedgerAddress): LedgerHome {\n\tif (address.scope === 'database') return { scope: 'database' };\n\tif (!address.schema)\n\t\tthrow new Error(\n\t\t\t`schema-scoped managed claim ${address.name} has no schema`,\n\t\t);\n\treturn { scope: 'schema', schema: address.schema };\n}\n\nfunction sameLedgerHome(left: LedgerHome, right: LedgerHome): boolean {\n\treturn left.scope === right.scope && left.schema === right.schema;\n}\n\nfunction recoveryAddresses(\n\tjournal: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n): readonly LedgerAddress[] {\n\treturn journal.plan.steps.flatMap((step) => {\n\t\tconst generated = step as { readonly address?: LedgerAddress };\n\t\tconst address = step.managedClaim?.address ?? generated.address;\n\t\treturn address === undefined ? [] : [address];\n\t});\n}\n\nfunction formatLedgerHome(home: LedgerHome): string {\n\treturn home.scope === 'database' ? 'database' : `schema ${home.schema}`;\n}\n\n/**\n * Recovery must not turn an ordinary command into a marker upgrade path. The\n * persisted run supplies the finite homes to inspect, but no recovery\n * selection, authorization replay, or ledger append may follow a stale marker.\n */\nasync function recoverMarkerRefusal(\n\ttarget: Parameters<typeof acquireTransitionTargetLease>[0],\n\tjournal: TransitionRunJournal & {\n\t\treadonly plan: import('@dbsp/types').ProvenPlanShape;\n\t},\n): Promise<\n\t| {\n\t\t\treadonly detail: string;\n\t\t\treadonly refusal: PreAppendRefusal;\n\t }\n\t| undefined\n> {\n\tconst addresses = recoveryAddresses(journal);\n\tconst homes: Array<{\n\t\treadonly address: LedgerAddress;\n\t\treadonly home: LedgerHome;\n\t}> = [];\n\tfor (const address of addresses) {\n\t\tconst home = ledgerHome(address);\n\t\tif (homes.some((candidate) => sameLedgerHome(candidate.home, home)))\n\t\t\tcontinue;\n\t\thomes.push({ address, home });\n\t}\n\tconst lease = await acquireTransitionTargetLease(target);\n\ttry {\n\t\tfor (const { address, home } of homes) {\n\t\t\tconst currency = await readPgLedgerScopeCurrency(lease.session, home);\n\t\t\tif (currency.kind === 'current') continue;\n\t\t\tconst detail =\n\t\t\t\tcurrency.kind === 'not-current' && currency.reason === 'lineage'\n\t\t\t\t\t? `ledger lineage mismatch in ${formatLedgerHome(home)}; run dbsp preflight --reinitialize`\n\t\t\t\t\t: `ledger marker ${currency.marker.kind} in ${formatLedgerHome(home)}; run dbsp preflight --reinitialize`;\n\t\t\treturn {\n\t\t\t\tdetail,\n\t\t\t\trefusal: preAppendRefusalFor('ERR-03', {\n\t\t\t\t\taddress,\n\t\t\t\t\tstate: 'unknown',\n\t\t\t\t}),\n\t\t\t};\n\t\t}\n\t} finally {\n\t\tawait lease.release();\n\t}\n\treturn undefined;\n}\n\nexport type RecoverCommandResult = (\n\t| {\n\t\t\treadonly outcome: Exclude<RecoverOutcome, 'run-busy' | 'recovery-failed'>;\n\t\t\treadonly runId: string;\n\t\t\treadonly result?: ApplyResult;\n\t\t\treadonly detail?: string;\n\t\t\treadonly refusal?: PreAppendRefusal;\n\t }\n\t| { readonly outcome: 'run-busy'; readonly runId: string }\n) & {\n\treadonly cleanupError?: string;\n};\n\ntype RecoverRunResult =\n\t| RecoverCommandResult\n\t| {\n\t\t\treadonly outcome:\n\t\t\t\t| 'plan-digest-required'\n\t\t\t\t| 'recovery-plan-digest-mismatch';\n\t\t\treadonly runId: string;\n\t\t\treadonly cleanupError?: string;\n\t };\n\nexport async function runRecover(\n\trunId: string,\n\toptions: { readonly db: string; readonly planDigest?: string },\n\tpool?: Pool,\n): Promise<RecoverRunResult> {\n\tif (!options.planDigest) return { outcome: 'plan-digest-required', runId };\n\tconst expectedPlanDigest = options.planDigest;\n\tconst owned =\n\t\tpool === undefined ? (await createDbConnection(options.db)).pool : pool;\n\tlet result: RecoverRunResult;\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\towned,\n\t\t\trunId,\n\t\t\tasync (target) => {\n\t\t\t\tconst loaded = await loadVerifiedRecoveryJournal(\n\t\t\t\t\trunId,\n\t\t\t\t\texpectedPlanDigest,\n\t\t\t\t\t(id) => load(target, id),\n\t\t\t\t);\n\t\t\t\tif (!loaded.ok) {\n\t\t\t\t\tswitch (loaded.code) {\n\t\t\t\t\t\tcase 'load-failed':\n\t\t\t\t\t\t\treturn { outcome: 'recovery-load-failed' as const };\n\t\t\t\t\t\tcase 'plan-digest-mismatch':\n\t\t\t\t\t\t\treturn { outcome: 'recovery-plan-digest-mismatch' as const };\n\t\t\t\t\t\tcase 'event-invalid':\n\t\t\t\t\t\t\treturn { outcome: 'recovery-context-mismatch' as const };\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn { outcome: 'recovery-plan-invalid' as const };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst writabilityLease = await acquireTransitionTargetLease(target);\n\t\t\t\ttry {\n\t\t\t\t\tawait assertPgDatabaseWritable(writabilityLease.session);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\toutcome: 'database-read-only' as const,\n\t\t\t\t\t\t\tdetail: error.message,\n\t\t\t\t\t\t};\n\t\t\t\t\tthrow error;\n\t\t\t\t} finally {\n\t\t\t\t\tawait writabilityLease.release();\n\t\t\t\t}\n\t\t\t\tconst markerRefusal = await recoverMarkerRefusal(\n\t\t\t\t\ttarget,\n\t\t\t\t\tloaded.journal,\n\t\t\t\t);\n\t\t\t\tif (markerRefusal)\n\t\t\t\t\treturn {\n\t\t\t\t\t\toutcome: 'recovery-context-mismatch' as const,\n\t\t\t\t\t\t...markerRefusal,\n\t\t\t\t\t};\n\t\t\t\tconst authorization =\n\t\t\t\t\tloaded.journal.events.length === 0\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: recoveryPolicyForJournal(loaded.journal, runId);\n\t\t\t\tif (authorization && !authorization.ok)\n\t\t\t\t\treturn { outcome: authorization.outcome };\n\t\t\t\tconst result = await createApplier(\n\t\t\t\t\tcreatePackRegistry([createPgTransitionPack({})]),\n\t\t\t\t\t{ persist: async () => undefined },\n\t\t\t\t).resume(\n\t\t\t\t\tloaded.journal,\n\t\t\t\t\t(leasedTarget) => readPgObservationContextFromLessor(leasedTarget),\n\t\t\t\t\tauthorization?.policy,\n\t\t\t\t\ttarget,\n\t\t\t\t\tasync (leasedTarget, contract) => {\n\t\t\t\t\t\tconst lease = await acquireTransitionTargetLease(leasedTarget);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await preparePgRecoveryAdmission(lease.session, contract);\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait lease.release();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\treturn { outcome: outcomeForRecoveryResult(result), result };\n\t\t\t},\n\t\t);\n\t\tresult =\n\t\t\tlocked.kind === 'busy'\n\t\t\t\t? { outcome: 'run-busy', runId }\n\t\t\t\t: { ...locked.value, runId };\n\t} catch (error) {\n\t\tif (pool === undefined) {\n\t\t\ttry {\n\t\t\t\tawait owned.end();\n\t\t\t} catch {\n\t\t\t\t// Preserve the primary recovery error for the CLI boundary.\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t}\n\tif (pool === undefined) {\n\t\treturn withPoolCleanupReported(result, () => owned.end());\n\t}\n\treturn result;\n}\n\nexport const recoverCommand = new Command('recover')\n\t.description(\n\t\t'Observe and classify an attempted durable run; performs no planned target DDL and does not re-authorize assumptions',\n\t)\n\t.argument('<run-id>', 'Durable run identifier')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.requiredOption(\n\t\t'--plan-digest <sha>',\n\t\t'Plan digest printed by dbsp plan; required to anchor recovery outside the database',\n\t)\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(\n\t\tasync (\n\t\t\trunId: string,\n\t\t\toptions: { db: string; planDigest: string; format?: 'text' | 'json' },\n\t\t) => {\n\t\t\tlet result:\n\t\t\t\t| RecoverCommandResult\n\t\t\t\t| {\n\t\t\t\t\t\treadonly outcome: 'recovery-failed';\n\t\t\t\t\t\treadonly runId: string;\n\t\t\t\t\t\treadonly error: string;\n\t\t\t\t };\n\t\t\ttry {\n\t\t\t\tresult = await runRecover(runId, options);\n\t\t\t} catch (error) {\n\t\t\t\tresult = {\n\t\t\t\t\toutcome: 'recovery-failed',\n\t\t\t\t\trunId,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst document = {\n\t\t\t\t...result,\n\t\t\t\texitCode: exitCodeForRecoverOutcome(result.outcome),\n\t\t\t};\n\t\t\tif (options.format === 'json') printCliJson(document);\n\t\t\telse console.log(`${result.outcome}: ${runId}`);\n\t\t\tprocess.exitCode = document.exitCode;\n\t\t},\n\t)\n\t.addHelpText(\n\t\t'after',\n\t\t`\\nJSON result contract (outcome -> exit code):\\n${RECOVER_OUTCOME_CONTRACT.map(([outcome, code, description]) => ` ${outcome} -> ${code}: ${description}`).join('\\n')}\\n`,\n\t);\n","/** `dbsp release` stops managing one address and deliberately emits no DDL. */\nimport {\n\tcreatePgTransitionLessor,\n\tescapeDiagnosticText,\n\treleasePgManagedAddress,\n} from '@dbsp/adapter-pgsql';\nimport { acquireTransitionLease } from '@dbsp/core';\nimport type { LedgerAddress, LedgerRefusal } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { createDbConnection } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { inspectAddress } from './inspect.js';\n\nexport interface ReleaseOptions {\n\treadonly db: string;\n\treadonly schema?: string;\n\treadonly kind?: string;\n\treadonly parent?: string;\n\treadonly databaseLedger?: boolean;\n\treadonly format?: 'text' | 'json';\n}\n\nexport type ReleaseCommandResult =\n\t| { readonly outcome: 'released' }\n\t| {\n\t\t\treadonly outcome: 'database-read-only';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| { readonly outcome: 'release-unavailable'; readonly detail: string }\n\t| {\n\t\t\treadonly outcome: 'release-refused';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t\t\treadonly refusal: LedgerRefusal;\n\t };\n\nexport async function runRelease(\n\tselector: string,\n\toptions: ReleaseOptions,\n): Promise<ReleaseCommandResult> {\n\tconst { pool } = await createDbConnection(options.db);\n\tconst schema = options.schema ?? 'public';\n\ttry {\n\t\tconst lease = await acquireTransitionLease(createPgTransitionLessor(pool));\n\t\ttry {\n\t\t\tconst databaseRow = await lease.session.query(\n\t\t\t\t'SELECT current_database() AS database',\n\t\t\t);\n\t\t\tconst database = databaseRow.rows[0]?.database;\n\t\t\tif (typeof database !== 'string')\n\t\t\t\tthrow new Error('PostgreSQL current_database() is unreadable');\n\t\t\t// Keep the leased session alive until the release preflight/transaction has\n\t\t\t// settled. A bare promise return would enter the finally blocks below\n\t\t\t// immediately, ending this pool while the adapter is still reading it.\n\t\t\treturn (await releasePgManagedAddress({\n\t\t\t\texecutor: lease.session,\n\t\t\t\thome: options.databaseLedger\n\t\t\t\t\t? { scope: 'database' }\n\t\t\t\t\t: { scope: 'schema', schema },\n\t\t\t\taddress: inspectAddress(\n\t\t\t\t\tdatabase,\n\t\t\t\t\tschema,\n\t\t\t\t\tselector,\n\t\t\t\t\toptions.kind,\n\t\t\t\t\toptions.parent,\n\t\t\t\t\toptions.databaseLedger ? 'database' : 'schema',\n\t\t\t\t),\n\t\t\t})) as ReleaseCommandResult;\n\t\t} finally {\n\t\t\tawait lease.release();\n\t\t}\n\t} finally {\n\t\tawait pool.end();\n\t}\n}\n\nexport function formatReleaseHuman(result: ReleaseCommandResult): string {\n\tif (result.outcome === 'released') return 'released';\n\tif (result.outcome === 'database-read-only')\n\t\treturn `database-read-only: ${escapeDiagnosticText(result.detail)}`;\n\tif (result.outcome === 'release-unavailable')\n\t\treturn `release-unavailable: ${escapeDiagnosticText(result.detail)}`;\n\treturn [\n\t\t`release-refused: ${escapeDiagnosticText(result.detail)}`,\n\t\t`address: ${escapeDiagnosticText(JSON.stringify(result.address))}`,\n\t\t`state: ${escapeDiagnosticText(result.refusal.state)}`,\n\t\t`withheld authority: ${escapeDiagnosticText(result.refusal.withheldAuthority)}`,\n\t\t`resolving command: ${escapeDiagnosticText(result.refusal.resolvingCommand)}`,\n\t].join('\\n');\n}\n\nexport const releaseCommand = new Command('release')\n\t.description(\n\t\t'End management for one address without touching the database object',\n\t)\n\t.argument('<address>', 'Address as name or kind:name')\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema <name>', 'Schema ledger containing the address', 'public')\n\t.option('--kind <kind>', 'Kind for an unqualified address', 'table')\n\t.option(\n\t\t'--parent <kind:name>',\n\t\t'Required parent for column, index, constraint, or policy',\n\t)\n\t.option(\n\t\t'--database-ledger',\n\t\t'Release from the database ledger (for extensions)',\n\t)\n\t.option('--format <format>', 'Output format: text or json', 'text')\n\t.action(async (address: string, options: ReleaseOptions) => {\n\t\ttry {\n\t\t\tconst result = await runRelease(address, options);\n\t\t\tif (options.format === 'json') printCliJson(result);\n\t\t\telse console.log(formatReleaseHuman(result));\n\t\t\tprocess.exitCode = result.outcome === 'released' ? 0 : 1;\n\t\t} catch (error) {\n\t\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\t\tif (options.format === 'json')\n\t\t\t\tprintCliJson({ outcome: 'release-refused', detail });\n\t\t\telse console.error(`release-refused: ${escapeDiagnosticText(detail)}`);\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t});\n","/**\n * DX-030 Block 1: REPL Command\n *\n * dbsp repl [--schema <path>] - Launch interactive REPL.\n * CLI-022: Batch mode support with --eval and --input options.\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { DbCasing } from '@dbsp/types';\nimport { Command } from 'commander';\nimport { config } from '../config.js';\nimport { validateIdentifier } from '../utils/identifier-validation.js';\nimport { loadSchema, loadSchemaFromCwd } from '../utils/schema-loader.js';\n\nexport interface ReplOptions {\n\tschema?: string;\n\t/** CLI-020: Database connection URL for execution mode */\n\tdb?: string;\n\t/** CLI-022: Single query to evaluate (batch mode) */\n\teval?: string;\n\t/** CLI-022: File containing queries to execute (batch mode, one per line) */\n\tinput?: string;\n\t/** CLI-022: Output format for batch mode */\n\tformat?: 'text' | 'json';\n\t/** DEMO-E2E: Assertion file for validating query output */\n\tassert?: string;\n\t/** CLI-IMPORT: SQL files to import before queries (injected as .import commands) */\n\timport?: string[];\n\t/** CLI-USE: PostgreSQL schema to use (injected as .use command) */\n\tuse?: string;\n\t/** CLI-MUT: Start REPL with parse mode enabled */\n\tparse?: boolean;\n\t/** CLI-MUT: Start REPL with exec mode enabled */\n\texec?: boolean;\n\t/** CLI-CONFIG: Custom config file path (default: ~/.dbsp/config.json) */\n\tconfig?: string;\n\t/** CLI-CASING: Column naming convention (describes DB column casing) */\n\tcasing?: 'snake' | 'camel' | 'none';\n}\n\nexport const replCommand = new Command('repl')\n\t.description('Launch interactive REPL for exploring schema and queries')\n\t.option('-s, --schema <path>', 'Path to schema file (default: auto-detect)')\n\t.option(\n\t\t'-d, --db <url>',\n\t\t'PostgreSQL connection URL for execution mode (e.g., postgres://localhost/mydb)',\n\t)\n\t.option('-e, --eval <query>', 'Execute a single query and exit (batch mode)')\n\t.option(\n\t\t'-i, --input <file>',\n\t\t'Execute queries from file, one per line (batch mode)',\n\t)\n\t.option(\n\t\t'-f, --format <format>',\n\t\t'Output format for batch mode: text (default) or json',\n\t\t'text',\n\t)\n\t.option(\n\t\t'-a, --assert <file>',\n\t\t'Assertion file to validate query output (requires --input)',\n\t)\n\t.option(\n\t\t'--import <files...>',\n\t\t'SQL files to import before queries (equivalent to .import commands)',\n\t)\n\t.option(\n\t\t'--use <schema>',\n\t\t'PostgreSQL schema to use (equivalent to .use command)',\n\t)\n\t.option('--parse', 'Start REPL with parse mode enabled (.parse toggle)')\n\t.option('--exec', 'Start REPL with exec mode enabled (.exec toggle)')\n\t.option(\n\t\t'--casing <type>',\n\t\t'Column naming convention: snake (DB uses snake_case), camel (DB uses camelCase), none (preserve as-is)',\n\t)\n\t.option(\n\t\t'-c, --config <path>',\n\t\t'Custom config file path (default: ~/.dbsp/config.json)',\n\t)\n\t.action(async (options: ReplOptions) => {\n\t\t// Set custom config path if provided\n\t\tif (options.config) {\n\t\t\tconfig.setConfigPath(options.config);\n\t\t}\n\t\t// Load config\n\t\tconfig.load();\n\t\ttry {\n\t\t\t// Load schema\n\t\t\tlet schemaPath: string;\n\t\t\tlet schema: Awaited<ReturnType<typeof loadSchema>>;\n\n\t\t\tif (options.schema) {\n\t\t\t\tschema = await loadSchema(options.schema);\n\t\t\t\tschemaPath = options.schema;\n\t\t\t} else {\n\t\t\t\tconst result = await loadSchemaFromCwd();\n\t\t\t\tschema = result.schema;\n\t\t\t\tschemaPath = result.path;\n\t\t\t}\n\n\t\t\t// DEMO-E2E: Validate --assert requires --input\n\t\t\tif (options.assert && !options.input) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'--assert requires --input (assertion files validate query output from input files)',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// CLI-IMPORT: Validate that --import requires batch mode (SQL file execution)\n\t\t\t// Note: --use, --parse, --exec work in interactive mode (REPL state setup)\n\t\t\tif (options.import && !options.eval && !options.input) {\n\t\t\t\tthrow new Error('--import requires batch mode (--eval or --input)');\n\t\t\t}\n\n\t\t\t// SEC: Validate --use schema name at the entry point so both the batch path\n\t\t\t// (which injects `.use <schema>`) and the interactive path (which passes\n\t\t\t// initialSchemaName) are protected against SQL injection.\n\t\t\tif (options.use) {\n\t\t\t\tvalidateIdentifier(options.use, 'schema');\n\t\t\t}\n\n\t\t\t// CLI-CASING: explicit flag wins; otherwise use the schema declaration.\n\t\t\tconst dbCasing = mapReplCasingOption(options.casing) ?? schema.dbCasing;\n\n\t\t\t// CLI-022: Batch mode - execute queries without interactive UI\n\t\t\tif (options.eval || options.input) {\n\t\t\t\tconst { runBatchMode } = await import('../repl/batch.js');\n\t\t\t\tconst queries: string[] = [];\n\n\t\t\t\t// CLI-USE: Inject .use command first (schema scoping)\n\t\t\t\tif (options.use) {\n\t\t\t\t\tqueries.push(`.use ${options.use}`);\n\t\t\t\t}\n\n\t\t\t\t// CLI-IMPORT: Inject .import commands for SQL files\n\t\t\t\tif (options.import) {\n\t\t\t\t\tfor (const file of options.import) {\n\t\t\t\t\t\tqueries.push(`.import ${file}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (options.eval) {\n\t\t\t\t\tqueries.push(options.eval);\n\t\t\t\t}\n\n\t\t\t\tif (options.input) {\n\t\t\t\t\t// EH-2: Map ENOENT to a friendly error instead of raw stack trace\n\t\t\t\t\tlet content: string;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontent = readFileSync(options.input, 'utf-8');\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconst isNotFound =\n\t\t\t\t\t\t\terr instanceof Error &&\n\t\t\t\t\t\t\t'code' in err &&\n\t\t\t\t\t\t\t(err as NodeJS.ErrnoException).code === 'ENOENT';\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tisNotFound\n\t\t\t\t\t\t\t\t? `Input file not found: ${options.input}`\n\t\t\t\t\t\t\t\t: `Failed to read input file: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tqueries.push(...content.split('\\n'));\n\t\t\t\t}\n\n\t\t\t\tawait runBatchMode({\n\t\t\t\t\tqueries,\n\t\t\t\t\tschema,\n\t\t\t\t\tschemaPath,\n\t\t\t\t\tformat: options.format ?? 'text',\n\t\t\t\t\t...(options.db && { databaseUrl: options.db }),\n\t\t\t\t\t...(options.assert && { assertFile: options.assert }),\n\t\t\t\t\t...(dbCasing && { dbCasing }),\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Dynamic import to avoid loading React/Ink for other commands\n\t\t\tconst { startRepl } = await import('../repl/index.js');\n\t\t\t// CLI-020: Pass database URL if provided\n\t\t\t// CLI-MUT: Pass initial REPL state options\n\t\t\tawait startRepl({\n\t\t\t\tschema,\n\t\t\t\tschemaPath,\n\t\t\t\t...(options.db && { databaseUrl: options.db }),\n\t\t\t\t...(options.use && { initialSchemaName: options.use }),\n\t\t\t\t...(options.parse && { initialParseMode: true }),\n\t\t\t\t...(options.exec && { initialExecMode: true }),\n\t\t\t\t...(dbCasing && { dbCasing }),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconsole.error(`❌ ${message}`);\n\t\t\tprocess.exit(1);\n\t\t}\n\t});\n\nfunction mapReplCasingOption(\n\tcasing: ReplOptions['casing'],\n): DbCasing | undefined {\n\tswitch (casing) {\n\t\tcase 'snake':\n\t\t\treturn 'snake_case';\n\t\tcase 'camel':\n\t\t\treturn 'camelCase';\n\t\tcase 'none':\n\t\t\treturn 'preserve';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n","/**\n * Verify Command — Schema Drift Detection\n *\n * dbsp verify - Compare schema vs real database using the comparison engine.\n * Detects drift in tables, columns, types, nullable, defaults, FKs, indexes.\n */\n\nimport {\n\tcomparePgsqlDatabaseSchema,\n\tcreatePgsqlAdapter,\n\tescapeDiagnosticText,\n} from '@dbsp/adapter-pgsql';\nimport { Command } from 'commander';\nimport { createDbConnection, redactDbUrl } from '../utils/db-utils.js';\nimport { printCliJson } from '../utils/output.js';\nimport { loadSchema } from '../utils/schema-loader.js';\nimport { formatVerifyResult, verifyFromDiff } from '../verifier.js';\n\nexport const verifyCommand = new Command('verify')\n\t.description('Compare schema vs real database (drift detection)')\n\t.option(\n\t\t'-s, --schema <path>',\n\t\t'Path to schema file (default: dbsp.schema.ts)',\n\t)\n\t.requiredOption('-d, --db <url>', 'Database connection URL (required)')\n\t.option('--schema-name <name>', 'Database schema name (default: public)')\n\t.option('--json', 'Output as JSON')\n\t.action(\n\t\tasync (options: {\n\t\t\tschema?: string;\n\t\t\tdb: string;\n\t\t\tschemaName?: string;\n\t\t\tjson?: boolean;\n\t\t}) => {\n\t\t\tconst schemaPath = options.schema ?? 'dbsp.schema.ts';\n\n\t\t\tconst redactedUrl = redactDbUrl(options.db);\n\n\t\t\tif (!options.json) {\n\t\t\t\tconsole.log(`🔍 Verifying schema: ${schemaPath}`);\n\t\t\t\tconsole.log(` Database: ${redactedUrl}`);\n\t\t\t\tif (options.schemaName) {\n\t\t\t\t\tconsole.log(` Schema: ${options.schemaName}`);\n\t\t\t\t}\n\t\t\t\tconsole.log('');\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Load schema from file → ModelIR\n\t\t\t\tconst loaded = await loadSchema(schemaPath);\n\t\t\t\tconst schemaModel = loaded.model;\n\n\t\t\t\t// Connect to database\n\t\t\t\tconst { pool } = await createDbConnection(options.db);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst adapter = createPgsqlAdapter(pool);\n\t\t\t\t\t// Live diff: introspect database and canonicalise PostgreSQL CHECK\n\t\t\t\t\t// expressions before comparing.\n\t\t\t\t\tconst diff = await comparePgsqlDatabaseSchema(adapter, schemaModel, {\n\t\t\t\t\t\t...(options.schemaName ? { schema: options.schemaName } : {}),\n\t\t\t\t\t\t...(loaded.dbCasing !== undefined\n\t\t\t\t\t\t\t? { dbCasing: loaded.dbCasing }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\tonExpressionCanonicalizationWarning: (warning) =>\n\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t`⚠️ [${warning.kind} ${escapeDiagnosticText(warning.table)}.${escapeDiagnosticText(warning.name)}] ${warning.message}`,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t});\n\n\t\t\t\t\t// Convert to verify result\n\t\t\t\t\t// Keep the legacy reporting fields sourced from introspection so\n\t\t\t\t\t// --json consumers continue to see database table names as before.\n\t\t\t\t\tconst dbModel = await adapter.introspect({\n\t\t\t\t\t\t...(options.schemaName ? { schema: options.schemaName } : {}),\n\t\t\t\t\t});\n\t\t\t\t\tconst schemaTables = Array.from(schemaModel.tables.keys());\n\t\t\t\t\tconst dbTables = Array.from(dbModel.tables.keys());\n\t\t\t\t\tconst result = verifyFromDiff(diff, schemaTables, dbTables);\n\n\t\t\t\t\t// Output\n\t\t\t\t\tif (options.json) {\n\t\t\t\t\t\t// Exclude the full diff meta from JSON output (too verbose)\n\t\t\t\t\t\tconst { diff: _diff, ...jsonResult } = result;\n\t\t\t\t\t\tprintCliJson({\n\t\t\t\t\t\t\t...jsonResult,\n\t\t\t\t\t\t\tsummary: diff.summary,\n\t\t\t\t\t\t\thasDestructive: diff.hasDestructive,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(formatVerifyResult(result));\n\t\t\t\t\t}\n\n\t\t\t\t\t// EH-14: set exit code; let finally run pool.end() before process exits\n\t\t\t\t\tprocess.exitCode = result.valid ? 0 : 1;\n\t\t\t\t\treturn;\n\t\t\t\t} finally {\n\t\t\t\t\t// Close database connection\n\t\t\t\t\tawait pool.end();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message =\n\t\t\t\t\terror instanceof Error ? error.message : 'Unknown error occurred';\n\t\t\t\t// CC-2+EH-7: If --json, error goes to stdout as JSON; otherwise stderr\n\t\t\t\tif (options.json) {\n\t\t\t\t\tprintCliJson({ status: 'error', error: message });\n\t\t\t\t} else {\n\t\t\t\t\tconsole.error(`❌ Error: ${message}`);\n\t\t\t\t}\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t},\n\t);\n","/**\n * Schema Verifier — Drift Detection via Comparison Engine\n *\n * Compares schema definition against real database using the\n * adapter's compareSchemata engine for full drift detection.\n *\n * Detects: tables, columns, types, nullable, defaults, FKs, indexes, PKs.\n */\n\nimport type { ChangeKind, SchemaChange, SchemaDiff } from '@dbsp/adapter-pgsql';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type DriftSeverity = 'error' | 'warning' | 'info';\n\n/** The observed occupancy state of a declared paired table re-address. */\nexport type ReaddressDriftState =\n\t| 'source-only'\n\t| 'target-only'\n\t| 'target-occupied'\n\t| 'source-missing'\n\t| 'unknown';\n\nexport type DriftType =\n\t// Tables\n\t| 'missing_table_in_db'\n\t| 'missing_table_in_schema'\n\t| 'readdress_table'\n\t// Columns\n\t| 'missing_column_in_db'\n\t| 'missing_column_in_schema'\n\t| 'type_mismatch'\n\t| 'nullable_mismatch'\n\t| 'default_mismatch'\n\t| 'unique_mismatch'\n\t// Constraints\n\t| 'primary_key_mismatch'\n\t| 'missing_fk_in_db'\n\t| 'missing_fk_in_schema'\n\t| 'fk_on_delete_mismatch'\n\t// Indexes\n\t| 'missing_index_in_db'\n\t| 'missing_index_in_schema'\n\t// CHECK constraints\n\t| 'missing_check_in_db'\n\t| 'missing_check_in_schema'\n\t// ENUM types\n\t| 'missing_enum_in_db'\n\t| 'missing_enum_in_schema'\n\t| 'enum_value_mismatch'\n\t// Column enhancements\n\t| 'collation_mismatch'\n\t| 'identity_mismatch'\n\t// Comments\n\t| 'comment_mismatch'\n\t// Extensions & Sequences\n\t| 'missing_extension'\n\t| 'missing_sequence'\n\t| 'sequence_mismatch'\n\t// Constraints\n\t| 'constraint_validation_mismatch'\n\t// Row-Level Security\n\t| 'rls_enabled_mismatch'\n\t| 'missing_policy_in_db'\n\t| 'missing_policy_in_schema';\n\nexport interface DriftIssue {\n\t/** Issue severity */\n\tseverity: DriftSeverity;\n\t/** Human-readable message */\n\tmessage: string;\n\t/** Table affected (if any) */\n\ttable?: string;\n\t/** Column affected (if any) */\n\tcolumn?: string;\n\t/** Issue type for programmatic handling */\n\ttype: DriftType;\n\t/** Present for a declared re-address; describes its executable/refused state. */\n\treaddress?: {\n\t\treadonly state: ReaddressDriftState;\n\t\treadonly sourcePresent?: boolean;\n\t\treadonly targetPresent?: boolean;\n\t};\n}\n\nexport interface VerifyResult {\n\t/** Whether the schema matches the database */\n\tvalid: boolean;\n\t/** List of drift issues found */\n\tissues: DriftIssue[];\n\t/** Tables in schema */\n\tschemaTables: string[];\n\t/** Tables in database */\n\tdbTables: string[];\n\t/** Structured diff (for programmatic consumers) */\n\tdiff: SchemaDiff;\n}\n\n// ============================================================================\n// Change → Drift Mapping\n// ============================================================================\n\nconst CHANGE_TO_DRIFT: Record<\n\tChangeKind,\n\t{ type: DriftType; severity: DriftSeverity }\n> = {\n\tcreate_table: { type: 'missing_table_in_db', severity: 'error' },\n\tdrop_table: { type: 'missing_table_in_schema', severity: 'warning' },\n\treaddress_table: { type: 'readdress_table', severity: 'error' },\n\tadd_column: { type: 'missing_column_in_db', severity: 'error' },\n\tdrop_column: { type: 'missing_column_in_schema', severity: 'info' },\n\talter_column_type: { type: 'type_mismatch', severity: 'error' },\n\talter_column_nullable: { type: 'nullable_mismatch', severity: 'warning' },\n\talter_column_default: { type: 'default_mismatch', severity: 'warning' },\n\talter_column_unique: { type: 'unique_mismatch', severity: 'warning' },\n\tadd_primary_key: { type: 'primary_key_mismatch', severity: 'error' },\n\tdrop_primary_key: { type: 'primary_key_mismatch', severity: 'error' },\n\tadd_foreign_key: { type: 'missing_fk_in_db', severity: 'error' },\n\tdrop_foreign_key: { type: 'missing_fk_in_schema', severity: 'warning' },\n\talter_foreign_key: { type: 'fk_on_delete_mismatch', severity: 'warning' },\n\tcreate_index: { type: 'missing_index_in_db', severity: 'warning' },\n\tdrop_index: { type: 'missing_index_in_schema', severity: 'info' },\n\t// CHECK constraints\n\tadd_check_constraint: { type: 'missing_check_in_db', severity: 'warning' },\n\tdrop_check_constraint: { type: 'missing_check_in_schema', severity: 'info' },\n\t// ENUM types\n\tcreate_enum: { type: 'missing_enum_in_db', severity: 'error' },\n\talter_enum_add_value: { type: 'enum_value_mismatch', severity: 'warning' },\n\tdrop_enum: { type: 'missing_enum_in_schema', severity: 'warning' },\n\t// Column enhancements\n\talter_column_collation: { type: 'collation_mismatch', severity: 'warning' },\n\talter_column_identity: { type: 'identity_mismatch', severity: 'warning' },\n\t// Comments\n\tadd_comment: { type: 'comment_mismatch', severity: 'info' },\n\tdrop_comment: { type: 'comment_mismatch', severity: 'info' },\n\t// Extensions & Sequences\n\tcreate_extension: { type: 'missing_extension', severity: 'error' },\n\tdrop_extension: { type: 'missing_extension', severity: 'info' },\n\tcreate_sequence: { type: 'missing_sequence', severity: 'warning' },\n\talter_sequence: { type: 'sequence_mismatch', severity: 'warning' },\n\tdrop_sequence: { type: 'missing_sequence', severity: 'info' },\n\t// Constraints\n\tvalidate_constraint: {\n\t\ttype: 'constraint_validation_mismatch',\n\t\tseverity: 'warning',\n\t},\n\t// Row-Level Security\n\tenable_rls: { type: 'rls_enabled_mismatch', severity: 'warning' },\n\tdisable_rls: { type: 'rls_enabled_mismatch', severity: 'warning' },\n\tcreate_policy: { type: 'missing_policy_in_db', severity: 'warning' },\n\tdrop_policy: { type: 'missing_policy_in_schema', severity: 'warning' },\n};\n\nfunction changeToDriftIssue(change: SchemaChange): DriftIssue {\n\tconst mapping = CHANGE_TO_DRIFT[change.kind] ?? {\n\t\ttype: 'type_mismatch' as DriftType,\n\t\tseverity: 'warning' as DriftSeverity,\n\t};\n\tif (change.kind === 'readdress_table') {\n\t\tconst assessment = change.meta?.readdressAssessment;\n\t\tconst state: ReaddressDriftState =\n\t\t\tassessment === 'source-only' ||\n\t\t\tassessment === 'target-only' ||\n\t\t\tassessment === 'target-occupied' ||\n\t\t\tassessment === 'source-missing'\n\t\t\t\t? assessment\n\t\t\t\t: 'unknown';\n\t\tconst sourcePresent = change.meta?.sourcePresent;\n\t\tconst targetPresent = change.meta?.targetPresent;\n\t\treturn {\n\t\t\tseverity:\n\t\t\t\tstate === 'source-only' || state === 'target-only'\n\t\t\t\t\t? 'warning'\n\t\t\t\t\t: mapping.severity,\n\t\t\ttype: mapping.type,\n\t\t\ttable: change.table,\n\t\t\tmessage: change.details,\n\t\t\treaddress: {\n\t\t\t\tstate,\n\t\t\t\t...(typeof sourcePresent === 'boolean' ? { sourcePresent } : {}),\n\t\t\t\t...(typeof targetPresent === 'boolean' ? { targetPresent } : {}),\n\t\t\t},\n\t\t};\n\t}\n\treturn {\n\t\tseverity: mapping.severity,\n\t\ttype: mapping.type,\n\t\ttable: change.table,\n\t\t...(change.column !== undefined ? { column: change.column } : {}),\n\t\tmessage: change.details,\n\t};\n}\n\n// ============================================================================\n// Verification (from SchemaDiff)\n// ============================================================================\n\n/**\n * Convert a SchemaDiff into a VerifyResult.\n *\n * @param diff - Structured diff from compareSchemata()\n * @param schemaTables - Table names in schema (for backward compat)\n * @param dbTables - Table names in database (for backward compat)\n */\nexport function verifyFromDiff(\n\tdiff: SchemaDiff,\n\tschemaTables: string[],\n\tdbTables: string[],\n): VerifyResult {\n\tconst issues = diff.changes.map(changeToDriftIssue);\n\n\t// Sort by severity (error > warning > info)\n\tconst severityOrder: Record<DriftSeverity, number> = {\n\t\terror: 0,\n\t\twarning: 1,\n\t\tinfo: 2,\n\t};\n\tissues.sort(\n\t\t(a: DriftIssue, b: DriftIssue) =>\n\t\t\tseverityOrder[a.severity] - severityOrder[b.severity],\n\t);\n\n\tconst hasErrors = issues.some((i: DriftIssue) => i.severity === 'error');\n\n\treturn {\n\t\tvalid: !hasErrors,\n\t\tissues,\n\t\tschemaTables,\n\t\tdbTables,\n\t\tdiff,\n\t};\n}\n\n// ============================================================================\n// Format\n// ============================================================================\n\n/**\n * Format verification result for CLI output.\n */\nexport function formatVerifyResult(result: VerifyResult): string {\n\tconst lines: string[] = [];\n\n\tif (result.valid) {\n\t\tlines.push('✅ Schema matches database');\n\t} else {\n\t\tlines.push('❌ Schema drift detected');\n\t}\n\n\tlines.push('');\n\tlines.push(`Tables in schema: ${result.schemaTables.length}`);\n\tlines.push(`Tables in database: ${result.dbTables.length}`);\n\tlines.push('');\n\n\tif (result.issues.length === 0) {\n\t\tlines.push('No issues found.');\n\t} else {\n\t\tconst errors = result.issues.filter((i) => i.severity === 'error');\n\t\tconst warnings = result.issues.filter((i) => i.severity === 'warning');\n\t\tconst infos = result.issues.filter((i) => i.severity === 'info');\n\n\t\tif (errors.length > 0) {\n\t\t\tlines.push(`❌ ${errors.length} error(s):`);\n\t\t\tfor (const issue of errors) {\n\t\t\t\tlines.push(` ${issue.message}`);\n\t\t\t}\n\t\t\tlines.push('');\n\t\t}\n\n\t\tif (warnings.length > 0) {\n\t\t\tlines.push(`⚠️ ${warnings.length} warning(s):`);\n\t\t\tfor (const issue of warnings) {\n\t\t\t\tlines.push(` ${issue.message}`);\n\t\t\t}\n\t\t\tlines.push('');\n\t\t}\n\n\t\tif (infos.length > 0) {\n\t\t\tlines.push(`ℹ️ ${infos.length} info:`);\n\t\t\tfor (const issue of infos) {\n\t\t\t\tlines.push(` ${issue.message}`);\n\t\t\t}\n\t\t\tlines.push('');\n\t\t}\n\t}\n\n\treturn lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAQA,SAAS,qBAAqB;AAC9B,SAAS,WAAAA,WAAS,sBAAsB;;;ACRxC,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAChC;AAAA,EACC;AAAA,EACA;AAAA,EACA,4BAAAC;AAAA,EACA,0BAAAC;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA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M,EACX,YAAY,sDAAsD,EAClE,QAAQ,YAAY,OAAO;AAG7B,QAAQ,WAAW,eAAe;AAClC,QAAQ,WAAW,iBAAiB;AACpC,QAAQ,WAAW,WAAW;AAC9B,QAAQ,WAAW,gBAAgB;AACnC,QAAQ,WAAW,YAAY;AAC/B,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,cAAc;AACjC,QAAQ,WAAW,gBAAgB;AACnC,QAAQ,WAAW,WAAW;AAC9B,QAAQ,WAAW,aAAa;AAEhC,IAAM,gBAAgB,aAAa,QAAQ,KAAK,MAAM,CAAC,CAAC;AAIxD,IAAI,eAAe;AAClB,aAAW,WAAW,CAAC,SAAS,GAAG,QAAQ,QAAQ;AAClD,YAAQ,gBAAgB,EAAE,UAAU,MAAM;AAAA,IAAC,EAAE,CAAC;AAChD;AAIA,WAAW,WAAW,CAAC,SAAS,GAAG,QAAQ,QAAQ,EAAG,SAAQ,aAAa;AAE3E,IAAI;AACH,UAAQ,MAAM;AACf,SAAS,KAAK;AAGb,MAAI,eAAe,kBAAkB,IAAI,aAAa,GAAG;AACxD,YAAQ,KAAK,CAAC;AAAA,EACf;AACA,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AACrD,MAAI,eAAe;AAClB,iBAAa,EAAE,QAAQ,SAAS,OAAO,QAAQ,CAAC;AAAA,EACjD,OAAO;AACN,YAAQ,MAAM,UAAK,OAAO,EAAE;AAAA,EAC7B;AACA,UAAQ,KAAK,CAAC;AACf;","names":["Command","createPgTransitionLessor","createPgTransitionPack","escapeDiagnosticText","readPgLedgerAddressChain","acquireTransitionLease","createPackRegistry","transitionPlanDigest","validateNormalizedManagedStepManifest","ledgerAddressKey","REFUSAL_VOCABULARY","Command","record","address","decision","randomUUID","createPgsqlAdapter","readPgCatalogueIdentity","canonicalJson","canonicalJsonDigest","validateNormalizedManagedStepManifest","canonicalJson","canonicalJsonDigest","validateNormalizedManagedStepManifest","databaseId","createPgsqlAdapter","readPgCatalogueIdentity","randomUUID","createPgsqlAdapter","createPgTransitionLessor","createPgTransitionRunPersister","acquireTransitionLease","acquireTransitionLease","createPgTransitionLessor","observed","createPgsqlAdapter","registry","createPgTransitionRunPersister","escapeDiagnosticText","ledgerAddressKey","home","readPgLedgerAddressChain","canonicalJson","record","acceptance","canonicalJson","createPackRegistry","createPgTransitionPack","escapeDiagnosticText","acceptance","REFUSAL_VOCABULARY","acquireTransitionLease","createPgTransitionLessor","transitionPlanDigest","validateNormalizedManagedStepManifest","record","Command","result","exitCode","Command","Command","outputPath","isDeepStrictEqual","createPgTransitionLessor","escapeDiagnosticText","readPgCatalogueIdentity","readPgLedgerAddressChain","acquireTransitionLease","projectLedgerChain","Command","isDeepStrictEqual","acquireTransitionLease","createPgTransitionLessor","projectLedgerChain","readPgLedgerAddressChain","readPgCatalogueIdentity","Command","escapeDiagnosticText","mkdirSync","writeFileSync","dirname","resolve","Command","Command","resolve","mkdirSync","dirname","writeFileSync","createHash","dirname","escapeDiagnosticText","getNamingPluginForDbCasing","declarationSetFromModel","Command","dirname","declarationSetFromModel","createHash","record","getNamingPluginForDbCasing","escapeDiagnosticText","Command","createHash","escapeDiagnosticText","readPgLedgerAddressChain","readPgLedgerReservationsForExecution","readPgLedgerScopeCurrency","readTransitionJournal","withPgTransitionRunLock","acquireExclusiveTransitionLease","canonicalJson","canonicalJsonDigest","outcomeClaimId","projectLedgerChain","transitionPlanDigest","Command","canonicalJson","canonicalJsonDigest","escapeDiagnosticText","createHash","transitionPlanDigest","outcomeClaimId","acceptance","withPgTransitionRunLock","acquireExclusiveTransitionLease","readTransitionJournal","home","readPgLedgerScopeCurrency","readPgLedgerReservationsForExecution","readPgLedgerAddressChain","projectLedgerChain","open","Command","assertPgDatabaseWritable","createPgTransitionPack","isPgDatabaseReadOnlyError","readPgLedgerScopeCurrency","readPgObservationContextFromLessor","readTransitionJournal","withPgTransitionRunLock","assumptionAccepted","createApplier","createPackRegistry","transitionPlanDigest","Command","assumptionAccepted","transitionPlanDigest","readTransitionJournal","ledgerHome","home","readPgLedgerScopeCurrency","withPgTransitionRunLock","assertPgDatabaseWritable","isPgDatabaseReadOnlyError","result","createApplier","createPackRegistry","createPgTransitionPack","readPgObservationContextFromLessor","Command","createPgTransitionLessor","escapeDiagnosticText","acquireTransitionLease","Command","acquireTransitionLease","createPgTransitionLessor","escapeDiagnosticText","Command","Command","Command","comparePgsqlDatabaseSchema","createPgsqlAdapter","escapeDiagnosticText","Command","assessment","Command","createPgsqlAdapter","comparePgsqlDatabaseSchema","escapeDiagnosticText","Command"]}