@dbsp/core 3.4.0 → 4.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.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import * as _dbsp_types from '@dbsp/types';
2
- import { PseudoColumnMetadata, RecursiveMetadata, RelationIR, RelationKind, AdapterCapabilities, Adapter, BaseAdapter, DDLGeneratingAdapter, ExecutingAdapter, IntrospectingAdapter, RawSqlAdapter, StreamingAdapter, TransactionalAdapter, ColumnType, ColumnJsReadType as ColumnJsReadType$1, WhereIntent, OnDeleteAction, ModelIR, DbCasing, QueryIntent, PlanOptions, PlanReport, RecursiveIntent, RecursivePlanOptions, RecursivePlanReport, ObservationContext, TransitionSessionClient, IssuedObservation, RecoveryArtefact, FingerprintManifest, OperationSemantics, OperationKindRef, PhysicalOperation, EvidenceObservation, DurableIntentRecord, OperationEffectAssessment, ObservationIssuer, ApplyGuard, OperationExecutionOutcome, TransactionalCompletionRecord, StepJournal, TransitionRule, EquivalenceCapability, CapabilityDescriptor, TransitionCompositionFact, RuleRef, SemanticArtifactRef, TransitionRunJournal, ProvenPlanShape, TransitionLessor, ApplyPolicy, CheckConstraintIR, Comparator, EnumIR, ObservationRequest, EvidenceView, ProofObligation, ExecutionContract, ExecutionRequirement, AdvisoryObservationId, AssumptionId, ClaimId, EvidenceId, SemanticArtifactId, IndexIR, Assumption, ResourceAddress, ResourceSelector, TransitionRunMetadata, ApplyResult, TransitionCandidate, TransitionFragmentComposition, PlanAssessment, CompareOutcome, TransitionQueryClient, TransitionFragment, ProofClaim, ApplicableAssessment, InapplicableAssessment, TableIR, SequenceIR, AmbiguityCheckResult, DialectCapabilities, DDLFeature, DDLFeatureVersionRange, SelectIntent, IncludeIntent, AggregateIntent, OrderByIntent, SortDirection, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, TransactionBeginOptions, Dump, SetOperationIntent, LockStrength, LockWaitPolicy, DumpMeta, JoinIntent, UnnestCteIntent, CteQueryIntent, CompileOptions, CompiledQuery, MutationIntent as MutationIntent$1, DumpSequenceStep, UpsertConflictTarget, UpsertConflictAction, RawCteIntent, TruncateOptions, VacuumOptions, AlterColumnOptions, CreateIndexOptions, DropIndexOptions, IndexInfo, TransactionOptions, PinnedConnectionOptions, ExpressionIntent, ComparisonOperator, WhereSubqueryIntent, SubqueryRefIntent, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereRelationFilterIntent, RecursiveExistsOptions, WhereExistsIntent, WhereInIntent, WhereNullIntent, WhereLikeIntent, WhereNotIntent, WhereNotExistsIntent, WhereOrIntent, WhereRawExistsIntent, WhereRawNotExistsIntent, WhereExpressionIntent, AggOrderByArg, RelationType as RelationType$1, Cardinality, FeatureWarning, UnsupportedFeatureBehavior, FeatureBehaviorConfig, RangeValue, WhereRangeIntent, RangeOperand, SubqueryIncludeInfo, JsonValue as JsonValue$1 } from '@dbsp/types';
3
- export { Adapter, AdapterCapabilities, AdapterLogger, AdapterStreamOptions, AdjacencyTraversal, AggregateExpressionIntent, AggregateFunction, AggregateIntent, AggregateWindowFunction, AliasIncludedColumnsMode, AlterColumnOptions, AmbiguityCheckResult, ApplicableAssessment, ApplicableEvaluation, ApplyPolicy, ArrayOperator, Assumption, BaseAdapter, CTEDefinition, CapabilityDescriptor, Cardinality, CaseExpressionIntent, CoalesceExpressionIntent, ColumnAliasIntent, ColumnExpressionIntent, ColumnIR, ColumnJsReadType, ColumnType, CommonColumnType, Comparator, CompareOutcome, ComparisonExpressionIntent, ComparisonOperator, CompileOnlyAdapter, CompileOptions, CompileResultWithIncludes, CompiledQuery, CompilingAdapter, ConnectionAvailability, CreateIndexOptions, CustomTraversal, DDLGeneratingAdapter, DbCasing, DecisionType, DeleteIntent, DialectCapabilities, DialectName, DropIndexOptions, DuckDBColumnType, Dump, DumpMeta, DurableIntentRecord, EdgeTableTraversal, EmitJoinClause, ExecutingAdapter, ExpressionIntent, FilterStrategy, FingerprintManifest, ForeignKeyIR, InapplicableAssessment, IncludeIntent, IncludeStrategy, IndexColumnDef, IndexIR, IndexInfo, IndexMethod, InsertFromIntent, InsertIntent, IntrospectingAdapter, IsTypeSupported, JoinDefault, JoinIntent, LiteralExpressionIntent, LogicalIdentity, LogicalIdentityCarrier, LogicalOperator, MSSQLColumnType, ModelIR, MutationIntent, MySQLColumnType, NullOperator, NullsPosition, ObservationContext, ObservationIssuer, ObservationRequest, OffsetWindowFunction, OnDeleteAction, OperationEffectAssessment, OperationSemantics, Optionality, OrderByIntent, PartitionIR, PhysicalOperation, PlanDecision, PlanOptions, PlanReport, PlanWarning, PlanWarningCode, PostgresColumnType, PostgresOnlyColumnType, ProvenApplyGuard, ProvenGuardProtocol, ProvenPlanShape, ProvenPlanStep, PseudoColumnExpressionIntent, PseudoColumnMetadata, PseudoColumnTraversal, QueryIntent, RangeOperator, RangeValue, RankingWindowFunction, RawExpressionIntent, RawSqlAdapter, RecognitionResult, RecursiveAdvancedOptions, RecursiveDedupe, RecursiveDirection, RecursiveEmitOptions, RecursiveExistsOptions, RecursiveIntent, RecursiveMetadata, RecursiveNodeIdExpr, RecursivePlanOptions, RecursivePlanReport, RecursiveTrackOptions, RecursiveTraversal, RelationColumnIntent, RelationIR, RelationKind, RelationOperator, RelationType, RequiredEnumLabelIR, ResolvedIncludeStrategy, ResourceAddress, RuleEvaluation, RuleSupport, SQLiteColumnType, SelectAggregateIntent, SelectAllIntent, SelectFieldsIntent, SelectIntent, SelectWithExpressionsIntent, SerializedProvenPlan, SortDirection, StepJournal, StreamingAdapter, StringOperator, SubqueryIncludeInfo, SubqueryRefIntent, SupportedColumnTypes, TableIR, TransactionOptions, TransactionalAdapter, TransactionalCompletionRecord, TransitionCandidate, TransitionLessor, TransitionQueryClient, TransitionRule, TransitionRunMetadata, TransitionSessionClient, TruncateOptions, UpdateIntent, UpsertConflictAction, UpsertConflictTarget, UpsertFromIntent, UpsertIntent, VacuumOptions, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereExistsIntent, WhereInIntent, WhereIntent, WhereLikeIntent, WhereNotExistsIntent, WhereNotIntent, WhereNullIntent, WhereOrIntent, WhereRangeIntent, WhereRelationFilterIntent, WhereSubqueryIntent, WindowFunction, WindowIntent, WindowOrderBy, getNodeIdAlias, isAdjacencyTraversal, isAggregateWindowFunction, isCoalesceExpression, isColumnAliasExpression, isCustomTraversal, isDeleteIntent, isEdgeTableTraversal, isInsertIntent, isMutationIntent, isRankingWindowFunction, isRawExpression, isRecursiveIntent, isRelationColumnExpression, isSelectAggregate, isSelectAll, isSelectFields, isSelectWithExpressions, isSubqueryRef, isUpdateIntent, isUpsertIntent, isWhereAnd, isWhereAny, isWhereComparison, isWhereExists, isWhereIn, isWhereLike, isWhereLogical, isWhereNot, isWhereNotExists, isWhereNull, isWhereOr, isWhereRange, isWhereRelationBased, isWhereRelationFilter, isWhereSubquery, isWindowIntent } from '@dbsp/types';
2
+ import { PseudoColumnMetadata, RecursiveMetadata, RelationIR, RelationKind, AdapterCapabilities, Adapter, BaseAdapter, DDLGeneratingAdapter, ExecutingAdapter, IntrospectingAdapter, RawSqlAdapter, StreamingAdapter, TransactionalAdapter, ColumnType, ColumnJsReadType as ColumnJsReadType$1, WhereIntent, OnDeleteAction, TableReaddressDeclaration, ModelIR, DbCasing, QueryIntent, PlanOptions, PlanReport, RecursiveIntent, RecursivePlanOptions, RecursivePlanReport, ObservationContext, TransitionSessionClient, TransitionRunMetadata, IssuedObservation, RecoveryArtefact, ManagedStepClaimMaterial, LedgerPayload, FingerprintManifest, OperationSemantics, OperationKindRef, PhysicalOperation, EvidenceObservation, DurableIntentRecord, OperationEffectAssessment, ObservationIssuer, ApplyGuard, OperationExecutionOutcome, TransactionalCompletionRecord, StepJournal, TransitionRule, EquivalenceCapability, CapabilityDescriptor, TransitionCompositionFact, RuleRef, SemanticArtifactRef, TransitionRunJournal, ProvenPlanShape, ApplyPolicy, CheckConstraintIR, Comparator, ResourceAddress, JsonValue as JsonValue$1, DeclarationSet, EnumIR, ObservationRequest, EvidenceView, ProofObligation, ExecutionContract, ExecutionRequirement, AdvisoryObservationId, AssumptionId, ClaimId, EvidenceId, SemanticArtifactId, IndexIR, LedgerClaimKind, LedgerLifecycleGrammarColumn, LedgerHome, LedgerAddress, LedgerChainMember, LedgerStableState, LedgerOpenClaim, LedgerChainProjection, Assumption, ResourceSelector, TransitionLessor, ApplyResult, TransitionCandidate, TransitionFragmentComposition, PlanAssessment, CompareOutcome, TransitionFragment, ProofClaim, NormalizedManagedStep, ApplicableAssessment, ExclusiveTransitionTarget, DurableApplyOutcome, InapplicableAssessment, TableIR, SequenceIR, AmbiguityCheckResult, DialectCapabilities, DDLFeature, DDLFeatureVersionRange, SelectIntent, IncludeIntent, AggregateIntent, OrderByIntent, SortDirection, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, TransactionBeginOptions, Dump, SetOperationIntent, LockStrength, LockWaitPolicy, DumpMeta, JoinIntent, UnnestCteIntent, CteQueryIntent, CompileOptions, CompiledQuery, MutationIntent as MutationIntent$1, DumpSequenceStep, UpsertConflictTarget, UpsertConflictAction, RawCteIntent, TruncateOptions, VacuumOptions, AlterColumnOptions, CreateIndexOptions, DropIndexOptions, IndexInfo, TransactionOptions, PinnedConnectionOptions, ExpressionIntent, ComparisonOperator, WhereSubqueryIntent, SubqueryRefIntent, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereRelationFilterIntent, RecursiveExistsOptions, WhereExistsIntent, WhereInIntent, WhereNullIntent, WhereLikeIntent, WhereNotIntent, WhereNotExistsIntent, WhereOrIntent, WhereRawExistsIntent, WhereRawNotExistsIntent, WhereExpressionIntent, StandaloneWhereExpressionIntent, AggOrderByArg, PredicateOperator, RelationType as RelationType$1, Cardinality, FeatureWarning, UnsupportedFeatureBehavior, FeatureBehaviorConfig, RangeValue, WhereRangeIntent, RangeOperand, SubqueryIncludeInfo } from '@dbsp/types';
3
+ export { Adapter, AdapterCapabilities, AdapterLogger, AdapterStreamOptions, AdjacencyTraversal, AggregateExpressionIntent, AggregateFunction, AggregateIntent, AggregateWindowFunction, AliasIncludedColumnsMode, AlterColumnOptions, AmbiguityCheckResult, ApplicableAssessment, ApplicableEvaluation, ApplyPolicy, ArrayOperator, Assumption, BaseAdapter, CTEDefinition, CapabilityDescriptor, Cardinality, CaseExpressionIntent, CoalesceExpressionIntent, ColumnAliasIntent, ColumnExpressionIntent, ColumnIR, ColumnJsReadType, ColumnType, CommonColumnType, Comparator, CompareOutcome, ComparisonExpressionIntent, ComparisonOperator, CompileOnlyAdapter, CompileOptions, CompileResultWithIncludes, CompiledQuery, CompilingAdapter, ConnectionAvailability, CreateIndexOptions, CustomTraversal, DDLGeneratingAdapter, DbCasing, DecisionType, DeleteIntent, DialectCapabilities, DialectName, DropIndexOptions, DuckDBColumnType, Dump, DumpMeta, DurableIntentRecord, EdgeTableTraversal, EmitJoinClause, ExclusiveTransitionTarget, ExecutingAdapter, ExpressionIntent, FilterStrategy, FingerprintManifest, ForeignKeyIR, InapplicableAssessment, IncludeIntent, IncludeStrategy, IndexColumnDef, IndexIR, IndexInfo, IndexMethod, InsertFromIntent, InsertIntent, IntrospectingAdapter, IsTypeSupported, JoinDefault, JoinIntent, LiteralExpressionIntent, LogicalIdentity, LogicalIdentityCarrier, LogicalOperator, MSSQLColumnType, ModelIR, MutationIntent, MySQLColumnType, NullOperator, NullsPosition, ObservationContext, ObservationIssuer, ObservationRequest, OffsetWindowFunction, OnDeleteAction, OperationEffectAssessment, OperationSemantics, Optionality, OrderByIntent, PartitionIR, PhysicalOperation, PlanDecision, PlanOptions, PlanReport, PlanWarning, PlanWarningCode, PostgresColumnType, PostgresOnlyColumnType, PredicateOperator, ProvenApplyGuard, ProvenGuardProtocol, ProvenPlanShape, ProvenPlanStep, PseudoColumnExpressionIntent, PseudoColumnMetadata, PseudoColumnTraversal, QueryIntent, RangeOperator, RangeValue, RankingWindowFunction, RawExpressionIntent, RawSqlAdapter, RecognitionResult, RecursiveAdvancedOptions, RecursiveDedupe, RecursiveDirection, RecursiveEmitOptions, RecursiveExistsOptions, RecursiveIntent, RecursiveMetadata, RecursiveNodeIdExpr, RecursivePlanOptions, RecursivePlanReport, RecursiveTrackOptions, RecursiveTraversal, RelationColumnIntent, RelationIR, RelationKind, RelationOperator, RelationType, RequiredEnumLabelIR, ResolvedIncludeStrategy, ResourceAddress, RuleEvaluation, RuleSupport, SQLiteColumnType, SelectAggregateIntent, SelectAllIntent, SelectFieldsIntent, SelectIntent, SelectWithExpressionsIntent, SerializedProvenPlan, SortDirection, StepJournal, StreamingAdapter, StringOperator, SubqueryIncludeInfo, SubqueryRefIntent, SupportedColumnTypes, TableIR, TableReaddressAddress, TableReaddressDeclaration, TransactionOptions, TransactionalAdapter, TransactionalCompletionRecord, TransitionCandidate, TransitionLessor, TransitionQueryClient, TransitionRule, TransitionRunMetadata, TransitionSessionClient, TruncateOptions, UpdateIntent, UpsertConflictAction, UpsertConflictTarget, UpsertFromIntent, UpsertIntent, VacuumOptions, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereExistsIntent, WhereInIntent, WhereIntent, WhereLikeIntent, WhereNotExistsIntent, WhereNotIntent, WhereNullIntent, WhereOrIntent, WhereRangeIntent, WhereRelationFilterIntent, WhereSubqueryIntent, WindowFunction, WindowIntent, WindowOrderBy, getNodeIdAlias, isAdjacencyTraversal, isAggregateWindowFunction, isCoalesceExpression, isColumnAliasExpression, isCustomTraversal, isDeleteIntent, isEdgeTableTraversal, isInsertIntent, isMutationIntent, isRankingWindowFunction, isRawExpression, isRecursiveIntent, isRelationColumnExpression, isSelectAggregate, isSelectAll, isSelectFields, isSelectWithExpressions, isSubqueryRef, isUpdateIntent, isUpsertIntent, isWhereAnd, isWhereAny, isWhereComparison, isWhereExists, isWhereIn, isWhereLike, isWhereLogical, isWhereNot, isWhereNotExists, isWhereNull, isWhereOr, isWhereRange, isWhereRelationBased, isWhereRelationFilter, isWhereSubquery, isWindowIntent } from '@dbsp/types';
4
+ import { D as DurablyLoadedRun, T as TransitionReadTarget } from './internal-CNjWzMNe.js';
5
+ export { A as AdmittedDestructiveOutcomeClaim, a as TRANSITION_LESSOR_REJECTION, b as TransitionLeaseFailure, c as acquireExclusiveTransitionLease, d as acquireTransitionLease, e as acquireTransitionTargetLease, f as classifyOutcomeRecovery, g as createExclusiveTransitionTarget, h as createTransitionLessor, i as findUniqueLedgerTerminal, j as isExclusiveTransitionTarget, k as isTransitionLessor, o as outcomeClaimEventId, l as outcomeClaimId, p as planOperationSession } from './internal-CNjWzMNe.js';
4
6
  import { NqlCompilerOptions } from '@dbsp/nql';
