@dbsp/adapter-pgsql 6.0.0 → 7.0.0

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/explain/explain.ts","../src/extensions/paradedb.ts","../src/extensions/pgsql-builtins.ts","../src/extensions/pgvector.ts","../src/naming.ts","../src/redact-params.ts","../src/transition/release.ts","../src/transition/public-api.ts","../src/transition/reconcile.ts"],"sourcesContent":["/**\n * @dbsp/adapter-pgsql\n *\n * Native PostgreSQL adapter using tree-to-tree transformation:\n * PlanReport → PostgreSQL AST → SQL (via pgsql-deparser)\n */\n\n// Assert & Convention helpers — public API\nexport {\n\tDEFAULT_PK_COLUMN,\n\tdefaultFkDerivation,\n\ttype FkColumnDerivation,\n} from './assert-field.js';\n// AST Helpers — public API (internal helpers remain in ./ast-helpers.js)\nexport { normalizeSQL } from './ast-helpers.js';\n// Compiler\nexport {\n\ttype BatchValuesJoinDecision,\n\ttype CompiledResult,\n\ttype CompilerOptions,\n\tcompilePlan,\n\tisBatchValuesJoinDecision,\n\tisJoinDecision,\n\tisPrecompiledJoinDecision,\n\ttype JoinDecision,\n\tPlanCompiler,\n\ttype PlanDecision,\n\ttype PrecompiledJoinDecision,\n\ttype SimplifiedPlanReport,\n} from './compiler.js';\n// PostgreSQL type spelling/canonicalization boundary.\nexport { dbTypesEqual } from './db-type.js';\n// DDL Generation\nexport {\n\ttype AddedEnumValue,\n\tAutoIncrementTransitionUnsupportedError,\n\tassertCreateIndexesSupported,\n\tassertCreateIndexSupported,\n\tassertDeclarableChangeKind,\n\tassertGeneratedPostconditionSession,\n\tassertNoRepeatedExpressionSurfaceDrift,\n\ttype ChangeKind,\n\tCheckConstraintNewEnumValueError,\n\ttype ComparePgsqlDatabaseSchemaOptions,\n\ttype CompareSchemataOptions,\n\tcanGenerateCreateIndex,\n\tclassifyGeneratedMutation,\n\tcomparePgsqlDatabaseSchema,\n\tcompareSchemata,\n\tcreatePgsqlGeneratedManagedStep,\n\ttype DiffSummary,\n\tdecodeGeneratedPostcondition,\n\tdecodeGeneratedPostconditionPayload,\n\tExpressionCanonicalizationUnavailableError,\n\tExpressionKeyedIndexPredicateCanonicalizationUnsupportedError,\n\ttype GenerateDDLOptions,\n\ttype GeneratedIdentityObservation,\n\ttype GeneratedMutationClassification,\n\ttype GeneratedPostcondition,\n\ttype GeneratedPostconditionBindingAddress,\n\tGeneratedPostconditionBindingResolutionError,\n\ttype GeneratedPostconditionObservation,\n\tGeneratedPostconditionProofInFlightError,\n\ttype GeneratedPostconditionReadBack,\n\tGeneratedPostconditionReplanRequiredError,\n\ttype GeneratedPostconditionSession,\n\tGeneratedPostconditionSessionDeactivatedError,\n\tGeneratedPostconditionWorkInFlightError,\n\ttype GeneratedStructuralObservation,\n\tgenerateCreateIndex,\n\tgenerateDDL,\n\tgenerateDownSQL,\n\tgeneratedPostconditionDigest,\n\tgeneratedPostconditionForChange,\n\tgenerateMigrationSQL,\n\ttype IndexCapabilityContext,\n\tIndexFeatureUnsupportedError,\n\tIndexPredicateCanonicalizationError,\n\ttype IndexRenderSpec,\n\tisGeneratedMutationDestructive,\n\ttype MigrationSQLOptions,\n\tmapColumnType,\n\tmapOnDeleteAction,\n\tNonConvergentSchemaDiffError,\n\ttype NonConvergentSchemaDiffSurface,\n\tPartialIndexPredicateNewEnumValueError,\n\ttype PgSchemaDiff,\n\tRawIndexPredicateFallbackError,\n\ttype ReferencedKeyKind,\n\ttype ReferencedKeyRemovalConflict,\n\tReferencedKeyRemovalError,\n\treadGeneratedPostcondition,\n\treadGeneratedPostconditionReadBack,\n\trefusesRecordedPlanRemoval,\n\trenderCreateIndex,\n\ttype SchemaChange,\n\ttype SchemaDiff,\n\ttoGeneratedPostconditionBindingAddress,\n\tverifyGeneratedCheckPostcondition,\n\tverifyGeneratedColumnPostcondition,\n\tverifyGeneratedIdentityPostcondition,\n\tverifyGeneratedIndexPostcondition,\n\tverifyGeneratedTablePostcondition,\n\twithGeneratedPostconditionSession,\n} from './ddl/index.js';\n// EXPLAIN support\nexport {\n\tbuildExplain,\n\tbuildExplainAnalyzeJson,\n\tbuildExplainPlan,\n\tbuildExplainVerbose,\n\ttype ExplainFormat,\n\ttype ExplainOptions,\n\ttype ExplainPlan,\n\tgetRowEstimates,\n\tgetTotalExecutionTime,\n\tparseExplainJson,\n} from './explain/index.js';\nexport {\n\ttype CanonicalizeCheckConstraintsOptions,\n\tCheckConstraintCanonicalizationError,\n\ttype CheckConstraintCanonicalizationWarning,\n\tColumnDefaultCanonicalizationError,\n\ttype ColumnDefaultCanonicalizationWarning,\n\tcanonicalizeCheckConstraints,\n\ttype ExpressionCanonicalizationWarning,\n} from './expression-canonicalizer.js';\n// Extensions (pgvector, ParadeDB, PG builtins)\nexport {\n\tbm25Search,\n\tbooleanSearch,\n\tboost,\n\tcosineDistance,\n\tgenerateSeries,\n\tinnerProduct,\n\tl2Distance,\n\tnextval,\n\tparse,\n\trawDistance,\n\tscore,\n\tvectorDims,\n} from './extensions/index.js';\n// Handler Registry — types only (implementation details remain in ./handlers/index.js)\nexport type {\n\tCompilerContext,\n\tCompilerState,\n\tDecision,\n\tExpressionHandler,\n\tIncludeHandler,\n\tIncludeResult,\n\tWhereDispatcher,\n\tWhereHandler,\n} from './handlers/index.js';\n// Introspection\nexport {\n\ttype DetectedHierarchy,\n\ttype IntrospectedModelIR,\n\ttype IntrospectionOptions,\n\tintrospect,\n\ttype SchemaScopeOptions,\n} from './introspection.js';\n// Mutations\nexport {\n\tbuildOnConflictClause,\n\ttype ConflictAction,\n\ttype ConflictTarget,\n\tcompileDelete,\n\tcompileInsert,\n\tcompileMutation,\n\tcompileUpdate,\n\tcompileUpsert,\n\tconditionalUpdate,\n\ttype DeleteConfig,\n\texcludedRef,\n\ttype InsertConfig,\n\ttype UpdateConfig,\n\ttype UpsertConfig,\n} from './mutations/index.js';\n// Naming resolution\nexport { resolveLogicalName } from './naming.js';\n// Naming plugins\nexport {\n\tCamelCaseNamingPlugin,\n\tcamelCaseNaming,\n\tgetNamingPluginForDbCasing,\n\tIdentityNamingPlugin,\n\tidentityNaming,\n\ttype NamingPlugin,\n} from './naming-plugin.js';\n// ParamRef validation\nexport {\n\tcollectAndValidateParamRefs,\n\tcreateAnyExpr,\n\tcreateEqualityExpr,\n\tcreateParamRef,\n\tcreateTypeCastParamRef,\n\ttype ParamRefValidationResult,\n\tvalidateParamRef,\n} from './param-ref.js';\n// Adapter\nexport {\n\tcreatePgsqlAdapter,\n\tcreatePgsqlCompileOnlyAdapter,\n\ttype PgAdvisoryLockKey,\n\ttype PgAdvisoryLockResult,\n\tPgsqlAdapter,\n\ttype PgsqlAdapterOptions,\n\tPgsqlAdvisoryLockOptionsError,\n\ttype PgsqlBorrowedClientAdapterOptions,\n\ttype PgsqlCompileOnlyAdapterOptions,\n\tPgsqlPinnedConnectionAbortSignalError,\n\ttype PgsqlPoolAdapterOptions,\n\tPgsqlPreparedStatementReplayError,\n\ttype PgsqlPreparedStatementsOptions,\n\tPgsqlRawSqlTransactionControlError,\n\tPgsqlTransactionAbortedCommitError,\n\tPgsqlTransactionAbortedError,\n\tPgsqlTransactionAbortSignalError,\n\tPgsqlTransactionOptionsError,\n\tPgsqlTransactionTimeoutError,\n\ttype RollbackOnlyPgsqlScope,\n} from './pgsql-adapter.js';\n// PostgreSQL physical-name authority\nexport {\n\tcreatePgPhysicalModel,\n\ttype PgPhysicalModel,\n\ttype PgPhysicalModelInput,\n\tPgPhysicalModelInputError,\n\ttype PgPhysicalNameClaim,\n\ttype PgPhysicalNameCollision,\n\tPgPhysicalNameCollisionError,\n\ttype PgPhysicalNamespace,\n} from './physical-model/index.js';\nexport { derivePostgresqlCapabilitiesForVersion } from './postgresql-capabilities.js';\n// Redaction (params logging safety)\nexport {\n\tDEFAULT_REDACTION_PATTERNS,\n\ttype RedactionConfig,\n\ttype RedactionPattern,\n\tredactParams,\n} from './redact-params.js';\n// Set operations (UNION/INTERSECT/EXCEPT)\nexport {\n\tcompileSetOperation,\n\tcreateLeafCompileFn,\n\ttype LeafCompileFn,\n\ttype SetOperationResult,\n} from './set-operation.js';\n// Streaming (cursor-based)\nexport {\n\tbuildCloseCursor,\n\tbuildDeclareCursor,\n\tbuildFetch,\n\tbuildFetchAll,\n\tbuildFetchFirst,\n\tbuildFetchForward,\n\tbuildFetchNext,\n\tbuildStreamingStatements,\n\ttype CursorHoldOption,\n\ttype CursorOptions,\n\ttype CursorScrollOption,\n\ttype FetchDirection,\n\ttype FetchOptions,\n\tgenerateCursorName,\n\ttype StreamConfig,\n} from './streaming/index.js';\nexport type {\n\tPgApplicationStepOwnedState,\n\tPgApplicationStepTx,\n\tPgConvergeApplicationStep,\n\tPgConvergeAssertStep,\n\tPgConvergeOnceStep,\n\tPgOwnedCheckState,\n} from './transition/application-step.js';\n// Startup convergence\nexport {\n\ttype PgConvergeCheckResult,\n\ttype PgConvergeInitializationFailure,\n\ttype PgConvergePlannedStep,\n\ttype PgConvergeRefusal,\n\ttype PgConvergeRefusalChange,\n\tPgConvergeRefusalError,\n\ttype PgConvergeResult,\n} from './transition/converge.js';\n// ADR-0003 transition planner pack\nexport {\n\tADD_CHECK_RULE_ID,\n\tALTER_AUTHORITY_OBSERVATION,\n\tALTER_COLUMN_SET_NOT_NULL_OPERATION_KIND,\n\tALTER_TYPE_ADD_VALUE_OPERATION_KIND,\n\ttype AlterColumnSetNotNullPayload,\n\ttype AlterTypeAddValuePayload,\n\tATTACH_LOGICAL_IDENTITY_OPERATION_KIND,\n\ttype AttachLogicalIdentityPayload,\n\tacquirePgLedgerLocks,\n\tacquirePgTransitionClient,\n\tappendIntentJournal,\n\tappendTransitionAuthorization,\n\tassertCreateUniqueIndexConcurrentlyRecoveryNotInvalid,\n\tassertPgDatabaseWritable,\n\tCOLUMN_EXISTS_OBSERVATION,\n\tclassifyPgDatabaseWritability,\n\tclassifyPgReaddressRecovery,\n\tclassifyPgReaddressSupport,\n\tclassifyPgWrite,\n\tclassifyRemovalEffectsClosure,\n\tcontainmentAuthorityOutcome,\n\tcreateAlterColumnSetNotNullOperationRuntime,\n\tcreateAlterTypeAddValueOperationRuntime,\n\tcreateAttachLogicalIdentityOperationRuntime,\n\tcreateEnumAddValueRule,\n\tcreateLogicalIdentityAdoptionRule,\n\tcreateManualSqlOperationRuntime,\n\tcreatePgExecutionContract,\n\tcreatePgObservationIssuer,\n\tcreatePgTransitionLessor,\n\tcreatePgTransitionPack,\n\tcreatePgTransitionRunPersister,\n\tcreateSetNotNullRule,\n\tDATABASE_READ_ONLY_OUTCOME,\n\tDBSP_LEDGER_EVENT_TABLE,\n\tDBSP_LEDGER_IDENTITY_TABLE,\n\tDBSP_LEDGER_MARKER_TABLE,\n\tDBSP_LEDGER_RESERVATION_TABLE,\n\tDBSP_LOGICAL_IDENTITY_TABLE,\n\tDBSP_META_SCHEMA,\n\tDBSP_TRANSITION_AUTHORIZATION_TABLE,\n\tDBSP_TRANSITION_JOURNAL_TABLE,\n\tDBSP_TRANSITION_RUN_PLAN_TABLE,\n\tDBSP_TRANSITION_RUN_TABLE,\n\tENGINE_VERSION_OBSERVATION,\n\tENUM_ADD_VALUE_RULE_ID,\n\tENUM_LABEL_VISIBLE_OBSERVATION,\n\tENUM_TYPE_EXISTS_OBSERVATION,\n\ttype EnumAddValueMatch,\n\ttype EnumAddValueRuleOptions,\n\tensureDbspMetaLedger,\n\tensurePgLedger,\n\tensurePgLedgerStorageVersion,\n\tensureTransitionJournal,\n\tevaluatePgExecutionContract,\n\texecutePgAdmittedOperation,\n\texecutePgDeclaredAdoption,\n\texecutePgObservationFromLessor,\n\texecutePgPersistedTableReaddress,\n\tfindPgLedgerTerminalMember,\n\ttype IdentityAdoptionAsserter,\n\tisPgDatabaseReadOnlyError,\n\tLOGICAL_IDENTITY_ADOPTION_RULE_ID,\n\tLOGICAL_IDENTITY_CARRIER_OBSERVATION,\n\ttype LogicalIdentityAdoptionMatch,\n\ttype LogicalIdentityAdoptionRuleOptions,\n\tMANUAL_SQL_OPERATION_KIND,\n\ttype ManualSqlPayload,\n\tNO_NULLS_GUARD,\n\tnormalizeManualSqlPayload,\n\tPG_INTROSPECTION_ARTIFACT,\n\tPG_LEDGER_SHAPE_VERSION,\n\tPG_OPERATION_PACK_ARTIFACT,\n\tPG_RULE_PACK_ARTIFACT,\n\ttype PgAdmittedOperation,\n\ttype PgAdmittedOperationResult,\n\ttype PgAdoptionPreflightResult,\n\ttype PgAdoptionResult,\n\ttype PgCatalogueIdentityQueryable,\n\tPgDatabaseReadOnlyError,\n\ttype PgDatabaseWritability,\n\ttype PgDeclaredAdoptionInput,\n\tPgExecutionContractDerivationError,\n\ttype PgLedgerAddressChain,\n\ttype PgLedgerLockResult,\n\ttype PgLedgerScopeCurrency,\n\tPgLedgerStorageUnsupportedError,\n\ttype PgLedgerTarget,\n\ttype PgLockedRun,\n\ttype PgOutcomeCheckpoint,\n\ttype PgOutcomeCheckpointObserver,\n\ttype PgOutcomeClaimRequest,\n\ttype PgOutcomeExecutionRequest,\n\ttype PgOutcomeNonTransactionalRequest,\n\ttype PgOutcomeReadBackFactory,\n\ttype PgOutcomeRecoveryRequest,\n\ttype PgOutcomeRecoveryResult,\n\ttype PgOutcomeResolution,\n\ttype PgOutcomeResolutionAppendResult,\n\ttype PgOutcomeResult,\n\ttype PgOutcomeTransactionalRequest,\n\ttype PgPersistedDeclaredAdoptionInput,\n\ttype PgPersistedReaddressInput,\n\ttype PgReaddressPairRecoveryResult,\n\ttype PgReinitializePreflightOptions,\n\ttype PgReinitializePreflightPool,\n\ttype PgReleaseResult,\n\ttype PgRemovalEffectAddress,\n\ttype PgRemovalEffectsClosure,\n\ttype PgTransitionClientLease,\n\ttype PgTransitionPackOptions,\n\tpgTargetIdentityMismatch,\n\tpreflightPgDeclaredAdoption,\n\tpreparePgExecutionSession,\n\tpreparePgRecoveryAdmission,\n\treadPgCatalogueIdentity,\n\treadPgExecutionTargetFromClient,\n\treadPgLedgerAddressChain,\n\treadPgLedgerControllerOid,\n\treadPgLedgerMarker,\n\treadPgLedgerReservationsForExecution,\n\treadPgLedgerScopeCurrency,\n\treadPgObservationContextFromClient,\n\treadPgObservationContextFromLessor,\n\treadPgOutcomeRecoveryReadBack,\n\treadPgRemovalEffectsClosure,\n\treadTransitionJournal,\n\treadVerifiedPgLedgerReservationsForPair,\n\trecordPgLedgerIdentity,\n\trecoverPgReaddressPair,\n\treleasePgManagedAddress,\n\trenderAlterColumnSetNotNullSql,\n\trenderAlterTypeAddValueSql,\n\trenderAttachLogicalIdentityLockSql,\n\trenderCreateDbspMetaSchemaSql,\n\trenderCreateLedgerEventTableSql,\n\trenderCreateLedgerIdentityTableSql,\n\trenderCreateLedgerImmutabilityFunctionSql,\n\trenderCreateLedgerImmutabilityTriggerSql,\n\trenderCreateLedgerMarkerTableSql,\n\trenderCreateLedgerReservationTableSql,\n\trenderCreateLedgerTerminalMemberIndexSql,\n\trenderCreateLogicalIdentityIndexesSql,\n\trenderCreateLogicalIdentitySideTableSql,\n\trenderCreateTransitionAuthorizationTableSql,\n\trenderCreateTransitionJournalTableSql,\n\trenderCreateTransitionRunPlanTableSql,\n\trenderCreateTransitionRunTableSql,\n\trenderInsertLogicalIdentitySql,\n\trenderNoNullsCheckSql,\n\trenderPgTableReaddressStatements,\n\trenderSetNotNullLockSql,\n\treservationsForRemovalClosure,\n\trunPgReinitializePreflight,\n\tSET_NOT_NULL_RULE_ID,\n\ttype SetNotNullMatch,\n\tTransitionRunIdentityMismatchError,\n\tvalidatePgLedgerRuntimeIntegrity,\n\tvalidatePgManagedLedgerCurrency,\n\twithPgTransitionRunLock,\n} from './transition/index.js';\nexport {\n\ttype ConvergePgBaseOptions,\n\ttype ConvergePgCheckOptions,\n\ttype ConvergePgOptions,\n\tconvergePg,\n} from './transition/public-api.js';\n// Durable transition recovery. This is the supported non-CLI reconciliation API.\nexport {\n\texecutionIdsForRun,\n\ttype PgReconcileFailureStage,\n\ttype PgReconcileRecoveryFailureCause,\n\ttype PgReconcileRecoveryOutcome,\n\ttype PgReconcileRecoveryReport,\n\ttype PgReconcileSelectedIssue,\n\tPgReconcileTransitionRunError,\n\ttype PgReconcileTransitionRunResult,\n\treconcilePgTransitionRun,\n} from './transition/reconcile.js';\n// Validation\nexport {\n\tescapeDiagnosticText,\n\tInvalidIdentifierError,\n\tisReservedKeyword,\n\tsanitizeForDisplay,\n\tvalidateIdentifier,\n\tvalidateIdentifiers,\n\tvalidateQualifiedIdentifier,\n\tvalidateSqlExpression,\n} from './validate.js';\n","/**\n * EXPLAIN Statement Compiler\n *\n * Generates PostgreSQL EXPLAIN statements with various options.\n * Supports:\n * - ANALYZE (execute and show actual run times)\n * - FORMAT (text, json, xml, yaml)\n * - VERBOSE, COSTS, BUFFERS, TIMING, SETTINGS\n */\n\nimport type { Node } from '@pgsql/types';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Output format for EXPLAIN results.\n */\nexport type ExplainFormat = 'text' | 'json' | 'xml' | 'yaml';\n\n/**\n * Options for EXPLAIN statement.\n */\nexport interface ExplainOptions {\n\t/** Execute the query and show actual run times */\n\tanalyze?: boolean;\n\t/** Show more detailed output */\n\tverbose?: boolean;\n\t/** Show cost estimates (default: true) */\n\tcosts?: boolean;\n\t/** Show buffer usage (requires analyze) */\n\tbuffers?: boolean;\n\t/** Show actual timing (requires analyze) */\n\ttiming?: boolean;\n\t/** Show non-default settings */\n\tsettings?: boolean;\n\t/** Output format */\n\tformat?: ExplainFormat;\n}\n\n// ============================================================================\n// EXPLAIN Builder\n// ============================================================================\n\n/**\n * Build an EXPLAIN statement wrapping a query.\n *\n * @param query - The query to explain (SelectStmt, InsertStmt, etc.)\n * @param options - EXPLAIN options\n * @returns ExplainStmt AST node\n *\n * @example\n * ```typescript\n * const selectAst = { SelectStmt: { ... } };\n * const explainAst = buildExplain(selectAst, { analyze: true, format: 'json' });\n * // Produces: EXPLAIN (ANALYZE, FORMAT JSON) SELECT ...\n * ```\n */\nexport function buildExplain(query: Node, options: ExplainOptions = {}): Node {\n\tconst defElems: Node[] = [];\n\n\t// Add options in standard order\n\tif (options.analyze !== undefined) {\n\t\tdefElems.push(buildDefElem('analyze', options.analyze));\n\t}\n\n\tif (options.verbose !== undefined) {\n\t\tdefElems.push(buildDefElem('verbose', options.verbose));\n\t}\n\n\tif (options.costs !== undefined) {\n\t\tdefElems.push(buildDefElem('costs', options.costs));\n\t}\n\n\tif (options.buffers !== undefined) {\n\t\tdefElems.push(buildDefElem('buffers', options.buffers));\n\t}\n\n\tif (options.timing !== undefined) {\n\t\tdefElems.push(buildDefElem('timing', options.timing));\n\t}\n\n\tif (options.settings !== undefined) {\n\t\tdefElems.push(buildDefElem('settings', options.settings));\n\t}\n\n\tif (options.format) {\n\t\tdefElems.push(buildDefElem('format', options.format));\n\t}\n\n\tconst explainStmt: { query: Node; options?: Node[] } = { query };\n\tif (defElems.length > 0) {\n\t\texplainStmt.options = defElems;\n\t}\n\n\treturn { ExplainStmt: explainStmt };\n}\n\n/**\n * Build EXPLAIN ANALYZE with JSON format (common pattern).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with ANALYZE and JSON format\n */\nexport function buildExplainAnalyzeJson(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tformat: 'json',\n\t});\n}\n\n/**\n * Build simple EXPLAIN (plan only, no execution).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with default options\n */\nexport function buildExplainPlan(query: Node): Node {\n\treturn buildExplain(query);\n}\n\n/**\n * Build verbose EXPLAIN with costs and buffers.\n *\n * @param query - The query to explain\n * @returns ExplainStmt with verbose options\n */\nexport function buildExplainVerbose(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tverbose: true,\n\t\tbuffers: true,\n\t\ttiming: true,\n\t});\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Build a DefElem node for EXPLAIN options.\n *\n * @param name - Option name (analyze, verbose, format, etc.)\n * @param value - Option value (boolean or string)\n * @returns DefElem AST node\n */\nfunction buildDefElem(name: string, value: boolean | string): Node {\n\tlet arg: Node | undefined;\n\n\tif (typeof value === 'boolean') {\n\t\t// Boolean options: ANALYZE TRUE/FALSE\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value ? 'true' : 'false',\n\t\t\t},\n\t\t};\n\t} else {\n\t\t// String options: FORMAT json\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\tDefElem: {\n\t\t\tdefname: name,\n\t\t\targ,\n\t\t\tdefaction: 'DEFELEM_UNSPEC',\n\t\t},\n\t};\n}\n\n/**\n * Parse EXPLAIN JSON output to get execution statistics.\n *\n * @param jsonOutput - The JSON string from EXPLAIN (ANALYZE, FORMAT JSON)\n * @returns Parsed plan with execution statistics\n */\nexport function parseExplainJson(jsonOutput: string): ExplainPlan[] {\n\ttry {\n\t\tconst parsed = JSON.parse(jsonOutput);\n\t\treturn Array.isArray(parsed) ? parsed : [parsed];\n\t} catch {\n\t\tthrow new Error('Failed to parse EXPLAIN JSON output');\n\t}\n}\n\n/**\n * Parsed EXPLAIN plan structure (simplified).\n */\nexport interface ExplainPlan {\n\tPlan: {\n\t\t'Node Type': string;\n\t\t'Relation Name'?: string;\n\t\tAlias?: string;\n\t\t'Startup Cost'?: number;\n\t\t'Total Cost'?: number;\n\t\t'Plan Rows'?: number;\n\t\t'Plan Width'?: number;\n\t\t'Actual Startup Time'?: number;\n\t\t'Actual Total Time'?: number;\n\t\t'Actual Rows'?: number;\n\t\t'Actual Loops'?: number;\n\t\tPlans?: ExplainPlan['Plan'][];\n\t};\n\t'Planning Time'?: number;\n\t'Execution Time'?: number;\n\tTriggers?: unknown[];\n}\n\n/**\n * Extract total execution time from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Total execution time in milliseconds\n */\nexport function getTotalExecutionTime(plans: ExplainPlan[]): number {\n\tif (plans.length === 0) return 0;\n\n\tconst plan = plans[0]!;\n\tconst planning = plan['Planning Time'] ?? 0;\n\tconst execution = plan['Execution Time'] ?? 0;\n\n\treturn planning + execution;\n}\n\n/**\n * Extract row counts from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Object with estimated and actual row counts\n */\nexport function getRowEstimates(plans: ExplainPlan[]): {\n\testimated: number;\n\tactual: number;\n} {\n\tif (plans.length === 0) return { estimated: 0, actual: 0 };\n\n\tconst rootPlan = plans[0]?.Plan;\n\tif (!rootPlan) return { estimated: 0, actual: 0 };\n\n\treturn {\n\t\testimated: rootPlan['Plan Rows'] ?? 0,\n\t\tactual: rootPlan['Actual Rows'] ?? 0,\n\t};\n}\n","/**\n * ParadeDB Extension Wrappers\n *\n * Type-safe query builders for ParadeDB BM25 full-text search.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(score('id').as('score'))\n * - WHERE: .where(bm25Search('symbols', query, { name: 3.0, doc: 1.0 }))\n * - ORDER BY: .orderBy(score('id'), 'desc')\n *\n * @remarks\n * ParadeDB functions accept both named and positional arguments.\n * This module uses named args via namedArg() for parse(), which produces:\n * paradedb.parse(field => 'field_name', query_string => $1)\n * Named parameter syntax is supported via the NamedArgExpressionIntent (EXT-NAMED-PARAMS).\n */\n\nimport {\n\tarray,\n\tExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\tnamedArg,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * BM25 relevance score for a row.\n *\n * Use in SELECT and ORDER BY to retrieve and sort by full-text relevance.\n * Requires a BM25 index on the table.\n *\n * @param keyField - The key field of the BM25 index (typically the primary key, e.g. 'id')\n * @returns ExpressionRef that compiles to: paradedb.score(\"keyField\")\n *\n * @example\n * orm.select('symbols').column(score('id').as('score')).orderBy(score('id'), 'desc')\n * // → paradedb.score(\"id\") AS \"score\"\n */\nexport function score(keyField: string): ExpressionRef {\n\treturn fn('paradedb.score', exprRef(keyField));\n}\n\n/**\n * Parse a single-field BM25 query expression.\n *\n * Compiles to: paradedb.parse(field => 'field_name', query_string => $N)\n *\n * @param field - Column name to search in (must be indexed in the BM25 index)\n * @param query - Query string value (will be bound as a parameter)\n * @returns ExpressionRef for use with boost() or booleanSearch()\n *\n * @example\n * parse('name', 'hello world')\n * // → paradedb.parse(field => 'name', query_string => $1)\n */\nexport function parse(\n\tfield: string,\n\tquery: ExpressionRef | unknown,\n): ExpressionRef {\n\t// If query is already an ExpressionRef, pass it directly so fn() unwraps .intent.\n\t// Otherwise, wrap it in param() so it becomes a bound $N parameter.\n\tconst queryExpr: ExpressionRef =\n\t\tquery instanceof ExpressionRef ? query : param(query);\n\treturn fn(\n\t\t'paradedb.parse',\n\t\tnamedArg('field', literal(field)),\n\t\tnamedArg('query_string', queryExpr),\n\t);\n}\n\n/**\n * Apply a boost multiplier to a BM25 sub-expression.\n *\n * Compiles to: paradedb.boost(factor, expr)\n *\n * @param factor - Boost multiplier (e.g. 3.0 for 3x weight)\n * @param expr - Expression to boost (typically a parse() call)\n * @returns ExpressionRef for use with booleanSearch()\n *\n * @example\n * boost(3.0, parse('name', 'hello'))\n * // → paradedb.boost(3.0, paradedb.parse('name', $1))\n */\nexport function boost(factor: number, expr: ExpressionRef): ExpressionRef {\n\treturn fn('paradedb.boost', literal(factor), expr);\n}\n\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(expr1, expr2, ...)\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(paradedb.boost(3.0, ...), paradedb.boost(1.0, ...))\n */\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(should => ARRAY[expr1, expr2, ...])\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(should => ARRAY[paradedb.boost(3.0, ...), paradedb.boost(1.0, ...)])\n */\nexport function booleanSearch(exprs: ExpressionRef[]): ExpressionRef {\n\treturn fn('paradedb.boolean', namedArg('should', array(...exprs)));\n}\n\n/**\n * Full BM25 multi-field search with per-field boost weights.\n *\n * Produces: table @@@ paradedb.boolean(boost1, boost2, ...)\n *\n * Each field in `fieldBoosts` generates a `paradedb.boost(weight, paradedb.parse(field, $N))`\n * sub-expression. The same query string is used for all fields (single parameter binding).\n *\n * @param table - Table alias for the left side of the @@@ operator\n * @param query - Query string (bound as a single $N parameter, shared across all fields)\n * @param fieldBoosts - Map of column name → boost weight\n * @returns ExpressionRef for use in .where()\n *\n * @example\n * bm25Search('s', searchTerm, {\n * name_searchable: 3.0,\n * name: 1.0,\n * signature: 1.5,\n * doc_searchable: 1.0,\n * })\n * // → s @@@ paradedb.boolean(\n * // paradedb.boost(3.0, paradedb.parse('name_searchable', $1)),\n * // paradedb.boost(1.0, paradedb.parse('name', $1)),\n * // paradedb.boost(1.5, paradedb.parse('signature', $1)),\n * // paradedb.boost(1.0, paradedb.parse('doc_searchable', $1))\n * // )\n *\n * @remarks\n * The query parameter is shared: all parse() calls reference the same $N slot.\n * If you need different query strings per field, compose parse()/boost()/booleanSearch() manually.\n *\n * @remarks\n * ParadeDB's boolean() function accepts both positional args and the named\n * `should => ARRAY[...]` syntax. This wrapper uses positional args.\n * Named parameter syntax is deferred to EXT-NAMED-PARAMS.\n */\nexport function bm25Search(\n\ttable: string,\n\tquery: unknown,\n\tfieldBoosts: Record<string, number>,\n): ExpressionRef {\n\tconst queryParam = param(query);\n\tconst boostExprs = Object.entries(fieldBoosts).map(([field, weight]) =>\n\t\tboost(weight, fn('paradedb.parse', literal(field), queryParam)),\n\t);\n\tconst booleanExpr = booleanSearch(boostExprs);\n\treturn op('@@@', exprRef(table), booleanExpr);\n}\n","/**\n * PostgreSQL built-in function helpers.\n *\n * Thin wrappers around core expression primitives for common PostgreSQL functions.\n * Same pattern as pgvector.ts and paradedb.ts.\n */\nimport { type ExpressionRef, fn, literal } from '@dbsp/core';\n\n/**\n * Generate a series of values: generate_series(start, stop[, step])\n *\n * Returns a set of values from start to stop (inclusive), with an optional step.\n * Commonly used with CTE for batch operations.\n *\n * @example generateSeries(1, 100) → generate_series(1, 100)\n * @example generateSeries(0, 50, 5) → generate_series(0, 50, 5)\n */\nexport function generateSeries(\n\tstart: number,\n\tstop: number,\n\tstep?: number,\n): ExpressionRef {\n\tconst args: ExpressionRef[] = [literal(start), literal(stop)];\n\tif (step !== undefined) {\n\t\targs.push(literal(step));\n\t}\n\treturn fn('generate_series', ...args);\n}\n\n/**\n * Get next value from a sequence: nextval('sequence_name')\n *\n * @example nextval('order_id_seq') → nextval('order_id_seq')\n */\nexport function nextval(sequenceName: string): ExpressionRef {\n\treturn fn('nextval', literal(sequenceName));\n}\n","/**\n * pgvector Extension Wrappers\n *\n * Type-safe query builders for pgvector distance operators.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(cosineDistance('vector', qv).as('score'))\n * - WHERE: .where(cosineDistance('vector', qv).gte(0.5))\n * - ORDER BY: .orderBy(rawDistance('vector', qv), 'asc')\n */\n\nimport {\n\tcast,\n\ttype ExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * Cosine similarity: 1 - (col <=> vector)\n *\n * Score in [0, 1], higher = more similar.\n * Use in SELECT to get a similarity score.\n *\n * @example\n * orm.select('embeddings').column(cosineDistance('vector', qv).as('score'))\n */\nexport function cosineDistance(\n\tcolumn: string,\n\tvector: number[],\n): ExpressionRef {\n\treturn op(\n\t\t'-',\n\t\tliteral(1),\n\t\top('<=>', exprRef(column), cast(param(vector), 'vector')),\n\t);\n}\n\n/**\n * Raw cosine distance: col <=> vector\n *\n * Lower = closer. Index-friendly — use in ORDER BY for ANN search.\n * Do NOT use in SELECT as a similarity score (lower = closer is counterintuitive).\n *\n * @example\n * orm.select('embeddings').orderBy(rawDistance('vector', qv), 'asc')\n */\nexport function rawDistance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<=>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * L2 (Euclidean) distance: col <-> vector\n *\n * @example\n * orm.select('embeddings').orderBy(l2Distance('vector', qv), 'asc')\n */\nexport function l2Distance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<->', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Inner product distance: col <#> vector (negative inner product)\n *\n * For maximum inner product search: ORDER BY innerProduct('vector', qv) ASC.\n *\n * @example\n * orm.select('embeddings').orderBy(innerProduct('vector', qv), 'asc')\n */\nexport function innerProduct(column: string, vector: number[]): ExpressionRef {\n\treturn op('<#>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Get the number of dimensions of a vector column: vector_dims(col)\n *\n * Returns an integer — the dimension count of the stored vector.\n * Useful for sanity-checking that embeddings match the expected model dimension.\n *\n * @example\n * orm.from(embeddings).columns([vectorDims('vector').as('dim')]).first()\n * // → SELECT vector_dims(\"t0\".\"vector\") AS \"dim\" FROM \"embeddings\" AS \"t0\"\n */\nexport function vectorDims(column: string): ExpressionRef {\n\treturn fn('vector_dims', exprRef(column));\n}\n","/**\n * @module naming\n * Utilities for resolving database names to logical model names.\n *\n * The ModelIR.getTable() method expects logical (camelCase) names,\n * but the adapter often works with database (snake_case) names.\n * This module bridges that gap.\n */\n\nimport type { DbCasing, ModelIR } from '@dbsp/types';\nimport { getNamingPluginForDbCasing } from './naming-plugin.js';\n\n/**\n * Resolve a database table name to the corresponding logical model name.\n *\n * Converts the DB name using the naming convention, then looks it up in the model.\n * Falls back to exact match if conversion doesn't find a match.\n *\n * @param model - The model IR to search in\n * @param dbName - Database table name (e.g. \"post_comments\")\n * @param convention - Naming convention used by the adapter\n * @returns The logical table name if found, undefined otherwise\n *\n * @example\n * ```typescript\n * // With camelCase convention:\n * resolveLogicalName(model, \"post_comments\", \"camelCase\") // → \"postComments\"\n * resolveLogicalName(model, \"posts\", \"camelCase\") // → \"posts\"\n * resolveLogicalName(model, \"unknown\", \"camelCase\") // → undefined\n * ```\n */\nexport function resolveLogicalName(\n\tmodel: ModelIR,\n\tdbName: string,\n\tcasing: DbCasing,\n): string | undefined {\n\tconst plugin = getNamingPluginForDbCasing(casing);\n\tconst logicalName = plugin.toModel(dbName);\n\n\t// Try converted name first\n\tif (model.getTable(logicalName)) {\n\t\treturn logicalName;\n\t}\n\n\t// Fallback: exact match (handles identity/preserve cases)\n\tif (logicalName !== dbName && model.getTable(dbName)) {\n\t\treturn dbName;\n\t}\n\n\treturn undefined;\n}\n","/**\n * Redact sensitive values in a query dump's `params` array before logging.\n *\n * Defense-in-depth helper: when application code may have inserted PII as\n * literal parameter values (e.g. an email in a WHERE clause), this replaces\n * any string value matching a configured pattern with the `replacement`\n * placeholder. Non-string values are passed through unchanged.\n */\n\nexport type RedactionPattern = string | RegExp;\n\nexport type RedactionConfig = {\n\t/** Patterns to match against string param values. String = substring (case-insensitive); RegExp = `.test()`. */\n\treadonly patterns: ReadonlyArray<RedactionPattern>;\n\t/** Placeholder substituted for matched values. Default `'[REDACTED]'`. */\n\treadonly replacement?: string;\n};\n\n/**\n * Curated regex set for common PII shapes. Match against the value itself\n * (not the column name), so they detect data shaped like an email / token /\n * credit-card / SSN regardless of which `$N` slot it landed in.\n *\n * @stable Adding entries is non-breaking; removing one is a semver-major change\n * because callers may rely on a specific shape being redacted.\n */\nexport const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp> = Object.freeze([\n\t/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/, // email\n\t/^Bearer\\s+[A-Za-z0-9._-]+$/i, // bearer token\n\t/^eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/, // JWT\n\t/^\\d{3}-\\d{2}-\\d{4}$/, // US SSN\n\t/^\\d(?:[ -]?\\d){12,18}$/, // credit card (13-19 digits, optional spaces/dashes between)\n\t/^sk-[A-Za-z0-9]{20,}$/, // OpenAI-style API key\n]);\n\nconst DEFAULT_REPLACEMENT = '[REDACTED]';\n\n/**\n * Returns a NEW array of params with sensitive string values replaced.\n * The input array is never mutated. Non-string values pass through unchanged.\n */\nexport function redactParams(\n\tparams: readonly unknown[],\n\tconfig: RedactionConfig,\n): readonly unknown[] {\n\tconst replacement = config.replacement ?? DEFAULT_REPLACEMENT;\n\treturn params.map((value) =>\n\t\tmatchesAnyPattern(value, config.patterns) ? replacement : value,\n\t);\n}\n\nfunction matchesAnyPattern(\n\tvalue: unknown,\n\tpatterns: ReadonlyArray<RedactionPattern>,\n): boolean {\n\tif (typeof value !== 'string') return false;\n\tconst lowerValue = value.toLowerCase();\n\tfor (const pattern of patterns) {\n\t\tif (typeof pattern === 'string') {\n\t\t\tif (pattern.length > 0 && lowerValue.includes(pattern.toLowerCase()))\n\t\t\t\treturn true;\n\t\t} else {\n\t\t\tconst re =\n\t\t\t\tpattern.global || pattern.sticky\n\t\t\t\t\t? new RegExp(pattern.source, pattern.flags)\n\t\t\t\t\t: pattern;\n\t\t\tif (re.test(value)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n","/** End management without issuing DDL or accepting a caller-supplied controller. */\nimport { randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport { projectLedgerChain } from '@dbsp/core';\nimport type { LedgerAddress, LedgerHome, LedgerRefusal } from '@dbsp/types';\nimport * as transitionTypes from '@dbsp/types';\nimport { refusalFor } from '@dbsp/types';\nimport type { readPgCatalogueIdentity } from './catalogue-identity.js';\nimport {\n\treadPgLedgerAddressChain,\n\treadPgLedgerControllerOid,\n} from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport type { TransitionJournalQueryable } from './journal.js';\nimport {\n\tacquirePgLedgerLocks,\n\tappendPgLedgerRelease,\n\ttype PgLedgerTarget,\n} from './ledger.js';\nimport {\n\tformatPgTransitionUnknownError,\n\tPgResolvableRelationIdentityReadError,\n\treadPgCatalogueIdentityWithResolvableRelationLock,\n} from './lock-relation.js';\nimport {\n\tsetPgTransitionLockTimeout,\n\twithPgTransitionTransaction,\n} from './outcome-protocol.js';\nimport { createPostLockAdmissionEvidence } from './post-lock-admission-evidence.js';\nimport { readPgLedgerScopeCurrency } from './reinitialize-preflight.js';\n\ntype ControllerIdentity = { readonly name: string; readonly oid: string };\ntype ControllerIdentityHelper = (\n\trecorded: ControllerIdentity,\n\tcurrent: ControllerIdentity,\n) => boolean;\n\nconst sameControllerIdentity =\n\t(\n\t\ttransitionTypes as typeof transitionTypes & {\n\t\t\treadonly sameControllerIdentity?: ControllerIdentityHelper;\n\t\t}\n\t).sameControllerIdentity ??\n\t((recorded, current) =>\n\t\trecorded.name === current.name && recorded.oid === current.oid);\n\nexport type PgReleaseResult =\n\t| { readonly outcome: 'released' }\n\t| {\n\t\t\t/** A managed mutation must name a non-writable target before any release read. */\n\t\t\treadonly outcome: 'database-read-only';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\t/** Transport/query/read-only failure; never mislabel it malformed chain. */\n\t\t\treadonly outcome: 'release-unavailable';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\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\nfunction releaseRefusal(\n\taddress: LedgerAddress,\n\tcode: 'ERR-02' | 'ERR-05' | 'ERR-06' | 'ERR-08' | 'ERR-09',\n\tstate: LedgerRefusal['state'],\n): Extract<PgReleaseResult, { readonly outcome: 'release-refused' }> {\n\tconst refusal = refusalFor(code, { address, state });\n\treturn {\n\t\toutcome: 'release-refused',\n\t\tdetail: refusal.cause,\n\t\taddress,\n\t\trefusal,\n\t};\n}\n\nfunction target(home: LedgerHome): PgLedgerTarget {\n\tif (home.scope === 'database') return { scope: 'database' };\n\tif (!home.schema) throw new Error('schema release requires a schema ledger');\n\treturn { scope: 'schema', schema: home.schema };\n}\n\n/**\n * Refuse from the live subject before opening a release transaction.\n *\n * This is intentionally only an early refusal pass: success still repeats\n * every fact under the ledger lock below. It means a pending, blocked,\n * foreign-controller, or stale-lineage address keeps its classified refusal\n * even when a subsequently unnecessary transaction cleanup loses transport.\n */\nasync function preflightReleaseRefusal(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult | undefined> {\n\tconst currency = await readPgLedgerScopeCurrency(input.executor, input.home);\n\tif (currency.kind !== 'current')\n\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\tconst chain = await readPgLedgerAddressChain(\n\t\tinput.executor,\n\t\tinput.home,\n\t\tinput.address,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\tif (projection.kind !== 'projected-ledger-chain')\n\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\tif (projection.openClaim !== undefined)\n\t\treturn releaseRefusal(input.address, 'ERR-08', projection.stableState);\n\tif (projection.stableState !== 'managed' || !chain.terminalMember)\n\t\treturn releaseRefusal(input.address, 'ERR-02', projection.stableState);\n\tconst user = await input.executor.query(\n\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t);\n\tconst currentUser = user.rows[0]?.current_user;\n\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\tif (typeof currentUser !== 'string' || typeof currentUserOid !== 'string')\n\t\tthrow new Error('current_user role identity is unreadable');\n\tconst controllerOid =\n\t\t(\n\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\treadonly controllerOid?: string;\n\t\t\t}\n\t\t).controllerOid ??\n\t\t(await readPgLedgerControllerOid(\n\t\t\tinput.executor,\n\t\t\tinput.home,\n\t\t\tinput.address,\n\t\t\tchain.terminalMember.eventId,\n\t\t));\n\tif (\n\t\t!sameControllerIdentity(\n\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t)\n\t)\n\t\treturn releaseRefusal(input.address, 'ERR-05', projection.stableState);\n\treturn undefined;\n}\n\nexport async function releasePgManagedAddress(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult> {\n\ttry {\n\t\ttry {\n\t\t\tawait assertPgDatabaseWritable(input.executor);\n\t\t} catch (error) {\n\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'database-read-only',\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\tdetail: error.message,\n\t\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t\tconst earlyRefusal = await preflightReleaseRefusal(input);\n\t\tif (earlyRefusal) return earlyRefusal;\n\t\treturn await withPgTransitionTransaction(\n\t\t\tinput.executor,\n\t\t\tasync (executor) => {\n\t\t\t\tawait setPgTransitionLockTimeout(executor);\n\t\t\t\tconst lock = await acquirePgLedgerLocks(executor, [input.home]);\n\t\t\t\tif (lock.kind !== 'acquired') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait createPostLockAdmissionEvidence(executor, lock.proof);\n\t\t\t\t} catch {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\t\t\t\t}\n\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\texecutor,\n\t\t\t\t\tinput.home,\n\t\t\t\t\tinput.address,\n\t\t\t\t);\n\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\tif (projection.kind !== 'projected-ledger-chain') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\tif (projection.openClaim !== undefined) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-08',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (projection.stableState !== 'managed' || !chain.terminalMember) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-02',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst user = await executor.query(\n\t\t\t\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t\t\t\t);\n\t\t\t\tconst currentUser = user.rows[0]?.current_user;\n\t\t\t\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\t\t\t\tif (\n\t\t\t\t\ttypeof currentUser !== 'string' ||\n\t\t\t\t\ttypeof currentUserOid !== 'string'\n\t\t\t\t)\n\t\t\t\t\tthrow new Error('current_user role identity is unreadable');\n\t\t\t\tconst controllerOid =\n\t\t\t\t\t(\n\t\t\t\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\t\t\t\treadonly controllerOid?: string;\n\t\t\t\t\t\t}\n\t\t\t\t\t).controllerOid ??\n\t\t\t\t\t(await readPgLedgerControllerOid(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.home,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\tchain.terminalMember.eventId,\n\t\t\t\t\t));\n\t\t\t\tif (\n\t\t\t\t\t!sameControllerIdentity(\n\t\t\t\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet live: Awaited<ReturnType<typeof readPgCatalogueIdentity>>;\n\t\t\t\ttry {\n\t\t\t\t\tlive = await readPgCatalogueIdentityWithResolvableRelationLock(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'release',\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof PgResolvableRelationIdentityReadError))\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-09',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!live?.catalogueIdentity ||\n\t\t\t\t\t!chain.terminalMember.catalogueIdentity ||\n\t\t\t\t\t!isDeepStrictEqual(\n\t\t\t\t\t\tlive.catalogueIdentity,\n\t\t\t\t\t\tchain.terminalMember.catalogueIdentity,\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t// Kinds without a lockable relation retain the narrow window after this\n\t\t\t\t// final identity read and before their release append.\n\t\t\t\tconst eventId = `dbsp.release.${randomUUID()}`;\n\t\t\t\tawait appendPgLedgerRelease(executor, target(input.home), {\n\t\t\t\t\teventId,\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\teventKind: 'released',\n\t\t\t\t\tpredecessor: chain.terminalMember.eventId,\n\t\t\t\t});\n\t\t\t\treturn { outcome: 'released' };\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'release-unavailable',\n\t\t\taddress: input.address,\n\t\t\tdetail: formatPgTransitionUnknownError(error),\n\t\t};\n\t}\n}\n","import type { Pool } from 'pg';\nimport type { PgPhysicalModel } from '../physical-model/index.js';\nimport { escapeDiagnosticText, validateIdentifier } from '../validate.js';\nimport {\n\tconvergePgPhysical,\n\ttype ConvergePgOptions as InternalConvergePgOptions,\n\ttype PgConvergeCheckResult,\n\tPgConvergeRefusalError,\n\ttype PgConvergeResult,\n\tphysicalConvergeOptions,\n} from './converge.js';\n\nexport interface ConvergePgBaseOptions\n\textends Omit<\n\t\tInternalConvergePgOptions,\n\t\t'schema' | 'dbCasing' | 'mode' | 'declaredSequenceNames' | 'fkAutoIndex'\n\t> {}\nexport interface ConvergePgOptions extends ConvergePgBaseOptions {\n\treadonly mode?: 'apply';\n}\n\nexport interface ConvergePgCheckOptions extends ConvergePgBaseOptions {\n\treadonly mode: 'check';\n}\n\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions?: ConvergePgOptions,\n): Promise<PgConvergeResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgCheckOptions,\n): Promise<PgConvergeCheckResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgOptions | ConvergePgCheckOptions = {},\n): Promise<PgConvergeResult | PgConvergeCheckResult> {\n\ttry {\n\t\tvalidateIdentifier(physical.schema, 'schema');\n\t} catch (error) {\n\t\tthrow new PgConvergeRefusalError(\n\t\t\t'invalid-options',\n\t\t\t[],\n\t\t\t`converge refuses physical schema ${escapeDiagnosticText(String(physical.schema))}: ${escapeDiagnosticText(error instanceof Error ? error.message : String(error))}`,\n\t\t);\n\t}\n\treturn convergePgPhysical(\n\t\tpool,\n\t\tphysical,\n\t\tphysicalConvergeOptions(physical, options),\n\t);\n}\n","import { createHash } from 'node:crypto';\nimport {\n\tacquireExclusiveTransitionLease,\n\tassumptionAccepted,\n\tcanonicalJson,\n\tcanonicalJsonDigest,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\tresourceScopeCovers,\n\ttransitionPlanDigest,\n} from '@dbsp/core';\nimport type {\n\tLedgerAddress,\n\tLedgerHome,\n\tLedgerPayload,\n\tLedgerReservationRow,\n\tOutcomeIndeterminateRecoveryEvidence,\n\tResourceAddress,\n} from '@dbsp/types';\nimport { sameLedgerAddress } from '@dbsp/types';\nimport type { Pool } from 'pg';\nimport { readPgLedgerAddressChain } from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport { readTransitionJournal } from './journal.js';\nimport { readPgLedgerReservationsForExecution } from './ledger.js';\nimport { withPgTransitionRunLock } from './lessor.js';\nimport { assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid } from './operations/create-unique-index-concurrently.js';\nimport { recoverPgOutcomeClaim } from './outcome-protocol.js';\nimport { recoverPgReaddressPair } from './readdress.js';\nimport {\n\ttype PgLedgerScopeCurrency,\n\treadPgLedgerScopeCurrency,\n\treadVerifiedPgLedgerReservationsForPair,\n} from './reinitialize-preflight.js';\n\nexport type PgReconcileRecoveryOutcome =\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\nexport type PgReconcileRecoveryFailureCause =\n\t| 'catalogue'\n\t| 'malformed-journal'\n\t| 'transport';\n\n/** One ordered recovery attempt; diagnostics are raw and presentation-free. */\nexport interface PgReconcileRecoveryReport {\n\treadonly address: LedgerAddress;\n\treadonly outcome: PgReconcileRecoveryOutcome;\n\treadonly reason?: string;\n\treadonly pairId?: string;\n\treadonly failureCause?: PgReconcileRecoveryFailureCause;\n}\n\n/** The selected semantic refusal condition, never a CLI refusal document. */\nexport type PgReconcileSelectedIssue =\n\t| {\n\t\t\treadonly kind: 'ledger-not-current';\n\t\t\treadonly currency: Exclude<\n\t\t\t\tPgLedgerScopeCurrency,\n\t\t\t\t{ readonly kind: 'current' }\n\t\t\t>;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly reason: string;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'catalogue-unavailable';\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\treadonly kind: 'malformed-chain';\n\t\t\treadonly address: LedgerAddress;\n\t };\n\ninterface PgReconcileBaseResult {\n\treadonly runId: string;\n\treadonly addresses: readonly ResourceAddress[];\n\treadonly recovery?: readonly PgReconcileRecoveryReport[];\n\treadonly selectedIssue?: PgReconcileSelectedIssue;\n}\n\nexport type PgReconcileTransitionRunResult =\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'completed';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'unresolved';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'selection-unavailable';\n\t\t\treadonly detail?: string;\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly selectedIssue: Extract<\n\t\t\t\tPgReconcileSelectedIssue,\n\t\t\t\t{ readonly kind: 'database-read-only' }\n\t\t\t>;\n\t })\n\t| {\n\t\t\treadonly kind: 'busy';\n\t\t\treadonly runId: string;\n\t\t\treadonly addresses: readonly ResourceAddress[];\n\t };\n\nexport type PgReconcileFailureStage = 'reconcile' | 'journal' | 'catalogue';\n\n/** A read/recovery failure whose original cause remains available to callers. */\nexport class PgReconcileTransitionRunError extends Error {\n\tconstructor(\n\t\treadonly stage: PgReconcileFailureStage,\n\t\treadonly originalCause: unknown,\n\t) {\n\t\tsuper('PostgreSQL transition-run reconciliation failed', {\n\t\t\tcause: originalCause,\n\t\t});\n\t\tthis.name = 'PgReconcileTransitionRunError';\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\n/** Canonicalizes catalogue identity for an outcome resolution payload. */\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 { value, digest: canonicalJsonDigest(value) };\n}\n\nfunction recoveryReport(\n\taddress: LedgerAddress,\n\tresult: Awaited<ReturnType<typeof recoverPgOutcomeClaim>>,\n): PgReconcileRecoveryReport {\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};\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};\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): PgReconcileRecoveryReport {\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\nfunction isUnresolvedRecoveryOutcome(\n\treport: PgReconcileRecoveryReport,\n): boolean {\n\treturn [\n\t\t'pending',\n\t\t'blocked',\n\t\t'malformed-chain',\n\t\t'protocol-refused',\n\t\t'transport-ambiguous',\n\t\t'no-open-claim',\n\t\t'indeterminate-appended',\n\t\t'indeterminate-pair',\n\t].includes(report.outcome);\n}\n\nfunction selectedRecoveryIssue(\n\treports: readonly PgReconcileRecoveryReport[],\n): PgReconcileSelectedIssue | undefined {\n\tfor (const report of reports) {\n\t\tif (report.failureCause === 'malformed-journal')\n\t\t\treturn { kind: 'malformed-chain', address: report.address };\n\t\tif (report.failureCause === 'catalogue')\n\t\t\treturn { kind: 'catalogue-unavailable', address: report.address };\n\t}\n\treturn undefined;\n}\n\nfunction statementBundleDigest(\n\tstatements: readonly { readonly ordinal: number; readonly sql: string }[],\n): string {\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\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\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 * Returns recovery decisions for one durable run without reissuing DDL.\n *\n * Reconciliation keeps the run-lock session while `recoverPgOutcomeClaim`\n * acquires its own outcome session. The supplied pool must allow at least two\n * concurrent connections: a pool with `max: 1` waits forever under the lock.\n */\nexport async function reconcilePgTransitionRun(\n\tpool: Pool,\n\trunId: string,\n): Promise<PgReconcileTransitionRunResult> {\n\tlet stage: PgReconcileFailureStage = 'reconcile';\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\tpool,\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: LedgerAddress;\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.map((step) => {\n\t\t\t\t\t\t\tconst generatedStep = step as {\n\t\t\t\t\t\t\t\treadonly address?: LedgerAddress;\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\tconst addresses = material.map((claim) => claim.address);\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\trunId,\n\t\t\t\t\t\t\t\taddresses,\n\t\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\t\treason: error.message,\n\t\t\t\t\t\t\t\t\taffectedAddresses: addresses,\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\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\trunId,\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\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 affectedAddresses = material\n\t\t\t\t\t\t\t.filter((claim) => {\n\t\t\t\t\t\t\t\tconst claimHome = ledgerHome(claim.address);\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\tclaimHome.scope === home.scope &&\n\t\t\t\t\t\t\t\t\tclaimHome.schema === home.schema\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.map((claim) => claim.address);\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\trunId,\n\t\t\t\t\t\t\taddresses: affectedAddresses,\n\t\t\t\t\t\t\trecovery: affectedAddresses.map((address) => ({\n\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\toutcome: 'blocked' as const,\n\t\t\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\t\tcurrency.kind === 'not-current'\n\t\t\t\t\t\t\t\t\t\t? currency.reason\n\t\t\t\t\t\t\t\t\t\t: currency.kind,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\tkind: 'ledger-not-current' as const,\n\t\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t\t\taffectedAddresses,\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\trunId,\n\t\t\t\t\t\t\taddresses: material.map((claim) => claim.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: PgReconcileRecoveryReport[] = [];\n\t\t\t\t\tfor (const pairRows of readdressPairs.values()) {\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 closure = await readVerifiedPgLedgerReservationsForPair(\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\trunId,\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\trunId,\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\trunId,\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\trunId,\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\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: LedgerAddress,\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\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(pool, {\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 = recovery.some(isUnresolvedRecoveryOutcome);\n\t\t\t\t\tconst issue = selectedRecoveryIssue(recovery);\n\t\t\t\t\treturn unresolved\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t\t\t...(issue === undefined ? {} : { selectedIssue: issue }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\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') return { kind: 'busy', runId, addresses: [] };\n\t\treturn locked.value;\n\t} catch (error) {\n\t\tthrow new PgReconcileTransitionRunError(stage, error);\n\t}\n}\n\n/** Finds every execution id durably attributable to one transition run. */\nexport function executionIdsForRun(\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n): readonly string[] {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA;AAMA;AAEA;AAeA;;;AC4BO,SAAS,aAAa,OAAa,UAA0B,CAAC,GAAS;AAC7E,QAAM,WAAmB,CAAC;AAG1B,MAAI,QAAQ,YAAY,QAAW;AAClC,aAAS,KAAK,aAAa,WA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Aa,IAAI,OAAO,WAAW;AACpC,QACC,MAAM,UAAU,cAChB,YAAY,UACZ,OAAO,UACP,OAAO,OAAO,OAAO,gBAAgB;AAErC,mBAAa,IAAI,OAAO,OAAO,WAAW;AAAA,EAC5C;AACA,MAAI,eAAe,QAAQ;AAC1B,iBAAa,IAAI,4BAA4B,QAAQ,IAAI,KAAK,EAAE;AACjE,SAAO,CAAC,GAAG,YAAY;AACxB;;;ATrPA;","names":["fn","literal","exprRef","fn","literal","op","param","sameControllerIdentity","projectLedgerChain","target","projectLedgerChain"]}
1
+ {"version":3,"sources":["../src/explain/explain.ts","../src/extensions/paradedb.ts","../src/extensions/pgsql-builtins.ts","../src/extensions/pgvector.ts","../src/redact-params.ts","../src/transition/release.ts","../src/transition/public-api.ts","../src/transition/reconcile.ts"],"sourcesContent":["/**\n * EXPLAIN Statement Compiler\n *\n * Generates PostgreSQL EXPLAIN statements with various options.\n * Supports:\n * - ANALYZE (execute and show actual run times)\n * - FORMAT (text, json, xml, yaml)\n * - VERBOSE, COSTS, BUFFERS, TIMING, SETTINGS\n */\n\nimport type { Node } from '@pgsql/types';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Output format for EXPLAIN results.\n */\nexport type ExplainFormat = 'text' | 'json' | 'xml' | 'yaml';\n\n/**\n * Options for EXPLAIN statement.\n */\nexport interface ExplainOptions {\n\t/** Execute the query and show actual run times */\n\tanalyze?: boolean;\n\t/** Show more detailed output */\n\tverbose?: boolean;\n\t/** Show cost estimates (default: true) */\n\tcosts?: boolean;\n\t/** Show buffer usage (requires analyze) */\n\tbuffers?: boolean;\n\t/** Show actual timing (requires analyze) */\n\ttiming?: boolean;\n\t/** Show non-default settings */\n\tsettings?: boolean;\n\t/** Output format */\n\tformat?: ExplainFormat;\n}\n\n// ============================================================================\n// EXPLAIN Builder\n// ============================================================================\n\n/**\n * Build an EXPLAIN statement wrapping a query.\n *\n * @param query - The query to explain (SelectStmt, InsertStmt, etc.)\n * @param options - EXPLAIN options\n * @returns ExplainStmt AST node\n *\n * @example\n * ```typescript\n * const selectAst = { SelectStmt: { ... } };\n * const explainAst = buildExplain(selectAst, { analyze: true, format: 'json' });\n * // Produces: EXPLAIN (ANALYZE, FORMAT JSON) SELECT ...\n * ```\n */\nexport function buildExplain(query: Node, options: ExplainOptions = {}): Node {\n\tconst defElems: Node[] = [];\n\n\t// Add options in standard order\n\tif (options.analyze !== undefined) {\n\t\tdefElems.push(buildDefElem('analyze', options.analyze));\n\t}\n\n\tif (options.verbose !== undefined) {\n\t\tdefElems.push(buildDefElem('verbose', options.verbose));\n\t}\n\n\tif (options.costs !== undefined) {\n\t\tdefElems.push(buildDefElem('costs', options.costs));\n\t}\n\n\tif (options.buffers !== undefined) {\n\t\tdefElems.push(buildDefElem('buffers', options.buffers));\n\t}\n\n\tif (options.timing !== undefined) {\n\t\tdefElems.push(buildDefElem('timing', options.timing));\n\t}\n\n\tif (options.settings !== undefined) {\n\t\tdefElems.push(buildDefElem('settings', options.settings));\n\t}\n\n\tif (options.format) {\n\t\tdefElems.push(buildDefElem('format', options.format));\n\t}\n\n\tconst explainStmt: { query: Node; options?: Node[] } = { query };\n\tif (defElems.length > 0) {\n\t\texplainStmt.options = defElems;\n\t}\n\n\treturn { ExplainStmt: explainStmt };\n}\n\n/**\n * Build EXPLAIN ANALYZE with JSON format (common pattern).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with ANALYZE and JSON format\n */\nexport function buildExplainAnalyzeJson(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tformat: 'json',\n\t});\n}\n\n/**\n * Build simple EXPLAIN (plan only, no execution).\n *\n * @param query - The query to explain\n * @returns ExplainStmt with default options\n */\nexport function buildExplainPlan(query: Node): Node {\n\treturn buildExplain(query);\n}\n\n/**\n * Build verbose EXPLAIN with costs and buffers.\n *\n * @param query - The query to explain\n * @returns ExplainStmt with verbose options\n */\nexport function buildExplainVerbose(query: Node): Node {\n\treturn buildExplain(query, {\n\t\tanalyze: true,\n\t\tverbose: true,\n\t\tbuffers: true,\n\t\ttiming: true,\n\t});\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Build a DefElem node for EXPLAIN options.\n *\n * @param name - Option name (analyze, verbose, format, etc.)\n * @param value - Option value (boolean or string)\n * @returns DefElem AST node\n */\nfunction buildDefElem(name: string, value: boolean | string): Node {\n\tlet arg: Node | undefined;\n\n\tif (typeof value === 'boolean') {\n\t\t// Boolean options: ANALYZE TRUE/FALSE\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value ? 'true' : 'false',\n\t\t\t},\n\t\t};\n\t} else {\n\t\t// String options: FORMAT json\n\t\targ = {\n\t\t\tString: {\n\t\t\t\tsval: value,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\tDefElem: {\n\t\t\tdefname: name,\n\t\t\targ,\n\t\t\tdefaction: 'DEFELEM_UNSPEC',\n\t\t},\n\t};\n}\n\n/**\n * Parse EXPLAIN JSON output to get execution statistics.\n *\n * @param jsonOutput - The JSON string from EXPLAIN (ANALYZE, FORMAT JSON)\n * @returns Parsed plan with execution statistics\n */\nexport function parseExplainJson(jsonOutput: string): ExplainPlan[] {\n\ttry {\n\t\tconst parsed = JSON.parse(jsonOutput);\n\t\treturn Array.isArray(parsed) ? parsed : [parsed];\n\t} catch {\n\t\tthrow new Error('Failed to parse EXPLAIN JSON output');\n\t}\n}\n\n/**\n * Parsed EXPLAIN plan structure (simplified).\n */\nexport interface ExplainPlan {\n\tPlan: {\n\t\t'Node Type': string;\n\t\t'Relation Name'?: string;\n\t\tAlias?: string;\n\t\t'Startup Cost'?: number;\n\t\t'Total Cost'?: number;\n\t\t'Plan Rows'?: number;\n\t\t'Plan Width'?: number;\n\t\t'Actual Startup Time'?: number;\n\t\t'Actual Total Time'?: number;\n\t\t'Actual Rows'?: number;\n\t\t'Actual Loops'?: number;\n\t\tPlans?: ExplainPlan['Plan'][];\n\t};\n\t'Planning Time'?: number;\n\t'Execution Time'?: number;\n\tTriggers?: unknown[];\n}\n\n/**\n * Extract total execution time from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Total execution time in milliseconds\n */\nexport function getTotalExecutionTime(plans: ExplainPlan[]): number {\n\tif (plans.length === 0) return 0;\n\n\tconst plan = plans[0]!;\n\tconst planning = plan['Planning Time'] ?? 0;\n\tconst execution = plan['Execution Time'] ?? 0;\n\n\treturn planning + execution;\n}\n\n/**\n * Extract row counts from EXPLAIN ANALYZE JSON output.\n *\n * @param plans - Parsed EXPLAIN plans\n * @returns Object with estimated and actual row counts\n */\nexport function getRowEstimates(plans: ExplainPlan[]): {\n\testimated: number;\n\tactual: number;\n} {\n\tif (plans.length === 0) return { estimated: 0, actual: 0 };\n\n\tconst rootPlan = plans[0]?.Plan;\n\tif (!rootPlan) return { estimated: 0, actual: 0 };\n\n\treturn {\n\t\testimated: rootPlan['Plan Rows'] ?? 0,\n\t\tactual: rootPlan['Actual Rows'] ?? 0,\n\t};\n}\n","/**\n * ParadeDB Extension Wrappers\n *\n * Type-safe query builders for ParadeDB BM25 full-text search.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(score('id').as('score'))\n * - WHERE: .where(bm25Search('symbols', query, { name: 3.0, doc: 1.0 }))\n * - ORDER BY: .orderBy(score('id'), 'desc')\n *\n * @remarks\n * ParadeDB functions accept both named and positional arguments.\n * This module uses named args via namedArg() for parse(), which produces:\n * paradedb.parse(field => 'field_name', query_string => $1)\n * Named parameter syntax is supported via the NamedArgExpressionIntent (EXT-NAMED-PARAMS).\n */\n\nimport {\n\tarray,\n\tExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\tnamedArg,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * BM25 relevance score for a row.\n *\n * Use in SELECT and ORDER BY to retrieve and sort by full-text relevance.\n * Requires a BM25 index on the table.\n *\n * @param keyField - The key field of the BM25 index (typically the primary key, e.g. 'id')\n * @returns ExpressionRef that compiles to: paradedb.score(\"keyField\")\n *\n * @example\n * orm.select('symbols').column(score('id').as('score')).orderBy(score('id'), 'desc')\n * // → paradedb.score(\"id\") AS \"score\"\n */\nexport function score(keyField: string): ExpressionRef {\n\treturn fn('paradedb.score', exprRef(keyField));\n}\n\n/**\n * Parse a single-field BM25 query expression.\n *\n * Compiles to: paradedb.parse(field => 'field_name', query_string => $N)\n *\n * @param field - Column name to search in (must be indexed in the BM25 index)\n * @param query - Query string value (will be bound as a parameter)\n * @returns ExpressionRef for use with boost() or booleanSearch()\n *\n * @example\n * parse('name', 'hello world')\n * // → paradedb.parse(field => 'name', query_string => $1)\n */\nexport function parse(\n\tfield: string,\n\tquery: ExpressionRef | unknown,\n): ExpressionRef {\n\t// If query is already an ExpressionRef, pass it directly so fn() unwraps .intent.\n\t// Otherwise, wrap it in param() so it becomes a bound $N parameter.\n\tconst queryExpr: ExpressionRef =\n\t\tquery instanceof ExpressionRef ? query : param(query);\n\treturn fn(\n\t\t'paradedb.parse',\n\t\tnamedArg('field', literal(field)),\n\t\tnamedArg('query_string', queryExpr),\n\t);\n}\n\n/**\n * Apply a boost multiplier to a BM25 sub-expression.\n *\n * Compiles to: paradedb.boost(factor, expr)\n *\n * @param factor - Boost multiplier (e.g. 3.0 for 3x weight)\n * @param expr - Expression to boost (typically a parse() call)\n * @returns ExpressionRef for use with booleanSearch()\n *\n * @example\n * boost(3.0, parse('name', 'hello'))\n * // → paradedb.boost(3.0, paradedb.parse('name', $1))\n */\nexport function boost(factor: number, expr: ExpressionRef): ExpressionRef {\n\treturn fn('paradedb.boost', literal(factor), expr);\n}\n\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(expr1, expr2, ...)\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(paradedb.boost(3.0, ...), paradedb.boost(1.0, ...))\n */\n/**\n * Combine multiple BM25 sub-expressions with boolean OR logic.\n *\n * Compiles to: paradedb.boolean(should => ARRAY[expr1, expr2, ...])\n *\n * @param exprs - One or more sub-expressions (typically boost() calls)\n * @returns ExpressionRef for use on the right side of the @@@ operator\n *\n * @example\n * booleanSearch([boost(3.0, parse('name', q)), boost(1.0, parse('doc', q))])\n * // → paradedb.boolean(should => ARRAY[paradedb.boost(3.0, ...), paradedb.boost(1.0, ...)])\n */\nexport function booleanSearch(exprs: ExpressionRef[]): ExpressionRef {\n\treturn fn('paradedb.boolean', namedArg('should', array(...exprs)));\n}\n\n/**\n * Full BM25 multi-field search with per-field boost weights.\n *\n * Produces: table @@@ paradedb.boolean(boost1, boost2, ...)\n *\n * Each field in `fieldBoosts` generates a `paradedb.boost(weight, paradedb.parse(field, $N))`\n * sub-expression. The same query string is used for all fields (single parameter binding).\n *\n * @param table - Table alias for the left side of the @@@ operator\n * @param query - Query string (bound as a single $N parameter, shared across all fields)\n * @param fieldBoosts - Map of column name → boost weight\n * @returns ExpressionRef for use in .where()\n *\n * @example\n * bm25Search('s', searchTerm, {\n * name_searchable: 3.0,\n * name: 1.0,\n * signature: 1.5,\n * doc_searchable: 1.0,\n * })\n * // → s @@@ paradedb.boolean(\n * // paradedb.boost(3.0, paradedb.parse('name_searchable', $1)),\n * // paradedb.boost(1.0, paradedb.parse('name', $1)),\n * // paradedb.boost(1.5, paradedb.parse('signature', $1)),\n * // paradedb.boost(1.0, paradedb.parse('doc_searchable', $1))\n * // )\n *\n * @remarks\n * The query parameter is shared: all parse() calls reference the same $N slot.\n * If you need different query strings per field, compose parse()/boost()/booleanSearch() manually.\n *\n * @remarks\n * ParadeDB's boolean() function accepts both positional args and the named\n * `should => ARRAY[...]` syntax. This wrapper uses positional args.\n * Named parameter syntax is deferred to EXT-NAMED-PARAMS.\n */\nexport function bm25Search(\n\ttable: string,\n\tquery: unknown,\n\tfieldBoosts: Record<string, number>,\n): ExpressionRef {\n\tconst queryParam = param(query);\n\tconst boostExprs = Object.entries(fieldBoosts).map(([field, weight]) =>\n\t\tboost(weight, fn('paradedb.parse', literal(field), queryParam)),\n\t);\n\tconst booleanExpr = booleanSearch(boostExprs);\n\treturn op('@@@', exprRef(table), booleanExpr);\n}\n","/**\n * PostgreSQL built-in function helpers.\n *\n * Thin wrappers around core expression primitives for common PostgreSQL functions.\n * Same pattern as pgvector.ts and paradedb.ts.\n */\nimport { type ExpressionRef, fn, literal } from '@dbsp/core';\n\n/**\n * Generate a series of values: generate_series(start, stop[, step])\n *\n * Returns a set of values from start to stop (inclusive), with an optional step.\n * Commonly used with CTE for batch operations.\n *\n * @example generateSeries(1, 100) → generate_series(1, 100)\n * @example generateSeries(0, 50, 5) → generate_series(0, 50, 5)\n */\nexport function generateSeries(\n\tstart: number,\n\tstop: number,\n\tstep?: number,\n): ExpressionRef {\n\tconst args: ExpressionRef[] = [literal(start), literal(stop)];\n\tif (step !== undefined) {\n\t\targs.push(literal(step));\n\t}\n\treturn fn('generate_series', ...args);\n}\n\n/**\n * Get next value from a sequence: nextval('sequence_name')\n *\n * @example nextval('order_id_seq') → nextval('order_id_seq')\n */\nexport function nextval(sequenceName: string): ExpressionRef {\n\treturn fn('nextval', literal(sequenceName));\n}\n","/**\n * pgvector Extension Wrappers\n *\n * Type-safe query builders for pgvector distance operators.\n * All functions return ExpressionRef instances that can be used in:\n * - SELECT: .column(cosineDistance('vector', qv).as('score'))\n * - WHERE: .where(cosineDistance('vector', qv).gte(0.5))\n * - ORDER BY: .orderBy(rawDistance('vector', qv), 'asc')\n */\n\nimport {\n\tcast,\n\ttype ExpressionRef,\n\texprRef,\n\tfn,\n\tliteral,\n\top,\n\tparam,\n} from '@dbsp/core';\n\n/**\n * Cosine similarity: 1 - (col <=> vector)\n *\n * Score in [0, 1], higher = more similar.\n * Use in SELECT to get a similarity score.\n *\n * @example\n * orm.select('embeddings').column(cosineDistance('vector', qv).as('score'))\n */\nexport function cosineDistance(\n\tcolumn: string,\n\tvector: number[],\n): ExpressionRef {\n\treturn op(\n\t\t'-',\n\t\tliteral(1),\n\t\top('<=>', exprRef(column), cast(param(vector), 'vector')),\n\t);\n}\n\n/**\n * Raw cosine distance: col <=> vector\n *\n * Lower = closer. Index-friendly — use in ORDER BY for ANN search.\n * Do NOT use in SELECT as a similarity score (lower = closer is counterintuitive).\n *\n * @example\n * orm.select('embeddings').orderBy(rawDistance('vector', qv), 'asc')\n */\nexport function rawDistance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<=>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * L2 (Euclidean) distance: col <-> vector\n *\n * @example\n * orm.select('embeddings').orderBy(l2Distance('vector', qv), 'asc')\n */\nexport function l2Distance(column: string, vector: number[]): ExpressionRef {\n\treturn op('<->', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Inner product distance: col <#> vector (negative inner product)\n *\n * For maximum inner product search: ORDER BY innerProduct('vector', qv) ASC.\n *\n * @example\n * orm.select('embeddings').orderBy(innerProduct('vector', qv), 'asc')\n */\nexport function innerProduct(column: string, vector: number[]): ExpressionRef {\n\treturn op('<#>', exprRef(column), cast(param(vector), 'vector'));\n}\n\n/**\n * Get the number of dimensions of a vector column: vector_dims(col)\n *\n * Returns an integer — the dimension count of the stored vector.\n * Useful for sanity-checking that embeddings match the expected model dimension.\n *\n * @example\n * orm.from(embeddings).columns([vectorDims('vector').as('dim')]).first()\n * // → SELECT vector_dims(\"t0\".\"vector\") AS \"dim\" FROM \"embeddings\" AS \"t0\"\n */\nexport function vectorDims(column: string): ExpressionRef {\n\treturn fn('vector_dims', exprRef(column));\n}\n","/**\n * Redact sensitive values in a query dump's `params` array before logging.\n *\n * Defense-in-depth helper: when application code may have inserted PII as\n * literal parameter values (e.g. an email in a WHERE clause), this replaces\n * any string value matching a configured pattern with the `replacement`\n * placeholder. Non-string values are passed through unchanged.\n */\n\nexport type RedactionPattern = string | RegExp;\n\nexport type RedactionConfig = {\n\t/** Patterns to match against string param values. String = substring (case-insensitive); RegExp = `.test()`. */\n\treadonly patterns: ReadonlyArray<RedactionPattern>;\n\t/** Placeholder substituted for matched values. Default `'[REDACTED]'`. */\n\treadonly replacement?: string;\n};\n\n/**\n * Curated regex set for common PII shapes. Match against the value itself\n * (not the column name), so they detect data shaped like an email / token /\n * credit-card / SSN regardless of which `$N` slot it landed in.\n *\n * @stable Adding entries is non-breaking; removing one is a semver-major change\n * because callers may rely on a specific shape being redacted.\n */\nexport const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp> = Object.freeze([\n\t/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/, // email\n\t/^Bearer\\s+[A-Za-z0-9._-]+$/i, // bearer token\n\t/^eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/, // JWT\n\t/^\\d{3}-\\d{2}-\\d{4}$/, // US SSN\n\t/^\\d(?:[ -]?\\d){12,18}$/, // credit card (13-19 digits, optional spaces/dashes between)\n\t/^sk-[A-Za-z0-9]{20,}$/, // OpenAI-style API key\n]);\n\nconst DEFAULT_REPLACEMENT = '[REDACTED]';\n\n/**\n * Returns a NEW array of params with sensitive string values replaced.\n * The input array is never mutated. Non-string values pass through unchanged.\n */\nexport function redactParams(\n\tparams: readonly unknown[],\n\tconfig: RedactionConfig,\n): readonly unknown[] {\n\tconst replacement = config.replacement ?? DEFAULT_REPLACEMENT;\n\treturn params.map((value) =>\n\t\tmatchesAnyPattern(value, config.patterns) ? replacement : value,\n\t);\n}\n\nfunction matchesAnyPattern(\n\tvalue: unknown,\n\tpatterns: ReadonlyArray<RedactionPattern>,\n): boolean {\n\tif (typeof value !== 'string') return false;\n\tconst lowerValue = value.toLowerCase();\n\tfor (const pattern of patterns) {\n\t\tif (typeof pattern === 'string') {\n\t\t\tif (pattern.length > 0 && lowerValue.includes(pattern.toLowerCase()))\n\t\t\t\treturn true;\n\t\t} else {\n\t\t\tconst re =\n\t\t\t\tpattern.global || pattern.sticky\n\t\t\t\t\t? new RegExp(pattern.source, pattern.flags)\n\t\t\t\t\t: pattern;\n\t\t\tif (re.test(value)) return true;\n\t\t}\n\t}\n\treturn false;\n}\n","/** End management without issuing DDL or accepting a caller-supplied controller. */\nimport { randomUUID } from 'node:crypto';\nimport { isDeepStrictEqual } from 'node:util';\nimport { projectLedgerChain } from '@dbsp/core/internal';\nimport type { LedgerAddress, LedgerHome } from '@dbsp/types';\nimport * as transitionTypes from '@dbsp/types';\nimport { refusalFor } from '@dbsp/types';\nimport type { LedgerRefusal } from '@dbsp/types/internal';\nimport type { readPgCatalogueIdentity } from './catalogue-identity.js';\nimport {\n\treadPgLedgerAddressChain,\n\treadPgLedgerControllerOid,\n} from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport type { TransitionJournalQueryable } from './journal.js';\nimport {\n\tacquirePgLedgerLocks,\n\tappendPgLedgerRelease,\n\ttype PgLedgerTarget,\n} from './ledger.js';\nimport {\n\tformatPgTransitionUnknownError,\n\tPgResolvableRelationIdentityReadError,\n\treadPgCatalogueIdentityWithResolvableRelationLock,\n} from './lock-relation.js';\nimport {\n\tsetPgTransitionLockTimeout,\n\twithPgTransitionTransaction,\n} from './outcome-protocol.js';\nimport { createPostLockAdmissionEvidence } from './post-lock-admission-evidence.js';\nimport { readPgLedgerScopeCurrency } from './reinitialize-preflight.js';\n\ntype ControllerIdentity = { readonly name: string; readonly oid: string };\ntype ControllerIdentityHelper = (\n\trecorded: ControllerIdentity,\n\tcurrent: ControllerIdentity,\n) => boolean;\n\nconst sameControllerIdentity =\n\t(\n\t\ttransitionTypes as typeof transitionTypes & {\n\t\t\treadonly sameControllerIdentity?: ControllerIdentityHelper;\n\t\t}\n\t).sameControllerIdentity ??\n\t((recorded, current) =>\n\t\trecorded.name === current.name && recorded.oid === current.oid);\n\nexport type PgReleaseResult =\n\t| { readonly outcome: 'released' }\n\t| {\n\t\t\t/** A managed mutation must name a non-writable target before any release read. */\n\t\t\treadonly outcome: 'database-read-only';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\t/** Transport/query/read-only failure; never mislabel it malformed chain. */\n\t\t\treadonly outcome: 'release-unavailable';\n\t\t\treadonly detail: string;\n\t\t\treadonly address: LedgerAddress;\n\t }\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\nfunction releaseRefusal(\n\taddress: LedgerAddress,\n\tcode: 'ERR-02' | 'ERR-05' | 'ERR-06' | 'ERR-08' | 'ERR-09',\n\tstate: LedgerRefusal['state'],\n): Extract<PgReleaseResult, { readonly outcome: 'release-refused' }> {\n\tconst refusal = refusalFor(code, { address, state });\n\treturn {\n\t\toutcome: 'release-refused',\n\t\tdetail: refusal.cause,\n\t\taddress,\n\t\trefusal,\n\t};\n}\n\nfunction target(home: LedgerHome): PgLedgerTarget {\n\tif (home.scope === 'database') return { scope: 'database' };\n\tif (!home.schema) throw new Error('schema release requires a schema ledger');\n\treturn { scope: 'schema', schema: home.schema };\n}\n\n/**\n * Refuse from the live subject before opening a release transaction.\n *\n * This is intentionally only an early refusal pass: success still repeats\n * every fact under the ledger lock below. It means a pending, blocked,\n * foreign-controller, or stale-lineage address keeps its classified refusal\n * even when a subsequently unnecessary transaction cleanup loses transport.\n */\nasync function preflightReleaseRefusal(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult | undefined> {\n\tconst currency = await readPgLedgerScopeCurrency(input.executor, input.home);\n\tif (currency.kind !== 'current')\n\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\tconst chain = await readPgLedgerAddressChain(\n\t\tinput.executor,\n\t\tinput.home,\n\t\tinput.address,\n\t);\n\tconst projection = projectLedgerChain(chain);\n\tif (projection.kind !== 'projected-ledger-chain')\n\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\tif (projection.openClaim !== undefined)\n\t\treturn releaseRefusal(input.address, 'ERR-08', projection.stableState);\n\tif (projection.stableState !== 'managed' || !chain.terminalMember)\n\t\treturn releaseRefusal(input.address, 'ERR-02', projection.stableState);\n\tconst user = await input.executor.query(\n\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t);\n\tconst currentUser = user.rows[0]?.current_user;\n\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\tif (typeof currentUser !== 'string' || typeof currentUserOid !== 'string')\n\t\tthrow new Error('current_user role identity is unreadable');\n\tconst controllerOid =\n\t\t(\n\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\treadonly controllerOid?: string;\n\t\t\t}\n\t\t).controllerOid ??\n\t\t(await readPgLedgerControllerOid(\n\t\t\tinput.executor,\n\t\t\tinput.home,\n\t\t\tinput.address,\n\t\t\tchain.terminalMember.eventId,\n\t\t));\n\tif (\n\t\t!sameControllerIdentity(\n\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t)\n\t)\n\t\treturn releaseRefusal(input.address, 'ERR-05', projection.stableState);\n\treturn undefined;\n}\n\nexport async function releasePgManagedAddress(input: {\n\treadonly executor: TransitionJournalQueryable;\n\treadonly home: LedgerHome;\n\treadonly address: LedgerAddress;\n}): Promise<PgReleaseResult> {\n\ttry {\n\t\ttry {\n\t\t\tawait assertPgDatabaseWritable(input.executor);\n\t\t} catch (error) {\n\t\t\tif (isPgDatabaseReadOnlyError(error))\n\t\t\t\treturn {\n\t\t\t\t\toutcome: 'database-read-only',\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\tdetail: error.message,\n\t\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t\tconst earlyRefusal = await preflightReleaseRefusal(input);\n\t\tif (earlyRefusal) return earlyRefusal;\n\t\treturn await withPgTransitionTransaction(\n\t\t\tinput.executor,\n\t\t\tasync (executor) => {\n\t\t\t\tawait setPgTransitionLockTimeout(executor);\n\t\t\t\tconst lock = await acquirePgLedgerLocks(executor, [input.home]);\n\t\t\t\tif (lock.kind !== 'acquired') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait createPostLockAdmissionEvidence(executor, lock.proof);\n\t\t\t\t} catch {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-06', 'unknown');\n\t\t\t\t}\n\t\t\t\tconst chain = await readPgLedgerAddressChain(\n\t\t\t\t\texecutor,\n\t\t\t\t\tinput.home,\n\t\t\t\t\tinput.address,\n\t\t\t\t);\n\t\t\t\tconst projection = projectLedgerChain(chain);\n\t\t\t\tif (projection.kind !== 'projected-ledger-chain') {\n\t\t\t\t\treturn releaseRefusal(input.address, 'ERR-08', 'unknown');\n\t\t\t\t}\n\t\t\t\tif (projection.openClaim !== undefined) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-08',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (projection.stableState !== 'managed' || !chain.terminalMember) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-02',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst user = await executor.query(\n\t\t\t\t\t'SELECT current_user AS current_user, current_user::regrole::oid::text AS current_user_oid',\n\t\t\t\t);\n\t\t\t\tconst currentUser = user.rows[0]?.current_user;\n\t\t\t\tconst currentUserOid = user.rows[0]?.current_user_oid;\n\t\t\t\tif (\n\t\t\t\t\ttypeof currentUser !== 'string' ||\n\t\t\t\t\ttypeof currentUserOid !== 'string'\n\t\t\t\t)\n\t\t\t\t\tthrow new Error('current_user role identity is unreadable');\n\t\t\t\tconst controllerOid =\n\t\t\t\t\t(\n\t\t\t\t\t\tchain.terminalMember as typeof chain.terminalMember & {\n\t\t\t\t\t\t\treadonly controllerOid?: string;\n\t\t\t\t\t\t}\n\t\t\t\t\t).controllerOid ??\n\t\t\t\t\t(await readPgLedgerControllerOid(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.home,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\tchain.terminalMember.eventId,\n\t\t\t\t\t));\n\t\t\t\tif (\n\t\t\t\t\t!sameControllerIdentity(\n\t\t\t\t\t\t{ name: chain.terminalMember.controller, oid: controllerOid },\n\t\t\t\t\t\t{ name: currentUser, oid: currentUserOid },\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet live: Awaited<ReturnType<typeof readPgCatalogueIdentity>>;\n\t\t\t\ttry {\n\t\t\t\t\tlive = await readPgCatalogueIdentityWithResolvableRelationLock(\n\t\t\t\t\t\texecutor,\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'release',\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof PgResolvableRelationIdentityReadError))\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-09',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!live?.catalogueIdentity ||\n\t\t\t\t\t!chain.terminalMember.catalogueIdentity ||\n\t\t\t\t\t!isDeepStrictEqual(\n\t\t\t\t\t\tlive.catalogueIdentity,\n\t\t\t\t\t\tchain.terminalMember.catalogueIdentity,\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\treturn releaseRefusal(\n\t\t\t\t\t\tinput.address,\n\t\t\t\t\t\t'ERR-05',\n\t\t\t\t\t\tprojection.stableState,\n\t\t\t\t\t);\n\t\t\t\t// Kinds without a lockable relation retain the narrow window after this\n\t\t\t\t// final identity read and before their release append.\n\t\t\t\tconst eventId = `dbsp.release.${randomUUID()}`;\n\t\t\t\tawait appendPgLedgerRelease(executor, target(input.home), {\n\t\t\t\t\teventId,\n\t\t\t\t\taddress: input.address,\n\t\t\t\t\teventKind: 'released',\n\t\t\t\t\tpredecessor: chain.terminalMember.eventId,\n\t\t\t\t});\n\t\t\t\treturn { outcome: 'released' };\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\treturn {\n\t\t\toutcome: 'release-unavailable',\n\t\t\taddress: input.address,\n\t\t\tdetail: formatPgTransitionUnknownError(error),\n\t\t};\n\t}\n}\n","import type { Pool } from 'pg';\nimport type { PgPhysicalModel } from '../physical-model/index.js';\nimport { escapeDiagnosticText, validateIdentifier } from '../validate.js';\nimport {\n\tconvergePgPhysical,\n\ttype ConvergePgOptions as InternalConvergePgOptions,\n\ttype PgConvergeCheckResult,\n\tPgConvergeRefusalError,\n\ttype PgConvergeResult,\n\tphysicalConvergeOptions,\n} from './converge.js';\n\nexport interface ConvergePgBaseOptions\n\textends Omit<\n\t\tInternalConvergePgOptions,\n\t\t'schema' | 'dbCasing' | 'mode' | 'declaredSequenceNames' | 'fkAutoIndex'\n\t> {}\nexport interface ConvergePgOptions extends ConvergePgBaseOptions {\n\treadonly mode?: 'apply';\n}\n\nexport interface ConvergePgCheckOptions extends ConvergePgBaseOptions {\n\treadonly mode: 'check';\n}\n\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions?: ConvergePgOptions,\n): Promise<PgConvergeResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgCheckOptions,\n): Promise<PgConvergeCheckResult>;\nexport function convergePg(\n\tpool: Pool,\n\tphysical: PgPhysicalModel,\n\toptions: ConvergePgOptions | ConvergePgCheckOptions = {},\n): Promise<PgConvergeResult | PgConvergeCheckResult> {\n\ttry {\n\t\tvalidateIdentifier(physical.schema, 'schema');\n\t} catch (error) {\n\t\tthrow new PgConvergeRefusalError(\n\t\t\t'invalid-options',\n\t\t\t[],\n\t\t\t`converge refuses physical schema ${escapeDiagnosticText(String(physical.schema))}: ${escapeDiagnosticText(error instanceof Error ? error.message : String(error))}`,\n\t\t);\n\t}\n\treturn convergePgPhysical(\n\t\tpool,\n\t\tphysical,\n\t\tphysicalConvergeOptions(physical, options),\n\t);\n}\n","import { createHash } from 'node:crypto';\nimport {\n\tacquireExclusiveTransitionLease,\n\tassumptionAccepted,\n\tcanonicalJson,\n\tcanonicalJsonDigest,\n\toutcomeClaimId,\n\tprojectLedgerChain,\n\tresourceScopeCovers,\n\ttransitionPlanDigest,\n} from '@dbsp/core/internal';\nimport type {\n\tLedgerAddress,\n\tLedgerHome,\n\tLedgerPayload,\n\tResourceAddress,\n} from '@dbsp/types';\nimport { sameLedgerAddress } from '@dbsp/types';\nimport type {\n\tLedgerReservationRow,\n\tOutcomeIndeterminateRecoveryEvidence,\n} from '@dbsp/types/internal';\nimport type { Pool } from 'pg';\nimport { readPgLedgerAddressChain } from './chain-reader.js';\nimport {\n\tassertPgDatabaseWritable,\n\tisPgDatabaseReadOnlyError,\n} from './database-writability.js';\nimport { readTransitionJournal } from './journal.js';\nimport { readPgLedgerReservationsForExecution } from './ledger.js';\nimport { withPgTransitionRunLock } from './lessor.js';\nimport { assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid } from './operations/create-unique-index-concurrently.js';\nimport { recoverPgOutcomeClaim } from './outcome-protocol.js';\nimport { recoverPgReaddressPair } from './readdress.js';\nimport {\n\ttype PgLedgerScopeCurrency,\n\treadPgLedgerScopeCurrency,\n\treadVerifiedPgLedgerReservationsForPair,\n} from './reinitialize-preflight.js';\n\nexport type PgReconcileRecoveryOutcome =\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\nexport type PgReconcileRecoveryFailureCause =\n\t| 'catalogue'\n\t| 'malformed-journal'\n\t| 'transport';\n\n/** One ordered recovery attempt; diagnostics are raw and presentation-free. */\nexport interface PgReconcileRecoveryReport {\n\treadonly address: LedgerAddress;\n\treadonly outcome: PgReconcileRecoveryOutcome;\n\treadonly reason?: string;\n\treadonly pairId?: string;\n\treadonly failureCause?: PgReconcileRecoveryFailureCause;\n}\n\n/** The selected semantic refusal condition, never a CLI refusal document. */\nexport type PgReconcileSelectedIssue =\n\t| {\n\t\t\treadonly kind: 'ledger-not-current';\n\t\t\treadonly currency: Exclude<\n\t\t\t\tPgLedgerScopeCurrency,\n\t\t\t\t{ readonly kind: 'current' }\n\t\t\t>;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly reason: string;\n\t\t\treadonly affectedAddresses: readonly LedgerAddress[];\n\t }\n\t| {\n\t\t\treadonly kind: 'catalogue-unavailable';\n\t\t\treadonly address: LedgerAddress;\n\t }\n\t| {\n\t\t\treadonly kind: 'malformed-chain';\n\t\t\treadonly address: LedgerAddress;\n\t };\n\ninterface PgReconcileBaseResult {\n\treadonly runId: string;\n\treadonly addresses: readonly ResourceAddress[];\n\treadonly recovery?: readonly PgReconcileRecoveryReport[];\n\treadonly selectedIssue?: PgReconcileSelectedIssue;\n}\n\nexport type PgReconcileTransitionRunResult =\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'completed';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'unresolved';\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'selection-unavailable';\n\t\t\treadonly detail?: string;\n\t })\n\t| (PgReconcileBaseResult & {\n\t\t\treadonly kind: 'database-read-only';\n\t\t\treadonly selectedIssue: Extract<\n\t\t\t\tPgReconcileSelectedIssue,\n\t\t\t\t{ readonly kind: 'database-read-only' }\n\t\t\t>;\n\t })\n\t| {\n\t\t\treadonly kind: 'busy';\n\t\t\treadonly runId: string;\n\t\t\treadonly addresses: readonly ResourceAddress[];\n\t };\n\nexport type PgReconcileFailureStage = 'reconcile' | 'journal' | 'catalogue';\n\n/** A read/recovery failure whose original cause remains available to callers. */\nexport class PgReconcileTransitionRunError extends Error {\n\tconstructor(\n\t\treadonly stage: PgReconcileFailureStage,\n\t\treadonly originalCause: unknown,\n\t) {\n\t\tsuper('PostgreSQL transition-run reconciliation failed', {\n\t\t\tcause: originalCause,\n\t\t});\n\t\tthis.name = 'PgReconcileTransitionRunError';\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\n/** Canonicalizes catalogue identity for an outcome resolution payload. */\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 { value, digest: canonicalJsonDigest(value) };\n}\n\nfunction recoveryReport(\n\taddress: LedgerAddress,\n\tresult: Awaited<ReturnType<typeof recoverPgOutcomeClaim>>,\n): PgReconcileRecoveryReport {\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};\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};\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): PgReconcileRecoveryReport {\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\nfunction isUnresolvedRecoveryOutcome(\n\treport: PgReconcileRecoveryReport,\n): boolean {\n\treturn [\n\t\t'pending',\n\t\t'blocked',\n\t\t'malformed-chain',\n\t\t'protocol-refused',\n\t\t'transport-ambiguous',\n\t\t'no-open-claim',\n\t\t'indeterminate-appended',\n\t\t'indeterminate-pair',\n\t].includes(report.outcome);\n}\n\nfunction selectedRecoveryIssue(\n\treports: readonly PgReconcileRecoveryReport[],\n): PgReconcileSelectedIssue | undefined {\n\tfor (const report of reports) {\n\t\tif (report.failureCause === 'malformed-journal')\n\t\t\treturn { kind: 'malformed-chain', address: report.address };\n\t\tif (report.failureCause === 'catalogue')\n\t\t\treturn { kind: 'catalogue-unavailable', address: report.address };\n\t}\n\treturn undefined;\n}\n\nfunction statementBundleDigest(\n\tstatements: readonly { readonly ordinal: number; readonly sql: string }[],\n): string {\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\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\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 * Returns recovery decisions for one durable run without reissuing DDL.\n *\n * Reconciliation keeps the run-lock session while `recoverPgOutcomeClaim`\n * acquires its own outcome session. The supplied pool must allow at least two\n * concurrent connections: a pool with `max: 1` waits forever under the lock.\n */\nexport async function reconcilePgTransitionRun(\n\tpool: Pool,\n\trunId: string,\n): Promise<PgReconcileTransitionRunResult> {\n\tlet stage: PgReconcileFailureStage = 'reconcile';\n\ttry {\n\t\tconst locked = await withPgTransitionRunLock(\n\t\t\tpool,\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: LedgerAddress;\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.map((step) => {\n\t\t\t\t\t\t\tconst generatedStep = step as {\n\t\t\t\t\t\t\t\treadonly address?: LedgerAddress;\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\tconst addresses = material.map((claim) => claim.address);\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\trunId,\n\t\t\t\t\t\t\t\taddresses,\n\t\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\t\tkind: 'database-read-only' as const,\n\t\t\t\t\t\t\t\t\treason: error.message,\n\t\t\t\t\t\t\t\t\taffectedAddresses: addresses,\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\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\trunId,\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\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 affectedAddresses = material\n\t\t\t\t\t\t\t.filter((claim) => {\n\t\t\t\t\t\t\t\tconst claimHome = ledgerHome(claim.address);\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\tclaimHome.scope === home.scope &&\n\t\t\t\t\t\t\t\t\tclaimHome.schema === home.schema\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.map((claim) => claim.address);\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\trunId,\n\t\t\t\t\t\t\taddresses: affectedAddresses,\n\t\t\t\t\t\t\trecovery: affectedAddresses.map((address) => ({\n\t\t\t\t\t\t\t\taddress,\n\t\t\t\t\t\t\t\toutcome: 'blocked' as const,\n\t\t\t\t\t\t\t\treason:\n\t\t\t\t\t\t\t\t\tcurrency.kind === 'not-current'\n\t\t\t\t\t\t\t\t\t\t? currency.reason\n\t\t\t\t\t\t\t\t\t\t: currency.kind,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\tselectedIssue: {\n\t\t\t\t\t\t\t\tkind: 'ledger-not-current' as const,\n\t\t\t\t\t\t\t\tcurrency,\n\t\t\t\t\t\t\t\taffectedAddresses,\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\trunId,\n\t\t\t\t\t\t\taddresses: material.map((claim) => claim.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: PgReconcileRecoveryReport[] = [];\n\t\t\t\t\tfor (const pairRows of readdressPairs.values()) {\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 closure = await readVerifiedPgLedgerReservationsForPair(\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\trunId,\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\trunId,\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\trunId,\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\trunId,\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\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: LedgerAddress,\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\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(pool, {\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 = recovery.some(isUnresolvedRecoveryOutcome);\n\t\t\t\t\tconst issue = selectedRecoveryIssue(recovery);\n\t\t\t\t\treturn unresolved\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: 'unresolved' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\t\t\t\t\t\t...(issue === undefined ? {} : { selectedIssue: issue }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tkind: 'completed' as const,\n\t\t\t\t\t\t\t\trunId,\n\t\t\t\t\t\t\t\taddresses: reservations.map((item) => item.address),\n\t\t\t\t\t\t\t\trecovery,\n\t\t\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') return { kind: 'busy', runId, addresses: [] };\n\t\treturn locked.value;\n\t} catch (error) {\n\t\tthrow new PgReconcileTransitionRunError(stage, error);\n\t}\n}\n\n/** Finds every execution id durably attributable to one transition run. */\nexport function executionIdsForRun(\n\tjournal: Awaited<ReturnType<typeof readTransitionJournal>>,\n): readonly string[] {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DO,SAAS,aAAa,OAAa,UAA0B,CAAC,GAAS;AAC7E,QAAM,WAAmB,CAAC;AAG1B,MAAI,QAAQ,YAAY,QAAW;AAClC,aAAS,KAAK,aAAa,WAAW,QAAQ,OAAO,CAAC;AAAA,EACvD;AAEA,MAAI,QAAQ,YAAY,QAAW;AAClC,aAAS,KAAK,aAAa,WAAW,QAAQ,OAAO,CAAC;AAAA,EACvD;AAEA,MAAI,QAAQ,UAAU,QAAW;AAChC,aAAS,KAAK,aAAa,SAAS,QAAQ,KAAK,CAAC;AAAA,EACnD;AAEA,MAAI,QAAQ,YAAY,QAAW;AAClC,aAAS,KAAK,aAAa,WAAW,QAAQ,OAAO,CAAC;AAAA,EACvD;AAEA,MAAI,QAAQ,WAAW,QAAW;AACjC,aAAS,KAAK,aAAa,UAAU,QAAQ,MAAM,CAAC;AAAA,EACrD;AAEA,MAAI,QAAQ,aAAa,QAAW;AACnC,aAAS,KAAK,aAAa,YAAY,QAAQ,QAAQ,CAAC;AAAA,EACzD;AAEA,MAAI,QAAQ,QAAQ;AACnB,aAAS,KAAK,aAAa,UAAU,QAAQ,MAAM,CAAC;AAAA,EACrD;AAEA,QAAM,cAAiD,EAAE,MAAM;AAC/D,MAAI,SAAS,SAAS,GAAG;AACxB,gBAAY,UAA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S,OAAO;AACf,UAAM,IAAI,8BAA8B,OAAO,KAAK;AAAA,EACrD;AACD;AAGO,SAAS,mBACf,SACoB;AACpB,QAAM,eAAe,oBAAI,IAAY,CAAC,QAAQ,IAAI,KAAK,CAAC;AACxD,aAAW,SAAS,QAAQ,QAAQ;AACnC,UAAM,SAAS,MAAM;AACrB,QACC,MAAM,UAAU,YAChB,iBAAiB,UACjB,OAAO,OAAO,gBAAgB;AAE9B,mBAAa,IAAI,OAAO,WAAW;AACpC,QACC,MAAM,UAAU,cAChB,YAAY,UACZ,OAAO,UACP,OAAO,OAAO,OAAO,gBAAgB;AAErC,mBAAa,IAAI,OAAO,OAAO,WAAW;AAAA,EAC5C;AACA,MAAI,eAAe,QAAQ;AAC1B,iBAAa,IAAI,4BAA4B,QAAQ,IAAI,KAAK,EAAE;AACjE,SAAO,CAAC,GAAG,YAAY;AACxB;","names":["fn","literal","exprRef","fn","literal","op","param","sameControllerIdentity","projectLedgerChain","target","projectLedgerChain"]}