5
7
 
6
8
  /**
@@ -487,7 +489,7 @@ type InferColumnTypes<TColumns extends Record<string, ColumnRef<string, string,
487
489
  * // { id: number; name: string; email: string }
488
490
  * ```
489
491
  */
490
- type InferTableRow<T> = T extends TableRef<string, infer TColumns, infer _TRelations> ? InferColumnTypes<TColumns> : never;
492
+ type InferTableRow<T> = T extends TableRef<infer _TName, infer TColumns> ? InferColumnTypes<TColumns> : never;
491
493
  /**
492
494
  * Type guard to check if a value is a TableRef.
493
495
  *
@@ -927,6 +929,12 @@ interface SchemaTableOptions {
927
929
  }>;
928
930
  /** Composite foreign keys for this table (use ref() with columns/references) */
929
931
  foreignKeys?: RefDefinition[];
932
+ /** Explicit rename or schema move for this desired table. */
933
+ readdress?: TableReaddressDeclaration;
934
+ /** Explicitly bring this existing table under managed state. */
935
+ adopt?: true;
936
+ /** Request a reviewed retire-and-create replacement of this table. */
937
+ replace?: true;
930
938
  }
931
939
  /**
932
940
  * Per-table constraint options, keyed by table name.
@@ -940,10 +948,10 @@ interface SchemaExtras {
940
948
  extensions?: string[];
941
949
  /** Sequences to create (CREATE SEQUENCE). Key = sequence name */
942
950
  sequences?: Record<string, {
943
- startWith?: number;
944
- incrementBy?: number;
945
- minValue?: number;
946
- maxValue?: number;
951
+ startWith?: number | string;
952
+ incrementBy?: number | string;
953
+ minValue?: number | string;
954
+ maxValue?: number | string;
947
955
  cycle?: boolean;
948
956
  }>;
949
957
  }
@@ -1019,6 +1027,10 @@ interface Schema<T extends SchemaDefinition> {
1019
1027
  readonly definition: T;
1020
1028
  /** Table-level constraints supplied to schema() or reconstructed from introspection */
1021
1029
  readonly constraints?: SchemaConstraints;
1030
+ /** Schema-wide objects supplied to schema(); retained for durable declarations. */
1031
+ readonly extras?: SchemaExtras;
1032
+ /** Planning inputs supplied to schema(); retained without changing model semantics. */
1033
+ readonly options?: SchemaOptions;
1022
1034
  /** Converted ModelIR for use with ORM */
1023
1035
  readonly model: ModelIR;
1024
1036
  /** Table names */
@@ -1473,12 +1485,47 @@ interface GuardExecutionResult {
1473
1485
  }
1474
1486
  interface TransitionExecutionClient {
1475
1487
  readonly opaqueClient: TransitionSessionClient;
1488
+ /** Mark the checked-out client unsafe to return to its pool. */
1489
+ markClientCompromised(): void;
1476
1490
  }
1477
1491
  interface NonRollbackableExecutionTracker {
1478
1492
  markNonRollbackableOperationExecuted(): void;
1479
1493
  }
1494
+ /**
1495
+ * Adapter boundary for a plan-carried managed statement bundle. Core owns the
1496
+ * immutable material and the run link; the adapter owns claim admission,
1497
+ * token-gated SQL, and the INV-07 transaction composition.
1498
+ */
1499
+ interface ManagedOutcomeExecutionRequest {
1500
+ readonly claim: ManagedStepClaimMaterial;
1501
+ readonly run: TransitionRunMetadata;
1502
+ /** Core-minted proof that this run crossed a verified execution boundary. */
1503
+ readonly durablyLoadedRun: DurablyLoadedRun;
1504
+ /** Minted once by apply(), never reused when a recorded run is applied again. */
1505
+ readonly executionId: string;
1506
+ readonly transactional: boolean;
1507
+ readonly lockTimeoutMs: number;
1508
+ /** The operation's own live postcondition observation, never a generic identity probe. */
1509
+ readBack(): Promise<LedgerPayload>;
1510
+ }
1511
+ /** The plan and session facts an adapter may inspect before the step intent. */
1512
+ type ManagedOutcomePreflightRequest = Pick<ManagedOutcomeExecutionRequest, 'claim' | 'run' | 'transactional' | 'lockTimeoutMs'>;
1480
1513
  interface ExecutionCoordinator {
1481
1514
  readonly transactionDomain: string;
1515
+ /**
1516
+ * When supplied, core calls this after `begin` and before application locks
1517
+ * for transactional segments. It may reserve the durable run journal on the
1518
+ * same session so later intent writes keep journal-then-application lock
1519
+ * order. Generic runtimes without an operation/journal reservation protocol
1520
+ * leave this absent; in particular a non-transactional segment cannot retain
1521
+ * a transaction-scoped journal row lock across application locking.
1522
+ *
1523
+ * Before an intent exists, core can invoke `begin`, `setLockTimeout`, this
1524
+ * optional reservation, `rollback`, and `isLockTimeout`. They must
1525
+ * not perform operation DDL or any external effect. `executeOperation` is
1526
+ * the first callback allowed to do so.
1527
+ */
1528
+ reserveJournalRun?(client: TransitionExecutionClient, run: TransitionRunMetadata): Promise<void>;
1482
1529
  begin(client: TransitionExecutionClient): Promise<void>;
1483
1530
  setLockTimeout(client: TransitionExecutionClient, maxWaitMs: number): Promise<void>;
1484
1531
  commit(client: TransitionExecutionClient): Promise<void>;
@@ -1490,6 +1537,19 @@ interface TransactionCoordinatorBinding {
1490
1537
  readonly transactionDomain: string;
1491
1538
  }
1492
1539
  interface OperationRuntime extends RegisteredOperationSemantics {
1540
+ /**
1541
+ * Before `writeIntentJournal`, core can invoke `effectsOf`, `begin`,
1542
+ * `setLockTimeout`, optional `reserveJournalRun`, `acquireLocks`,
1543
+ * `observeContext`,
1544
+ * `observeOperation`, `buildFingerprints`, `rollback`, and `isLockTimeout`.
1545
+ * All must perform no operation DDL or external effect. The only
1546
+ * pre-intent diagnostic exception is `writeObservedJournal` after a
1547
+ * fingerprint-construction failure: it may append that immutable failure
1548
+ * event, but may not perform operation DDL or an external effect. This lets a
1549
+ * refusal before the intent leave the run pristine; `executeOperation` is the
1550
+ * first callback allowed to perform the operation's DDL or external effect.
1551
+ */
1552
+ reserveJournalRun?(client: TransitionExecutionClient, run: TransitionRunMetadata): Promise<void>;
1493
1553
  writeIntentJournal(client: TransitionExecutionClient, record: DurableIntentRecord): Promise<void>;
1494
1554
  begin(client: TransitionExecutionClient): Promise<void>;
1495
1555
  setLockTimeout(client: TransitionExecutionClient, maxWaitMs: number): Promise<void>;
@@ -1498,6 +1558,17 @@ interface OperationRuntime extends RegisteredOperationSemantics {
1498
1558
  observeOperation(client: TransitionExecutionClient, operation: PhysicalOperation, context: ObservationContext, phase: 'before' | 'after', issuer: ObservationIssuer): Promise<OperationObservation>;
1499
1559
  checkGuard(client: TransitionExecutionClient, operation: PhysicalOperation, guard: ApplyGuard, context: ObservationContext): Promise<GuardExecutionResult>;
1500
1560
  executeOperation(client: TransitionExecutionClient, operation: PhysicalOperation, context: ObservationContext, duringGuards?: readonly ApplyGuard[], executionTracker?: NonRollbackableExecutionTracker): Promise<OperationExecutionOutcome>;
1561
+ /**
1562
+ * Required when a plan step carries managed claim material. The applier
1563
+ * never falls back to `executeOperation` for such a step.
1564
+ */
1565
+ executeManagedOutcome?(client: TransitionExecutionClient, request: ManagedOutcomeExecutionRequest): Promise<OperationExecutionOutcome>;
1566
+ /**
1567
+ * Refuses a managed outcome before its durable step intent is recorded.
1568
+ * This boundary is for adapter-owned prerequisites such as an incompatible
1569
+ * ledger marker; it must not execute DDL or append ledger members.
1570
+ */
1571
+ preflightManagedOutcome?(client: TransitionExecutionClient, request: ManagedOutcomePreflightRequest): Promise<string | undefined>;
1501
1572
  writeCompletionJournal(client: TransitionExecutionClient, operation: PhysicalOperation, record: TransactionalCompletionRecord): Promise<void>;
1502
1573
  commit(client: TransitionExecutionClient): Promise<void>;
1503
1574
  rollback(client: TransitionExecutionClient): Promise<void>;
@@ -1564,17 +1635,47 @@ declare class PackRegistry {
1564
1635
  declare function createPackRegistry(packs: readonly TransitionPack[]): PackRegistry;
1565
1636
 
1566
1637
  interface ResumeTransitionInput {
1567
- readonly runId: string;
1568
- readonly loadCurrent: (runId: string) => Promise<TransitionRunJournal & {
1569
- readonly plan: ProvenPlanShape;
1570
- }>;
1571
- readonly readContext: (target: TransitionLessor, run: TransitionRunJournal['run']) => Promise<ObservationContext>;
1572
- readonly policy: ApplyPolicy;
1573
- readonly target: TransitionLessor;
1638
+ readonly journal: VerifiedRecoveryJournal;
1639
+ readonly readContext: (target: TransitionReadTarget, run: TransitionRunJournal['run']) => Promise<ObservationContext>;
1640
+ readonly policy?: ApplyPolicy;
1641
+ readonly target: TransitionReadTarget;
1642
+ readonly admitRecovery?: TransitionRecoveryAdmission;
1574
1643
  }
1644
+ /**
1645
+ * A frozen journal whose run identity, durable digest, external review digest,
1646
+ * and plan structure were verified together. The WeakSet is the runtime brand:
1647
+ * callers may cast a lookalike, but recovery will not accept it.
1648
+ */
1649
+ type VerifiedRecoveryJournal = TransitionRunJournal & {
1650
+ readonly plan: ProvenPlanShape;
1651
+ };
1652
+ type RecoveryJournalLoadResult = {
1653
+ readonly ok: true;
1654
+ readonly journal: VerifiedRecoveryJournal;
1655
+ } | {
1656
+ readonly ok: false;
1657
+ readonly code: 'load-failed' | 'run-id-mismatch' | 'plan-digest-mismatch' | 'plan-invalid' | 'event-invalid';
1658
+ readonly detail: string;
1659
+ };
1660
+ /** Load exactly once, snapshot and freeze the complete durable evidence set. */
1661
+ declare function loadVerifiedRecoveryJournal(runId: string, expectedPlanDigest: string, loadCurrent: (runId: string) => Promise<TransitionRunJournal & {
1662
+ readonly plan: ProvenPlanShape;
1663
+ }>): Promise<RecoveryJournalLoadResult>;
1575
1664
 
1576
1665
  declare function createApplier(registry: PackRegistry, persister: TransitionRunPersister): Applier;
1577
1666
 
1667
+ /** Raised when a value cannot cross the durable JSON payload boundary. */
1668
+ declare class CanonicalJsonError extends TypeError {
1669
+ constructor(path: string, detail: string, options?: ErrorOptions);
1670
+ }
1671
+ /**
1672
+ * Encodes a JSON value with lexically sorted object keys and preserved array
1673
+ * order. Unlike JSON.stringify, this refuses values it would omit or coerce.
1674
+ */
1675
+ declare function canonicalJson(value: unknown): string;
1676
+ /** Hashes the canonical durable representation of a JSON payload. */
1677
+ declare function canonicalJsonDigest(value: unknown): string;
1678
+
1578
1679
  type CheckSetEntry = Pick<CheckConstraintIR, 'name' | 'expression' | 'notValid'>;
1579
1680
  type CheckDelta = {
1580
1681
  readonly kind: 'none';
@@ -1598,6 +1699,43 @@ declare function createComparator(registry: PackRegistry): Comparator;
1598
1699
 
1599
1700
  declare function observationContextDigest(context: ObservationContext): string;
1600
1701
 
1702
+ interface DeclarationAddressContext {
1703
+ readonly engine: string;
1704
+ readonly database: string;
1705
+ readonly schema: string;
1706
+ }
1707
+ /**
1708
+ * The declaration layer deliberately depends on this small structural naming
1709
+ * boundary rather than an adapter package. Callers pass the same strategy that
1710
+ * comparison and proof use for the target database.
1711
+ */
1712
+ interface DeclarationNamingStrategy {
1713
+ toDatabase(identifier: string): string;
1714
+ }
1715
+ /**
1716
+ * Reject every JavaScript value whose JSON representation is lossy or
1717
+ * host-dependent. JSON.stringify alone is unsuitable because it silently drops
1718
+ * functions and undefined object members, exactly the ColumnDef.default case.
1719
+ */
1720
+ declare function assertCanonicalizableJson(value: unknown, path?: string, seen?: WeakSet<object>): asserts value is JsonValue$1;
1721
+ /**
1722
+ * Slice only the declarable part of ModelIR. Deliberately absent are
1723
+ * logicalIdentity, pseudoColumns, comment, partition, rlsEnabled and policies;
1724
+ * their omission is encoded here once, rather than re-checked at every caller.
1725
+ */
1726
+ declare function declarationSetFromModel(model: ModelIR, context: DeclarationAddressContext, naming?: DeclarationNamingStrategy): DeclarationSet;
1727
+ /** Validate the complete declarable surface before comparison can short-circuit plan time. */
1728
+ declare function validateDeclarationModel(model: ModelIR): void;
1729
+ /** Compare only the recorded/live identity and retain the precise mismatch reason. */
1730
+ declare function admitRecordedIdentity(recorded: ResourceAddress, live: ResourceAddress): {
1731
+ readonly ok: true;
1732
+ } | {
1733
+ readonly ok: false;
1734
+ readonly detail: string;
1735
+ };
1736
+ /** Attach the canonical declaration artifact before metadata/digest minting. */
1737
+ declare function bindDeclarationSet(plan: InProcessProvenPlan, declarations: DeclarationSet): InProcessProvenPlan;
1738
+
1601
1739
  type EnumAddDelta = {
1602
1740
  readonly kind: 'none';
1603
1741
  } | {
@@ -1679,6 +1817,38 @@ type IndexPerspective = 'desired' | 'current';
1679
1817
  declare function normalizedIndex(tableName: string, index: IndexIR, perspective?: IndexPerspective): IndexSetEntry;
1680
1818
  declare function indexDelta(tableName: string, desiredIndexes: readonly IndexIR[], currentIndexes: readonly IndexIR[]): IndexDelta;
1681
1819
 
1820
+ /** Bump whenever the malformed-chain vocabulary or interpretation changes. */
1821
+ declare const LEDGER_PROJECTION_CODE_VERSION: 1;
1822
+ /**
1823
+ * The one closed grammar matrix. Later claim and token producers consume this
1824
+ * interpreter; they do not reconstruct lifecycle state from ledger spellings.
1825
+ */
1826
+ declare const LEDGER_LIFECYCLE_GRAMMAR: Readonly<Record<LedgerClaimKind, LedgerLifecycleGrammarColumn>>;
1827
+ interface LifecycleFrame {
1828
+ readonly stableState: LedgerStableState;
1829
+ readonly openClaim?: LedgerOpenClaim;
1830
+ }
1831
+ type LifecycleStep = {
1832
+ readonly kind: 'ok';
1833
+ readonly frame: LifecycleFrame;
1834
+ } | {
1835
+ readonly kind: 'invalid';
1836
+ readonly detail: string;
1837
+ };
1838
+ interface LedgerChainProjectionInput {
1839
+ readonly ledger: LedgerHome;
1840
+ readonly address: LedgerAddress;
1841
+ readonly events: readonly LedgerChainMember[];
1842
+ }
1843
+ /** Interprets exactly one terminal-to-next lifecycle edge. */
1844
+ declare function interpretLedgerLifecycle(frame: LifecycleFrame, event: LedgerChainMember): LifecycleStep;
1845
+ /**
1846
+ * Projects a whole address chain without using insertion order. Malformed
1847
+ * chains deliberately return a structured value so mutation callers fail
1848
+ * closed while readers retain the evidence needed to diagnose it.
1849
+ */
1850
+ declare function projectLedgerChain(input: LedgerChainProjectionInput): LedgerChainProjection;
1851
+
1682
1852
  /**
1683
1853
  * Canonical digest used to bind a durable transition run to its proven plan.
1684
1854
  */
@@ -1698,6 +1868,8 @@ declare function assumptionAccepted(assumption: Assumption, policy: ApplyPolicy)
1698
1868
  * caller-supplied snapshot. That is the exact context resume verifies.
1699
1869
  */
1700
1870
  declare function createTransitionRunMetadata(plan: InProcessProvenPlan): TransitionRunMetadata;
1871
+ /** Label a generator removal before persistence; it can never become replayable. */
1872
+ declare function markGeneratorRemovalNonReplayable(run: TransitionRunMetadata): TransitionRunMetadata;
1701
1873
 
1702
1874
  interface StagedTransitionInput {
1703
1875
  readonly desired: ModelIR;
@@ -1741,48 +1913,6 @@ declare function chooseReadyCandidate(preflight: Extract<StagedCompositionPrefli
1741
1913
  }>): StagedCompositionCandidate;
1742
1914
  declare function projectCompareToSingleCandidate(compare: TransitionCompare, entry: StagedCompositionCandidate): TransitionCompare;
1743
1915
 
1744
- declare const TRANSITION_LESSOR_REJECTION = "transition target must be a core-minted lessor";
1745
- /** A core-owned lease: packs receive its session, while core retains release. */
1746
- type TransitionLease = {
1747
- readonly session: TransitionSessionClient;
1748
- readonly release: (failure?: TransitionLeaseFailure) => Promise<void>;
1749
- };
1750
- /**
1751
- * Cross the engine's acquisition boundary.
1752
- *
1753
- * A lessor brand is a declaration, not a security boundary, so every
1754
- * acquisition is checked here even when a caller forged that declaration.
1755
- */
1756
- declare function acquireTransitionLease(target: TransitionLessor): Promise<TransitionLease>;
1757
- /**
1758
- * Mint a declared source of transition leases.
1759
- *
1760
- * This declares a source of leases; it does not inspect individual
1761
- * acquisitions. Every acquisition crosses `acquireTransitionLease`, the
1762
- * runtime boundary that validates and captures it exactly once.
1763
- *
1764
- * The wrapper is allocated and frozen by core. Its non-writable,
1765
- * non-configurable `Symbol.for('dbsp.transition.lessor')` brand carries this
1766
- * protocol version, so independently installed incompatible core versions do
1767
- * not accept one another's lessors. The global symbol is intentionally not a
1768
- * security boundary: code already running in this realm can forge it. This
1769
- * protects callers from passing the wrong connection object by accident.
1770
- */
1771
- declare function createTransitionLessor(acquire: () => Promise<TransitionQueryClient>): TransitionLessor;
1772
- /**
1773
- * Recognize a core-minted transition lessor. The shape check only rejects a
1774
- * contradictory declaration (a branded object without acquire()); the brand
1775
- * and protocol version are the declaration.
1776
- */
1777
- declare function isTransitionLessor(value: unknown): value is TransitionLessor;
1778
- /**
1779
- * Carries the error that ended a lease's use. Its presence — not the value it
1780
- * holds — is what says the lease is being returned after a failure.
1781
- */
1782
- type TransitionLeaseFailure = {
1783
- readonly error: unknown;
1784
- };
1785
-
1786
1916
  type TransitionRelationalValidationInput = {
1787
1917
  readonly kind: 'fragment';
1788
1918
  readonly fragment: TransitionFragment;
@@ -1799,6 +1929,25 @@ type TransitionRelationalValidationResult = {
1799
1929
  readonly ok: false;
1800
1930
  readonly detail: string;
1801
1931
  };
1932
+ declare const validatedManagedStepManifestBrand: unique symbol;
1933
+ /** A manifest normalized and accepted by the managed lifecycle boundary. */
1934
+ interface ValidatedManagedStepManifest {
1935
+ readonly steps: readonly NormalizedManagedStep[];
1936
+ readonly [validatedManagedStepManifestBrand]: 'dbsp-validated-managed-step-manifest';
1937
+ }
1938
+ type ValidatedManagedStepManifestResult = {
1939
+ readonly ok: true;
1940
+ readonly manifest: ValidatedManagedStepManifest;
1941
+ } | {
1942
+ readonly ok: false;
1943
+ readonly detail: string;
1944
+ };
1945
+ /**
1946
+ * Generic lifecycle invariants for adapter-produced normalized managed steps.
1947
+ * Mapping a concrete DDL kind remains adapter work; core only validates the
1948
+ * durable protocol shape before it becomes digest-covered plan material.
1949
+ */
1950
+ declare function validateNormalizedManagedStepManifest(steps: readonly NormalizedManagedStep[]): ValidatedManagedStepManifestResult;
1802
1951
  /**
1803
1952
  * Diagnostic consistency check for transition fragments and already-trusted,
1804
1953
  * in-process plans. For plan inputs this is not an untrusted serialized-plan
@@ -1850,8 +1999,65 @@ interface Applier {
1850
1999
  readonly plan: InProcessProvenPlan;
1851
2000
  readonly assessment: ApplicableAssessment;
1852
2001
  }, policy: ApplyPolicy, target: TransitionLessor): Promise<ApplyResult>;
1853
- resume(runId: string, loadCurrent: ResumeTransitionInput['loadCurrent'], readContext: ResumeTransitionInput['readContext'], policy: ApplyPolicy, target: TransitionLessor): Promise<ApplyResult>;
2002
+ applyDurable(input: DurableApplyInput): Promise<DurableApplyResult>;
2003
+ resume(journal: VerifiedRecoveryJournal, readContext: ResumeTransitionInput['readContext'], policy: ApplyPolicy | undefined, target: TransitionReadTarget, admitRecovery?: TransitionRecoveryAdmission): Promise<ApplyResult>;
1854
2004
  }
2005
+ /** Durable-run entry point; it snapshots and verifies serialized evidence. */
2006
+ interface DurableApplyInput {
2007
+ readonly runId: string;
2008
+ /**
2009
+ * Content hash the operator reviewed outside the target database. Durable
2010
+ * apply refuses unless it is the hash of the loaded plan itself.
2011
+ */
2012
+ readonly expectedPlanDigest: string;
2013
+ readonly loadCurrent: TransitionResumeJournalLoader;
2014
+ readonly policy: ApplyPolicy;
2015
+ readonly target: ExclusiveTransitionTarget;
2016
+ /** Runs on the held execution lease before authorization, a transaction, intent, or DDL. */
2017
+ readonly prepareExecutionSession: (target: TransitionSessionClient, contract: ExecutionContract, plan: ProvenPlanShape) => Promise<{
2018
+ readonly ok: true;
2019
+ readonly context: ObservationContext;
2020
+ } | {
2021
+ readonly ok: false;
2022
+ /** Omitted by legacy adapters; treated as a contract refusal. */
2023
+ readonly kind?: 'refused' | 'failed' | 'read-only';
2024
+ readonly detail: string;
2025
+ }>;
2026
+ /** Called on that same preflight lease, after admission and before any step attempt. */
2027
+ readonly authorize: (run: TransitionRunJournal['run'], plan: ProvenPlanShape, target: TransitionSessionClient) => Promise<void>;
2028
+ }
2029
+ type DurableApplyResult = (ApplyResult & {
2030
+ readonly unresolvedOutcome: {
2031
+ readonly kind: 'recovery-required';
2032
+ readonly claimId: string;
2033
+ readonly detail: string;
2034
+ };
2035
+ readonly durableOutcome: 'recovery-required';
2036
+ }) | (ApplyResult & {
2037
+ readonly unresolvedOutcome: {
2038
+ readonly kind: 'transport-ambiguous';
2039
+ readonly detail: string;
2040
+ };
2041
+ readonly durableOutcome: 'transport-ambiguous';
2042
+ }) | (Omit<ApplyResult, 'unresolvedOutcome' | 'durableOutcome'> & {
2043
+ readonly unresolvedOutcome?: never;
2044
+ readonly durableOutcome: Exclude<DurableApplyOutcome, 'recovery-required' | 'transport-ambiguous'>;
2045
+ });
2046
+ type TransitionResumeJournalLoader = (runId: string) => Promise<TransitionRunJournal & {
2047
+ readonly plan: ProvenPlanShape;
2048
+ }>;
2049
+ /**
2050
+ * Recovery admission identifies the physical PostgreSQL target before any
2051
+ * classification journal can be written. It deliberately does not re-check
2052
+ * apply authority or the historic observation-context digest.
2053
+ */
2054
+ type TransitionRecoveryAdmission = (target: TransitionReadTarget, contract: ExecutionContract) => Promise<{
2055
+ readonly ok: true;
2056
+ readonly context: ObservationContext;
2057
+ } | {
2058
+ readonly ok: false;
2059
+ readonly detail: string;
2060
+ }>;
1855
2061
 
1856
2062
  /**
1857
2063
  * @module model-impl
@@ -2418,7 +2624,7 @@ declare class IntentBuilder<TResult = unknown> {
2418
2624
  */
2419
2625
 
2420
2626
  /** Query execution result types for afterQuery generics */
2421
- type QueryResultType = 'all' | 'first' | 'count' | 'exists' | 'aggregate';
2627
+ type QueryResultType = 'all' | 'first' | 'exists';
2422
2628
  /**
2423
2629
  * Context passed to query hooks (beforeQuery/afterQuery).
2424
2630
  * Frozen via Object.freeze — hooks must return new objects to modify.
@@ -2477,11 +2683,16 @@ type ErrorHookContext = {
2477
2683
  };
2478
2684
  /** Hook invoked before query execution. Can modify intent via return. */
2479
2685
  type BeforeQueryHook = (ctx: QueryHookContext) => QueryHookContext | Promise<QueryHookContext> | undefined;
2480
- /** Hook invoked after query execution. Can transform results via return. */
2686
+ /** Observer invoked after query execution. Its return value is ignored. */
2687
+ type AfterQueryObserver = (ctx: QueryHookContext, result: unknown) => void | Promise<void>;
2688
+ /** Hook invoked after query execution. Can transform results without changing their shape. */
2481
2689
  type AfterQueryHook = <R>(ctx: QueryHookContext, result: R) => R | Promise<R> | undefined;
2482
2690
  /** Hook invoked before mutation execution. Can modify context via return. */
2483
2691
  type BeforeMutationHook = <T>(ctx: MutationHookContext<T>) => MutationHookContext<T> | Promise<MutationHookContext<T>> | undefined;
2484
- /** Hook invoked after mutation execution. Can transform RETURNING results. */
2692
+ /** Observer invoked after mutation execution. Its return value is ignored. */
2693
+ type AfterMutationObserver = (ctx: MutationHookContext, result: unknown) => void | Promise<void>;
2694
+ type ObserverRegistration<T extends (...args: never[]) => unknown, TObserver extends (...args: never[]) => unknown> = ReturnType<T> extends ReturnType<TObserver> ? unknown : never;
2695
+ /** Hook invoked after mutation execution. Can transform RETURNING results without changing their shape. */
2485
2696
  type AfterMutationHook = <T>(ctx: MutationHookContext<T>, result: T[]) => T[] | Promise<T[]> | undefined;
2486
2697
  /** Hook invoked on query/mutation errors. Can transform the error. */
2487
2698
  type OnErrorHook = (ctx: ErrorHookContext) => undefined | Error | Promise<undefined | Error>;
@@ -2490,11 +2701,21 @@ type OnErrorHook = (ctx: ErrorHookContext) => undefined | Error | Promise<undefi
2490
2701
  * Returns 'continue' to skip failed hook, 'abort' to propagate error.
2491
2702
  */
2492
2703
  type HookErrorHandler = (error: Error, hookName: string, ctx: QueryHookContext | MutationHookContext, phase: string) => 'continue' | 'abort';
2704
+ /**
2705
+ * Diagnostic sink for observer failures and snapshot skips.
2706
+ *
2707
+ * Unlike {@link HookErrorHandler}, this handler has no control-flow return:
2708
+ * observer diagnostics always go to a void sink and can never abort work that
2709
+ * has already executed.
2710
+ */
2711
+ type ObserverErrorHandler = (error: Error, observerName: string, phase: 'afterQuery' | 'afterMutation') => void | Promise<void>;
2493
2712
  /** Immutable builder interface for registering hooks */
2494
2713
  interface HookManager {
2495
2714
  beforeQuery(hook: BeforeQueryHook): HookManager;
2715
+ observeAfterQuery<T extends AfterQueryObserver>(observer: T & ObserverRegistration<T, AfterQueryObserver>): HookManager;
2496
2716
  afterQuery(hook: AfterQueryHook): HookManager;
2497
2717
  beforeMutation(hook: BeforeMutationHook): HookManager;
2718
+ observeAfterMutation<T extends AfterMutationObserver>(observer: T & ObserverRegistration<T, AfterMutationObserver>): HookManager;
2498
2719
  afterMutation(hook: AfterMutationHook): HookManager;
2499
2720
  onError(hook: OnErrorHook): HookManager;
2500
2721
  freeze(): HookManager;
@@ -2502,8 +2723,10 @@ interface HookManager {
2502
2723
  /** @internal Hook storage — exposed for runner access */
2503
2724
  type HookStore = {
2504
2725
  readonly beforeQuery: readonly BeforeQueryHook[];
2726
+ readonly afterQueryObservers: readonly AfterQueryObserver[];
2505
2727
  readonly afterQuery: readonly AfterQueryHook[];
2506
2728
  readonly beforeMutation: readonly BeforeMutationHook[];
2729
+ readonly afterMutationObservers: readonly AfterMutationObserver[];
2507
2730
  readonly afterMutation: readonly AfterMutationHook[];
2508
2731
  readonly onError: readonly OnErrorHook[];
2509
2732
  readonly frozen: boolean;
@@ -2535,6 +2758,7 @@ interface QueryBuilderContext {
2535
2758
  readonly defaultFilters?: DefaultFilters | undefined;
2536
2759
  readonly hookStore?: HookStore | undefined;
2537
2760
  readonly onHookError?: HookErrorHandler | undefined;
2761
+ readonly onObserverError?: ObserverErrorHandler | undefined;
2538
2762
  readonly inTransaction?: boolean | undefined;
2539
2763
  }
2540
2764
 
@@ -3140,7 +3364,7 @@ interface QueryBuilder<TResult = unknown> {
3140
3364
  * orm.select('users').where({ active: true, role: 'admin' })
3141
3365
  * ```
3142
3366
  */
3143
- where(condition: WhereIntent | WhereFilter<TResult>): QueryBuilder<TResult>;
3367
+ where(condition: WhereIntent | PredicateRef | WhereFilter<TResult>): QueryBuilder<TResult>;
3144
3368
  /**
3145
3369
  * Add an explicit SQL JOIN clause to the query (non-hydrating, flat result).
3146
3370
  *
@@ -3682,7 +3906,7 @@ declare class QueryBuilderImpl<TResult = unknown> implements QueryBuilder<TResul
3682
3906
  }): QueryBuilder<TResult>;
3683
3907
  limit(count: number): QueryBuilder<TResult>;
3684
3908
  offset(count: number): QueryBuilder<TResult>;
3685
- where(condition: WhereIntent | WhereFilter<TResult>): QueryBuilder<TResult>;
3909
+ where(condition: WhereIntent | PredicateRef | WhereFilter<TResult>): QueryBuilder<TResult>;
3686
3910
  join(relationOrTableOrBatch: string | BatchValuesRef, opts?: {
3687
3911
  type?: 'inner' | 'left';
3688
3912
  on?: WhereIntent;
@@ -3921,6 +4145,39 @@ declare class CteQueryBuilder<TResult = unknown> {
3921
4145
  * Part of DX-010: Mutations.
3922
4146
  */
3923
4147
 
4148
+ /**
4149
+ * A row shape accepted by INSERT and UPSERT values().
4150
+ *
4151
+ * The public ORM type carries row types, but not the per-column default or
4152
+ * serial metadata needed to make only generated columns optional. Until that
4153
+ * schema metadata is threaded through the mutation builders (#449), every row
4154
+ * column is optional here. Keys and value types remain constrained to the row
4155
+ * type; the database enforces required columns.
4156
+ */
4157
+ type Insertable<T> = T extends object ? Partial<T> : Record<string, unknown>;
4158
+ /** A partial row shape accepted by UPDATE and UPSERT update operations. */
4159
+ type Updateable<T> = T extends object ? {
4160
+ [K in keyof T]?: T[K] | SqlRawExpression;
4161
+ } : Record<string, unknown>;
4162
+ /** A scalar-only partial row shape accepted by batchSet(). */
4163
+ type BatchUpdateable<T> = T extends object ? Partial<T> : Record<string, unknown>;
4164
+ /**
4165
+ * Reject keys outside a mutation payload's row shape, including when callers
4166
+ * pass an object through a variable rather than an object literal.
4167
+ */
4168
+ type ExactMutationPayload<TInput, TShape> = TInput & Record<Exclude<keyof TInput, keyof TShape>, never>;
4169
+ type ExactMutationRows<TInput extends readonly unknown[], TShape> = TInput & {
4170
+ readonly [K in keyof TInput]: ExactMutationPayload<TInput[K], TShape>;
4171
+ };
4172
+ /**
4173
+ * Column names accepted by a mutation on a row shape.
4174
+ *
4175
+ * The tuple prevents conditional-type distribution: a mutation whose table is
4176
+ * a union may only name columns shared by every possible target table.
4177
+ */
4178
+ type MutationKey<T> = [T] extends [object] ? Extract<keyof T, string> : string;
4179
+ type MutationReturningRow<T, K extends MutationKey<T>> = T extends object ? Pick<T, Extract<K, keyof T>> : Record<string, unknown>;
4180
+ type MutationWhereCondition = WhereIntent | PredicateRef;
3924
4181
  /**
3925
4182
  * Dump output for mutations.
3926
4183
  * Similar to query Dump but without plan (mutations don't use the planner).
@@ -3945,6 +4202,7 @@ type MutationBaseOpts = {
3945
4202
  schemaName?: string | undefined;
3946
4203
  hookStore?: HookStore | undefined;
3947
4204
  onHookError?: HookErrorHandler | undefined;
4205
+ onObserverError?: ObserverErrorHandler | undefined;
3948
4206
  inTransaction?: boolean | undefined;
3949
4207
  };
3950
4208
  /**
@@ -3964,6 +4222,7 @@ declare abstract class MutationBuilderBase<T, TIntent extends InsertIntent | Upd
3964
4222
  protected readonly returningColumns: readonly string[] | undefined;
3965
4223
  protected readonly hookStore: HookStore | undefined;
3966
4224
  protected readonly onHookError: HookErrorHandler | undefined;
4225
+ protected readonly onObserverError: ObserverErrorHandler | undefined;
3967
4226
  protected readonly inTransaction: boolean | undefined;
3968
4227
  protected constructor(opts: MutationBaseOpts & {
3969
4228
  returning?: readonly string[] | undefined;
@@ -3986,7 +4245,7 @@ declare abstract class MutationBuilderBase<T, TIntent extends InsertIntent | Upd
3986
4245
  * Builder for INSERT operations.
3987
4246
  * Immutable - each method returns a new builder instance.
3988
4247
  */
3989
- declare class InsertBuilder<T = void> extends MutationBuilderBase<T, InsertIntent> {
4248
+ declare class InsertBuilder<TRow = unknown, TResult = void> extends MutationBuilderBase<TResult, InsertIntent> {
3990
4249
  private readonly valuesData;
3991
4250
  protected readonly operationName = "insert";
3992
4251
  constructor(opts: MutationBaseOpts & {
@@ -3997,7 +4256,7 @@ declare class InsertBuilder<T = void> extends MutationBuilderBase<T, InsertInten
3997
4256
  * Set values to insert.
3998
4257
  * Accepts a single object or an array for bulk insert.
3999
4258
  */
4000
- values(data: Record<string, unknown> | readonly Record<string, unknown>[]): InsertBuilder<T>;
4259
+ values<TInput extends Insertable<TRow> | readonly Insertable<TRow>[]>(data: TInput & (TInput extends readonly Insertable<TRow>[] ? ExactMutationRows<TInput, Insertable<TRow>> : ExactMutationPayload<TInput, Insertable<TRow>>)): InsertBuilder<TRow, TResult>;
4001
4260
  /**
4002
4261
  * Specify columns to return after insert (DX-026).
4003
4262
  * Requires adapter support for RETURNING clause.
@@ -4011,7 +4270,7 @@ declare class InsertBuilder<T = void> extends MutationBuilderBase<T, InsertInten
4011
4270
  * // inserted = [{ id: 1, created_at: '2024-01-01T00:00:00Z' }]
4012
4271
  * ```
4013
4272
  */
4014
- returning<R = Record<string, unknown>>(columns: readonly (keyof R & string)[]): InsertBuilder<R[]>;
4273
+ returning<K extends MutationKey<TRow>>(columns: readonly K[]): InsertBuilder<TRow, MutationReturningRow<TRow, K>[]>;
4015
4274
  protected buildIntent(): InsertIntent;
4016
4275
  protected compileIntent(adapter: Adapter, intent: InsertIntent, options?: CompileOptions): CompiledQuery;
4017
4276
  }
@@ -4019,7 +4278,7 @@ declare class InsertBuilder<T = void> extends MutationBuilderBase<T, InsertInten
4019
4278
  * Builder for UPDATE operations.
4020
4279
  * Immutable - each method returns a new builder instance.
4021
4280
  */
4022
- declare class UpdateBuilder<T = void> extends MutationBuilderBase<T, UpdateIntent | BatchUpdateIntent> {
4281
+ declare class UpdateBuilder<TRow = unknown, TResult = void> extends MutationBuilderBase<TResult, UpdateIntent | BatchUpdateIntent> {
4023
4282
  private readonly setData;
4024
4283
  private readonly whereIntent;
4025
4284
  private readonly allowAllFlag;
@@ -4039,11 +4298,11 @@ declare class UpdateBuilder<T = void> extends MutationBuilderBase<T, UpdateInten
4039
4298
  * Multiple calls merge fields (last value wins).
4040
4299
  * When combined with batchSet(), these become scalar SET assignments applied to all rows.
4041
4300
  */
4042
- set(data: Record<string, unknown>): UpdateBuilder<T>;
4301
+ set<TInput extends Updateable<TRow>>(data: ExactMutationPayload<TInput, Updateable<TRow>>): UpdateBuilder<TRow, TResult>;
4043
4302
  /**
4044
4303
  * Add WHERE condition.
4045
4304
  */
4046
- where(condition: WhereIntent): UpdateBuilder<T>;
4305
+ where(condition: MutationWhereCondition): UpdateBuilder<TRow, TResult>;
4047
4306
  /**
4048
4307
  * Specify columns to return after update (DX-026).
4049
4308
  * Requires adapter support for RETURNING clause.
@@ -4057,7 +4316,7 @@ declare class UpdateBuilder<T = void> extends MutationBuilderBase<T, UpdateInten
4057
4316
  * .execute();
4058
4317
  * ```
4059
4318
  */
4060
- returning<R = Record<string, unknown>>(columns: readonly (keyof R & string)[]): UpdateBuilder<R[]>;
4319
+ returning<K extends MutationKey<TRow>>(columns: readonly K[]): UpdateBuilder<TRow, MutationReturningRow<TRow, K>[]>;
4061
4320
  /**
4062
4321
  * Batch update multiple rows using unnest FROM strategy (BATCH-001).
4063
4322
  *
@@ -4078,7 +4337,7 @@ declare class UpdateBuilder<T = void> extends MutationBuilderBase<T, UpdateInten
4078
4337
  * .execute();
4079
4338
  * ```
4080
4339
  */
4081
- batchSet(matchColumn: string | string[], data: Record<string, unknown>[]): UpdateBuilder<T>;
4340
+ batchSet<TInput extends BatchUpdateable<TRow>>(matchColumn: MutationKey<TRow> | MutationKey<TRow>[], data: readonly ExactMutationPayload<TInput, BatchUpdateable<TRow>>[]): UpdateBuilder<TRow, TResult>;
4082
4341
  protected buildIntent(): UpdateIntent | BatchUpdateIntent;
4083
4342
  protected compileIntent(adapter: Adapter, intent: UpdateIntent | BatchUpdateIntent, options?: CompileOptions): CompiledQuery;
4084
4343
  }
@@ -4086,7 +4345,7 @@ declare class UpdateBuilder<T = void> extends MutationBuilderBase<T, UpdateInten
4086
4345
  * Builder for DELETE operations.
4087
4346
  * Immutable - each method returns a new builder instance.
4088
4347
  */
4089
- declare class DeleteBuilder<T = void> extends MutationBuilderBase<T, DeleteIntent> {
4348
+ declare class DeleteBuilder<TRow = unknown, TResult = void> extends MutationBuilderBase<TResult, DeleteIntent> {
4090
4349
  private readonly whereIntent;
4091
4350
  private readonly allowAllFlag;
4092
4351
  private readonly cascadeRelations;
@@ -4100,13 +4359,13 @@ declare class DeleteBuilder<T = void> extends MutationBuilderBase<T, DeleteInten
4100
4359
  /**
4101
4360
  * Add WHERE condition.
4102
4361
  */
4103
- where(condition: WhereIntent): DeleteBuilder<T>;
4362
+ where(condition: MutationWhereCondition): DeleteBuilder<TRow, TResult>;
4104
4363
  /**
4105
4364
  * Enable cascade delete.
4106
4365
  * Without arguments: deletes ALL related records.
4107
4366
  * With array: deletes only specified relations.
4108
4367
  */
4109
- cascade(relations?: readonly string[]): DeleteBuilder<T>;
4368
+ cascade(relations?: readonly string[]): DeleteBuilder<TRow, TResult>;
4110
4369
  /**
4111
4370
  * Specify columns to return after delete (DX-026).
4112
4371
  * Requires adapter support for RETURNING clause.
@@ -4119,7 +4378,7 @@ declare class DeleteBuilder<T = void> extends MutationBuilderBase<T, DeleteInten
4119
4378
  * .execute();
4120
4379
  * ```
4121
4380
  */
4122
- returning<R = Record<string, unknown>>(columns: readonly (keyof R & string)[]): DeleteBuilder<R[]>;
4381
+ returning<K extends MutationKey<TRow>>(columns: readonly K[]): DeleteBuilder<TRow, MutationReturningRow<TRow, K>[]>;
4123
4382
  protected buildIntent(): DeleteIntent;
4124
4383
  protected compileIntent(adapter: Adapter, intent: DeleteIntent, options?: CompileOptions): CompiledQuery;
4125
4384
  }
@@ -4152,7 +4411,7 @@ declare class DeleteBuilder<T = void> extends MutationBuilderBase<T, DeleteInten
4152
4411
  * .execute();
4153
4412
  * ```
4154
4413
  */
4155
- declare class UpsertBuilder<T = void> extends MutationBuilderBase<T, UpsertIntent> {
4414
+ declare class UpsertBuilder<TRow = unknown, TResult = void> extends MutationBuilderBase<TResult, UpsertIntent> {
4156
4415
  private readonly valuesData;
4157
4416
  private readonly conflictTarget;
4158
4417
  private readonly conflictAction;
@@ -4167,17 +4426,17 @@ declare class UpsertBuilder<T = void> extends MutationBuilderBase<T, UpsertInten
4167
4426
  * Set values to insert.
4168
4427
  * Accepts a single object or an array for bulk upsert.
4169
4428
  */
4170
- values(data: Record<string, unknown> | readonly Record<string, unknown>[]): UpsertBuilder<T>;
4429
+ values<TInput extends Insertable<TRow> | readonly Insertable<TRow>[]>(data: TInput & (TInput extends readonly Insertable<TRow>[] ? ExactMutationRows<TInput, Insertable<TRow>> : ExactMutationPayload<TInput, Insertable<TRow>>)): UpsertBuilder<TRow, TResult>;
4171
4430
  /**
4172
4431
  * Specify conflict target by column names.
4173
4432
  * These columns determine conflict detection.
4174
4433
  */
4175
- onConflict(columns: readonly string[]): UpsertBuilder<T>;
4434
+ onConflict(columns: readonly MutationKey<TRow>[]): UpsertBuilder<TRow, TResult>;
4176
4435
  /**
4177
4436
  * Specify conflict target by constraint name.
4178
4437
  * Alternative to onConflict() for named constraints.
4179
4438
  */
4180
- onConflictConstraint(constraintName: string): UpsertBuilder<T>;
4439
+ onConflictConstraint(constraintName: string): UpsertBuilder<TRow, TResult>;
4181
4440
  /**
4182
4441
  * On conflict, update the specified fields.
4183
4442
  * If no fields specified, auto-updates all non-conflict columns.
@@ -4185,16 +4444,16 @@ declare class UpsertBuilder<T = void> extends MutationBuilderBase<T, UpsertInten
4185
4444
  * @param set - Optional fields to update on conflict
4186
4445
  * @param where - Optional condition for the update
4187
4446
  */
4188
- doUpdate(set?: Record<string, unknown>, where?: WhereIntent): UpsertBuilder<T>;
4447
+ doUpdate<TInput extends Updateable<TRow>>(set?: ExactMutationPayload<TInput, Updateable<TRow>>, where?: MutationWhereCondition): UpsertBuilder<TRow, TResult>;
4189
4448
  /**
4190
4449
  * On conflict, do nothing (skip the insert).
4191
4450
  */
4192
- doNothing(): UpsertBuilder<T>;
4451
+ doNothing(): UpsertBuilder<TRow, TResult>;
4193
4452
  /**
4194
4453
  * Specify columns to return after upsert (DX-026).
4195
4454
  * Requires adapter support for RETURNING clause.
4196
4455
  */
4197
- returning<R = Record<string, unknown>>(columns: readonly (keyof R & string)[]): UpsertBuilder<R[]>;
4456
+ returning<K extends MutationKey<TRow>>(columns: readonly K[]): UpsertBuilder<TRow, MutationReturningRow<TRow, K>[]>;
4198
4457
  protected buildIntent(): UpsertIntent;
4199
4458
  protected compileIntent(adapter: Adapter, intent: UpsertIntent, options?: CompileOptions): CompiledQuery;
4200
4459
  }
@@ -4276,9 +4535,13 @@ declare function nqlRaw(fragment: string): NqlRawFragment;
4276
4535
  * @param model - ModelIR for plan execution
4277
4536
  * @param adapter - Optional adapter for query execution
4278
4537
  * @param schemaName - Optional schema name for multi-tenant queries
4538
+ * @param hookStore - Optional hook storage for query and mutation hooks
4539
+ * @param onHookError - Optional control-flow handler for hook failures
4540
+ * @param inTransaction - Whether execution is already within a transaction
4541
+ * @param onObserverError - Optional non-fatal diagnostic sink for observer failures
4279
4542
  * @returns NQL template tag function
4280
4543
  */
4281
- declare function createNqlTag(_schemaDefinition: unknown, model: ModelIR, adapter?: Adapter<unknown>, schemaName?: string, hookStore?: HookStore, onHookError?: HookErrorHandler, inTransaction?: boolean): NqlTag;
4544
+ declare function createNqlTag(_schemaDefinition: unknown, model: ModelIR, adapter?: Adapter<unknown>, schemaName?: string, hookStore?: HookStore, onHookError?: HookErrorHandler, inTransaction?: boolean, onObserverError?: ObserverErrorHandler): NqlTag;
4282
4545
  /**
4283
4546
  * Extract pseudo-column keywords from model configuration.
4284
4547
  * Collects all configured roles and recursive keywords from all tables'
@@ -4542,11 +4805,12 @@ interface OrmOptionsWithAdapter<DB = unknown> extends OrmOptionsBase<DB> {
4542
4805
  * - `orm.select(name)` - concise table-name form
4543
4806
  * - `orm.from(table)` - TableRef form with column-level types
4544
4807
  *
4545
- * Mutations use the typed TableRef-based methods:
4546
- * - `orm.into(table)` - INSERT
4547
- * - `orm.modify(table)` - UPDATE
4548
- * - `orm.removeFrom(table)` - DELETE
4549
- * - `orm.upsertInto(table)` - UPSERT (INSERT ... ON CONFLICT)
4808
+ * Mutations have two schema-keyed surfaces:
4809
+ * - `orm.insert(name)`, `orm.update(name)`, `orm.delete(name)`, and
4810
+ * `orm.upsert(name)` are concise when the table name is already available.
4811
+ * - `orm.into(table)`, `orm.modify(table)`, `orm.removeFrom(table)`, and
4812
+ * `orm.upsertInto(table)` take a TableRef and fit flows that also use its
4813
+ * column references for typed filters and queries.
4550
4814
  *
4551
4815
  * @typeParam DB - Database row map type.
4552
4816
  * Keys are table names, values are row types.
@@ -4649,6 +4913,14 @@ interface OrmInstance<DB = Record<string, unknown>> {
4649
4913
  * @returns A QueryBuilder for constructing the select
4650
4914
  */
4651
4915
  select<K extends keyof DB & string, TResult = DB[K]>(from: K): QueryBuilder<TResult>;
4916
+ /** Start a type-safe INSERT operation from a schema table name. */
4917
+ insert<K extends keyof DB & string>(table: K): InsertBuilder<DB[K]>;
4918
+ /** Start a type-safe UPDATE operation from a schema table name. */
4919
+ update<K extends keyof DB & string>(table: K): UpdateBuilder<DB[K]>;
4920
+ /** Start a type-safe DELETE operation from a schema table name. */
4921
+ delete<K extends keyof DB & string>(table: K): DeleteBuilder<DB[K]>;
4922
+ /** Start a type-safe UPSERT operation from a schema table name. */
4923
+ upsert<K extends keyof DB & string>(table: K): UpsertBuilder<DB[K]>;
4652
4924
  /**
4653
4925
  * Start building a SELECT query from a typed TableRef.
4654
4926
  *
@@ -4855,7 +5127,7 @@ interface OrmInstance<DB = Record<string, unknown>> {
4855
5127
  * .execute();
4856
5128
  * ```
4857
5129
  */
4858
- updateAll(table: string): UpdateBuilder;
5130
+ updateAll<K extends keyof DB & string>(table: K): UpdateBuilder<DB[K]>;
4859
5131
  /**
4860
5132
  * Start building a DELETE operation that affects all rows.
4861
5133
  * Use with caution - this explicitly allows deletes without WHERE.
@@ -4868,7 +5140,7 @@ interface OrmInstance<DB = Record<string, unknown>> {
4868
5140
  * await orm.deleteAll('tempData').execute();
4869
5141
  * ```
4870
5142
  */
4871
- deleteAll(table: string): DeleteBuilder;
5143
+ deleteAll<K extends keyof DB & string>(table: K): DeleteBuilder<DB[K]>;
4872
5144
  /**
4873
5145
  * Execute a callback within a database transaction.
4874
5146
  * Auto-commits on success, auto-rolls back on exception.
@@ -6158,7 +6430,7 @@ interface SqlRawExpression {
6158
6430
  * ```typescript
6159
6431
  * orm.upsert('files')
6160
6432
  * .values({ id: 1, name: 'test' })
6161
- * .onConflict({ columns: ['id'] })
6433
+ * .onConflict(['id'])
6162
6434
  * .doUpdate({ last_parsed: sql('now()'), count: sql('excluded.count + 1') })
6163
6435
  * .execute();
6164
6436
  *
@@ -6222,6 +6494,9 @@ declare function isSqlRaw(value: unknown): value is SqlRawExpression;
6222
6494
  * not a column name → use `literal()` instead).
6223
6495
  */
6224
6496
  type ExprInput = ExpressionRef | ExpressionSpec | AggOrderByArg | string | number | boolean | readonly unknown[];
6497
+
6498
+ type BinaryPredicateOperator = Exclude<PredicateOperator, 'AND' | 'OR' | 'NOT'>;
6499
+ type NonPredicateOperator<TOperator extends string> = TOperator extends PredicateOperator ? never : TOperator;
6225
6500
  /**
6226
6501
  * A chainable wrapper around an ExpressionIntent.
6227
6502
  *
@@ -6275,6 +6550,47 @@ declare class ExpressionRef {
6275
6550
  */
6276
6551
  filter(condition: WhereIntent): ExpressionRef;
6277
6552
  }
6553
+ /** Marker used to identify an invalid predicate from a different core copy. */
6554
+ declare const PREDICATE_REF_DISCRIMINATOR: "dbsp.predicate.v1";
6555
+ /**
6556
+ * A predicate that is also a scalar expression.
6557
+ *
6558
+ * Its one canonical representation is the expression intent inherited from
6559
+ * `ExpressionRef`; the WHERE form is derived when a builder consumes it.
6560
+ */
6561
+ declare class ExpressionPredicateRef extends ExpressionRef {
6562
+ readonly __predicateRef: "dbsp.predicate.v1";
6563
+ readonly intent: StandaloneWhereExpressionIntent;
6564
+ constructor(intent: StandaloneWhereExpressionIntent);
6565
+ as(alias: string): PredicateExpressionRef;
6566
+ }
6567
+ /** A scalar predicate created by `op()`, `boolFn()`, or `unsafeAsPredicate()`. */
6568
+ type PredicateExpressionRef = ExpressionPredicateRef;
6569
+ /**
6570
+ * A composed predicate has no scalar-expression representation in this API.
6571
+ * Its canonical representation is the complete WHERE intent.
6572
+ */
6573
+ declare class WhereOnlyPredicateRef {
6574
+ readonly intent: WhereIntent;
6575
+ readonly __predicateRef: "dbsp.predicate.v1";
6576
+ constructor(intent: WhereIntent);
6577
+ }
6578
+ /** A composed predicate that is accepted only in `.where()`. */
6579
+ type WhereOnlyPredicate = WhereOnlyPredicateRef;
6580
+ /**
6581
+ * A value accepted by `.where()` as a predicate.
6582
+ *
6583
+ * The constructors are intentionally module-private. Use `op()`, predicate
6584
+ * helpers, or `unsafeAsPredicate()` instead.
6585
+ */
6586
+ type PredicateRef = PredicateExpressionRef | WhereOnlyPredicate;
6587
+ /**
6588
+ * Recognize only predicate instances constructed by this installed core copy.
6589
+ *
6590
+ * A predicate from another installed copy is unsupported: reconstruct it with
6591
+ * this module's predicate factories before passing it to a builder.
6592
+ */
6593
+ declare function isPredicateRef(value: unknown): value is PredicateRef;
6278
6594
  /**
6279
6595
  * Column reference — refers to a named column (or table.column).
6280
6596
  *
@@ -6304,7 +6620,21 @@ declare function cast(expr: ExpressionRef, typeName: string): ExpressionRef;
6304
6620
  * @example op('<=>', 'embedding', [0.1, 0.2]) // implicit conversions
6305
6621
  * @throws Error if operator fails validation (injection guard)
6306
6622
  */
6307
- declare function op(operator: string, left: ExprInput, right: ExprInput): ExpressionRef;
6623
+ /** Logical AND / OR — both operands must be predicates. */
6624
+ declare function op(operator: 'AND' | 'OR', left: PredicateRef, right: PredicateRef): WhereOnlyPredicate;
6625
+ /** Logical NOT — its sole operand must be a predicate. */
6626
+ declare function op(operator: 'NOT', operand: PredicateRef): WhereOnlyPredicate;
6627
+ /** Predicate binary operators accept expression operands. */
6628
+ declare function op(operator: BinaryPredicateOperator, left: ExprInput, right: ExprInput): ExpressionPredicateRef;
6629
+ /** Any non-predicate operator remains an ordinary expression. */
6630
+ declare function op<TOperator extends string>(operator: NonPredicateOperator<TOperator>, left: ExprInput, right: ExprInput): ExpressionRef;
6631
+ /**
6632
+ * Assert that an arbitrary expression is boolean for use in WHERE.
6633
+ *
6634
+ * Use this only for a user-defined operator whose boolean result cannot be
6635
+ * represented by the closed PredicateOperator union.
6636
+ */
6637
+ declare function unsafeAsPredicate(expr: ExpressionRef): PredicateExpressionRef;
6308
6638
  /**
6309
6639
  * Custom function call — name(args...).
6310
6640
  * Supports schema-qualified names (e.g., 'paradedb.score', 'ST_Distance').
@@ -6330,6 +6660,18 @@ declare function op(operator: string, left: ExprInput, right: ExprInput): Expres
6330
6660
  * @throws Error if name fails validation (injection guard)
6331
6661
  */
6332
6662
  declare function fn(name: string, ...args: (ExprInput | DistinctField)[]): ExpressionRef;
6663
+ /**
6664
+ * Declare that a custom function call is boolean-valued for use in WHERE.
6665
+ *
6666
+ * This has the same trust boundary as the SQL function name and arguments the
6667
+ * caller writes: use it only when the declared function returns boolean.
6668
+ * Unlike `fn()`, which builds a scalar expression, `boolFn()` builds a
6669
+ * predicate that can be passed directly to `.where()`.
6670
+ *
6671
+ * @example boolFn('jsonb_exists', ref('data'), literal('phone'))
6672
+ * @throws Error if name fails validation (injection guard)
6673
+ */
6674
+ declare function boolFn(name: string, ...args: (ExprInput | DistinctField)[]): PredicateExpressionRef;
6333
6675
  /**
6334
6676
  * Literal value — inlined directly in SQL (not bound as parameter).
6335
6677
  * Use to distinguish SQL string literals from column references.
@@ -6995,7 +7337,7 @@ type FullTextSearchOptions = {
6995
7337
  * }))
6996
7338
  * ```
6997
7339
  */
6998
- declare function fullTextSearch({ query, fields, tableAlias, }: FullTextSearchOptions): ExpressionRef;
7340
+ declare function fullTextSearch({ query, fields, tableAlias, }: FullTextSearchOptions): PredicateExpressionRef;
6999
7341
  /**
7000
7342
  * BM25 relevance score expression for ParadeDB.
7001
7343
  *
@@ -7531,6 +7873,11 @@ interface SimplifiedOrmOptions<T extends SchemaDefinition = SchemaDefinition> {
7531
7873
  * or 'abort' to propagate the error.
7532
7874
  */
7533
7875
  readonly onHookError?: HookErrorHandler;
7876
+ /**
7877
+ * Non-fatal diagnostic sink for observer failures and snapshot skips.
7878
+ * Its return value is ignored and it can never abort query or mutation work.
7879
+ */
7880
+ readonly onObserverError?: ObserverErrorHandler;
7534
7881
  /**
7535
7882
  * Behavior when schema uses features the adapter doesn't support.
7536
7883
  * Default: 'warning' (emit warning + skip).
@@ -7657,7 +8004,7 @@ type RangeType = 'int4range' | 'int8range' | 'numrange' | 'tsrange' | 'tstzrange
7657
8004
  * @example rangeOverlaps('span', [1, 100], 'int4range')
7658
8005
  * → "span" && int4range($1, $2)
7659
8006
  */
7660
- declare function rangeOverlaps(column: string, range: readonly [unknown, unknown], rangeType?: RangeType): ExpressionRef;
8007
+ declare function rangeOverlaps(column: string, range: readonly [unknown, unknown], rangeType?: RangeType): PredicateExpressionRef;
7661
8008
  /**
7662
8009
  * Range OVERLAPS — object API: delegates to WhereRangeIntent (planner path)
7663
8010
  *
@@ -7670,7 +8017,7 @@ declare function rangeOverlaps(field: string, value: RangeValue): WhereRangeInte
7670
8017
  * @example rangeContains('dateRange', ['2024-06-15', '2024-06-15'])
7671
8018
  * → "dateRange" @> daterange($1, $2)
7672
8019
  */
7673
- declare function rangeContains(column: string, range: readonly [unknown, unknown], rangeType?: RangeType): ExpressionRef;
8020
+ declare function rangeContains(column: string, range: readonly [unknown, unknown], rangeType?: RangeType): PredicateExpressionRef;
7674
8021
  /**
7675
8022
  * Range CONTAINS — object API: delegates to WhereRangeIntent (planner path)
7676
8023
  *
@@ -7683,7 +8030,7 @@ declare function rangeContains(field: string, value: RangeOperand): WhereRangeIn
7683
8030
  * @example rangeContainedBy('dateRange', ['2024-01-01', '2024-12-31'])
7684
8031
  * → "dateRange" <@ daterange($1, $2)
7685
8032
  */
7686
- declare function rangeContainedBy(column: string, range: readonly [unknown, unknown], rangeType?: RangeType): ExpressionRef;
8033
+ declare function rangeContainedBy(column: string, range: readonly [unknown, unknown], rangeType?: RangeType): PredicateExpressionRef;
7687
8034
  /**
7688
8035
  * Range CONTAINED BY — object API: delegates to WhereRangeIntent (planner path)
7689
8036
  *
@@ -8186,4 +8533,4 @@ declare const assertIntentHasOrderBy: (result: AssertionQueryResult, expected: b
8186
8533
  */
8187
8534
  declare function runAssertions(blocks: AssertionBlock[], results: AssertionQueryResult[], queries: string[], hasDb?: boolean): AssertionSummary;
8188
8535
 
8189
- export { ASSERTION_TYPES, AdapterRequiredError, type AdjacencyOptions, type AfterMutationHook, type AfterQueryHook, type AggregateOptions, type AliasedColumn, type AliasedExprColumn, type AllColumns, AmbiguousPlanError, AmbiguousRelationError, type Applier, type Assertion, type AssertionBlock, type AssertionOutcome, type AssertionQueryResult, type AssertionSummary, type AssertionType, BRAND, type BatchValuesOptions, type BatchValuesRef, type BeforeMutationHook, type BeforeQueryHook, type BrandKey, COLUMN_META, type CardinalityShorthand, CaseBuilder, type CaseValue, type CheckDelta, type ColumnDef, type ColumnMetaKey, ColumnNotFoundError, type ColumnRef, type ColumnSpec, CteBuilder, type CteDump, CteQueryBuilder, type CursorPaginateOptions, type CursorPaginatedResult, DEFAULT_FEATURE_CHECKERS, DUCKDB_CAPABILITIES, type DefaultFilters, type DefineModelOptions, DeleteBuilder, type DistinctField, type DumpMetaInput, type EdgeTableOptions, type EmitWarningOptions, type EnumAddDelta, ErrorCode, type ErrorHookContext, Errors, type EstablishedProofClaim, type ExecutionCoordinator, ExecutionError, type ExprInput, ExpressionRef, type ExpressionSpec, type FeatureChecker, type FeatureUsage, type FilterOperators, type FilterValue, type FullTextSearchField, type FullTextSearchOptions, type GetSchemaFromDbOptions, type GuardExecutionResult, type HierarchyOptions, type HookErrorHandler, type HookManager, type HookPriority, type HydrateOptions, IRREGULAR_PLURALS, type InProcessProvenPlan, type IncludeOptions, type IncludeOptionsWithRecursive, type IndexDelta, type IndexSetEntry, type InferColumn, type InferColumnNonNull, type InferColumnType, type InferColumnTypes, type InferDB, type InferRefColumn, type InferRow, type InferSchemaDB, type InferTableRow, type InferTables, type InferredRangeValue, InsertBuilder, IntentBuilder, type IntentBuilderState, type IntentSummary, InvalidOperationError, InvalidRelationDefinitionError, type JoinOptions, type JsonValue, type LightweightRelationsDef, type ListHierarchyOptions, type ListIndexOptions, type Logger, MSSQL_CAPABILITIES, MYSQL_CAPABILITIES, ModelIRImpl, type MutationDump, type MutationHookContext, type MutationOperation, NamingConventionMismatchError, type NegotiationResult, type NestedInclude, type SchemaColumnType as NewSchemaColumnType, type NonRollbackableExecutionTracker, NotFoundError, type NqlBuilder, type NqlRawFragment, type NqlTag, type OnErrorHook, type OperationFingerprints, type OperationObservation, type OperationRuntime, type OrderByInput, type OrderByRecord, type OrderBySpec, type OrmInstance, type OrmOf, type OrmOptions, type OrmOptionsWithAdapter, type OrmOptionsWithModel, POSTGRESQL_CAPABILITIES, PackRegistry, type PaginateOptions, type PaginatedResult, type ParseError, type ParseResult, type ParsedRelationDef, type ParsedRelationKey, type PathOptions, type PrioritizedHook, type ProveOutcome, type Prover, type QueryAssertionResult, type QueryBuilder, type QueryHookContext, type QueryResultType, RELATION_META, type RangeType, RawCteQueryBuilder, type RecursiveDump, type RecursiveIncludeConfig, type RecursiveOptions, RecursiveShapeMismatchError, type RefDefinition, type RefOptions, type RegisteredOperationSemantics, type RelationHints, type RelationKey, type RelationMetaKey, RelationNotFoundError, type RelationObjectDef, type RelationPathIncludeNode, type RelationPathUsage, type RelationRef, type RelationShorthand, type RelationTupleDef, ResultHydrator, type RulePrecedenceFact, SQLITE_CAPABILITIES, SQL_RAW_MARKER, type Schema, type SchemaColumnType, type SchemaConstraints, type SchemaDefinition, SchemaValidationError as SchemaError, type SchemaExtras, type SchemaIndexOptions, type SchemaIndexValidationInput, type SchemaOptions, type SchemaTableOptions, SchemaValidationError, type SelectField, type SelfRefRoles, type SetOperationBuilder, type SimplifiedOrmOptions, type SqlRawExpression, type StagedCompositionCandidate, type StagedCompositionPreflight, type StagedCompositionPreflightInput, type StagedTransitionInput, type StagedTransitionOrchestrator, type StreamOptions, SubqueryBuilder, SubqueryExpression, TABLE_META, TRANSITION_LESSOR_REJECTION, type TableAssertionData, type TableDDL, type TableDef, type TableIndexes, type TableMetaKey, TableNotFoundError, type TableRef, type TransactionCoordinatorBinding, type TransitionExecutionClient, type TransitionLeaseFailure, type TransitionPack, type TransitionRelationalValidationInput, type TransitionRelationalValidationResult, type TransitionRunPersister, type TraversalDirection, UnhandledTypeInDialect, UnknownDialectError, UnsafeOperationError, UnsupportedCapabilityError, UnsupportedFeatureError, UnsupportedStrategyError, UpdateBuilder, UpsertBuilder, type WarningCategory, type WhereFilter, WindowBuilder, acquireTransitionLease, advisoryObservationId, aggOrderBy, and, any, array, arrayAgg, assertCapability, assertConnectionAvailable, assertContains, assertDbColumnExists, assertDbOutput, assertDbRowsEquals, assertDbRowsMax, assertDbRowsMin, assertDbValueEquals, assertEquals, assertIntentHasGroupBy, assertIntentHasOrderBy, assertIntentHasWhere, assertIntentTable, assertIntentType, assertIntentWith, assertMatches, assertParamsEquals, assertParamsLength, assertParamsType, assertParamsValue, assertSQLColumn, assertSQLEquals, assertSQLJoin, assertSQLTable, assertSuccess, assertTypeSupported, assumptionAccepted, assumptionId, batchValues, bindExecutionContract, capitalize, caseWhen, cast, checkDelta, chooseReadyCandidate, claimId, coalesce, col, composeAfterMutationHooks, composeAfterQueryHooks, composeBeforeMutationHooks, composeBeforeQueryHooks, composeOnErrorHooks, concludeEvidenceForObligation, countDistinctRelationPathsByName, createApplier, createComparator, createDialectCapabilities, createEvidenceView, createExecutionContract, createHookManager, createNqlTag, createOrm, createPackRegistry, createProver, createPseudoColumnMetadata, createRawCteBuilder, createRecursiveMetadata, createStagedTransitionOrchestrator, createTransitionLessor, createTransitionRunMetadata, decapitalize, defaultIndexName, defaultLogger, defineModel, denseRank, deriveRelationPathFromIntentPath, distinct, emitWarning, enumAddDelta, eq, every, evidenceId, exists, ref as exprRef, extendDialect, extractPseudoColumnKeywords, findClosestMatch, fn, fullTextSearch, getAvailableDialects, getDialectCapabilities, getLogger, getRelationKind, getSchemaFromDb, gt, gte, inArray, inSubquery, indexDelta, inferForeignKey, isAliasedColumn, isAllColumns, isBatchValuesRef, isCardinalityShorthand, isColumnRef, isDistinctField, isDistinctFrom, isExpressionSpec, isKnownDialect, isNotNull, isNull, isOperationRuntime, isOverallSuccess, isRecursiveIncludeOptions, isRecursiveRelation, isRef, isRelationObjectDef, isRelationRef, isRelationTupleDef, isSelfReferential, isSqlRaw, isSubqueryExpression, isTableRef, isTransitionLessor, isWhereIntent, lag, lead, like, literal, lt, lte, namedArg, negotiateFeatures, neq, none, normalizeSQL, normalizedIndex, not, notExists, nqlRaw, objectToWhereIntent, observationContextDigest, op, or, outerRef, param, parseAssertionFile, parseRelationDef, parseRelationKey, pipeAfterMutationHooks, pipeAfterQueryHooks, pipeBeforeMutationHooks, pipeBeforeQueryHooks, pipeOnErrorHooks, plan, planRecursive, pluralize, preflightStagedComposition, projectCompareToSingleCandidate, rangeContainedBy, rangeContains, rangeOverlaps, rank, raw, rawExists, rawNotExists, ref$1 as ref, registerDialect, relationColumn, requiresDatabase, resetLogger, resolveEnumSchemaForComparison, resolveQueryIndex, resourceIsWithin, resourceScopeCovers, rowNumber, runAssertions, schema, schemaToModelIR, selectorMatchesResource, semanticArtifactId, serverVersionNum, setLogger, silentLogger, singularize, some, sortByPriority, sql, star, stringAgg, subquery, supportsDDLGeneration, supportsExecution, supportsIntrospection, supportsRawSql, supportsStreaming, supportsTransactions, textScore, transitionPlanDigest, unary, validateAssertionBlocks, validateExecutionContract, validateRecursiveInclude, validateRecursiveShape, validateSchemaIndexOptions, validateTransitionRelationalInvariants, validateTypeName, wAvg, wCount, wMax, wMin, wSum, withPriority };
8536
+ export { ASSERTION_TYPES, AdapterRequiredError, type AdjacencyOptions, type AfterMutationHook, type AfterMutationObserver, type AfterQueryHook, type AfterQueryObserver, type AggregateOptions, type AliasedColumn, type AliasedExprColumn, type AllColumns, AmbiguousPlanError, AmbiguousRelationError, type Applier, type Assertion, type AssertionBlock, type AssertionOutcome, type AssertionQueryResult, type AssertionSummary, type AssertionType, BRAND, type BatchValuesOptions, type BatchValuesRef, type BeforeMutationHook, type BeforeQueryHook, type BrandKey, COLUMN_META, CanonicalJsonError, type CardinalityShorthand, CaseBuilder, type CaseValue, type CheckDelta, type ColumnDef, type ColumnMetaKey, ColumnNotFoundError, type ColumnRef, type ColumnSpec, CteBuilder, type CteDump, CteQueryBuilder, type CursorPaginateOptions, type CursorPaginatedResult, DEFAULT_FEATURE_CHECKERS, DUCKDB_CAPABILITIES, type DeclarationNamingStrategy, type DefaultFilters, type DefineModelOptions, DeleteBuilder, type DistinctField, type DumpMetaInput, type EdgeTableOptions, type EmitWarningOptions, type EnumAddDelta, ErrorCode, type ErrorHookContext, Errors, type EstablishedProofClaim, type ExecutionCoordinator, ExecutionError, type ExprInput, ExpressionRef, type ExpressionSpec, type FeatureChecker, type FeatureUsage, type FilterOperators, type FilterValue, type FullTextSearchField, type FullTextSearchOptions, type GetSchemaFromDbOptions, type GuardExecutionResult, type HierarchyOptions, type HookErrorHandler, type HookManager, type HookPriority, type HydrateOptions, IRREGULAR_PLURALS, type InProcessProvenPlan, type IncludeOptions, type IncludeOptionsWithRecursive, type IndexDelta, type IndexSetEntry, type InferColumn, type InferColumnNonNull, type InferColumnType, type InferColumnTypes, type InferDB, type InferRefColumn, type InferRow, type InferSchemaDB, type InferTableRow, type InferTables, type InferredRangeValue, InsertBuilder, type Insertable, IntentBuilder, type IntentBuilderState, type IntentSummary, InvalidOperationError, InvalidRelationDefinitionError, type JoinOptions, type JsonValue, LEDGER_LIFECYCLE_GRAMMAR, LEDGER_PROJECTION_CODE_VERSION, type LedgerChainProjectionInput, type LightweightRelationsDef, type ListHierarchyOptions, type ListIndexOptions, type Logger, MSSQL_CAPABILITIES, MYSQL_CAPABILITIES, type ManagedOutcomeExecutionRequest, type ManagedOutcomePreflightRequest, ModelIRImpl, type MutationDump, type MutationHookContext, type MutationOperation, NamingConventionMismatchError, type NegotiationResult, type NestedInclude, type SchemaColumnType as NewSchemaColumnType, type NonRollbackableExecutionTracker, NotFoundError, type NqlBuilder, type NqlRawFragment, type NqlTag, type ObserverErrorHandler, type OnErrorHook, type OperationFingerprints, type OperationObservation, type OperationRuntime, type OrderByInput, type OrderByRecord, type OrderBySpec, type OrmInstance, type OrmOf, type OrmOptions, type OrmOptionsWithAdapter, type OrmOptionsWithModel, POSTGRESQL_CAPABILITIES, PREDICATE_REF_DISCRIMINATOR, PackRegistry, type PaginateOptions, type PaginatedResult, type ParseError, type ParseResult, type ParsedRelationDef, type ParsedRelationKey, type PathOptions, type PredicateExpressionRef, type PredicateRef, type PrioritizedHook, type ProveOutcome, type Prover, type QueryAssertionResult, type QueryBuilder, type QueryHookContext, type QueryResultType, RELATION_META, type RangeType, RawCteQueryBuilder, type RecursiveDump, type RecursiveIncludeConfig, type RecursiveOptions, RecursiveShapeMismatchError, type RefDefinition, type RefOptions, type RegisteredOperationSemantics, type RelationHints, type RelationKey, type RelationMetaKey, RelationNotFoundError, type RelationObjectDef, type RelationPathIncludeNode, type RelationPathUsage, type RelationRef, type RelationShorthand, type RelationTupleDef, ResultHydrator, type RulePrecedenceFact, SQLITE_CAPABILITIES, SQL_RAW_MARKER, type Schema, type SchemaColumnType, type SchemaConstraints, type SchemaDefinition, SchemaValidationError as SchemaError, type SchemaExtras, type SchemaIndexOptions, type SchemaIndexValidationInput, type SchemaOptions, type SchemaTableOptions, SchemaValidationError, type SelectField, type SelfRefRoles, type SetOperationBuilder, type SimplifiedOrmOptions, type SqlRawExpression, type StagedCompositionCandidate, type StagedCompositionPreflight, type StagedCompositionPreflightInput, type StagedTransitionInput, type StagedTransitionOrchestrator, type StreamOptions, SubqueryBuilder, SubqueryExpression, TABLE_META, type TableAssertionData, type TableDDL, type TableDef, type TableIndexes, type TableMetaKey, TableNotFoundError, type TableRef, type TransactionCoordinatorBinding, type TransitionExecutionClient, type TransitionPack, TransitionReadTarget, type TransitionRelationalValidationInput, type TransitionRelationalValidationResult, type TransitionRunPersister, type TraversalDirection, UnhandledTypeInDialect, UnknownDialectError, UnsafeOperationError, UnsupportedCapabilityError, UnsupportedFeatureError, UnsupportedStrategyError, UpdateBuilder, type Updateable, UpsertBuilder, type ValidatedManagedStepManifest, type ValidatedManagedStepManifestResult, type WarningCategory, type WhereFilter, WindowBuilder, admitRecordedIdentity, advisoryObservationId, aggOrderBy, and, any, array, arrayAgg, assertCanonicalizableJson, assertCapability, assertConnectionAvailable, assertContains, assertDbColumnExists, assertDbOutput, assertDbRowsEquals, assertDbRowsMax, assertDbRowsMin, assertDbValueEquals, assertEquals, assertIntentHasGroupBy, assertIntentHasOrderBy, assertIntentHasWhere, assertIntentTable, assertIntentType, assertIntentWith, assertMatches, assertParamsEquals, assertParamsLength, assertParamsType, assertParamsValue, assertSQLColumn, assertSQLEquals, assertSQLJoin, assertSQLTable, assertSuccess, assertTypeSupported, assumptionAccepted, assumptionId, batchValues, bindDeclarationSet, bindExecutionContract, boolFn, canonicalJson, canonicalJsonDigest, capitalize, caseWhen, cast, checkDelta, chooseReadyCandidate, claimId, coalesce, col, composeAfterMutationHooks, composeAfterQueryHooks, composeBeforeMutationHooks, composeBeforeQueryHooks, composeOnErrorHooks, concludeEvidenceForObligation, countDistinctRelationPathsByName, createApplier, createComparator, createDialectCapabilities, createEvidenceView, createExecutionContract, createHookManager, createNqlTag, createOrm, createPackRegistry, createProver, createPseudoColumnMetadata, createRawCteBuilder, createRecursiveMetadata, createStagedTransitionOrchestrator, createTransitionRunMetadata, decapitalize, declarationSetFromModel, defaultIndexName, defaultLogger, defineModel, denseRank, deriveRelationPathFromIntentPath, distinct, emitWarning, enumAddDelta, eq, every, evidenceId, exists, ref as exprRef, extendDialect, extractPseudoColumnKeywords, findClosestMatch, fn, fullTextSearch, getAvailableDialects, getDialectCapabilities, getLogger, getRelationKind, getSchemaFromDb, gt, gte, inArray, inSubquery, indexDelta, inferForeignKey, interpretLedgerLifecycle, isAliasedColumn, isAllColumns, isBatchValuesRef, isCardinalityShorthand, isColumnRef, isDistinctField, isDistinctFrom, isExpressionSpec, isKnownDialect, isNotNull, isNull, isOperationRuntime, isOverallSuccess, isPredicateRef, isRecursiveIncludeOptions, isRecursiveRelation, isRef, isRelationObjectDef, isRelationRef, isRelationTupleDef, isSelfReferential, isSqlRaw, isSubqueryExpression, isTableRef, isWhereIntent, lag, lead, like, literal, loadVerifiedRecoveryJournal, lt, lte, markGeneratorRemovalNonReplayable, namedArg, negotiateFeatures, neq, none, normalizeSQL, normalizedIndex, not, notExists, nqlRaw, objectToWhereIntent, observationContextDigest, op, or, outerRef, param, parseAssertionFile, parseRelationDef, parseRelationKey, pipeAfterMutationHooks, pipeAfterQueryHooks, pipeBeforeMutationHooks, pipeBeforeQueryHooks, pipeOnErrorHooks, plan, planRecursive, pluralize, preflightStagedComposition, projectCompareToSingleCandidate, projectLedgerChain, rangeContainedBy, rangeContains, rangeOverlaps, rank, raw, rawExists, rawNotExists, ref$1 as ref, registerDialect, relationColumn, requiresDatabase, resetLogger, resolveEnumSchemaForComparison, resolveQueryIndex, resourceIsWithin, resourceScopeCovers, rowNumber, runAssertions, schema, schemaToModelIR, selectorMatchesResource, semanticArtifactId, serverVersionNum, setLogger, silentLogger, singularize, some, sortByPriority, sql, star, stringAgg, subquery, supportsDDLGeneration, supportsExecution, supportsIntrospection, supportsRawSql, supportsStreaming, supportsTransactions, textScore, transitionPlanDigest, unary, unsafeAsPredicate, validateAssertionBlocks, validateDeclarationModel, validateExecutionContract, validateNormalizedManagedStepManifest, validateRecursiveInclude, validateRecursiveShape, validateSchemaIndexOptions, validateTransitionRelationalInvariants, validateTypeName, wAvg, wCount, wMax, wMin, wSum, withPriority };