@orkestrel/scaffold 0.0.135 → 0.0.137

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.
Files changed (36) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +167 -4
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +20 -5
  3. package/dist/bin/main.js +12 -12
  4. package/dist/host/AGENTS.md +1 -1
  5. package/dist/host/agents/orchestration.md +2 -2
  6. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +201 -8
  7. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +24 -5
  8. package/dist/host/claude/agents/orkestrel.md +52 -52
  9. package/dist/host/claude/agents/reviewer.md +1 -1
  10. package/dist/host/claude/rules/documentation.md +1 -1
  11. package/dist/host/claude/rules/patterns.md +2 -2
  12. package/dist/host/claude/rules/workspace.md +9 -4
  13. package/dist/host/configs/helpers.ts +21 -6
  14. package/dist/host/guides/agent.md +3 -1
  15. package/dist/host/guides/brief.md +16 -16
  16. package/dist/host/guides/browser.md +1 -1
  17. package/dist/host/guides/contract.md +198 -163
  18. package/dist/host/guides/database.md +773 -310
  19. package/dist/host/guides/indexeddb.md +80 -66
  20. package/dist/host/guides/reason.md +1 -1
  21. package/dist/host/guides/relation.md +56 -32
  22. package/dist/host/guides/scaffold.md +8 -2
  23. package/dist/host/guides/sqlite.md +44 -23
  24. package/dist/host/guides/test.md +7 -3
  25. package/dist/host/guides/tool.md +2 -1
  26. package/dist/host/guides/toolbox.md +44 -44
  27. package/dist/host/guides/workflow.md +2 -2
  28. package/dist/host/manifest.json +26 -26
  29. package/dist/host/tests/config.test.ts +71 -3
  30. package/dist/src/core/index.cjs +112 -35
  31. package/dist/src/core/index.cjs.map +1 -1
  32. package/dist/src/core/index.d.cts +31 -5
  33. package/dist/src/core/index.d.ts +31 -5
  34. package/dist/src/core/index.js +112 -36
  35. package/dist/src/core/index.js.map +1 -1
  36. package/package.json +12 -12
@@ -1,8 +1,8 @@
1
1
  # Database
2
2
 
3
- > One typed database API for keyed rows, fluent queries, cursors, and
4
- > whole-store transactions, running unchanged over an in-memory map, a JSON
5
- > file, SQLite, or IndexedDB.
3
+ > One typed database API for keyed rows, batches, fluent queries, cursors, and
4
+ > transactions, running unchanged over an in-memory map, a JSON file, SQLite, or
5
+ > IndexedDB.
6
6
 
7
7
  A table is a contract. Declare a `tables` map of
8
8
  [`ContractShape`](contract.md)s once, and the row type, write-time admission,
@@ -10,8 +10,8 @@ JSON-Schema introspection, and seed data all flow from that one
10
10
  declaration — no separate schema, no annotations, no `as`.
11
11
 
12
12
  The design stance is native first, under the rule Contract invariant 3 places. A backend
13
- implements keyed read/write/insert/delete, an ordered `scan`, key listing, and a
14
- `snapshot`, and declares through `plan` which part of each read its engine answers; the
13
+ implements keyed read/write/insert/delete, each with a list overload that applies every row
14
+ or none, an ordered `scan`, and key listing, and declares through `plan` which part of each read its engine answers; the
15
15
  core's engine runs only the residual. A backend without `plan` inherits the whole WHERE /
16
16
  order / page / aggregate surface from that engine over `scan`.
17
17
  So this is deliberately not an ORM and not a query abstraction layer: there is
@@ -23,8 +23,8 @@ persistent drivers ship alongside it: a trusted-mode SQLite driver in
23
23
  [`src/server`](../src/server) (surfaced through `@orkestrel/database/server`)
24
24
  with native querying, paging, counting, aggregation, transactions, and atomic migration,
25
25
  and an IndexedDB driver in [`src/browser`](../src/browser)
26
- (surfaced through `@orkestrel/database/browser`) whose plan answers one condition with a
27
- key range over the primary key or an index — beside the I/O-free `MemoryDriver` and the
26
+ (surfaced through `@orkestrel/database/browser`) whose plan answers one ranked access path
27
+ over the primary key or an index, with its order, page, and count — beside the I/O-free `MemoryDriver` and the
28
28
  file-persisted `JSONDriver`, whose reads the core answers over `scan`.
29
29
 
30
30
  ## Surface
@@ -71,27 +71,31 @@ produces the JSON Schema, and seeds fixtures.
71
71
 
72
72
  ### Factories
73
73
 
74
- | Name | Kind | Signature | Summary |
75
- | ----------------------- | -------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
76
- | `createDatabase` | function | `<const T extends TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Creates a database over a driver and a declared `tables` schema. |
77
- | `createMemoryDriver` | function | `() => DriverInterface` | Creates the in-memory reference `DriverInterface`. |
78
- | `createJSONDriver` | function | `(path: string) => DriverInterface` | Creates a persistent JSON-file `DriverInterface` for a given path. |
79
- | `createSQLiteDriver` | function | `(options: SQLiteDriverOptions) => DriverInterface` | Creates a trusted-mode, server-native SQLite `DriverInterface` for a database path, or for `:memory:` when explicitly requested. |
80
- | `createIndexedDBDriver` | function | `(name: string) => DriverInterface` | Creates a persistent IndexedDB `DriverInterface` for a browser database name. |
74
+ | Name | Kind | Signature | Summary |
75
+ | ----------------------- | -------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
76
+ | `createDatabase` | function | `<const T extends TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Creates a database over a driver and a declared `tables` schema. |
77
+ | `createMemoryDriver` | function | `() => DriverInterface` | Creates the in-memory reference `DriverInterface`. |
78
+ | `createJSONDriver` | function | `(path: string) => DriverInterface` | Creates a persistent JSON-file `DriverInterface` for a given path. |
79
+ | `createSQLiteDriver` | function | `(options: SQLiteDriverOptions) => SQLiteDriverInterface` | Creates a trusted-mode, server-native SQLite `SQLiteDriverInterface` for a database path, or for `:memory:` when explicitly requested. |
80
+ | `createIndexedDBDriver` | function | `(name: string) => DriverInterface` | Creates a persistent IndexedDB `DriverInterface` for a browser database name. |
81
81
 
82
82
  ### Classes
83
83
 
84
- | Name | Kind | Signature | Summary |
85
- | ------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
86
- | `Database` | class | `new <T extends TableMap = TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Exposes a typed view over one shared internal lifecycle and storage context. |
87
- | `DriverIterator` | class | `new <T>(source: AsyncIterator<T>, guard: () => void) => AsyncIterableIterator<T>` | Forms the internal continuation boundary for a root driver async iterator. |
88
- | `MemoryDriver` | class | `new () => DriverInterface` | Implements the reference `DriverInterface` — nested maps, no I/O. |
89
- | `JSONDriver` | class | `new (path: string) => DriverInterface` | Implements a persistent `DriverInterface` backed by a single JSON file — the reference `MemoryDriver` plus file load / flush. |
90
- | `SQLiteDriver` | class | `new (options: SQLiteDriverOptions) => DriverInterface` | Implements the `DriverInterface` over SQLite — the server-native, trusted-mode backend built on the published `@orkestrel/sqlite` synchronous wrapper. |
91
- | `IndexedDBDriver` | class | `new (name: string) => DriverInterface` | Implements the `DriverInterface` over IndexedDB — the persistent browser backend, built on the published `@orkestrel/indexeddb` wrapper. |
92
- | `StreamPage` | class | `new (offset: number) => StreamPage` | Tracks the matching-row position of one streaming page. |
93
- | `JSONTransaction` | class | `new (memory: MemoryDriver, schema: readonly TableSchema[], identities: ReadonlyMap<string, object>) => JSONTransaction` | Owns the isolated memory store and schema of one JSON transaction. |
94
- | `SQLiteTransaction` | class | `new (schema: ReadonlyMap<string, TableSchema>, identities: ReadonlyMap<string, object>) => SQLiteTransaction` | Owns the candidate schema and table identities of one SQLite transaction. |
84
+ | Name | Kind | Signature | Summary |
85
+ | ------------------------ | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
86
+ | `Database` | class | `new <T extends TableMap = TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Exposes a typed view over one shared internal lifecycle and storage context. |
87
+ | `DriverIterator` | class | `new <T>(source: AsyncIterator<T>, guard: () => void) => AsyncIterableIterator<T>` | Forms the internal continuation boundary for a root driver async iterator. |
88
+ | `ScopedStorage` | class | `new (source: StorageInterface, guard: () => void) => StorageInterface` | Forms the lifetime boundary of a driver's scoped storage: each member runs the guard, then forwards to the storage it wraps. |
89
+ | `StorageJournal` | class | `new (source: StorageInterface) => StorageJournalInterface` | Records the prior row of each key a scope writes or deletes, on its first touch, and restores those keys on request — the transaction floor for a driver without `transaction`. |
90
+ | `MemoryDriver` | class | `new () => DriverInterface` | Implements the reference `DriverInterface` — nested maps, no I/O. |
91
+ | `JSONDriver` | class | `new (path: string) => DriverInterface` | Implements a persistent `DriverInterface` backed by a single JSON file — the reference `MemoryDriver` plus file load / flush. |
92
+ | `SQLiteDriver` | class | `new (options: SQLiteDriverOptions) => SQLiteDriverInterface` | Implements the `SQLiteDriverInterface` over SQLite — the server-native, trusted-mode backend built on the published `@orkestrel/sqlite` synchronous wrapper. |
93
+ | `IndexedDBDriver` | class | `new (name: string) => DriverInterface` | Implements the `DriverInterface` over IndexedDB — the persistent browser backend, built on the published `@orkestrel/indexeddb` wrapper. |
94
+ | `IndexedDBBatchIterator` | class | `new (read: (position: AccessPosition \| undefined, size: number) => Promise<AccessBatch>, limit?: number) => AsyncIterableIterator<readonly Row[]>` | Iterates the batches of one stream, each read by its own call, past the position the previous batch reports, up to a total row limit. |
95
+ | `StreamPage` | class | `new (offset: number) => StreamPageInterface` | Tracks the matching-row position of one streaming page. |
96
+ | `JSONTransaction` | class | `new (memory: MemoryDriver, schema: readonly TableSchema[], identities: ReadonlyMap<string, object>) => JSONTransaction` | Owns the isolated memory store and schema of one JSON transaction. |
97
+ | `SQLiteTransaction` | class | `new (schema: ReadonlyMap<string, TableSchema>, identities: ReadonlyMap<string, object>) => SQLiteTransaction` | Owns the candidate schema and table identities of one SQLite transaction. |
98
+ | `SQLiteConnection` | class | `new (database: SQLiteDatabaseInterface) => SQLiteConnection` | Owns one open SQLite connection of the SQLite driver and the prepared statements it reuses, keyed by SQL text and bounded by `STATEMENT_LIMIT` with least-recently-used eviction. |
95
99
 
96
100
  ### Server
97
101
 
@@ -99,9 +103,11 @@ produces the JSON Schema, and seeds fixtures.
99
103
  | ------------------------ | -------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
100
104
  | `METADATA_TABLE` | const | `"_metadata"` | Names the reserved metadata table the `SQLiteDriver` creates on `open` to persist its stamped `DriverMetadata` (`version` + declared schema JSON) — the SQLite realization of the `metadata` / `stamp` driver hooks. |
101
105
  | `PRAGMA_NAMES` | const | `readonly string[]` | Lists the PRAGMA names the `SQLiteDriver` admits in its `pragmas` option, each matched exactly; it refuses every other name, because one can change a read result the planner assumes. |
102
- | `validatePragmas` | function | `(pragmas: Readonly<Record<string, string \| number>> \| undefined) => void` | Validates the `pragmas` option of the SQLite driver: each name must be one of `PRAGMA_NAMES`, matched exactly, and each value a finite number or a bare keyword. |
106
+ | `STATEMENT_LIMIT` | const | `256` | Bounds the prepared statements one `SQLiteConnection` keeps, evicting the least recently used past it. |
107
+ | `validatePragmas` | function | `(pragmas: Readonly<Record<string, string \| number>> \| undefined) => void` | Validates the `pragmas` option of the SQLite driver: each name must pass `isPragmaName` and be one of `PRAGMA_NAMES`, matched exactly, and each value must pass `isPragmaValue`. |
103
108
  | `planSQLiteQuery` | function | `(input: ReadInput, schema: TableSchema) => ReadPlan` | Splits a read into the part SQLite answers natively and the residual the core runs — the SQLite driver's `plan`. |
104
109
  | `matchesSQLiteCondition` | function | `(condition: Condition, schema: TableSchema) => boolean` | Reports whether SQLite answers one `Condition` with the core engine's meaning. |
110
+ | `matchesSQLitePrefilter` | function | `(condition: Condition, schema: TableSchema) => boolean` | Reports whether SQLite applies a superset form of one `Condition` that the core then rechecks: `equals`, `not`, `any`, or `none` on a nested path under a declared `json` head, with scalar operands. |
105
111
  | `findSQLiteColumn` | function | `(path: FieldPath, schema: TableSchema) => ColumnSchema \| undefined` | Resolves the declared column a field path names when SQLite answers it natively: a flat path to a declared `text`, `integer`, `real`, or `boolean` column. |
106
112
  | `matchesPrimaryPin` | function | `(conditions: readonly Condition[], schema: TableSchema) => boolean` | Reports whether a WHERE fold pins its column references: every connector is `and` and one condition is `any` on the primary key. |
107
113
  | `computeSuccessor` | function | `(prefix: string) => string \| undefined` | Computes the least text above every text that starts with a prefix, in code-point order — the exclusive upper bound of the `starts` range. |
@@ -115,50 +121,67 @@ Pure, server-only functions that turn a core `QueryInput` / `TableSchema` into
115
121
  parameterized SQL text — the native-query payoff for a SQLite-backed driver.
116
122
  None of these import a SQLite package; they speak strings and values only.
117
123
 
118
- | Name | Kind | Signature | Summary |
119
- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
- | `inferValueStorage` | function | `(value: unknown) => ColumnStorage` | Reads the storage type a nested (`json_extract`) operand encodes as from its runtime value, never as `json`. |
121
- | `compileJSONTypeSQL` | function | `(path: readonly string[]) => string` | Compiles a nested `FieldPath` to the `json_type(<col>, <path>)` SQL expression — the `compileFieldSQL` `json_extract` sibling used to tell a present JSON `null` apart from an absent path (both read back as SQL `NULL` through `json_extract`, but `json_type` reports `'null'` for the former and SQL `NULL` for the latter). |
122
- | `compileConditionSQL` | function | `(condition: Condition, schema: TableSchema, pinned?: boolean) => CompiledSQL` | Compiles one condition to its SQL fragment and the parameters it binds, with the core engine's meaning under SQL's three-valued `NULL` logic. |
123
- | `compileWhereSQL` | function | `(conditions: readonly Condition[], schema: TableSchema) => CompiledSQL` | Folds the conditions into one WHERE clause, parenthesizing progressively left-to-right so the grouping matches the engine's `matchesQuery` fold. |
124
- | `compileOrderSQL` | function | `(order: readonly Order[] \| undefined, schema: TableSchema, pinned?: boolean) => string` | Compiles the ORDER BY clause from the order terms, ending with the primary key in the direction of the final term. |
125
- | `compilePageSQL` | function | `(limit: number \| undefined, offset: number \| undefined) => CompiledSQL` | Compiles the LIMIT / OFFSET clause. |
126
- | `compileQuerySQL` | function | `(input: QueryInput \| undefined, schema: TableSchema) => CompiledSQL` | Compiles a `QueryInput` into the SQL clause that follows a table name, with its bound parameters in clause order. |
127
- | `quoteIdentifier` | function | `(identifier: string) => string` | Quotes a SQL identifier (a table or column name) so any characters are literal. |
128
- | `compileFieldSQL` | function | `(path: FieldPath) => string` | Compiles a `FieldPath` to the SQL expression that reads it. |
129
- | `compileColumnSQL` | function | `(storage: ColumnStorage) => string` | Maps a portable `ColumnStorage` to its SQLite column type. |
130
- | `compileAggregateSQL` | function | `(operation: AggregateOperation, column: FieldPath) => string` | Compiles an `AggregateOperation` over a `FieldPath`. |
131
- | `matchesSQLiteAffinity` | function | `(declared: unknown, storage: ColumnStorage) => boolean` | Checks a declared SQLite type against a portable storage affinity. |
132
- | `matchesAbsentPath` | function | `(error: unknown) => boolean` | Reports whether a caught filesystem error says that nothing is there to read. |
133
- | `encodeValue` | function | `(value: unknown, column: ColumnSchema) => SQLiteValue` | Encodes a JS value to its stored `SQLiteValue` for a declared column. |
134
- | `decodeValue` | function | `(value: SQLiteValue, column: ColumnSchema, context?: Readonly<Record<string, unknown>>) => unknown` | Decodes a stored `SQLiteValue` back to its JS value for a declared column — the exact inverse of `encodeValue`. |
135
- | `encodeRow` | function | `(row: Row, schema: TableSchema) => SQLiteRow` | Encodes a whole `Row` to a `SQLiteRow` by its table's schema. |
136
- | `decodeRow` | function | `(row: SQLiteRow, schema: TableSchema) => Row` | Decodes a stored `SQLiteRow` back to a `Row` by its table's schema. |
137
- | `schemaToTable` | function | `(schema: TableSchema) => string` | Projects a `TableSchema` to its `CREATE TABLE IF NOT EXISTS` statement. |
138
- | `schemaToIndexes` | function | `(schema: TableSchema) => readonly string[]` | Projects a `TableSchema` to its declared SQLite indexes. |
139
- | `stepToSQL` | function | `(step: MigrationStep) => readonly string[]` | Projects one `MigrationStep` to SQLite DDL. |
140
- | `compileBoundSQL` | function | `(sql: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Encodes condition operands for a SQL fragment using their declared or inferred storage. |
141
- | `compileListSQL` | function | `(head: string, tail: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Compiles a membership list as one bound JSON parameter read through `json_each`, or as one parameter per operand when an encoded operand has no JSON form. |
142
- | `compileGuardedSQL` | function | `(fragment: string, guard: string) => string` | Parenthesizes a fragment when a guard term joins it, and leaves a bare fragment bare. |
143
- | `compileJoinedSQL` | function | `(parts: readonly CompiledSQL[], connective: string, empty: string) => CompiledSQL` | Joins SQL fragments with one connective, parenthesizing two or more, and returns a constant for none. |
124
+ | Name | Kind | Signature | Summary |
125
+ | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
126
+ | `inferValueStorage` | function | `(value: unknown) => ColumnStorage` | Reads the storage type a nested (`json_extract`) operand encodes as from its runtime value, never as `json`. |
127
+ | `inferSentinelType` | function | `(storage: ColumnStorage \| undefined) => 'blob' \| 'text'` | Reads the SQLite storage class of the sentinel a column that is both optional and nullable stores for explicit `null`. |
128
+ | `compileJSONTypeSQL` | function | `(path: readonly string[]) => string` | Compiles a nested `FieldPath` to the SQL expression that reads the JSON type at the path, through `compileJSONAccessSQL`. |
129
+ | `compileConditionSQL` | function | `(condition: Condition, schema: TableSchema, pinned?: boolean) => CompiledSQL` | Compiles one condition to its SQL fragment and the parameters it binds, with the core engine's meaning under SQL's three-valued `NULL` logic. |
130
+ | `compileNestedSQL` | function | `(condition: Condition) => CompiledSQL` | Compiles an `equals`, `not`, `any`, or `none` condition on a nested path to a form that tests the JSON type the path holds beside its value. |
131
+ | `compileWhereSQL` | function | `(conditions: readonly Condition[], schema: TableSchema) => CompiledSQL` | Folds the conditions into one WHERE clause, parenthesizing progressively left-to-right so the grouping matches the engine's `matchesQuery` fold. |
132
+ | `compileOrderSQL` | function | `(order: readonly Order[] \| undefined, schema: TableSchema, pinned?: boolean) => string` | Compiles the ORDER BY clause from the order terms, ending with the primary key in the direction of the final term. |
133
+ | `compilePageSQL` | function | `(limit: number \| undefined, offset: number \| undefined) => CompiledSQL` | Compiles the LIMIT / OFFSET clause. |
134
+ | `compileQuerySQL` | function | `(input: QueryInput \| undefined, schema: TableSchema) => CompiledSQL` | Compiles a `QueryInput` into the SQL clause that follows a table name, with its bound parameters in clause order. |
135
+ | `compileInsertSQL` | function | `(schema: TableSchema, replace: boolean) => string` | Compiles the statement that inserts one row of a table, binding one parameter per declared column in schema order. |
136
+ | `quoteIdentifier` | function | `(identifier: string) => string` | Quotes a SQL identifier (a table or column name) so any characters are literal. |
137
+ | `compileFieldSQL` | function | `(path: FieldPath) => string` | Compiles a `FieldPath` to the SQL expression that reads it. |
138
+ | `compileJSONPathSQL` | function | `(keys: readonly string[]) => string` | Compiles the keys of a nested path to a SQL string literal holding its JSON path, each key a quoted label. |
139
+ | `compileJSONAccessSQL` | function | `(path: readonly string[]) => string` | Compiles the arguments a JSON function reads a nested path through: the head column, read only when it holds text, and the path's quoted labels. |
140
+ | `compileColumnSQL` | function | `(storage: ColumnStorage) => string` | Maps a portable `ColumnStorage` to its SQLite column type. |
141
+ | `compileAggregateSQL` | function | `(operation: AggregateOperation, column: FieldPath) => string` | Compiles an `AggregateOperation` over a `FieldPath`. |
142
+ | `matchesSQLiteAffinity` | function | `(declared: unknown, storage: ColumnStorage) => boolean` | Checks a declared SQLite type against a portable storage affinity. |
143
+ | `matchesAbsentPath` | function | `(error: unknown) => boolean` | Reports whether a caught filesystem error says that nothing is there to read. |
144
+ | `encodeValue` | function | `(value: unknown, column: ColumnSchema) => SQLiteValue` | Encodes a JS value to its stored `SQLiteValue` for a declared column. |
145
+ | `decodeValue` | function | `(value: SQLiteValue, column: ColumnSchema, context?: Readonly<Record<string, unknown>>) => unknown` | Decodes a stored `SQLiteValue` back to its JS value for a declared column — the exact inverse of `encodeValue`. |
146
+ | `encodeRow` | function | `(row: Row, schema: TableSchema) => SQLiteRow` | Encodes a whole `Row` to a `SQLiteRow` by its table's schema. |
147
+ | `decodeRow` | function | `(row: SQLiteRow, schema: TableSchema) => Row` | Decodes a stored `SQLiteRow` back to a `Row` by its table's schema. |
148
+ | `schemaToTable` | function | `(schema: TableSchema) => string` | Projects a `TableSchema` to its `CREATE TABLE IF NOT EXISTS` statement. |
149
+ | `schemaToIndexes` | function | `(schema: TableSchema) => readonly string[]` | Projects a `TableSchema` to its declared SQLite indexes. |
150
+ | `stepToSQL` | function | `(step: MigrationStep) => readonly string[]` | Projects one `MigrationStep` to SQLite DDL. |
151
+ | `compileBoundSQL` | function | `(sql: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Encodes condition operands for a SQL fragment using their declared or inferred storage. |
152
+ | `compileListSQL` | function | `(head: string, tail: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Compiles a membership list as one bound JSON parameter read through `json_each`, or as one parameter per operand when an encoded operand has no JSON form. |
153
+ | `compileGuardedSQL` | function | `(fragment: string, guard: string) => string` | Parenthesizes a fragment when a guard term joins it, and leaves a bare fragment bare. |
154
+ | `compileJoinedSQL` | function | `(parts: readonly CompiledSQL[], connective: string, empty: string) => CompiledSQL` | Joins SQL fragments with one connective, parenthesizing two or more, and returns a constant for none. |
144
155
 
145
156
  ### Browser
146
157
 
147
- Pure functions behind the IndexedDB driver's planner — the one condition a key range
148
- answers stays native, and the core engine runs the rest.
149
-
150
- | Name | Kind | Signature | Summary |
151
- | -------------------------- | -------- | --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
152
- | `conditionToRange` | function | `(condition: Condition) => IDBKeyRange \| undefined` | Translates one `Condition` to the `IDBKeyRange` it maps to, when its operator is one of the exact key comparisons over scalar operands; otherwise returns `undefined`. |
153
- | `planIndexedDBQuery` | function | `(input: ReadInput, schema: TableSchema, available: readonly string[]) => ReadPlan` | Splits a read into the part IndexedDB answers natively and the residual the core runs — the IndexedDB driver's `plan`. |
154
- | `findAccessCondition` | function | `(input: QueryInput \| undefined, schema: TableSchema, available: readonly string[]) => Condition \| undefined` | Finds the condition an IndexedDB read narrows on: the first one an index or the primary key answers with an exact key range. |
155
- | `deriveAccessPlan` | function | `(condition: Condition \| undefined, schema: TableSchema) => AccessPlan` | Derives the key-range read for the condition an IndexedDB read narrows on. |
156
- | `INDEXABLE_STORAGE` | const | `readonly ColumnStorage[]` | Lists the declared `ColumnStorage`s that are valid, orderable IndexedDB keys. |
157
- | `METADATA_STORE` | const | `"__metadata__"` | Names the reserved out-of-line store `__metadata__` the `IndexedDBDriver` stamps its `DriverMetadata` into. |
158
- | `mapIndexedDBError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy — the default mapping used everywhere except inside `migrate()`. |
159
- | `mapMigrationError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy for use inside `migrate()` — the one context where `UPGRADE` means the migration itself failed, not a generic driver fault. |
160
- | `deriveIndexedDBIndexName` | function | `(columns: readonly string[]) => string` | Derives an IndexedDB index name for a declared column group — a bare column name for a single-column index, a deterministic collision-free encoding for a compound one. |
161
- | `schemaToStore` | function | `(schema: TableSchema) => StoreDefinition` | Projects a table schema into the IndexedDB wrapper's store definition. |
158
+ Pure functions behind the IndexedDB driver's planner: it ranks the access paths a read's
159
+ conditions admit, keeps the one it picks native with the order and page that path serves,
160
+ and leaves the rest to the core engine.
161
+
162
+ | Name | Kind | Signature | Summary |
163
+ | -------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
164
+ | `conditionToRange` | function | `(condition: Condition) => IDBKeyRange \| undefined` | Translates one `Condition` to the `IDBKeyRange` it maps to, when its operator is one of the exact key comparisons over scalar operands; otherwise returns `undefined`. |
165
+ | `planIndexedDBQuery` | function | `(input: ReadInput, schema: TableSchema, available: readonly string[]) => ReadPlan` | Splits a read into the part IndexedDB answers natively and the residual the core runs — the IndexedDB driver's `plan`. |
166
+ | `findAccessPlan` | function | `(input: ReadInput, schema: TableSchema, available: readonly string[]) => AccessPlan` | Finds the one access path an IndexedDB read takes. |
167
+ | `deriveConditionPlan` | function | `(condition: Condition, schema: TableSchema, available: readonly string[]) => AccessPlan \| undefined` | Derives the access path one condition admits on the primary key or on a single-column index, or `undefined` when it admits none. |
168
+ | `deriveCompoundPlan` | function | `(conditions: readonly Condition[], index: readonly string[], schema: TableSchema, available: readonly string[]) => AccessPlan \| undefined` | Derives the access path a compound index admits for a read's conditions, or `undefined` when it admits none. |
169
+ | `deriveOrderPlan` | function | `(order: readonly Order[] \| undefined, schema: TableSchema, available: readonly string[]) => AccessPlan \| undefined` | Derives the access path an order alone admits: the index whose columns are the order's columns, read in one direction, or `undefined` when no such index serves it. |
170
+ | `rankAccessPlan` | function | `(plan: AccessPlan) => number` | Ranks an access path by the rule `findAccessPlan` reads: a lower rank wins. |
171
+ | `buildCompoundRange` | function | `(values: readonly Key[], condition?: Condition) => IDBKeyRange \| undefined` | Builds the key range over a compound index's array keys that binds its leading columns to `values` and, when given, its next column to a range condition. |
172
+ | `matchesAccessOrder` | function | `(plan: AccessPlan, order: readonly Order[], primary: string) => boolean` | Checks whether an access path reads its rows in an order, ties broken by primary key in the order's direction. |
173
+ | `matchesKeyList` | function | `(plan: AccessPlan, order: readonly Order[] \| undefined, primary: string) => boolean` | Checks whether a read lists the primary keys of its access path and sorts them, rather than walking its source in order. |
174
+ | `resolveCount` | function | `(count: number \| undefined) => number \| undefined` | Resolves the count a native `getAll`, `getAllKeys`, or `advance` call takes for a row count. |
175
+ | `narrowRange` | function | `(range: IDBKeyRange \| undefined, key: IDBValidKey, direction: IDBCursorDirection, open: boolean) => IDBKeyRange \| undefined` | Narrows a key range to the keys past one key in a cursor direction, for a stream that resumes after the final key of its last batch. |
176
+ | `readIndexNames` | function | `(database: IDBDatabase, stores: readonly string[]) => ReadonlyMap<string, readonly string[]>` | Reads the index names each listed store of a connected database holds, in one readonly transaction. |
177
+ | `INDEXABLE_STORAGE` | const | `readonly ColumnStorage[]` | Lists the declared `ColumnStorage`s that are valid, orderable IndexedDB keys. |
178
+ | `METADATA_STORE` | const | `"__metadata__"` | Names the reserved out-of-line store `__metadata__` the `IndexedDBDriver` stamps its `DriverMetadata` into. |
179
+ | `STREAM_BATCH_SIZE` | const | `500` | Holds the number of rows the `IndexedDBDriver` reads per batch when it streams. |
180
+ | `COUNT_LIMIT` | const | `4294967295` | Holds the largest count IndexedDB's `getAll`, `getAllKeys`, and cursor `advance` accept: the Web IDL `unsigned long` maximum, past which the engine refuses the call with a `TypeError`. |
181
+ | `mapIndexedDBError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy — the default mapping used everywhere except inside `migrate()`. |
182
+ | `mapMigrationError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy for use inside `migrate()` — the one context where `UPGRADE` means the migration itself failed, not a generic driver fault. |
183
+ | `deriveIndexedDBIndexName` | function | `(columns: readonly string[]) => string` | Derives an IndexedDB index name for a declared column group — a bare column name for a single-column index, a deterministic collision-free encoding for a compound one. |
184
+ | `schemaToStore` | function | `(schema: TableSchema) => StoreDefinition` | Projects a table schema into the IndexedDB wrapper's store definition. |
162
185
 
163
186
  ### Errors
164
187
 
@@ -181,35 +204,77 @@ whose every entry passes Contract's `isAuditFault` function.
181
204
  The portable semantics every backend shares — pure, total functions the
182
205
  driver never re-implements.
183
206
 
184
- | Name | Kind | Signature | Summary |
185
- | ---------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
186
- | `compareValues` | function | `(left: unknown, right: unknown) => number` | Compares two arbitrary values under one total order — the comparator behind sorting and the range operators. |
187
- | `matchesCondition` | function | `(row: Row, condition: Condition, scalars?: ReadonlySet<unknown>) => boolean` | Evaluates one `Condition` against a row — the per-operator predicate. |
188
- | `matchesQuery` | function | `(row: Row, conditions: readonly Condition[], scalars?: ReadonlyArray<ReadonlySet<unknown>>) => boolean` | Folds a row through a list of conditions, joining each by its connector. |
189
- | `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]` | Sorts rows by an ordering specification, leaving the input untouched. |
190
- | `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]` | Applies a `QueryInput` to rows — filter, then sort, then page. |
191
- | `validatePage` | function | `(input?: QueryInput) => void` | Validates the paging fields of a portable query. |
192
- | `computeAggregate` | function | `(rows: readonly unknown[], operation: AggregateOperation, column: FieldPath) => number \| undefined` | Computes an aggregate over a column across rows. |
193
- | `extractKey` | function | `(row: Row, column: string) => Key \| undefined` | Reads a row's primary key from a column, when it is a usable `Key`. |
194
- | `bindRowKey` | function | `(row: Row, primary: string, key: Key) => Row` | Returns a fresh row whose primary column is authoritatively bound to its storage key. |
195
- | `shapeToColumnSchema` | function | `(name: string, shape: ContractShape) => ColumnSchema` | Projects one contract shape into a portable column schema. |
196
- | `findColumn` | function | `(name: string, schema: TableSchema) => ColumnSchema \| undefined` | Reads one flat column's declaration out of a table schema. |
197
- | `resolvePrimary` | function | `(primary: PrimaryMap, name: string) => string` | Resolves the primary-key column one table keys its rows by. |
198
- | `requireColumns` | function | `(<T extends TableMap, K extends keyof T & string>(tables: T, name: K) => T[K]) & ((tables: TableMap, name: string) => ColumnMap)` | Requires one declared table's columns out of a table map. |
199
- | `shapeToColumnStorage` | function | `(shape: ContractShape) => ColumnStorage` | Maps a column's `ContractShape` to its portable `ColumnStorage` — the value a `TableSchema` carries so a native backend can declare a real column. |
200
- | `filterRows` | function | `(rows: readonly Row[], conditions: readonly Condition[]) => readonly Row[]` | Filters rows by a list of conditions — the shared basis for a table's count and aggregate paths (no sort/page, unlike `applyQuery`). |
201
- | `equalsValue` | function | `(left: unknown, right: unknown) => boolean` | Compares two values structurally by SameValueZero leaves — the comparator behind conformance checks and any test/fixture that needs "same data", not "same reference". |
202
- | `collectScalars` | function | `(values: readonly unknown[]) => ReadonlySet<unknown>` | Collects the scalar operands of a membership list into one set. |
203
- | `matchesListed` | function | `(value: unknown, values: readonly unknown[], scalars?: ReadonlySet<unknown>) => boolean` | Checks whether a value equals one operand of a membership list. |
204
- | `prepareScalars` | function | `(conditions: readonly Condition[]) => ReadonlyArray<ReadonlySet<unknown>>` | Collects one scalar set per condition, by position — the `scalars` argument of `matchesQuery`. |
205
- | `normalizeReadInput` | function | `(input: ReadInput) => ReadInput` | Drops each clause a read does not hold, so an absent clause is an absent key. |
206
- | `planRead` | function | `(storage: StorageInterface, table: string, input: ReadInput) => ReadPlan` | Asks a storage for its plan of a read, with the read normalized first. |
207
- | `streamPlannedRows` | function | `(storage: StorageInterface, table: string, native: ReadInput, residual: ReadInput, step?: () => Promise<void>) => AsyncIterable<Row>` | Streams the native side of a plan and applies residual conditions and a residual page, stopping at `offset + limit` matches — step 3 of the read procedure. |
207
+ | Name | Kind | Signature | Summary |
208
+ | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
209
+ | `compareValues` | function | `(left: unknown, right: unknown) => number` | Compares two arbitrary values under one total order — the comparator behind sorting and the range operators. |
210
+ | `matchesCondition` | function | `(row: Row, condition: Condition, scalars?: ReadonlySet<unknown>) => boolean` | Evaluates one `Condition` against a row — the per-operator predicate. |
211
+ | `matchesQuery` | function | `(row: Row, conditions: readonly Condition[], scalars?: ReadonlyArray<ReadonlySet<unknown>>) => boolean` | Folds a row through a list of conditions, joining each by its connector. |
212
+ | `extractOrderKeys` | function | `(row: Row, order: readonly Order[]) => readonly unknown[]` | Extracts the values an ordering specification compares from one row, one per term. |
213
+ | `compareOrderKeys` | function | `(left: readonly unknown[], right: readonly unknown[], order: readonly Order[]) => number` | Compares two rows' order keys under an ordering specification. |
214
+ | `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]` | Sorts rows by an ordering specification, leaving the input untouched. |
215
+ | `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]` | Applies a `QueryInput` to rows — filter, then sort, then page. |
216
+ | `validatePage` | function | `(input?: QueryInput) => void` | Validates the paging fields of a portable query. |
217
+ | `buildBatch` | function | `(keys: Key \| readonly Key[], rows: Row \| readonly Row[]) => ReadonlyArray<readonly [Key, Row]>` | Assembles the entries of a storage write from its keys and rows, one row per key. |
218
+ | `computeRemoved` | function | `(keys: readonly unknown[], existed: readonly boolean[]) => readonly boolean[]` | Computes what a batch delete reports per key: true for the first occurrence of a key that held a row, and false for a miss and for every repeat of a key. |
219
+ | `computeFirstIndexes` | function | `(keys: readonly unknown[]) => ReadonlyMap<unknown, number>` | Computes the position of each key's first occurrence in a batch. |
220
+ | `applyKeys` | function | `(keys: Key \| readonly Key[], operation: (keys: readonly Key[]) => Promise<readonly boolean[]>) => Promise<boolean \| readonly boolean[]>` | Applies a keyed operation that takes a key list to a single key or a key list, and answers in the form the call took. |
221
+ | `computeAggregate` | function | `(rows: readonly unknown[], operation: AggregateOperation, column: FieldPath) => number \| undefined` | Computes an aggregate over a column across rows. |
222
+ | `extractKey` | function | `(row: Row, column: string) => Key \| undefined` | Reads a row's primary key from a column, when it is a usable `Key`. |
223
+ | `bindRowKey` | function | `(row: Row, primary: string, key: Key) => Row` | Returns a fresh row whose primary column is authoritatively bound to its storage key. |
224
+ | `shapeToColumnSchema` | function | `(name: string, shape: ContractShape) => ColumnSchema` | Projects one contract shape into a portable column schema. |
225
+ | `findColumn` | function | `(name: string, schema: TableSchema) => ColumnSchema \| undefined` | Reads one flat column's declaration out of a table schema. |
226
+ | `resolvePrimary` | function | `(primary: PrimaryMap, name: string) => string` | Resolves the primary-key column one table keys its rows by. |
227
+ | `requireColumns` | function | `(<T extends TableMap, K extends keyof T & string>(tables: T, name: K) => T[K]) & ((tables: TableMap, name: string) => ColumnMap)` | Requires one declared table's columns out of a table map. |
228
+ | `shapeToColumnStorage` | function | `(shape: ContractShape) => ColumnStorage` | Maps a column's `ContractShape` to its portable `ColumnStorage` — the value a `TableSchema` carries so a native backend can declare a real column. |
229
+ | `filterRows` | function | `(rows: readonly Row[], conditions: readonly Condition[]) => readonly Row[]` | Filters rows by a list of conditions — the shared basis for a table's count and aggregate paths (no sort/page, unlike `applyQuery`). |
230
+ | `equalsValue` | function | `(left: unknown, right: unknown) => boolean` | Compares two values structurally by SameValueZero leaves — the comparator behind conformance checks and any test/fixture that needs "same data", not "same reference". |
231
+ | `collectScalars` | function | `(values: readonly unknown[]) => ReadonlySet<unknown>` | Collects the scalar operands of a membership list into one set. |
232
+ | `matchesListed` | function | `(value: unknown, values: readonly unknown[], scalars?: ReadonlySet<unknown>) => boolean` | Checks whether a value equals one operand of a membership list. |
233
+ | `prepareScalars` | function | `(conditions: readonly Condition[]) => ReadonlyArray<ReadonlySet<unknown>>` | Collects one scalar set per condition, by position — the `scalars` argument of `matchesQuery`. |
234
+ | `normalizeReadInput` | function | `(input: ReadInput) => ReadInput` | Drops each clause a read does not hold, so an absent clause is an absent key. |
235
+ | `planRead` | function | `(storage: StorageInterface, table: string, input: ReadInput) => ReadPlan` | Asks a storage for its plan of a read, with the read normalized first. |
236
+ | `streamPlannedRows` | function | `(storage: StorageInterface, table: string, native: ReadInput, residual: ReadInput, step?: () => Promise<void>) => AsyncIterable<Row>` | Streams the native side of a plan and applies residual conditions and a residual page, stopping at `offset + limit` matches — step 3 of the read procedure. |
208
237
 
209
238
  For `minimum` and `maximum`, `computeAggregate` compares each numeric value
210
239
  with a scalar `Math.min` or `Math.max` call. The helper never passes a
211
240
  row-sized argument list.
212
241
 
242
+ ### Query door
243
+
244
+ Every read of a table passes this door before any driver call: the shape-derived guard of
245
+ `queryInputContract`, then a pass over the table's columns; see [The query door](#the-query-door)
246
+ for each refusal.
247
+
248
+ | Name | Kind | Signature | Summary |
249
+ | -------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
250
+ | `queryInputShape` | const | `import("@orkestrel/contract").ObjectShape<{ conditions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["absent", "present"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["equals", "not", "above", "below", "from", "to"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["like", "glob", "starts", "ends"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["between"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>, import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; operator: import("@orkestrel/contract").LiteralShape<readonly ["any", "none"]>; values: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").RawShape>; connector: import("@orkestrel/contract").LiteralShape<readonly ["and", "or"]>; }, boolean \| import("@orkestrel/contract").ContractShape>]>>>; order: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ column: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>]>; direction: import("@orkestrel/contract").LiteralShape<readonly ["ascending", "descending"]>; }, boolean \| import("@orkestrel/contract").ContractShape>>>; limit: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; offset: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; }, false>` | Declares a portable read, `QueryInput`, as a closed contract shape. |
251
+ | `queryInputContract` | const | `ContractInterface<QueryInput>` | Holds the compiled contract of a portable read, which a table admits every read through. |
252
+ | `maskUndefinedOperands` | function | `(input: unknown) => unknown` | Copies a read so that each `undefined` operand of `equals`, `not`, `any`, and `none` reads `null`, the form `queryInputShape` declares. |
253
+ | `restoreUndefinedOperands` | function | `(masked: QueryInput, source: unknown) => QueryInput` | Puts back the operands of a read whose masked form `maskUndefinedOperands` built and the query contract admitted. |
254
+ | `matchesIllFormedText` | function | `(value: unknown) => boolean` | Checks whether a value is a string holding a lone surrogate, which has no UTF-8 form. |
255
+ | `extractColumnHead` | function | `(column: unknown) => string \| undefined` | Extracts the leading column a column reference names: a column name, or the first key of a non-empty list of keys. |
256
+ | `scanAggregateFaults` | function | `(aggregate: unknown, columns: ReadonlyMap<string, ColumnSchema>) => readonly AuditFault[]` | Finds the faults of an aggregate: an operation outside `AGGREGATE_OPERATIONS`, and a column that is no column reference or that the table does not hold. |
257
+ | `cloneQueryInput` | function | `(value: unknown) => unknown` | Copies a read a table is about to admit, so a change its caller makes after admission never reaches the read. |
258
+ | `cloneQueryPart` | function | `(value: unknown) => unknown` | Copies one condition or ordering term of a read, with its list of keys and its operand list, reading each member once. |
259
+ | `scanQueryFaults` | function | `(input: unknown, columns: ReadonlyMap<string, ColumnSchema>, refused?: readonly AuditFault[]) => readonly AuditFault[]` | Finds what a read asks of a table's columns that they do not hold — the schema facts a shape cannot state. |
260
+ | `scanConditionFaults` | function | `(condition: unknown, path: readonly string[], columns: ReadonlyMap<string, ColumnSchema>) => readonly AuditFault[]` | Finds what one condition asks of a table's columns that they do not hold, under the rules `scanQueryFaults` states. |
261
+ | `scanColumnFaults` | function | `(column: unknown, path: readonly string[], columns: ReadonlyMap<string, ColumnSchema>) => readonly AuditFault[]` | Finds the fault of a column reference: an undeclared leading column, or a nested path under a column that is not `json`. |
262
+ | `scanOperandFaults` | function | `(value: unknown, path: readonly string[], column: ColumnSchema \| undefined, nullish: boolean) => readonly AuditFault[]` | Finds the fault of one operand against its column's storage class. |
263
+ | `findIllFormedColumn` | function | `(row: Row, columns: ReadonlyMap<string, ColumnSchema>) => string \| undefined` | Finds the first `text` column of a row whose string is not well-formed UTF-16. |
264
+ | `collectColumns` | function | `(columns: ColumnMap) => ReadonlyMap<string, ColumnSchema>` | Collects a table's column map into each column's portable schema, by name, in declaration order. |
265
+
266
+ ### Recording
267
+
268
+ The rows-read instrument: a recorder wraps a real driver and counts the keys each storage call
269
+ addresses and the rows it returns or yields. A call log records calls; this counts rows too.
270
+
271
+ | Name | Kind | Signature | Summary |
272
+ | -------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
273
+ | `StorageRecorder` | class | `new (source: DriverInterface) => StorageRecorder` | Wraps a driver and records the keys each storage member addresses and the rows it returns or yields, inside a transaction scope too — the rows-read instrument of a native-first reading. |
274
+ | `RecordedStorage` | class | `new (source: StorageInterface, record: (member: StorageMember, keys: number, rows: StreamPage) => void) => StorageInterface` | Forwards each required member of a storage in the form it received and reports each call when it is invoked: the member, the keys it addresses, and a counter of the rows it returns or yields. |
275
+ | `tallyCalls` | function | `(calls: readonly StorageCall[], member: StorageMember) => StorageTally` | Totals the calls, addressed keys, and returned rows of one member across recorded calls. |
276
+ | `streamRecordedRows` | function | `(source: AsyncIterable<Row>, rows: StreamPageInterface) => AsyncIterable<Row>` | Yields a source's rows, counting each row on a counter as its consumer pulls it. |
277
+
213
278
  ### Abort
214
279
 
215
280
  | Name | Kind | Signature | Summary |
@@ -231,15 +296,16 @@ transform. Versioning drivers persist reconciliation metadata through the paired
231
296
 
232
297
  ### Conformance
233
298
 
234
- | Name | Kind | Signature | Summary |
235
- | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
236
- | `conformDriver` | function | `(factory: () => DriverInterface) => Promise<void>` | Runs the driver-conformance battery, throwing on the first violated invariant — the fail-fast entry point most callers (test setup, CI smoke checks) want. |
237
- | `scanDriver` | function | `(factory: () => DriverInterface) => AsyncIterable<ConformanceFinding>` | Walks the driver-conformance battery against a fresh `DriverInterface` per phase, yielding one `ConformanceFinding` per violated invariant — the shared invariant suite every backend (in-memory, SQLite, IndexedDB) must uphold to be a drop-in `DriverInterface`. |
238
- | `auditDriver` | function | `(factory: () => DriverInterface) => Promise<readonly ConformanceFinding[]>` | Runs the full driver-conformance battery and collects every violation — the audit entry point for a driver author who wants a complete report rather than a single fail-fast throw. |
239
- | `findPlanFaults` | function | `(input: ReadInput, plan: ReadPlan) => readonly string[]` | Lists the invariants a `ReadPlan` breaks for the read it splits. |
240
- | `readPlannedRows` | function | `(storage: StorageInterface, table: string, input: QueryInput, step?: () => Promise<void>) => Promise<readonly Row[]>` | Reads the rows of a read through a storage's plan — the read procedure `Table.records` runs and the conformance differential checks. |
241
- | `readPlannedAggregate` | function | `(storage: StorageInterface, table: string, input: QueryInput, aggregate: Aggregate, step?: () => Promise<void>) => Promise<number \| undefined>` | Computes an aggregate read through a storage's plan — the read procedure `Table.count` and `Table.aggregate` run and the conformance differential checks. |
242
- | `scanPlans` | function | `(storage: StorageInterface, check: string) => AsyncIterable<ConformanceFinding>` | Compares a storage's planned answer to every conformance read against the core engine's answer over its `scan`, and checks each plan's invariants. |
299
+ | Name | Kind | Signature | Summary |
300
+ | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
301
+ | `conformDriver` | function | `(factory: () => DriverInterface) => Promise<void>` | Runs the driver-conformance battery, throwing on the first violated invariant — the fail-fast entry point most callers (test setup, CI smoke checks) want. |
302
+ | `scanDriver` | function | `(factory: () => DriverInterface) => AsyncIterable<ConformanceFinding>` | Walks the driver-conformance battery against a fresh `DriverInterface` per phase, yielding one `ConformanceFinding` per violated invariant — the shared invariant suite every backend (in-memory, SQLite, IndexedDB) must uphold to be a drop-in `DriverInterface`. |
303
+ | `buildFailureFinding` | function | `(check: string, error: unknown) => ConformanceFinding` | Builds the finding a conformance phase yields when it throws, naming the phase. |
304
+ | `auditDriver` | function | `(factory: () => DriverInterface) => Promise<readonly ConformanceFinding[]>` | Runs the full driver-conformance battery and collects every violation — the audit entry point for a driver author who wants a complete report rather than a single fail-fast throw. |
305
+ | `findPlanFaults` | function | `(input: ReadInput, plan: ReadPlan) => readonly string[]` | Lists the invariants a `ReadPlan` breaks for the read it splits. |
306
+ | `readPlannedRows` | function | `(storage: StorageInterface, table: string, input: QueryInput, step?: () => Promise<void>, accept?: (row: Row) => boolean) => Promise<readonly Row[]>` | Reads the rows of a read through a storage's plan — the read procedure `Table.records` runs and the conformance differential checks. |
307
+ | `readPlannedAggregate` | function | `(storage: StorageInterface, table: string, input: QueryInput, aggregate: Aggregate, step?: () => Promise<void>) => Promise<number \| undefined>` | Computes an aggregate read through a storage's plan — the read procedure `Table.count` and `Table.aggregate` run and the conformance differential checks. |
308
+ | `scanPlans` | function | `(storage: StorageInterface, check: string) => AsyncIterable<ConformanceFinding>` | Compares a storage's planned answer to every conformance read against the core engine's answer over its `scan`, and checks each plan's invariants. |
243
309
 
244
310
  ### Helpers & guards
245
311
 
@@ -261,6 +327,8 @@ Pure helpers behind the query engine's pattern matching.
261
327
  | `isMigration` | function | `(value: unknown) => value is Migration` | Checks whether a value is an ordered migration plan. |
262
328
  | `isMigrationInput` | function | `(value: unknown) => value is MigrationInput` | Checks whether a value is one atomic migration request. |
263
329
  | `isKey` | function | `(value: unknown) => value is Key` | Checks whether a value is a usable database key. |
330
+ | `isAggregate` | function | `(value: unknown) => value is Aggregate` | Checks whether a value is an `Aggregate`: one of `AGGREGATE_OPERATIONS` over a column name or a non-empty list of keys. |
331
+ | `isAggregateOperation` | const | `Guard<AggregateOperation>` | Checks whether a value is one of `AGGREGATE_OPERATIONS`. |
264
332
  | `isScalar` | function | `(value: unknown) => value is Scalar` | Checks whether a value is a scalar: not an object and not a function. |
265
333
  | `cloneDriverSchema` | function | `(value: unknown) => readonly TableSchema[]` | Clones unknown driver schema into a distinct deeply frozen snapshot. |
266
334
  | `cloneMigrationInput` | function | `(value: unknown) => MigrationInput` | Clones unknown migration input into a distinct deeply frozen snapshot. |
@@ -268,15 +336,18 @@ Pure helpers behind the query engine's pattern matching.
268
336
 
269
337
  ### Constants
270
338
 
271
- | Name | Kind | Signature | Summary |
272
- | -------------------------- | ----- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
273
- | `DEFAULT_PRIMARY` | const | `"id"` | Supplies the primary-key column, `'id'`, assumed when `PrimaryMap` does not name one. |
274
- | `MAX_PATTERN_LENGTH` | const | `1024` | Sets the longest `LIKE` / `GLOB` pattern the wildcard matcher accepts, 1024 characters, before rejecting it. |
275
- | `CONFORMANCE_USERS_SCHEMA` | const | `TableSchema` | Describes the `users` table the driver-conformance battery opens — keyed by the default `id` primary column. |
276
- | `CONFORMANCE_POSTS_SCHEMA` | const | `TableSchema` | Describes the `posts` table the driver-conformance battery opens — keyed by a non-`id` `slug` primary column. |
277
- | `CONFORMANCE_SCHEMA` | const | `readonly TableSchema[]` | Holds the fixed `users` and `posts` schema every driver-conformance phase opens. |
278
- | `CONFORMANCE_ROWS` | const | `readonly Row[]` | Holds the `users` rows the conformance differential seeds: ties, an absent `age`, ASCII and non-ASCII case variants, a supplementary-plane character, an empty name, and a `[`. |
279
- | `CONFORMANCE_READS` | const | `readonly ReadInput[]` | Holds the reads the conformance differential runs over `CONFORMANCE_ROWS`: every operator on a required text column and an optional integer column, `null` operands, `or` folds, a nested path, orders with ties, a page, and every aggregate. |
339
+ | Name | Kind | Signature | Summary |
340
+ | -------------------------- | ----- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
341
+ | `DEFAULT_PRIMARY` | const | `"id"` | Supplies the primary-key column, `'id'`, assumed when `PrimaryMap` does not name one. |
342
+ | `NULLISH_OPERATORS` | const | `readonly ConditionOperator[]` | Lists the operators whose operand can be `null` on a nullable column and `undefined` on an optional one: `equals`, `not`, `any`, and `none`. |
343
+ | `AGGREGATE_OPERATIONS` | const | `readonly AggregateOperation[]` | Lists the aggregates a read can compute: `count`, `sum`, `average`, `minimum`, and `maximum`. |
344
+ | `PATTERN_OPERATORS` | const | `readonly ConditionOperator[]` | Lists the operators that match a string pattern, which read a `text` or `json` column: `like`, `glob`, `starts`, and `ends`. |
345
+ | `MAX_PATTERN_LENGTH` | const | `1024` | Sets the longest `LIKE` / `GLOB` pattern the wildcard matcher accepts, 1024 characters, before rejecting it. |
346
+ | `CONFORMANCE_USERS_SCHEMA` | const | `TableSchema` | Describes the `users` table the driver-conformance battery opens — keyed by the default `id` primary column. |
347
+ | `CONFORMANCE_POSTS_SCHEMA` | const | `TableSchema` | Describes the `posts` table the driver-conformance battery opens — keyed by a non-`id` `slug` primary column. |
348
+ | `CONFORMANCE_SCHEMA` | const | `readonly TableSchema[]` | Holds the fixed `users` and `posts` schema every driver-conformance phase opens. |
349
+ | `CONFORMANCE_ROWS` | const | `readonly Row[]` | Holds the `users` rows the conformance differential seeds: ties, an absent `age`, ASCII and non-ASCII case variants, a supplementary-plane character, an empty name, and a `[`. |
350
+ | `CONFORMANCE_READS` | const | `readonly ReadInput[]` | Holds the reads the conformance differential runs over `CONFORMANCE_ROWS`: every operator on a required text column and an optional integer column, `null` operands, `or` folds, a nested path, orders with ties, a page, and every aggregate. |
280
351
 
281
352
  ### Types
282
353
 
@@ -316,13 +387,23 @@ Pure helpers behind the query engine's pattern matching.
316
387
  | `MigrationInput` | interface | `{ plan, metadata? }` | Represents one atomic migration request. |
317
388
  | `StorageInterface` | interface | `{ read(), write(), insert(), delete(), keys(), scan(), clear(), plan?(), records?(), aggregate?(), stream?(), migrate?(), metadata?(), stamp?() }` | Declares the storage operations available only inside a driver's transaction scope. |
318
389
  | `DriverMetadata` | interface | `{ version, schema }` | Represents persisted schema metadata a versioning driver owns as an immutable snapshot. |
319
- | `DriverInterface` | interface | `{ open(), close(), snapshot(), transaction?() }` | Declares the storage contract a backend implements: its engine's native operations first, and the core's engine only for the residual its plan returns. |
390
+ | `DriverInterface` | interface | `{ open(), close(), transaction?() }` | Declares the storage contract a backend implements: its engine's native operations first, and the core's engine only for the residual its plan returns. |
391
+ | `StorageMember` | type | `'read' \| 'write' \| 'insert' \| 'delete' \| 'keys' \| 'scan' \| 'clear' \| 'plan' \| 'records' \| 'stream' \| 'aggregate'` | Names a `StorageInterface` member a `StorageRecorder` observes. |
392
+ | `StorageCall` | interface | `{ member, keys, rows, scoped }` | Represents one storage call a `StorageRecorder` observed: the member, the keys it addressed, the rows it returned or yielded, and whether a transaction scope made it. |
393
+ | `StorageTally` | interface | `{ calls, keys, rows }` | Represents the calls, addressed keys, and returned rows of one member across recorded calls. |
394
+ | `StorageResult` | interface | `{ value, calls }` | Represents one measured operation's value and the storage calls it made. |
395
+ | `StreamPageInterface` | interface | `{ count, next() }` | Represents the matching-row position of one streaming page: `next` advances past one matching row and `count` reads the rows past the page's offset. |
396
+ | `StorageJournalInterface` | interface | `{ restore() }` | Records the prior row of each key a scope writes or deletes, on its first touch, and restores those keys on request. |
320
397
  | `DatabaseOptions` | interface | `{ on?, error?, driver, tables, primary?, indexes?, name?, generator?, version? }` | Options for `createDatabase`. |
321
398
  | `CompiledSQL` | interface | `{ sql, parameters }` | Represents a parameterized SQL fragment or statement plus its bind values. The `@orkestrel/database/server` entry point exports this type. |
322
399
  | `SQLiteDriverOptions` | interface | `{ path, readonly?, timeout?, references?, pragmas? }` | Configures `createSQLiteDriver`. The `@orkestrel/database/server` entry point exports this type. |
323
- | `AccessPlan` | interface | `{ index?, range? }` | Represents the key-range read behind a plan's native side — an optional index and an optional `IDBKeyRange`. An omitted `index` selects the primary store; an omitted `range` reads the whole store, so `{}` is a whole-store read. The `@orkestrel/database/browser` entry point exports this type. |
400
+ | `SQLiteDriverInterface` | interface | `{ pragma() }` | Represents the SQLite driver: the storage contract plus a read of one connection pragma. |
401
+ | `AccessPlan` | interface | `{ conditions, columns, prefix, index?, range?, keys? }` | Represents the one access path an IndexedDB read takes: the conditions it answers, the primary store or the index it reads, and the key range or key list it reads there. |
402
+ | `AccessBatch` | interface | `{ rows, position? }` | Represents one batch a stream reads in one transaction: its rows, and the position of its final entry, which the next batch reads past. |
403
+ | `AccessPosition` | interface | `{ key, primary }` | Represents the position of one entry in an access path: its key in the path's source and its primary key, which are the same key on the primary store. |
324
404
  | `TableDefinition` | interface | `{ primary, columns, schema }` | Represents one table's portable definition, produced by `export` — the unit of schema / migration exchange across environments. |
325
405
  | `DatabaseStorageInterface` | interface | `{ table() }` | Represents a table-only database view. |
406
+ | `DatabaseTableOptions` | interface | `{ on?, error? }` | Options for one table handle that `table` returns. |
326
407
  | `DatabaseInterface` | interface | `{ emitter, name, status, import(), export(), open(), close(), transaction(), migrate() }` | Represents a database — the ergonomic entry point that owns the driver and its tables. |
327
408
  | `TableInterface` | interface | `{ emitter, name, primary, contract, get(), resolve(), has(), keys(), records(), count(), aggregate(), scan(), set(), add(), update(), remove(), clear(), query(), cursor() }` | Exposes typed keyed CRUD plus fluent query and cursor access. |
328
409
  | `QueryInterface` | interface | `{ condition(), order(), filter(), limit(), offset(), collect(), find(), count(), stream(), aggregate() }` | Builds a read through a fluent chain. |
@@ -387,46 +468,108 @@ method below runs inside that scope, and each carries the same contract its
387
468
  `StorageInterface` and `DriverInterface` tables share one description per
388
469
  method.
389
470
 
390
- | Method | Returns | Summary |
391
- | ----------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
392
- | `read` | `Promise<Row \| undefined>` | Reads one row by key. |
393
- | `write` | `Promise<void>` | Writes one row at a key. |
394
- | `insert` | `Promise<void>` | Inserts one row atomically, rejecting `CONFLICT` when its key already exists. |
395
- | `delete` | `Promise<boolean>` | Deletes one row by key. |
396
- | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
397
- | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
398
- | `clear` | `Promise<void>` | Empties a table. |
399
- | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
400
- | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
401
- | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
402
- | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
403
- | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
404
- | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
405
- | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
471
+ | Method | Returns | Summary |
472
+ | ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
473
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
474
+ | `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
475
+ | `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
476
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
477
+ | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
478
+ | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
479
+ | `clear` | `Promise<void>` | Empties a table. |
480
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
481
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
482
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
483
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
484
+ | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
485
+ | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
486
+ | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
406
487
 
407
488
  #### `DriverInterface`
408
489
 
409
- The complete backend extends `StorageInterface` with lifecycle, the
410
- snapshot floor, and an optional native transaction callback. The inherited
490
+ The complete backend extends `StorageInterface` with lifecycle and an optional native
491
+ transaction callback. The inherited
411
492
  storage/query/migration/metadata methods carry the same contract they carry on
412
493
  `StorageInterface`, addressed against the whole backend rather than one
413
494
  transaction scope. `open` receives the derived `TableSchema` list: a native
414
495
  backend builds real tables and indexes from it, a scan-only backend reads
415
- `name` alone. `snapshot` with no `tables` captures the whole store, while a
416
- list scopes capture and restore to those tables. A driver without `plan` answers
417
- nothing natively — the core runs the whole read over `scan` — and a driver without
418
- `transaction` runs a scope on the snapshot floor (see
419
- [Native transactions](#native-transactions)).
496
+ `name` alone. Each keyed member takes one key, or a list that one call applies whole: a
497
+ list `write` or `insert` pairs `keys[i]` with `rows[i]` and applies every row or none, and
498
+ a list `delete` reports, per key, whether the call removed its row: it is the storage contract,
499
+ not a manager verb, and `Table.remove` emits `remove` for each removed key before it folds the
500
+ list into one answer. A driver without
501
+ `plan` answers nothing natively — the core runs the whole read over `scan` — and a driver
502
+ without `transaction` runs a scope on the core's journal (see
503
+ [Transactions](#transactions)).
504
+
505
+ | Method | Returns | Summary |
506
+ | ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
507
+ | `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
508
+ | `close` | `Promise<void>` | Releases the backend. |
509
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
510
+ | `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
511
+ | `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
512
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
513
+ | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
514
+ | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
515
+ | `clear` | `Promise<void>` | Empties a table. |
516
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
517
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
518
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
519
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
520
+ | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
521
+ | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
522
+ | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
523
+ | `transaction` | `Promise<R>` | Opens a native transaction scope — an optional driver hook. The driver owns acquisition, commit or rollback, release, and invalidation of the scoped capability. |
524
+
525
+ #### `StorageJournalInterface`
526
+
527
+ `StorageJournalInterface` extends `StorageInterface`. Each inherited member forwards to the
528
+ storage the journal wraps, and a write, insert, delete, or clear first records the prior rows
529
+ it would change.
530
+
531
+ | Method | Returns | Summary |
532
+ | ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
533
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
534
+ | `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
535
+ | `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
536
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
537
+ | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
538
+ | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
539
+ | `clear` | `Promise<void>` | Empties a table. |
540
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
541
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
542
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
543
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
544
+ | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
545
+ | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
546
+ | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
547
+ | `restore` | `Promise<void>` | Restores every key and table the journal recorded to its prior rows. |
548
+
549
+ #### `StreamPageInterface`
550
+
551
+ The matching-row position of one streaming page; its `count` data member stays in the Surface
552
+ row.
553
+
554
+ | Method | Returns | Summary |
555
+ | ------ | --------- | ------------------------------- |
556
+ | `next` | `boolean` | Advances past one matching row. |
557
+
558
+ #### `SQLiteDriverInterface`
559
+
560
+ `SQLiteDriverInterface` extends `DriverInterface`, and `createSQLiteDriver` returns it. Each
561
+ inherited member carries its `DriverInterface` contract. `pragma` is a root member: the scoped
562
+ capability a transaction passes does not declare it, and a call while a transaction is active
563
+ raises `CONFLICT`.
420
564
 
421
565
  | Method | Returns | Summary |
422
566
  | ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
423
567
  | `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
424
568
  | `close` | `Promise<void>` | Releases the backend. |
425
- | `snapshot` | `Promise<() => Promise<void>>` | Captures table rows and returns a repeatable thunk that restores those rows — the primitive transactions are built on. |
426
- | `read` | `Promise<Row \| undefined>` | Reads one row by key. |
427
- | `write` | `Promise<void>` | Writes one row at a key. |
428
- | `insert` | `Promise<void>` | Inserts one row atomically, rejecting `CONFLICT` when its key already exists. |
429
- | `delete` | `Promise<boolean>` | Deletes one row by key. |
569
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
570
+ | `write` | `Promise<void>` | Writes one row at a key, or each listed row at the key of the same position, applying every row or none. |
571
+ | `insert` | `Promise<void>` | Inserts one row at a key, or each listed row at the key of the same position, rejecting `CONFLICT` with no row applied when a key already exists. |
572
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
430
573
  | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
431
574
  | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
432
575
  | `clear` | `Promise<void>` | Empties a table. |
@@ -438,6 +581,7 @@ nothing natively — the core runs the whole read over `scan` — and a driver w
438
581
  | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
439
582
  | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
440
583
  | `transaction` | `Promise<R>` | Opens a native transaction scope — an optional driver hook. The driver owns acquisition, commit or rollback, release, and invalidation of the scoped capability. |
584
+ | `pragma` | `SQLiteValue \| undefined` | Runs `PRAGMA name` with no value and returns the first value the engine answers. |
441
585
 
442
586
  #### `DatabaseInterface`
443
587
 
@@ -468,6 +612,11 @@ for work started after the transaction settles.
468
612
  | ------- | ----------------------------- | ---------------------------------------------- |
469
613
  | `table` | `TableInterface<RowOf<T[K]>>` | Returns the typed handle for a declared table. |
470
614
 
615
+ `table(name, options)` takes `DatabaseTableOptions`: `on` registers initial `TableEventMap` listeners
616
+ on the handle's emitter, and `error` routes their throws instead of the database's `error` option.
617
+ A handle has no lifecycle verb: its emitter ends with the handle, and after the database closes
618
+ no operation runs, so no handle emits.
619
+
471
620
  #### `AdmissionInterface`
472
621
 
473
622
  The admission boundary the root database context and a transaction scope both
@@ -486,8 +635,9 @@ it raises `DRIVER` with `table`, `key`, and the contract's `faults`. `count()` i
486
635
  `aggregate('count')`, which reads the stored set `records()` reads while ignoring paging,
487
636
  so the two agree. `records`,
488
637
  `count`, `aggregate`, `scan`, `set`, `add`, `update`, and `remove` each take an
489
- optional `OperationOptions`: its `signal` reaches every backend commit point,
490
- and an aborted batch keeps the items already committed.
638
+ optional `OperationOptions`: its `signal` reaches every backend commit point. A list form
639
+ is one driver call that admits every row first and applies every row or none; `update`
640
+ of a list is one list `read` and one list `write`.
491
641
 
492
642
  | Method | Returns | Summary |
493
643
  | ----------- | ------------------------------------ | ----------------------------------------------------------------------------------------- |
@@ -502,7 +652,7 @@ and an aborted batch keeps the items already committed.
502
652
  | `set` | `Promise<Key>` (or array) | Upserts one or more rows. |
503
653
  | `add` | `Promise<Key>` (or array) | Inserts one or more rows, throwing `CONFLICT` on a duplicate key. |
504
654
  | `update` | `Promise<boolean>` (or array) | Applies a partial change to one or more rows. |
505
- | `remove` | `Promise<boolean>` (or array) | Deletes one or more rows. |
655
+ | `remove` | `Promise<boolean>` | Deletes one or more rows. |
506
656
  | `clear` | `Promise<void>` | Empties the table. |
507
657
  | `query` | `QueryInterface<T>` | Opens a fluent query builder over the table. |
508
658
  | `cursor` | `Promise<CursorInterface<T>>` | Opens a forward row cursor for bulk mutation. |
@@ -550,19 +700,20 @@ These invariants hold across the core database source tree ↔ this guide:
550
700
  an entry barrel remain internal.
551
701
  2. **A table is a contract.** Every write is admitted whole through the
552
702
  table's compiled contract — `set` / `add` / `update` run the row through
553
- Contract's `admitValue`, which admits a lossless repair such as `'36'` to
554
- `36` for a number column and enforces constraints such as `min` /
555
- `pattern`. A row that carries an undeclared top-level column, omits a
556
- required column, or needs a lossy repair such as `'036'` to `36` throws
557
- `VALIDATION`; the table never removes a column to admit the rest. A
703
+ Contract's `admitValue`, which enforces types and constraints such as
704
+ `min` / `pattern` and repairs nothing. A row that carries an undeclared
705
+ top-level column, omits a required column, or holds a mistyped value such
706
+ as `'36'` for an integer column throws `VALIDATION`; the table never
707
+ removes a column to admit the rest. A caller that wants a lossless repair
708
+ runs `repairValue(table.contract, row)` before the write. A
558
709
  `rawShape` column admits any defined value, so the nested keys of a JSON
559
710
  column never refuse. Reads are narrowed back to the table's row type
560
711
  through the guard — never an `as` (see `AGENTS.md` § Non-negotiable
561
712
  rules). The row type is the shape's `Infer`, so a `tables` map types every
562
713
  table from one declaration. A refusal's context carries `table` and
563
714
  `faults`, the `AuditFault` list `admitValue` returned, and its message
564
- names the table and the first fault through Contract's `describeFaultLine`
565
- function. A fault's `received` member and the message carry Contract's
715
+ names the table and every fault through Contract's `describeFaults`
716
+ function, bounded by `FAULT_TEXT_LIMIT`. A fault's `received` member and the message carry Contract's
566
717
  JSON-encoded, length-capped rendering of the received value; the rejected
567
718
  row and the parser cause never enter the message, context, serialized
568
719
  error, or table events.
@@ -575,33 +726,35 @@ These invariants hold across the core database source tree ↔ this guide:
575
726
  backend can build real tables and indexes; a scan-only backend reads only `name`. A
576
727
  driver declares its native coverage per read through `plan`, which returns a `ReadPlan`;
577
728
  `Table` calls `records`, `stream`, and `aggregate` with `plan.native` only, and runs the
578
- residual through `applyQuery`, `matchesQuery`, `sortRows`, and `computeAggregate`. A read
729
+ residual through `matchesQuery`, `compareOrderKeys`, and `sortRows`, folding a residual
730
+ aggregate as its rows stream. A read
579
731
  is wholly native when `residual` equals `{}`. `scanDriver` checks every plan's invariants,
580
732
  the transaction capability's mirror of the native members, and a differential of each
581
733
  planned driver against the core engine over `scan`. The following table rules where
582
734
  each clause runs in this release:
583
735
 
584
- | Clause | `SQLiteDriver` | `IndexedDBDriver` | `MemoryDriver`, `JSONDriver` |
585
- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- |
586
- | Every operator on a flat `text`, `integer`, `real`, or `boolean` column | Native under every flag combination, with the null forms chosen from the column's flags; `starts` is an index range and `any` / `none` bind one `json_each` parameter | The first `and`-joined `equals`, `above`, `from`, or `between` over an index, or a comparison over the primary key | Residual over `scan` |
587
- | A nested path; a `json` or `blob` column | Residual | Residual | Residual over `scan` |
588
- | An `or` fold | Native when every condition is; otherwise wholly residual | Residual | Residual over `scan` |
589
- | Order | Native on a flat column that is not both optional and nullable | Residual | Residual over `scan` |
590
- | Page | `LIMIT` and `OFFSET` when the residual holds no condition and no order | Residual, stopping the stream at `offset + limit` matches | Residual over `scan` |
591
- | `count` | `COUNT(*)` when the residual holds no condition | Residual | Residual over `scan` |
592
- | `sum`, `average`, `minimum`, `maximum` | Native on an `integer` or `real` column that is not both optional and nullable | Residual | Residual over `scan` |
593
- | Transaction | `BEGIN` / `COMMIT` / `ROLLBACK`; the scoped capability declares `plan`, `records`, `stream`, and `aggregate` | The snapshot floor | `JSONDriver`: native; `MemoryDriver`: the snapshot floor |
736
+ | Clause | `SQLiteDriver` | `IndexedDBDriver` | `MemoryDriver`, `JSONDriver` |
737
+ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
738
+ | Every operator on a flat `text`, `integer`, `real`, or `boolean` column | Native under every flag combination, with the null forms chosen from the column's flags; `starts` is an index range and `any` / `none` bind one `json_each` parameter | One access path when every connector is `and`, ranked by rule: primary-key `equals` or `any`; a compound index matched on two or more columns; a single-column index with `equals` or `any`, or a compound index whose leading column alone an `equals` binds; then a range or `starts` on the primary key or an index. `below` and `to` read an index only on a required column. The other conditions are residual | Residual over `scan` |
739
+ | A nested path; a `json` or `blob` column | A prefilter for `equals`, `not`, `any`, and `none` with scalar operands on a nested path under a `json` head, which the core rechecks; residual otherwise | Residual | Residual over `scan` |
740
+ | An `or` fold | Native when every condition is; otherwise wholly residual | Residual | Residual over `scan` |
741
+ | Order | Native on a flat column; a column that is both optional and nullable sorts behind a rank of absence, `null`, then its values | Native on the primary key, on a point of an index, and on the access path's index when the order is its unbound required columns in one direction; otherwise residual | Residual over `scan` |
742
+ | Page | `LIMIT` and `OFFSET` when the residual holds no condition and no order | `records(range, limit)`, or a cursor with `advance(offset)`, when the residual holds no condition and no order; otherwise residual, stopping the stream at `offset + limit` matches | Residual over `scan` |
743
+ | `count` | `COUNT(*)` when the residual holds no condition | `count(range)`, a sum of counts for `any`, when the residual holds no condition | Residual over `scan` |
744
+ | `sum`, `average`, `minimum`, `maximum` | Native on an `integer` or `real` column that is not both optional and nullable; `sum` is `TOTAL`, `NULL` over no value | `minimum` and `maximum`: the first entry of the column's index on a required `integer` or `real` column, when the residual holds no condition; `sum` and `average`: residual | Residual over `scan` |
745
+ | Transaction | `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`; the scoped capability declares `plan`, `records`, `stream`, and `aggregate` | The core's before-image journal | `JSONDriver`: native; `MemoryDriver`: the core's before-image journal |
594
746
 
595
747
  The rule fixes these semantics on every driver: text order and text ranges are the
596
748
  engine's binary order, so SQLite orders by code point where the core orders by UTF-16
597
749
  code unit, and the two differ only between a supplementary-plane character and one in
598
750
  U+E000 to U+FFFF; `like` folds ASCII letters only, and `_` and `?` match one code point;
599
751
  ties resolve by primary key in the direction of the final order term; `sum` and
600
- `average` on a numeric column are the engine's arithmetic. Every write is admitted
752
+ `average` on a numeric column are the engine's arithmetic, and SQLite's `sum` is its
753
+ floating-point `TOTAL`, which an integer sum past 2^53 reads as without raising. Every write is admitted
601
754
  through the contract, so every stored row conforms; a returned stored row that fails the
602
755
  contract raises `DRIVER`, and SQLite raises `DRIVER` for a stored value that does not
603
- match its column's declaration. `MemoryDriver` still lacks a native `transaction?`, so its
604
- transactions always use the snapshot floor; `JSONDriver` does implement
756
+ match its column's declaration. `MemoryDriver` lacks a native `transaction?`, so the
757
+ core's journal carries its transactions; `JSONDriver` does implement
605
758
  `transaction?` — it clones the committed memory/schema/metadata into an
606
759
  isolated candidate, passes only that candidate's capability to the callback,
607
760
  and publishes it with one atomic file replacement only when the callback
@@ -614,7 +767,7 @@ These invariants hold across the core database source tree ↔ this guide:
614
767
  exactly once, and terminalizes the iterator; the transaction and driver
615
768
  remain usable. Memory and IndexedDB need no equivalent root wrapper because
616
769
  neither exposes a callback transaction. `Database.transaction` over a `JSONDriver`
617
- therefore prefers this native path over the snapshot floor. Both reference drivers also
770
+ therefore prefers this native path over the journal. Both reference drivers also
618
771
  implement the paired `metadata?` / `stamp?` — `MemoryDriver` in-process only
619
772
  (the owned `DriverMetadata` snapshot lives in instance memory), `JSONDriver` persisted:
620
773
  the file is `{ metadata?: DriverMetadata, tables }`, with `metadata` present only
@@ -635,18 +788,18 @@ These invariants hold across the core database source tree ↔ this guide:
635
788
  `DatabaseError('DRIVER', 'Stored SQLite table is missing')` before any DDL in its
636
789
  open transaction, and IndexedDB throws
637
790
  `DatabaseError('DRIVER', 'Stored IndexedDB store is missing')` before its final
638
- open. Extra physical objects remain allowed, and SQLite may reconstruct a
639
- missing declared index because the table and its records still exist. IndexedDB
791
+ open. Extra tables and stores remain allowed, apart from an IndexedDB index the deployed
792
+ schema does not declare, which open drops; SQLite may reconstruct a missing declared index
793
+ because the table and its records still exist, and a writable SQLite open also drops each
794
+ created index of a deployed table that the deployed schema no longer declares. IndexedDB
640
795
  captures the bootstrap connection's exact stores and version in the same
641
- lifetime, then pins the persisted final open to that version; a concurrent
642
- versionchange makes the stale open reject instead of silently bumping and
643
- recreating storage. Existing unreadable, malformed, structurally incompatible,
796
+ lifetime, then pins the persisted final open to that version, or to the next one when
797
+ it drops an undeclared index; a concurrent versionchange makes the stale open reject
798
+ instead of silently bumping and recreating storage. Existing unreadable, malformed, structurally incompatible,
644
799
  or physically incomplete state throws `DRIVER` without publishing a handle or
645
800
  attempting table/store repair; after external repair, the same driver instance
646
801
  may retry `open`.
647
- `IndexedDBDriver.snapshot()` captures every store in one read transaction,
648
- so the capture is point-in-time consistent across stores even under
649
- concurrent writers; `restore` was already atomic. `SQLiteDriver` and
802
+ `SQLiteDriver` and
650
803
  `IndexedDBDriver` each implement `migrate?` natively and treat `MigrationInput` as one commit unit:
651
804
  `SQLiteDriver` applies schema, rows, and optional metadata inside one native
652
805
  SQLite transaction (`stepToSQL` projects each step's DDL), while a migration
@@ -662,9 +815,9 @@ These invariants hold across the core database source tree ↔ this guide:
662
815
  nothing is rewritten. Both implement the paired `metadata?` /
663
816
  `stamp?` into a reserved store name a user table must avoid:
664
817
  `SQLiteDriver` uses a single-row `_metadata` table (`METADATA_TABLE`), and
665
- `IndexedDBDriver` uses an out-of-line `__metadata__` store (`METADATA_STORE`), both
666
- excluded from a whole-store `snapshot`. `SQLiteDriver` implements
667
- `transaction?` as a callback-scoped real `BEGIN` / `COMMIT` / `ROLLBACK`;
818
+ `IndexedDBDriver` uses an out-of-line `__metadata__` store (`METADATA_STORE`), which no
819
+ table reaches. `SQLiteDriver` implements
820
+ `transaction?` as a callback-scoped real `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`;
668
821
  the capability performs reads, writes, migration, and metadata work inside
669
822
  that one native transaction, then becomes invalid. `IndexedDBDriver`
670
823
  deliberately omits `transaction?`: an `IDBTransaction` can auto-commit when
@@ -674,7 +827,8 @@ These invariants hold across the core database source tree ↔ this guide:
674
827
 
675
828
  4. **Total query helpers; the equality family is structural, not ranked.**
676
829
  `compareValues`, `matchesCondition`, and `matchesQuery` never throw — a
677
- type mismatch is a non-match and the comparator is a total order (it
830
+ type mismatch is a non-match there, which invariant 15 keeps from any read of a table,
831
+ and the comparator is a total order (it
678
832
  never returns `NaN`), mirroring the contracts guards' totality (see
679
833
  `.claude/rules/patterns.md` § Validation and contracts). The range
680
834
  operators (`above` / `below` / `from` / `to` /
@@ -704,9 +858,10 @@ These invariants hold across the core database source tree ↔ this guide:
704
858
  tables, queries, cursors, and streams also throw `CONFLICT` after settlement.
705
859
  When the driver implements `transaction?(scope)`, the driver owns
706
860
  acquisition, commit on fulfillment, rollback on rejection, release, and
707
- invalidation. Otherwise the universal single-writer floor snapshots the
708
- whole store, runs the same scoped callback, and restores the snapshot on
709
- rejection. Either path emits the identical `transaction` / `commit`
861
+ invalidation. Otherwise the core's before-image journal records the prior row of each
862
+ key the scope writes or deletes, on its first touch, and restores those keys on
863
+ rejection; a `clear` journals its table alone, and reads go to the driver, so a native
864
+ read sees the scope's writes. It gives rollback on rejection and no crash atomicity. Either path emits the identical `transaction` / `commit`
710
865
  lifecycle; `rollback(error)` is emitted only when rollback completed and the
711
866
  original scope/drain error remains the propagated rejection, never when
712
867
  cleanup itself replaced that error.
@@ -728,7 +883,14 @@ These invariants hold across the core database source tree ↔ this guide:
728
883
  restores, and the original transaction error still propagates (proven by
729
884
  the emit-safety tests). Reads / queries / counts are not emitted (a
730
885
  reader does not mutate, and those paths are too hot). The observation
731
- lives in the core layer; the drivers stay storage primitives.
886
+ lives in the core layer; the drivers stay storage primitives. `close`
887
+ destroys the database emitter last, after its `close` event and even when
888
+ the driver refuses to close, so a listener registered before `close`
889
+ receives nothing after it. `table(name, options)` takes `DatabaseTableOptions`:
890
+ `on` registers initial listeners on that handle's emitter, and `error`
891
+ routes their throws instead of the database's `error` option. A handle has no
892
+ lifecycle verb: its emitter ends with the handle, and after the database closes
893
+ no operation runs, so no handle emits.
732
894
  7. **Views share a driver.** A database is a typed view over a set of tables
733
895
  on one driver. `import(tables)` returns a new view of only those tables
734
896
  over the **same** driver (sharing storage and transactions); `export()`
@@ -745,13 +907,13 @@ These invariants hold across the core database source tree ↔ this guide:
745
907
  `migrate?` / `metadata?` / `stamp?` may be omitted). `MemoryDriver` and
746
908
  `JSONDriver` both omit `records?` / `aggregate?`, and both
747
909
  implement `stream?` / `migrate?` / `metadata?` / `stamp?`; `MemoryDriver` still
748
- omits `transaction?` (snapshot floor only) while `JSONDriver`
910
+ omits `transaction?` (the core's journal carries its scopes) while `JSONDriver`
749
911
  implements `transaction?` too (isolated candidate state plus one atomic
750
912
  publish on callback fulfillment). `SQLiteDriver` implements every optional hook — `records?` /
751
913
  `aggregate?` / `transaction?` / `stream?` / `migrate?` / `metadata?`
752
914
  / `stamp?` — the fully-native backend. `IndexedDBDriver` implements
753
- `records?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
754
- omits `transaction?` and `aggregate?` by IndexedDB's nature, not by
915
+ `records?` / `aggregate?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
916
+ omits `transaction?` by IndexedDB's nature, not by
755
917
  choice (see `.claude/rules/documentation.md` § Parity). A renamed / added /
756
918
  removed method breaks the gate
757
919
  until the table is reconciled.
@@ -777,9 +939,8 @@ These invariants hold across the core database source tree ↔ this guide:
777
939
  the temp file before rejection, and reads wait behind that unit. Once an
778
940
  commit point that cannot be aborted (`SQLite` call entry, IndexedDB transaction
779
941
  completion, JSON `rename` dispatch) has won, the operation awaits and reports its real
780
- result; a late signal cannot convert success to `ABORTED`. Batch items remain
781
- sequential and independent: earlier committed items survive an abort of a
782
- later item.
942
+ result; a late signal cannot convert success to `ABORTED`. A batch is one driver call,
943
+ so an abort ahead of its commit point applies no row of it.
783
944
  10. **Key generation is host-neutral and overridable.** When an optional
784
945
  primary column is omitted, a table uses global `crypto.randomUUID()`.
785
946
  `DatabaseOptions.generator` (a `KeyFunction`) authoritatively replaces
@@ -850,16 +1011,17 @@ These invariants hold across the core database source tree ↔ this guide:
850
1011
  README all call it the same way. It opens the fixed `users` and `posts`
851
1012
  schema per phase (calling `factory()` fresh each time so failures stay
852
1013
  isolated) and verifies the required surface's invariants (copy-in/copy-out
853
- isolation, upsert-overwrite, key-ordered `keys`/`scan`, `snapshot` rollback, a
854
- non-`id` primary key, structural round-tripping through `equalsValue`), then
1014
+ isolation, upsert-overwrite, key-ordered `keys`/`scan`, the batch invariants (a list
1015
+ read in key order, a list write that applies every row, a list insert with a conflicting
1016
+ final member and a mismatched batch that apply none, a list delete that reports each key
1017
+ once), the journal's round trip of prior rows, a non-`id` primary key, structural round-tripping through `equalsValue`), then
855
1018
  presence-gates the optional `migrate?` / `stream?` / `transaction?`
856
1019
  hooks when the driver implements them. The battery's `write-read` phase
857
1020
  is deepened with nested-field checks (a written row's nested object/array
858
1021
  fields must copy-in/copy-out isolated, not only its top-level fields),
859
- and a dedicated `snapshot-nested` phase asserts the same nested isolation
860
- across a `snapshot()` capture/restore round-trip — a driver that
861
- shallow-copies anywhere in its write/read/scan/snapshot boundary
862
- fails conformance (`MemoryDriver` passes by deep-copying through
1022
+ and the journal phase asserts the same nested isolation for a list read whose rows the
1023
+ journal restores — a driver that shallow-copies anywhere in its write/read/scan
1024
+ boundary fails conformance (`MemoryDriver` passes by deep-copying through
863
1025
  `structuredClone` at every one of those boundaries). The first violated
864
1026
  invariant throws a `CONFORMANCE` `DatabaseError` naming the failed check.
865
1027
  13. **Backend faults surface as `DatabaseError`, never raw.** No native
@@ -869,16 +1031,14 @@ These invariants hold across the core database source tree ↔ this guide:
869
1031
  (`#guard` internally on the SQLite side; `mapIndexedDBError` /
870
1032
  `mapMigrationError` on the IndexedDB side), preserving the original
871
1033
  error as `context.cause`. `SQLiteDriver`: a constraint violation maps to
872
- `CONFLICT`, a closed-connection fault to `CLOSED`, a busy/locked database
873
- to `DRIVER` with a `retryable` context flag, anything else to `DRIVER`.
874
- Snapshot capture puts the open gate, every prepare/read, and captured-map
875
- population inside one `#guard`; replay likewise contains the open gate,
876
- native transaction, deletes, prepares, and reinserts in one `#guard`.
877
- Public `close()` crosses that same boundary. A physically dropped declared
878
- table therefore rejects capture as top-level `DRIVER`, and a zero-timeout
879
- exclusive lock rejects replay as retryable `DRIVER` with
880
- `context.code === 'BUSY'`; both retain the actual `SQLiteError` only at
881
- `context.cause`.
1034
+ `CONFLICT`, a closed-connection fault to `CLOSED`, a busy database (`SQLITE_BUSY`, another
1035
+ connection's lock) to `DRIVER` with a `retryable` context flag, and anything else to
1036
+ `DRIVER`, `SQLITE_LOCKED` included: a lock the same connection holds, such as an open
1037
+ stream under a `migrate` that drops an index, carries no `retryable` flag, and its
1038
+ `context.cause.context.errcode` is 6.
1039
+ Public `close()` crosses that same boundary, and a zero-timeout exclusive lock rejects a
1040
+ write as retryable `DRIVER` with `context.code === 'BUSY'`, retaining the actual
1041
+ `SQLiteError` only at `context.cause`.
882
1042
  `IndexedDBDriver`: a constraint violation maps to `CONFLICT`; a
883
1043
  closed/not-open/invalid-state fault to `CLOSED`; a quota fault to
884
1044
  `DRIVER` with `code: 'QUOTA'`; `migrate`'s versionchange path remaps an
@@ -893,11 +1053,43 @@ These invariants hold across the core database source tree ↔ this guide:
893
1053
  as corrupted metadata. Because both drivers derive their index names from
894
1054
  a length-prefixed scheme (`deriveSQLiteIndexName` for SQLite,
895
1055
  `deriveIndexedDBIndexName` for IndexedDB) to stay collision-free across
896
- compound indexes, a database
897
- file/store created under an older naming scheme leaves its old-named
898
- indexes orphaned (unreferenced, harmless) on reopen under the new scheme —
899
- they are never queried and never collide, but a storage audit may notice
900
- them.
1056
+ compound indexes. A writable SQLite open drops every created index of a deployed table
1057
+ whose name its deployed schema does not derive, an old-named index included; an IndexedDB
1058
+ store created under an older naming scheme leaves its old-named indexes orphaned
1059
+ (unreferenced, harmless) on reopen — they are never queried and never collide, but a
1060
+ storage audit may notice them.
1061
+
1062
+ 15. **Every read passes the query door.** `records`, `count`, `aggregate`, `scan`, and each
1063
+ `query()` terminal, a filtered `aggregate` included, admit a copy of their read after the
1064
+ driver is ready and before any driver call, and read only that copy, so a change the
1065
+ caller makes afterward never reaches the read. Only an absent read (`undefined`) skips
1066
+ the door; `null` refuses. The shape-derived guard of `queryInputContract` holds the
1067
+ structure: each condition is a union keyed on `operator` that fixes the arity of
1068
+ `values`, `like`, `glob`, `starts`, and `ends` take a string operand, a column is a name
1069
+ or a non-empty list of strings, `connector` and `direction` are their literals, `limit`
1070
+ and `offset` are nonnegative integers, and every object refuses an undeclared key. A pass
1071
+ over the table's columns holds the schema facts: the leading column of a condition, an
1072
+ ordering term, and the aggregate column is declared; a nested path descends only a
1073
+ `json` column; an operand matches its column's storage class (a string for `text`, a
1074
+ number for `integer` and `real`, a boolean for `boolean`, any value on `json`); `null`
1075
+ stands only on a nullable column and `undefined` only on an optional one, each for
1076
+ `equals`, `not`, `any`, and `none`, never under a range operator; `like`, `glob`,
1077
+ `starts`, and `ends` read a `text` or `json` column; the aggregate operation is one of
1078
+ `AGGREGATE_OPERATIONS`; and every string operand is well-formed UTF-16, on a `json`
1079
+ column and under a nested path too. The pass reads no refinement: integer-ness, bounds,
1080
+ patterns, and literal membership stay the contract's. A literal whose members span more
1081
+ than one class is `json` storage, as a union is. A refusal is `VALIDATION` whose context
1082
+ carries `table` and `faults`: the guard's `admitValue` faults, computed only after the
1083
+ guard refuses, then the faults of the column pass, which also runs when the guard refuses
1084
+ and skips each condition and ordering term a guard fault names, so one refusal names every
1085
+ fault once. The message is a header and the contract's `describeFaults` rendering, bounded
1086
+ by `FAULT_TEXT_LIMIT`. When the column pass reports, the header and the context add the
1087
+ `column` its first fault names, and the `operator` when the guard admitted the read, and
1088
+ the header lists the declared columns. An aggregate is admitted as a copy with its read, and
1089
+ the table computes from that copy. A lone surrogate in a written `text` value or in a key
1090
+ is `VALIDATION` with `table` and `column` on every driver, because SQLite stores it as
1091
+ U+FFFD and reads back a changed value; a `json` cell holding one round-trips, because
1092
+ `JSON.stringify` escapes it.
901
1093
 
902
1094
  What ships is the **core in-between** (schema-aware: `open` receives a
903
1095
  derived `TableSchema[]`, with `shapeToColumnStorage` mapping each column's shape), its
@@ -905,7 +1097,7 @@ reference `MemoryDriver`, and the persistent `JSONDriver`, `SQLiteDriver`, and
905
1097
  `IndexedDBDriver` backends. `JSONDriver` in `src/server` is a decorator over
906
1098
  `MemoryDriver` that loads/flushes a single JSON file — every primitive
907
1099
  delegates to the inner memory driver, so querying, key-order `scan` / `keys`,
908
- and capture-replay `snapshot` are inherited unchanged; `JSONDriver.migrate`
1100
+ and the all-or-nothing batches are inherited unchanged; `JSONDriver.migrate`
909
1101
  additionally persists the migrated state, and every flush is atomic — written
910
1102
  to a sibling temp file and `rename`d onto the target path, so a crash mid-flush
911
1103
  can never truncate or corrupt the previous good file. Outside a `transaction`,
@@ -920,7 +1112,7 @@ active, and a captured capability used after settlement throw `CONFLICT`.
920
1112
  fully-native, **trusted-mode** backend on the published `@orkestrel/sqlite`
921
1113
  wrapper — real typed `CREATE TABLE` / `CREATE INDEX` DDL, native
922
1114
  `records?` / `aggregate?` / `stream?` compiled straight to SQL,
923
- real `BEGIN` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
1115
+ real `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
924
1116
  (`stepToSQL`; a root input uses one native transaction, while an input inside
925
1117
  an existing callback transaction uses the guarded fixed internal savepoint
926
1118
  literal for caught-inner-failure containment while the outer transaction stays
@@ -929,14 +1121,13 @@ and a reserved
929
1121
  `_metadata` table (`METADATA_TABLE`) for `metadata?` / `stamp?` versioning — every
930
1122
  optional `DriverInterface` hook, none skipped. `IndexedDBDriver` in
931
1123
  `src/browser`, on the published `@orkestrel/indexeddb` wrapper, is the
932
- persistent browser backend — `planIndexedDBQuery` keeps native the one condition a
933
- key range over the primary key or a single-column secondary index answers, and leaves the
934
- rest of the read residual for the core engine; `migrate?` applies a non-empty plan
1124
+ persistent browser backend — `planIndexedDBQuery` keeps native the one access path
1125
+ `findAccessPlan` ranks first, with the order, page, `count`, `minimum`, and `maximum` that
1126
+ path serves, and leaves the rest of the read residual for the core engine; `migrate?` applies a non-empty plan
935
1127
  and its metadata in one versionchange transaction, and `metadata?` / `stamp?`
936
1128
  persist into a reserved
937
1129
  `__metadata__` store (`METADATA_STORE`) — it omits `transaction?` because arbitrary
938
- callback awaits outlive an auto-committing `IDBTransaction`, and
939
- `aggregate?` (no native SUM/AVG/MIN/MAX) by IndexedDB's own nature. The core
1130
+ callback awaits outlive an auto-committing `IDBTransaction`. The core
940
1131
  `Database` / `Table` are also **observable** — each owns a typed `emitter`
941
1132
  (`DatabaseEventMap` / `TableEventMap`) carrying the transaction +
942
1133
  per-row lifecycle (see [Observing](#observing)); a driver stays a storage
@@ -980,7 +1171,7 @@ posts.primary // 'slug' — the declared override
980
1171
  Each `indexes` entry is one (possibly compound) index of column names; they
981
1172
  flow into each table's derived `TableSchema`. Neither driver here declares a
982
1173
  native index, so both ignore them; SQLite and IndexedDB build a native index from each
983
- supported declaration.
1174
+ supported declaration, and IndexedDB drops at open an index the declaration no longer names.
984
1175
 
985
1176
  ### Swapping the driver
986
1177
 
@@ -1075,6 +1266,47 @@ await users.count() // every row, unfiltered
1075
1266
  await users.aggregate('average', 'age') // number | undefined
1076
1267
  ```
1077
1268
 
1269
+ ### The query door
1270
+
1271
+ A table admits each read before any driver call, so a malformed read raises in place of an
1272
+ empty or a whole-table answer. The refusal names the table, and the key path and expected class
1273
+ of each fault; when the column pass reports, it also names the column and operator of its first
1274
+ fault and lists the declared columns:
1275
+
1276
+ ```ts
1277
+ import { createDatabase, createMemoryDriver } from '@orkestrel/database'
1278
+ import { integerShape, optionalShape, stringShape } from '@orkestrel/contract'
1279
+
1280
+ const items = createDatabase({
1281
+ driver: createMemoryDriver(),
1282
+ tables: {
1283
+ items: { id: stringShape(), rank: integerShape(), note: optionalShape(stringShape()) },
1284
+ },
1285
+ }).table('items')
1286
+ await items.set([
1287
+ { id: 'a', rank: 5 },
1288
+ { id: 'b', rank: 7, note: 'kept' },
1289
+ ])
1290
+
1291
+ await items.count({
1292
+ conditions: [{ column: 'note', operator: 'equals', values: [undefined], connector: 'and' }],
1293
+ }) // 1 — `undefined` stands on an optional column
1294
+ await items
1295
+ .count({ conditions: [{ column: 'rank', operator: 'equals', values: ['5'], connector: 'and' }] })
1296
+ .catch((error: unknown) => error)
1297
+ // DatabaseError VALIDATION, context { table: 'items', column: 'rank', operator: 'equals', faults: [
1298
+ // { reason: 'type', path: ['conditions', '0', 'values', '0'], expected: 'number', received: '"5"' }] }
1299
+ await items
1300
+ .records({ conditions: [{ column: 'rnk', operator: 'absent', values: [], connector: 'and' }] })
1301
+ .catch((error: unknown) => error)
1302
+ // DatabaseError VALIDATION; the message lists the declared columns: id text, rank integer, note text optional
1303
+ await items.get('a\uD800').catch((error: unknown) => error)
1304
+ // DatabaseError VALIDATION, context { table: 'items', column: 'id' } — a lone surrogate in a key
1305
+ ```
1306
+
1307
+ `queryInputContract` is the same door for a caller that admits a read before it reaches a
1308
+ table, such as a server that takes a read from a client.
1309
+
1078
1310
  ### Streaming with early exit
1079
1311
 
1080
1312
  `scan` (on a table) and `stream` (on a query) are lazy — rows are yielded one
@@ -1165,8 +1397,8 @@ write. Memory and SQLite check immediately before their synchronous mutation;
1165
1397
  IndexedDB aborts its explicit readwrite transaction while active; JSON aborts
1166
1398
  staging, cleans its temp file, and restores the preimage before rejecting. If
1167
1399
  the native commit has already been dispatched, the method ignores a late abort
1168
- and awaits the real success or failure. A batch passes the same signal to each
1169
- sequential item, so already-committed earlier items remain committed.
1400
+ and awaits the real success or failure. A batch is one driver call with one commit point,
1401
+ so an abort applies every row of it or none.
1170
1402
 
1171
1403
  ### Batch operations
1172
1404
 
@@ -1200,33 +1432,46 @@ await users.get(['u1', 'u2']) // → readonly (Row | undefined)[]
1200
1432
  await users.resolve(['u1', 'u2']) // → readonly Row[] (NOT_FOUND on any miss)
1201
1433
  await users.has(['u1', 'u2']) // → readonly boolean[]
1202
1434
  await users.update(['u1', 'u2'], { role: 'member' }) // same changes to each → readonly boolean[]
1203
- await users.remove(['u1', 'u2']) // → readonly boolean[]
1435
+ await users.remove(['u1', 'u2']) // → boolean, true only when every distinct listed key held a row and was removed
1204
1436
  ```
1205
1437
 
1206
- A batch runs as independent sequential operations; wrap it in `transaction`
1207
- when it must be atomic.
1438
+ A batch is one driver call that applies every row or none. The table admits every row through
1439
+ the contract ahead of that call, so a refused row applies none of the batch, and a conflicting
1440
+ `add` member does the same. SQLite runs the batch as one transaction, or as one savepoint
1441
+ inside a scope; IndexedDB runs it in one `database.write` scope; `MemoryDriver` and
1442
+ `JSONDriver` check every row ahead of the first change. `get`, `resolve`, and `has` of a key
1443
+ list are one list `read`, and `update` of a key list is one list `read` and one list
1444
+ `write`.
1208
1445
 
1209
1446
  ### Admission through the contract
1210
1447
 
1211
- Admits a numeric string against the table's contract, stores the repaired number, and refuses an undeclared column:
1448
+ Repairs a numeric string through the table's contract before the write, stores the number, and refuses the bare write and an undeclared column:
1212
1449
 
1213
1450
  ```ts
1214
1451
  import { createDatabase, createMemoryDriver, isDatabaseError } from '@orkestrel/database'
1215
- import { admitValue, integerShape, stringShape } from '@orkestrel/contract'
1452
+ import type { DatabaseInterface } from '@orkestrel/database'
1453
+ import { integerShape, repairValue, stringShape } from '@orkestrel/contract'
1216
1454
 
1217
- const users = createDatabase({
1455
+ // A DatabaseInterface hands out untyped rows, as a boundary that holds loose data needs.
1456
+ const db: DatabaseInterface = createDatabase({
1218
1457
  driver: createMemoryDriver(),
1219
1458
  tables: {
1220
1459
  users: { id: stringShape(), name: stringShape(), age: integerShape(), role: stringShape() },
1221
1460
  },
1222
- }).table('users')
1461
+ })
1462
+ const users = db.table('users')
1223
1463
 
1224
- // A numeric string is a lossless repair, so admitValue admits it as the number.
1225
- const admitted = admitValue(users.contract, { id: 'u2', name: 'Bo', age: '41', role: 'member' })
1226
- if (!admitted.success) throw new Error('Expected the row to admit')
1227
- await users.set(admitted.value.value)
1464
+ // A numeric string is a lossless repair, so repairValue admits it as the number before the write.
1465
+ const loose = { id: 'u2', name: 'Bo', age: '41', role: 'member' }
1466
+ const repaired = repairValue(users.contract, loose)
1467
+ if (!repaired.success) throw new Error('Expected the row to repair')
1468
+ await users.set(repaired.value.value)
1228
1469
  ;(await users.get('u2'))?.age // 41 (a number)
1229
1470
 
1471
+ // The bare write refuses the same row with DatabaseError('VALIDATION') and the type fault.
1472
+ const bare = await users.set({ ...loose, id: 'u4' }).catch((error: unknown) => error)
1473
+ if (isDatabaseError(bare)) bare.message // contains 'age: type; expected integer; received "41"'
1474
+
1230
1475
  // An undeclared column refuses with DatabaseError('VALIDATION') and the contract's faults.
1231
1476
  const imported = { id: 'u3', name: 'Cy', age: 29, role: 'member', nickname: 'Cy' }
1232
1477
  const refused = await users.set(imported).catch((error: unknown) => error)
@@ -1365,7 +1610,8 @@ await users
1365
1610
 
1366
1611
  The condition operators map to familiar SQL operators. The core engine evaluates each one
1367
1612
  over a residual; SQLite answers each natively on a flat declared column, and IndexedDB
1368
- answers one comparison with a key range, under these same semantics:
1613
+ answers the conditions of one access path with a key range or a key list, under these same
1614
+ semantics:
1369
1615
 
1370
1616
  | Operator | SQL |
1371
1617
  | --------- | ------------- |
@@ -1544,6 +1790,35 @@ error. `rollback(error)` reports only a completed rollback whose original
1544
1790
  scope/drain error is still being propagated — a cleanup failure is never
1545
1791
  reported as a successful rollback.
1546
1792
 
1793
+ On a driver without `transaction?` (`MemoryDriver`, `IndexedDBDriver`, a custom backend), the
1794
+ core runs the scope through its before-image journal, `StorageJournal`: each write, insert,
1795
+ or delete reads the prior rows of its untouched keys in one list `read` ahead of the write,
1796
+ and a `clear` reads its table's keys and rows ahead of emptying it. On rejection the journal
1797
+ writes back each cleared table and each recorded row and deletes each recorded key that held
1798
+ no row, so the cost of a scope follows the keys it touched rather than the store's size.
1799
+ Reads go to the driver, so a native read inside the scope sees the scope's writes. The
1800
+ journal gives rollback on rejection and no crash atomicity:
1801
+
1802
+ ```ts
1803
+ import { createMemoryDriver, StorageJournal } from '@orkestrel/database'
1804
+
1805
+ const driver = createMemoryDriver()
1806
+ await driver.open([
1807
+ {
1808
+ name: 'users',
1809
+ primary: 'id',
1810
+ columns: [{ name: 'id', storage: 'text', optional: false, nullable: false }],
1811
+ indexes: [],
1812
+ },
1813
+ ])
1814
+ await driver.write('users', 'u1', { id: 'u1', name: 'Ada' })
1815
+ const journal = new StorageJournal(driver)
1816
+ await journal.write('users', 'u1', { id: 'u1', name: 'Grace' })
1817
+ await journal.insert('users', 'u2', { id: 'u2', name: 'Alan' })
1818
+ await journal.restore()
1819
+ await driver.read('users', ['u1', 'u2']) // [{ id: 'u1', name: 'Ada' }, undefined]
1820
+ ```
1821
+
1547
1822
  Root promise operations enter the shared admission ledger synchronously, before
1548
1823
  their first `await`. `transaction()` closes root admission before it drains that
1549
1824
  ledger, so work accepted immediately before the transaction is included and work
@@ -1572,7 +1847,7 @@ await boundary.track(async () => 42) // 42
1572
1847
  ### Native transactions
1573
1848
 
1574
1849
  `transaction` uses a driver's optional native `transaction?(scope)` hook
1575
- instead of the snapshot floor. The driver passes a `StorageInterface`
1850
+ instead of the core's journal. The driver passes a `StorageInterface`
1576
1851
  capability to the callback, commits when it fulfills, rolls back when it
1577
1852
  rejects, and invalidates the capability after settlement. The database-level
1578
1853
  `transaction` / `commit` / `rollback` events fire the same either way:
@@ -1816,10 +2091,10 @@ schemaToStore(table)
1816
2091
 
1817
2092
  The helper delegates exact JSON ownership to Contract 0.0.9's
1818
2093
  `cloneJSONRecord`, then validates the owned output as `DriverMetadata`. A malformed
1819
- shape, cycle, function, accessor, or hostile/revoked proxy throws
2094
+ shape, cycle, function, accessor, or throwing/revoked proxy throws
1820
2095
  `DatabaseError('VALIDATION')` with `context.path === 'metadata'`; clone/traversal
1821
2096
  failures are retained only as `context.cause`, so no raw Contract or caller
1822
- error crosses the Database surface. Hostile values are never stringified or
2097
+ error crosses the Database surface. Untrusted values are never stringified or
1823
2098
  embedded in the diagnostic.
1824
2099
 
1825
2100
  `JSONDriver` applies that ownership rule at every file-backed seam: valid parsed
@@ -1834,7 +2109,7 @@ structured-clone behavior and are not forced through the JSON metadata cloner.
1834
2109
 
1835
2110
  `SQLiteDriver` applies the same boundary at persisted-row ingress, every
1836
2111
  root/scoped `stamp` and `migrate` ingress, and every `metadata()` copy-out.
1837
- Root lifecycle and scoped token gates run before hostile metadata traversal;
2112
+ Root lifecycle and scoped token gates run before untrusted metadata traversal;
1838
2113
  valid migration metadata is cloned before its first DDL statement. Malformed
1839
2114
  stored metadata fails closed with `DRIVER`, while valid copy-outs are distinct
1840
2115
  and deeply frozen. General SQLite rows continue through
@@ -1925,8 +2200,9 @@ const db = createDatabase({
1925
2200
  on: { commit: () => console.log('transaction committed') },
1926
2201
  })
1927
2202
 
1928
- const users = db.table('users') // hold the handle (the documented practice) and observe it
1929
- users.emitter.on('write', (key) => console.log('invalidate users', key))
2203
+ const users = db.table('users', {
2204
+ on: { write: (key) => console.log('invalidate users', key) },
2205
+ }) // hold the handle (the documented practice) and observe it
1930
2206
  users.emitter.on('remove', (key) => console.log('invalidate users', key))
1931
2207
  db.emitter.on('rollback', (error) => console.warn('transaction rolled back', error))
1932
2208
  ```
@@ -1941,7 +2217,7 @@ The event vocabulary:
1941
2217
  `open` fires once when the handle's driver connects (an explicit `open()`, or
1942
2218
  the lazy first-use connect); `close`
1943
2219
  when the driver is released; `transaction` when a scope begins after its
1944
- native boundary or fallback snapshot is acquired; `commit` only after a scope
2220
+ native boundary is acquired or its journal is created; `commit` only after a scope
1945
2221
  succeeds; `rollback` only after a throwing scope's tables are all restored;
1946
2222
  `migrate` after a migration commits. A `Table` fires `write` after any
1947
2223
  row put (set / add / update — re-read by key if you need the new value),
@@ -1949,7 +2225,12 @@ row put (set / add / update — re-read by key if you need the new value),
1949
2225
  and `clear` after the table is emptied. Reads / queries / counts are **not**
1950
2226
  emitted — a reader does not mutate, and those paths are too hot. Each
1951
2227
  `db.table(name)` returns a fresh handle with its own emitter, so subscribe
1952
- on the handle you hold and operate on that same handle.
2228
+ on the handle you hold and operate on that same handle, or pass initial
2229
+ listeners through the handle's `on` option. `close` destroys the database
2230
+ emitter after its `close` event, so a database listener receives nothing after
2231
+ `close`. A table handle has no lifecycle verb: its emitter ends with the handle, and
2232
+ after `close` every table operation refuses with `CLOSED`, so a table listener
2233
+ receives nothing after it either.
1953
2234
 
1954
2235
  **Listener isolation.** A listener throw never escapes
1955
2236
  into the engine: the emitter isolates it and routes it to
@@ -1966,8 +2247,8 @@ propagates, the tables still roll back), and a throwing `write` observer
1966
2247
  leaves the written row intact — proven by the per-entity emit-safety tests.
1967
2248
  (A `Table` reached through the `Database` receives the same `error` handler
1968
2249
  the `DatabaseOptions.error` option supplies, so a `Table` listener throw
1969
- routes there; with no `error` handler configured, the throw is swallowed
1970
- silently.)
2250
+ routes there unless the handle's own `DatabaseTableOptions.error` option supplies one;
2251
+ with no `error` handler configured, the throw is swallowed silently.)
1971
2252
 
1972
2253
  ### Importing and exporting schemas
1973
2254
 
@@ -2083,9 +2364,10 @@ await driver.write('users', 'u1', { id: 'u1', name: 'Ada Lovelace' }) // upsert
2083
2364
  await driver.read('users', 'u1') // { id: 'u1', name: 'Ada' } | undefined
2084
2365
  for await (const row of driver.scan('users')) row // every row, key order
2085
2366
  await driver.keys('users') // readonly Key[]
2086
- const rollback = await driver.snapshot() // capture, then...
2087
- await driver.delete('users', 'u1') // boolean
2088
- await rollback() // ...restore the captured state
2367
+ await driver.write('users', ['u2', 'u3'], [{ id: 'u2' }, { id: 'u3' }]) // every row or none
2368
+ await driver.read('users', ['u1', 'missing']) // [{ id: 'u1', name: 'Ada Lovelace' }, undefined]
2369
+ await driver.delete('users', ['u2', 'u2']) // [true, false]
2370
+ await driver.delete('users', 'u1') // true
2089
2371
  await driver.clear('users')
2090
2372
  await driver.close()
2091
2373
  ```
@@ -2140,6 +2422,36 @@ shapeToColumnStorage(integerShape()) // 'integer' — the type `open` hands a dr
2140
2422
  equalsValue({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }) // true — structural, not reference, equality
2141
2423
  ```
2142
2424
 
2425
+ ### Recording driver calls
2426
+
2427
+ `StorageRecorder` wraps a real driver and counts the keys each call addresses and the rows it
2428
+ returns or yields; `tallyCalls` totals one member. Its `driver` declares exactly the members
2429
+ its source declares, so a read plans as it would on the source:
2430
+
2431
+ ```ts
2432
+ import { integerShape, stringShape } from '@orkestrel/contract'
2433
+ import {
2434
+ createDatabase,
2435
+ createMemoryDriver,
2436
+ StorageRecorder,
2437
+ tallyCalls,
2438
+ } from '@orkestrel/database'
2439
+
2440
+ const recorder = new StorageRecorder(createMemoryDriver())
2441
+ const users = createDatabase({
2442
+ driver: recorder.driver,
2443
+ tables: { users: { id: stringShape(), age: integerShape() } },
2444
+ }).table('users')
2445
+ await users.set([
2446
+ { id: 'u1', age: 36 },
2447
+ { id: 'u2', age: 7 },
2448
+ ])
2449
+
2450
+ const { value, calls } = await recorder.measure(() => users.count())
2451
+ value // 2
2452
+ tallyCalls(calls, 'scan') // { calls: 1, keys: 0, rows: 2 } — the Memory driver answers over scan
2453
+ ```
2454
+
2143
2455
  ### Persistence with the JSON driver
2144
2456
 
2145
2457
  Opens a database over the JSON driver and writes one row, persisted to the backing file:
@@ -2192,12 +2504,12 @@ restored before that error leaves the exclusive queue, so the next operation
2192
2504
  can proceed after the temporary obstruction is removed. A successful staging
2193
2505
  write requests native `flush: true` before the same-directory atomic rename.
2194
2506
 
2195
- `JSONDriver.snapshot()` captures owned row data together with the table schema
2196
- needed to decode that capture. Its rollback thunk is repeatable and restores
2197
- data only into the driver's current schema: current metadata is never rewound,
2198
- a captured table removed after capture is skipped, and a table added later is
2199
- preserved. Replaying the same thunk again produces the same row result without
2200
- replacing the current schema or metadata.
2507
+ Each root write, insert, or delete, a list included, records its prior rows in a
2508
+ `StorageJournal` over the driver's memory, applies the change, and flushes the whole store
2509
+ once; a failed flush restores the journaled rows before the error leaves the queue, so memory
2510
+ and the file hold the same rows. An empty list changes no row and leaves the file in place.
2511
+ `clear` flushes the table as empty ahead of emptying memory, so a failed flush leaves memory
2512
+ holding every row it held.
2201
2513
 
2202
2514
  ### Compiling input to SQL
2203
2515
 
@@ -2240,7 +2552,7 @@ compileQuerySQL(
2240
2552
  quoteIdentifier('order') // '"order"'
2241
2553
  deriveSQLiteIndexName('users', ['age']) // 'idx_5_users_3_age'
2242
2554
  compileColumnSQL('integer') // 'INTEGER'
2243
- compileFieldSQL(['profile', 'score']) // 'json_extract("profile", \'$.score\')'
2555
+ compileFieldSQL(['profile', 'score']) // `json_extract(CASE WHEN typeof("profile") = 'text' THEN "profile" END, '$."score"')`
2244
2556
  compileAggregateSQL('average', 'age') // 'AVG("age")'
2245
2557
  planSQLiteQuery({ aggregate: { operation: 'minimum', column: 'age' } }, schema).residual // {}
2246
2558
  matchesSQLiteAffinity('INTEGER', 'integer') // true
@@ -2258,11 +2570,24 @@ A driver's `plan` splits each read into the part its engine answers and the resi
2258
2570
  core runs, under the native-first rule the `DriverInterface` doc block states. A read is
2259
2571
  wholly native when `residual` equals `{}`. `planSQLiteQuery` is the SQLite driver's plan,
2260
2572
  and `compileQuerySQL` compiles its native side; `planIndexedDBQuery` is the IndexedDB
2261
- driver's plan, which keeps one key-range condition native. A driver without `plan`, such as
2573
+ driver's plan, which keeps one ranked access path native with the order, page, and count it
2574
+ serves. A driver without `plan`, such as
2262
2575
  `MemoryDriver` and `JSONDriver`, answers the whole read as residual over `scan`. `Table` runs
2263
2576
  every read through `readPlannedRows`, `readPlannedAggregate`, and `streamPlannedRows`, the one
2264
2577
  read procedure `scanDriver`'s differential checks.
2265
2578
 
2579
+ Two SQLite forms keep a read native where a flag or a path would otherwise send it to the
2580
+ core. An order on a column that is both optional and nullable compiles a rank ahead of the
2581
+ column term, in the term's direction: absence ranks 0, the column's `null` sentinel ranks 1,
2582
+ and a value ranks 2, so the engine returns the core's total order, and the page stays native
2583
+ beside it. When every connector is `and`, `matchesSQLitePrefilter` admits `equals`, `not`,
2584
+ `any`, and `none` with scalar operands on a nested path under a `json` head, and the plan puts
2585
+ the condition on both sides: `compileNestedSQL` tests the JSON type at the path beside its
2586
+ value, so the engine keeps a superset of the rows and the core rechecks each one. A key that
2587
+ can name an array member, a canonical index such as `0` or `length`, keeps the condition
2588
+ residual alone, because a JSON path label names an object member only. A prefilter holds the
2589
+ page on the residual side, so the core still stops at `offset + limit` matches.
2590
+
2266
2591
  ```ts
2267
2592
  import type { Condition, TableSchema } from '@orkestrel/database'
2268
2593
  import {
@@ -2337,15 +2662,18 @@ await db
2337
2662
  // Real transactions and atomic migration ship with it:
2338
2663
  await db.transaction(async (transaction) => {
2339
2664
  await transaction.table('users').update('u1', { age: 37 })
2340
- }) // real BEGIN/COMMIT/ROLLBACK, not the snapshot floor
2665
+ }) // real BEGIN IMMEDIATE/COMMIT/ROLLBACK, not the core's journal
2341
2666
 
2342
- // createSQLiteDriver accepts a SQLiteDriverOptions bag:
2343
- createSQLiteDriver({
2344
- path: 'data/app.sqlite',
2345
- timeout: 5000,
2667
+ // createSQLiteDriver accepts a SQLiteDriverOptions bag and returns a SQLiteDriverInterface:
2668
+ const driver = createSQLiteDriver({
2669
+ path: 'data/reports.sqlite',
2346
2670
  references: true,
2347
- pragmas: { journal_mode: 'WAL' }, // applied through pragma() right after connect(), in order
2671
+ pragmas: { synchronous: 'FULL' }, // applied after the WAL default, in order
2348
2672
  })
2673
+ const reports = createDatabase({ driver, tables: { reports: { id: stringShape() } } })
2674
+ await reports.table('reports').set({ id: 'r1' })
2675
+ driver.pragma('journal_mode') // 'wal'
2676
+ driver.pragma('synchronous') // 2
2349
2677
  ```
2350
2678
 
2351
2679
  `SQLiteDriver` is the fully-native backend — it implements every optional
@@ -2364,17 +2692,72 @@ metadata. The same call inside a callback transaction uses a SQLite savepoint:
2364
2692
  the wrapper deliberately provides raw `execute`, not a savepoint manager, so the
2365
2693
  driver owns one guarded fixed internal SQL literal. If caller code catches its
2366
2694
  failure, the failed inner migration is rolled back to that savepoint while the
2367
- surrounding transaction remains active and may continue safely. Snapshot
2368
- capture and replay, plus public `close()`, contain their complete native bodies
2369
- inside `#guard`; no raw SQLite fault crosses the driver boundary. Candidate
2695
+ surrounding transaction remains active and may continue safely. A list write or insert
2696
+ uses one prepared statement per row, as one transaction outside a scope and inside the same
2697
+ savepoint form within one, so a conflicting row applies none of the batch; a list read and a
2698
+ list delete are each one statement with the keys bound as one JSON parameter. Public
2699
+ `close()` contains its complete native body inside `#guard`; no raw SQLite fault crosses the driver boundary. Candidate
2370
2700
  schema state becomes live only after the native commit. Point `write` / `insert` /
2371
2701
  `delete` check `OperationOptions.signal`
2372
2702
  immediately before the synchronous SQLite call; that call entry is the commit
2373
2703
  point, so there is no post-check that could relabel a completed commit.
2374
2704
 
2705
+ A writable file opens under `journal_mode = WAL`, issued ahead of the `pragmas` entries, unless
2706
+ `pragmas` names `journal_mode`; a `':memory:'` database and a `readonly`
2707
+ open keep their journal. The driver issues no other pragma: `synchronous` keeps the engine
2708
+ build's default, which is `FULL` on the SQLite that Node 22.23.5 bundles, and the busy timeout
2709
+ stays 0 unless the application sets `timeout`. A refused journal mode raises nothing, so an
2710
+ application that requires WAL reads `journal_mode` back through the `pragma` method.
2711
+
2712
+ Every driver transaction opens with `BEGIN IMMEDIATE`: a scope, a list write's commit, a root
2713
+ `migrate`, and the open's schema transaction. A contended writer is refused at its start,
2714
+ ahead of any work, and a set busy timeout applies there. One driver per file is the supported
2715
+ shape. Two connections on one thread never resolve by waiting, because the holder cannot
2716
+ advance while the waiter blocks the thread: with no `timeout`, the waiter's scope is refused at
2717
+ once as `DRIVER` with `context.retryable`, a read on it returns, and its scope runs after the
2718
+ holder settles, so share one driver instead. Set `timeout` only when another process or a
2719
+ worker thread opens the file; the wait blocks the event loop for up to its length, and the
2720
+ waiting scope runs after the holder commits. A copy of the main file alone misses the WAL.
2721
+ The application decides whether to retry a refusal.
2722
+
2723
+ The `pragma` method of the `SQLiteDriverInterface` that `createSQLiteDriver` returns runs
2724
+ `PRAGMA name` with no value and returns the first value the engine answers, or `undefined`
2725
+ when it answers no row. A name the engine treats as an action runs that action. A name that
2726
+ fails `isPragmaName` from `@orkestrel/sqlite` raises `VALIDATION` ahead of any SQL, and a call
2727
+ while a transaction is active raises `CONFLICT`. The `pragmas` option is the one place a
2728
+ setting is written: each name passes `isPragmaName` and is one of `PRAGMA_NAMES`, and each
2729
+ value passes `isPragmaValue`, a 32-bit signed integer or a keyword of ASCII letters and
2730
+ underscores, at construction.
2731
+
2732
+ A writable open runs `PRAGMA optimize = 0x10002` after its schema transaction, so an index the
2733
+ open created is analyzed too, and the `close` method runs nothing. Statistics are exact at a
2734
+ writable open of a table that holds none or whose row count changed tenfold since its
2735
+ statistics, and the prior statistics stand in between. The analysis reads every row of such a
2736
+ table, so its cost grows with the table. A busy refusal of it leaves the open in place, because
2737
+ it changes cost only and the next writable open analyzes again; any other refusal fails the
2738
+ open as `DRIVER`, so a file whose index is corrupt never opens. The busy path is unproven by
2739
+ test: the schema transaction takes the same write lock on the same thread immediately before the
2740
+ analysis, so nothing can stage the refusal between them without a seam, and a seam there
2741
+ would reopen it. The `pragma` method with
2742
+ `optimize` runs the engine's default mask, whose bounded statistics a following open keeps
2743
+ until the row count changes tenfold.
2744
+
2745
+ Inside the open transaction, after validation, a writable open drops every index created on
2746
+ a deployed table (`origin` `c` in `pragma_index_list`) whose name the deployed schema does not
2747
+ derive, so the file's created indexes equal the deployed schema's; an index is derived data,
2748
+ so a drop loses no row. A `readonly` open drops nothing, and an undeclared unique index still
2749
+ raises `DRIVER`.
2750
+
2751
+ Each open connection is a `SQLiteConnection`, which keeps up to `STATEMENT_LIMIT` prepared
2752
+ statements keyed by SQL text and evicts the least recently used. Point and list reads, list
2753
+ deletes, writes, pages, counts, and aggregates reuse them; a stream prepares its own statement,
2754
+ because a statement with an open iterator cannot run again. The `close` method and the next
2755
+ `open` drop the cache with the connection. A cached point read skips the statement's compile,
2756
+ which `tests/src/server/drivers/SQLiteDriver.bench.ts` reads beside the wrapper alone.
2757
+
2375
2758
  ### Persistence with the IndexedDB driver
2376
2759
 
2377
- Feature-detects `indexedDB`, opens a database over the IndexedDB driver, writes one row, and runs a query pushed down to a key range:
2760
+ Feature-detects `indexedDB`, opens a database over the IndexedDB driver, writes one row, and runs a query the driver answers with a key range:
2378
2761
 
2379
2762
  ```ts
2380
2763
  import { createDatabase } from '@orkestrel/database'
@@ -2392,7 +2775,7 @@ if (typeof indexedDB !== 'undefined') {
2392
2775
  .table('users')
2393
2776
  .query()
2394
2777
  .condition({ column: 'id', operator: 'equals', values: ['u1'], connector: 'and' })
2395
- .collect() // pushed down to a key range
2778
+ .collect() // answered by a key range on the primary key
2396
2779
  }
2397
2780
  ```
2398
2781
 
@@ -2404,50 +2787,80 @@ publishing schema/identity/connection state or changing the record. The
2404
2787
  bootstrap closes in every outcome, so external repair or version activity is
2405
2788
  not blocked and the same driver may retry. It then connects the deployed
2406
2789
  `DriverMetadata.schema` plus `__metadata__`; it does not create the target declaration
2407
- before reconciliation. Its plan keeps native the one condition a key range over the
2408
- primary key or a single-column secondary index answers (`planIndexedDBQuery`), and the core
2409
- engine runs the rest — see [Plans and residual work](#plans-and-residual-work).
2410
- It implements `plan?` / `records?` / `stream?` / `migrate?` / `metadata?` /
2411
- `stamp?` (persisted into a reserved `__metadata__` store, `METADATA_STORE` —
2790
+ before reconciliation.
2791
+
2792
+ `open()` drops every index of a deployed table that the deployed schema does not declare: the
2793
+ stored schema of a versioned database, and the declared schema of an unversioned one. It
2794
+ drops them on its own connection at the next version, then makes its final open pinned for
2795
+ a versioned database and unpinned for an unversioned one, and a dropped index loses no row.
2796
+ When another connection bumps the version between the driver's read of it and that
2797
+ upgrade, `open()` rejects with `DRIVER` whose `context.retryable` is `true`; call
2798
+ `open()` again. Two builds that declare different indexes on one unversioned database name
2799
+ each drop the other's index at their `open()`, and the other's next open creates it again,
2800
+ so give each build its own database name.
2801
+
2802
+ The plan keeps native the one access path `findAccessPlan` ranks first, with the order, the
2803
+ page, `count`, `minimum`, and `maximum` that path serves (`planIndexedDBQuery`), and the
2804
+ core engine runs the rest — see [Plans and residual work](#plans-and-residual-work) and
2805
+ [IndexedDB planning](#indexeddb-planning). A stream and `scan` read at most
2806
+ `STREAM_BATCH_SIZE` rows per transaction and resume after the final key of each batch,
2807
+ because a transaction cannot stay open across your awaits. A native page reads no row past
2808
+ `offset + limit`; a page with residual conditions stops after the batch that holds its last
2809
+ match. A stream walking the primary key or an index
2810
+ holds one batch; a listed stream, an `any` or an index range read out of its index order,
2811
+ holds its sorted primary keys plus one batch. A direct stream applies a residual condition
2812
+ and page to each batch as it arrives, and only a residual order holds every match. The
2813
+ stream reads each batch at its own moment, so a row another write moves past the stream's
2814
+ position can appear twice or not at all. A stored value that is no record raises `DRIVER` with `context.code` `'RECORD'`
2815
+ from a read, `MIGRATION` inside `migrate()`, and the payload-safe metadata refusal from
2816
+ `open()` and `metadata()`; none of them carries the stored value.
2817
+ `IndexedDBDriver` implements `plan?` / `records?` / `aggregate?` / `stream?` / `migrate?` /
2818
+ `metadata?` / `stamp?` (persisted into a reserved `__metadata__` store, `METADATA_STORE` —
2412
2819
  `open()` throws `DatabaseError('VALIDATION')` if a declared table is
2413
2820
  literally named `__metadata__`), but omits `transaction?` (the underlying
2414
2821
  `IDBTransaction` auto-commits the moment control yields to a non-IDB
2415
- `await`) and `aggregate?` (IndexedDB has no native SUM/AVG/MIN/MAX) by
2416
- IndexedDB's own nature. A non-empty `migrate({ plan, metadata })` performs DDL,
2822
+ `await`) by IndexedDB's own nature. A non-empty `migrate({ plan, metadata })` performs DDL,
2417
2823
  row transformations, and the metadata write in the same versionchange
2418
2824
  transaction; a metadata-only input uses one ordinary `__metadata__` write
2419
- transaction. A failed upgrade reconnects the old deployed schema. Each point
2825
+ transaction. A failed upgrade reconnects the old deployed schema, pinned at the stored version
2826
+ when metadata is stored, so `migrate()` raises `MIGRATION` and leaves the driver usable. Each point
2420
2827
  `write` / `insert` / `delete` still uses one explicit
2421
2828
  wrapper `database.write(table, scope)` transaction: the signal aborts it only
2422
2829
  while active, a signal-driven rollback maps to `DatabaseError('ABORTED')`, and
2423
2830
  native transaction completion is the commit boundary a late abort cannot
2424
2831
  rewrite.
2425
- Every public `QueryInput` boundary also calls `validatePage`: `limit` and
2426
- `offset`, when present, must be finite nonnegative integers. Validation is
2427
- deterministic (`limit` before `offset`), non-finite diagnostics retain
2428
- `'NaN'` / `'Infinity'` rather than JSON-coercing to `null`, and zero is
2429
- legal. Return kind determines timing: `Query.limit` / `Query.offset` and
2430
- `AsyncIterable` factories (`Table.scan` and every direct driver `stream`)
2431
- throw synchronously, while Promise terminals (`Table.records` / `count` /
2432
- `aggregate` and native Promise hooks) return rejected promises. Every path
2433
- reports identical `VALIDATION` evidence and applies the same page predicate.
2434
- Failed query-builder validation does not mutate builder state. `count` and
2435
- `aggregate` validate paging even though valid paging remains intentionally
2436
- ignored by their unpaged semantics.
2832
+ A table checks paging inside the query door: `limit` and `offset`, when present, must be
2833
+ nonnegative integers, and zero is legal. Every table and query path refuses with one evidence
2834
+ shape, `VALIDATION` with `table` and `faults`, a fault at `['limit']` or `['offset']`.
2835
+ `Query.limit` and `Query.offset` refuse synchronously through the same door and leave the
2836
+ builder unchanged; `Table.records`, `count`, and `aggregate` return a rejected promise; and
2837
+ `Table.scan` raises at its first step. `count` and `aggregate` check paging even though their
2838
+ unpaged semantics ignore it. A driver's own hooks (`records`, `stream`, `aggregate`, and the
2839
+ SQL compilers) keep `validatePage`, whose `VALIDATION` context names the `field` and its
2840
+ `value`, rendering `NaN` and infinity as strings.
2437
2841
 
2438
2842
  ### IndexedDB planning
2439
2843
 
2440
- The pure planner behind `IndexedDBDriver`'s `plan` — useful directly to see which condition
2441
- a key range answers before a read touches a browser database:
2844
+ The pure planner behind `IndexedDBDriver`'s `plan` shows which access path a read takes
2845
+ before the read touches a browser database. When every connector is `and`, it ranks the
2846
+ paths the conditions admit by a fixed rule, because IndexedDB has no statistics and reads
2847
+ one index per read: primary-key `equals` or `any` first, then a compound index matched on
2848
+ two or more columns, then a single-column index with `equals` or `any` beside a compound index
2849
+ whose leading column alone an `equals` binds, then a range or `starts` on the primary key or
2850
+ an index. An index holds no entry for a row whose field is
2851
+ absent or `null`, so `below`, `to`, an order, `minimum`, and `maximum` read an index only
2852
+ for a column declared required. `any` reads one `get(keys)` on the primary key, or one
2853
+ `only` range per value on an index sorted into primary-key order, and its page reads the
2854
+ listed keys first and only the page's rows. When the access path and the order's path
2855
+ differ, the access path wins and the order sorts as residual:
2442
2856
 
2443
2857
  ```ts
2444
2858
  import type { Condition, TableSchema } from '@orkestrel/database'
2445
2859
  import { isKey } from '@orkestrel/database'
2446
2860
  import {
2447
2861
  conditionToRange,
2448
- deriveAccessPlan,
2449
2862
  deriveIndexedDBIndexName,
2450
- findAccessCondition,
2863
+ findAccessPlan,
2451
2864
  planIndexedDBQuery,
2452
2865
  } from '@orkestrel/database/browser'
2453
2866
 
@@ -2457,8 +2870,9 @@ const schema: TableSchema = {
2457
2870
  columns: [
2458
2871
  { name: 'id', storage: 'text', optional: false, nullable: false },
2459
2872
  { name: 'age', storage: 'integer', optional: false, nullable: false },
2873
+ { name: 'city', storage: 'text', optional: true, nullable: false },
2460
2874
  ],
2461
- indexes: [['age']],
2875
+ indexes: [['age'], ['city']],
2462
2876
  }
2463
2877
 
2464
2878
  isKey('u1') // true — a string is a usable IndexedDB key
@@ -2473,15 +2887,21 @@ const equalsAge: Condition = {
2473
2887
  }
2474
2888
  conditionToRange(equalsAge) // an IDBKeyRange.only(30) — an exact comparison operator
2475
2889
 
2476
- // No condition narrows, so the plan reads the whole store and leaves the read residual:
2477
- planIndexedDBQuery({}, schema, ['age']) // { native: {}, residual: {} }
2890
+ // No condition narrows, so the plan reads the whole store; the page is native:
2891
+ planIndexedDBQuery({ limit: 10 }, schema, ['age', 'city']) // { native: { limit: 10 }, residual: {} }
2478
2892
 
2479
- // A comparison over the indexed `age` column stays native as that index's range:
2893
+ // A range over the required `age` index is the access path, and it serves an order on age:
2480
2894
  const fromAge: Condition = { column: 'age', operator: 'from', values: [18], connector: 'and' }
2481
- planIndexedDBQuery({ conditions: [fromAge], limit: 10 }, schema, ['age'])
2482
- // { native: { conditions: [fromAge] }, residual: { limit: 10 } }
2483
- deriveAccessPlan(findAccessCondition({ conditions: [fromAge] }, schema, ['age']), schema)
2484
- // { index: 'age', range: an IDBKeyRange bounding age >= 18 }
2895
+ const byAge = [{ column: 'age', direction: 'descending' as const }]
2896
+ planIndexedDBQuery({ conditions: [fromAge], order: byAge, limit: 10 }, schema, ['age', 'city'])
2897
+ // { native: { conditions: [fromAge], order: byAge, limit: 10 }, residual: {} }
2898
+
2899
+ // `below` on the optional `city` column would miss rows without a city, so it stays residual:
2900
+ const belowCity: Condition = { column: 'city', operator: 'below', values: ['m'], connector: 'and' }
2901
+ planIndexedDBQuery({ conditions: [belowCity] }, schema, ['age', 'city'])
2902
+ // { native: {}, residual: { conditions: [belowCity] } }
2903
+ findAccessPlan({ conditions: [fromAge] }, schema, ['age', 'city'])
2904
+ // { conditions: [fromAge], columns: ['age'], prefix: 0, index: 'age', range: an IDBKeyRange bounding age >= 18 }
2485
2905
  ```
2486
2906
 
2487
2907
  ### IndexedDB error mapping
@@ -2497,15 +2917,15 @@ import { mapIndexedDBError, mapMigrationError } from '@orkestrel/database/browse
2497
2917
  declare const fault: IndexedDBError // a caught backend fault
2498
2918
 
2499
2919
  mapIndexedDBError(fault) // → DatabaseError('CONFLICT' | 'CLOSED' | 'DRIVER', ...)
2500
- mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATION'
2920
+ mapMigrationError(fault) // → the same, but an UPGRADE or a RECORD fault becomes 'MIGRATION'
2501
2921
  ```
2502
2922
 
2503
2923
  ### Practices
2504
2924
 
2505
2925
  - **Declare tables in `createDatabase({ tables })` and hold the handles** —
2506
2926
  `const users = db.table('users')`; reuse them rather than re-resolving.
2507
- - **Writes admit whole, reads narrow.** At an unknown-input boundary, admit
2508
- loose data (`'41'`) through `admitValue(table.contract, input)` and write
2927
+ - **Writes admit whole, reads narrow.** At an unknown-input boundary, repair
2928
+ loose data (`'41'`) through `repairValue(table.contract, input)` and write
2509
2929
  its value; a refusal carries the faults to report. Trust `get` / `records`
2510
2930
  to return the row type.
2511
2931
  - **Use `resolve` when absence is an error**, `get` when it is expected —
@@ -2527,7 +2947,39 @@ mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATIO
2527
2947
  - **Use `MemoryDriver` for tests and ephemeral data** — no I/O, and
2528
2948
  `JSONDriver` swaps in unchanged when writes need to survive a restart.
2529
2949
 
2530
- ## Migrating from 0.0.23
2950
+ ## Migrating from 0.0.24
2951
+
2952
+ The coverage wave changes these exports and behaviors; each consumer changes in the release
2953
+ that adopts it. A name in this section that the package no longer exports is written plain.
2954
+
2955
+ | 0.0.24 | This release |
2956
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2957
+ | DriverInterface.snapshot, on `MemoryDriver`, `JSONDriver`, `SQLiteDriver`, and `IndexedDBDriver` | Removed; a scope on a driver without `transaction?` runs through `StorageJournal`, and a custom driver drops the member |
2958
+ | A custom `StorageInterface` with single-key `read`, `write`, `insert`, and `delete` | Each member adds its list overload: `read(table, keys)`, `write(table, keys, rows, options?)`, `insert(table, keys, rows, options?)`, and `delete(table, keys, options?)`, each one call that applies every row or none |
2959
+ | A `Table` batch (`set`, `add`, `update`, `remove` of a list) that kept the rows ahead of a failure | The batch applies no row; a caller that relied on the earlier rows writes them as their own batch |
2960
+ | An abort between the items of a batch | The signal is checked at entry and at the driver's commit point; an abort ahead of the commit applies no row |
2961
+ | `Table.remove(keys)` answering one boolean per key | One boolean, true only when every distinct listed key held a row and was removed, a repeated key counting as one; `has(keys)` keeps one answer per key |
2962
+ | A read naming an undeclared column in a condition, an ordering term, or the aggregate, an unknown operator, connector, or direction, a wrong arity, an empty or non-string column path, or an operand of another storage class, answered with 0 or every row | `VALIDATION` with `table` and every fault, raised before any driver call; a caller corrects the read |
2963
+ | A fractional or negative `limit` or `offset` refused without `table` | The door refuses it with `VALIDATION` and `table`, and `scan` raises at its first step instead of at the call |
2964
+ | A non-string operand of `like`, `glob`, `starts`, or `ends`, or a `null` read, matching no row | `VALIDATION` |
2965
+ | An unknown aggregate operation answering a maximum, or a missing column raising a raw `TypeError` | `VALIDATION` naming `aggregate.operation` or `aggregate.column` |
2966
+ | `null` on a column that is not nullable, `undefined` on one that is not optional, or either under a range operator, matching no row | `VALIDATION`; read absence with `absent` or `present` |
2967
+ | A lone surrogate in a `text` value, a key, or a text operand, stored by SQLite as U+FFFD | `VALIDATION` with `table` and `column` on every driver |
2968
+ | A `literalShape` column whose members span more than one class, stored as `text` | `json` storage, as a union is |
2969
+ | findAccessCondition(input, schema, indexes) and deriveAccessPlan(condition, schema) | `findAccessPlan(input, schema, indexes)`, which returns the ranked `AccessPlan`: its `conditions`, `columns`, `prefix`, and `index`, `range`, or `keys` |
2970
+ | `AccessPlan` as `{ index?, range? }` | `{ conditions, columns, prefix, index?, range?, keys? }`; `{}` as a whole-store read is `{ conditions: [], columns: [primary], prefix: 0 }` |
2971
+ | `IndexedDBDriver` answering one condition natively and reading every candidate row for an order, a page, or a count | It ranks one access path, serves the order, page, `count`, `minimum`, and `maximum` that path serves, declares `aggregate?`, and streams in batches of `STREAM_BATCH_SIZE` |
2972
+ | An undeclared index surviving `IndexedDBDriver.open()` | `open()` drops it on a connection at the next version; a concurrent bump raises `DRIVER` with `context.retryable` |
2973
+ | A stored IndexedDB value that is no record | A read raises `DRIVER` with `context.code` `'RECORD'`; `migrate()` raises `MIGRATION`; the metadata record raises the metadata-invalid refusal |
2974
+ | A transaction on `MemoryDriver` or `IndexedDBDriver` that copied the whole store | The journal reads and restores only the keys the scope touched, and a `clear` journals its table alone |
2975
+ | `createSQLiteDriver` returning `DriverInterface` | It returns `SQLiteDriverInterface`, which adds the `pragma` method; `SQLiteDriver` implements it |
2976
+ | A SQLite scope, list write, and `migrate` opening with a deferred `BEGIN` | Each opens with `BEGIN IMMEDIATE`; a contended scope is refused at its start, before its callback runs |
2977
+ | A writable SQLite file keeping the engine's journal mode | It opens under `journal_mode = WAL` unless `pragmas` names `journal_mode`; a `':memory:'` database and a `readonly` open keep theirs |
2978
+ | A SQLite open that analyzed nothing | A writable open runs `PRAGMA optimize = 0x10002` after its schema transaction; the `close` method runs nothing |
2979
+ | An index created on a deployed SQLite table and no longer declared, kept at open | A writable open drops it; a `readonly` open drops nothing |
2980
+ | A `pragmas` value that is any finite number | A value is a 32-bit signed integer or a bare keyword, through `isPragmaValue` |
2981
+ | An integer `sum` past 2^53 on SQLite raising `DRIVER` | `sum` compiles to `TOTAL`, the engine's float sum, with `undefined` over no value |
2982
+ | An order on a SQLite column that is both optional and nullable, and the equality family on a nested path, read by the core | The order is native behind a rank term, and the equality family with scalar operands under a `json` head is a prefilter the core rechecks |
2531
2983
 
2532
2984
  The paging wave changes these exports and behaviors; under the no-shim law, each consumer
2533
2985
  changes in the release that adopts it. A name in this section that the package no longer
@@ -2539,7 +2991,7 @@ exports is written plain, without code formatting.
2539
2991
  | `compileQuerySQL(input, schema)` | Same name and signature; pass it `planSQLiteQuery(input, schema).native`. Its SQL changes: `starts` compiles to an index range, `any` and `none` bind one `json_each` parameter, every condition beside an `any` on the primary key is pinned behind unary `+`, and the primary-key tie term carries the final order term's direction |
2540
2992
  | matchesConditionExactly | `matchesSQLiteCondition(condition, schema)` |
2541
2993
  | matchesOrderExactly, matchesAggregateExactly, EXACT_COLUMN_STORAGE, EXACT_RANGE_COLUMN_STORAGE | Removed; `planSQLiteQuery` answers each question |
2542
- | selectPlan(input, schema, indexes) | `deriveAccessPlan(findAccessCondition(input, schema, indexes), schema)` for the key-range read, and `planIndexedDBQuery(input, schema, indexes)` for the split |
2994
+ | selectPlan(input, schema, indexes) | `findAccessPlan(input, schema, indexes)` for the access path, and `planIndexedDBQuery(input, schema, indexes)` for the split |
2543
2995
  | QueryPlan | `AccessPlan` |
2544
2996
  | `MemoryDriver.stream`, `JSONDriver.stream` | Removed; call `Table.scan`, or `streamPlannedRows` over the driver |
2545
2997
  | `matchesWildcardSegment(value: string, segment: string, …)` | `matchesWildcardSegment(value: readonly string[], segment: readonly string[], …)`, over code points |
@@ -2548,7 +3000,7 @@ exports is written plain, without code formatting.
2548
3000
  | A read that skipped a nonconforming stored row | `get`, `records`, and `scan` raise `DRIVER` with `table`, `key`, and `faults` |
2549
3001
  | `count` skipping a nonconforming stored row | `count` is `aggregate('count')`: it counts every stored row its conditions match, a nonconforming row included, and raises nothing, because it returns no row |
2550
3002
  | A driver with `records`, `stream`, or `aggregate` and no `plan` | The core never calls those hooks and reads the driver over `scan`; a custom driver adds `plan` to keep its pushdown |
2551
- | Any `pragmas` entry on `createSQLiteDriver` | Each name must be one of `PRAGMA_NAMES`, matched exactly, and each value a finite number or a bare keyword; anything else throws `VALIDATION` from `validatePragmas` |
3003
+ | Any `pragmas` entry on `createSQLiteDriver` | Each name must pass `isPragmaName` and be one of `PRAGMA_NAMES`, matched exactly, and each value must pass `isPragmaValue`; anything else throws `VALIDATION` at construction |
2552
3004
  | `compileConditionSQL` and `compileQuerySQL` leaving `equals` / `not` with `undefined`, and lists holding `null` or `undefined`, to the core | Each compiles natively: `undefined` to `IS NULL` / `IS NOT NULL` on a column that stores absence, and a list to `IN (…)` joined with the null and absence tests its flags define, the `none` complement included |
2553
3005
 
2554
3006
  The paging wave added names that its review then renamed or folded before release:
@@ -2563,31 +3015,42 @@ to `Scalar`.
2563
3015
  ## Tests
2564
3016
 
2565
3017
  - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ compiler-resolved public-entry bijection across `src/core`, `src/server`, and `src/browser`, including fail-closed temporary-project coverage for barrel resolution and unsupported exports, each interface ↔ implementing-class method bijection, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Create a database` fence against the `@example` block of that title (pinned so the titled pair cannot be retired silently), and the README pitch against this guide's tagline. It also compiles every TypeScript fence against the published entry specifiers and runs the flagship fences, asserting the values their comments claim.
2566
- - [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — `cloneDriverMetadata` ownership: normalized deeply frozen distinct output, caller-mutation isolation, and `VALIDATION` translation for malformed, cyclic, functional, accessor, and hostile/revoked-proxy inputs without leaking raw Contract or caller errors.
3018
+ - [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — `cloneDriverMetadata` ownership: normalized deeply frozen distinct output, caller-mutation isolation, and `VALIDATION` translation for malformed, cyclic, functional, accessor, and unexpected/revoked-proxy inputs without leaking raw Contract or caller errors; `normalizeDriverSchema`'s sorted, deeply frozen canonical snapshot and its `VALIDATION` refusal.
3019
+ - [`tests/src/core/compilers.test.ts`](../tests/src/core/compilers.test.ts) — `planMigration`'s step order and its `MIGRATION` throw on a shared column's storage/nullability drift, and `projectMigrationSchema`'s sequential projection.
2567
3020
  - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — total boundary guards for keys, columns, tables, driver schemas, migrations, inputs, and metadata.
2568
- - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the query engine: `validatePage`'s strict page matrix, deterministic field order, exact non-finite diagnostics, and legal zero; `findColumn`'s flat-column lookup and its `undefined` miss; `resolvePrimary`'s declared-or-default key and `requireColumns`'s typed map lookup with its `NOT_FOUND` throw; `compareValues` total order, every `matchesCondition` operator (the equality family — `equals` / `not` / `any` / `none` — through `equalsValue`, including `NaN`-equals-`NaN`; the range family through `compareValues`), `matchesQuery` folding, `filterRows`, `sortRows`, `applyQuery`, `computeAggregate`, `extractKey`, `shapeToColumnStorage`'s shape → portable-type mapping (scalars, `json` for object/array/union/raw, optional/nullable unwrap, literal-by-values), total `isDriverMetadata` rejection of malformed and hostile getter/proxy input, `equalsValue`'s structural equality, `planMigration`'s `MIGRATION` throw on a shared column's storage/nullability drift, and the `scanDriver` / `conformDriver` / `auditDriver` battery against `MemoryDriver` and a deliberately-broken driver (each check fails with a `CONFORMANCE` `DatabaseError`), including the deepened `write-read` nested-field checks and the `snapshot-nested` phase (a shallow-copying driver fails it).
2569
- - [`tests/src/core/drivers/MemoryDriver.test.ts`](../tests/src/core/drivers/MemoryDriver.test.ts) — the driver primitive: `open(schema)` readies tables, read/write/atomic-insert/delete/keys/scan/clear + `snapshot` rollback, duplicate-insert `CONFLICT`, non-JSON row isolation through native `structuredClone`, metadata stamp/migrate/copy-out ownership through `cloneDriverMetadata`, strict stream paging, and pre-aborted point mutations rejecting `ABORTED` without changing rows.
3021
+ - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the query engine: `validatePage`'s strict page matrix, deterministic field order, exact non-finite diagnostics, and legal zero; `findColumn`'s flat-column lookup and its `undefined` miss; `resolvePrimary`'s declared-or-default key and `requireColumns`'s typed map lookup with its `NOT_FOUND` throw; `compareValues` total order, every `matchesCondition` operator (the equality family — `equals` / `not` / `any` / `none` — through `equalsValue`, including `NaN`-equals-`NaN`; the range family through `compareValues`), `matchesQuery` folding, `filterRows`, `sortRows`, `applyQuery`, `computeAggregate`, `extractKey`, `shapeToColumnStorage`'s shape → portable-type mapping (scalars, `json` for object/array/union/raw, optional/nullable unwrap, literal-by-values), total `isDriverMetadata` rejection of malformed and unexpected getter/proxy input, `equalsValue`'s structural equality, and the `scanDriver` / `conformDriver` / `auditDriver` battery against `MemoryDriver` and a deliberately-broken driver (each check fails with a `CONFORMANCE` `DatabaseError`), including the deepened `write-read` nested-field checks, the journal phase (a shallow-copying driver fails it), and the batch phase (a per-row list insert fails it); `buildBatch`'s pairing and refusals and `computeRemoved`'s first-occurrence rule.
3022
+ - [`tests/src/core/drivers/MemoryDriver.test.ts`](../tests/src/core/drivers/MemoryDriver.test.ts) — the driver primitive: `open(schema)` readies tables, read/write/atomic-insert/delete/keys/scan/clear, list reads in key order, list writes and inserts that apply every row or none, list deletes that report each key once, duplicate-insert `CONFLICT`, non-JSON row isolation through native `structuredClone`, metadata stamp/migrate/copy-out ownership through `cloneDriverMetadata`, strict stream paging, and pre-aborted point mutations rejecting `ABORTED` without changing rows.
2570
3023
  - [`tests/src/core/Database.test.ts`](../tests/src/core/Database.test.ts) — declared tables, lazy connect, typed CRUD, custom keys, indexes, import/export, and callback transactions: whole accepted-operation drain, synchronous-throw and asynchronous-rejection reason identity, caught-operation rejection still rolling back, callback-over-drain error precedence, root/import/lifecycle/nesting barriers, stale scoped table/query/cursor/stream invalidation, and truthful successful-rollback-only events. It also covers explicit migration and versioned open: deployed-schema-first reconciliation, fresh stamp, same-version no-op, atomic upgrade input, higher-version rejection, paired-hook enforcement (metadata-only and stamp-only are inert), and migrate-event behavior.
2571
3024
  - [`tests/src/core/ScopedIterator.test.ts`](../tests/src/core/ScopedIterator.test.ts) — direct internal continuation-lifetime coverage: tracked `next` / `return` / `throw`, the readiness thunk running before every advance and its failure preempting the source, synchronous source throws, missing methods, concurrent accepted continuations, idle iterators, late conflicts, and exactly-once rejected cleanup.
2572
3025
  - [`tests/src/core/DriverIterator.test.ts`](../tests/src/core/DriverIterator.test.ts) — direct root-driver continuation coverage: pre/post-read guards, produced-row discard, terminalization, return races, missing methods, throw delegation, and exactly-once cleanup.
2573
- - [`tests/src/core/Table.test.ts`](../tests/src/core/Table.test.ts) — `Table`'s keyed CRUD + batch overloads, payload-safe bounded contract diagnostics, strict paging at every read boundary, whole-row admission with its lossless repairs, its undeclared, missing, and lossy refusals, and the raw-column nested-key admission, `add` dispatch through atomic `insert` (including concurrent duplicate claims), sequential partial-batch abort semantics, and the emitter's post-commit and no-aborted-event behavior.
3026
+ - [`tests/src/core/Table.test.ts`](../tests/src/core/Table.test.ts) — `Table`'s keyed CRUD + batch overloads, payload-safe bounded contract diagnostics, strict paging at every read boundary, whole-row admission with its refusals of a mistyped value (a numeric string included), an undeclared column, a missing column, and two faults at once, each fault named in the message, and the raw-column nested-key admission, `add` dispatch through atomic `insert` (including concurrent duplicate claims), one driver call per batch read through a `StorageRecorder`, batches that apply every row or none, a list `remove` that answers true only when every distinct listed key held a row and was removed, a repeated key counting as one (a transaction view included), empty lists that answer and touch no row, and the emitter's post-commit and no-aborted-event behavior. The query door: every refusal class through `records`, `count`, `aggregate`, `scan`, and each `query()` terminal with no driver call, the reads admitted at each class's edge, and a lone surrogate refused in a written `text` value and a key.
2574
3027
  - [`tests/src/core/Query.test.ts`](../tests/src/core/Query.test.ts) — `Query`'s where / and / or dispatch, ordering, synchronous strict page builders with no failed mutation, legal zero, `filter`, and aggregates.
3028
+ - [`tests/src/core/contracts.test.ts`](../tests/src/core/contracts.test.ts) — `queryInputContract`: each operator's arity on both sides, the operator candidates of an unknown operator, the column forms, and the closed object.
3029
+ - [`tests/src/core/StorageRecorder.test.ts`](../tests/src/core/StorageRecorder.test.ts) — the recorder over real drivers: rows returned and yielded per member, scoped calls inside a native transaction, the members it declares, a rejected call and an unpulled stream each counted as invoked, and a stream abandoned early or failing part way.
3030
+ - [`tests/src/core/RecordedStorage.test.ts`](../tests/src/core/RecordedStorage.test.ts) — each call reported as it is invoked with its keys and rows, a rejected call and an unpulled scan counted, each keyed call forwarded in its received form, and a scan that throws part way.
3031
+ - [`tests/src/core/Table.bench.ts`](../tests/src/core/Table.bench.ts) — the point read on a held table and through `database.table(name)`, a scope with one read, and the door on a ten-condition count, beside a published build that `DATABASE_BASELINE` names; `npm run test:bench` runs it and no gate does.
3032
+ - [`tests/src/core/StorageJournal.test.ts`](../tests/src/core/StorageJournal.test.ts) — the before-image journal over a real `MemoryDriver`: restore of updated, inserted, and deleted keys, one list read per call and one restore call per kind, no call when nothing was recorded, and the adverse orderings (unawaited writes to one key, a write on each side of a `clear`, a table cleared alone, a failed prior read that records nothing so a later write records its prior row, a delayed prior read that a later write to the same key waits on, a mismatched batch).
3033
+ - [`tests/src/core/ScopedStorage.test.ts`](../tests/src/core/ScopedStorage.test.ts) — the scoped-storage lifetime boundary: forwarding of each member's single and list forms, refusal of every member once the guard throws, and a scan advance refused after the scope settles.
2575
3034
  - [`tests/src/core/Cursor.test.ts`](../tests/src/core/Cursor.test.ts) — cursor behavior over a key snapshot: `value` / `index` / `done`, serialized overlapping `next` / `update` / `remove`, rejection recovery, synchronous runner admission, terminal close before queued work and during dispatched reads/mutations, plus transaction-ledger regressions for deleted-key skipping, unawaited normalized updates, validation rollback, and retained closed/active conflicts.
2576
3035
  - [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — `createDatabase` / `createMemoryDriver` each return a working instance of their interface (a round-trip end to end).
2577
3036
  - [`tests/src/core/TransactionScope.test.ts`](../tests/src/core/TransactionScope.test.ts) — direct transaction-lifetime coverage: `accepting` and the `check` refusal, synchronous admission through `track`, a synchronous operation throw captured as a rejection, unawaited work contained by `drain`, the drain loop re-reading work another tracked operation admitted, first-failure identity preserved across repeated drains, and `stream`'s per-continuation boundary leaving an idle iterator unpinned.
2578
3037
  - [`tests/src/core/DatabaseContext.test.ts`](../tests/src/core/DatabaseContext.test.ts) — direct shared-context coverage: `register`'s identical-schema merge, its `VALIDATION` conflict, and its `CONFLICT` / `CLOSED` refusals; idle → open → closed transitions emitted once with one shared readiness promise; root admission, its transaction-time `CONFLICT`, and close-time drain; transaction commit / rollback events and value or error propagation, nested-transaction refusal, entry-only signal checking, and a fresh `TransactionScope` per attempt; explicit migration's missing-hook and post-open refusals; and versioned reconciliation's fresh stamp, newer-store rejection, differing-schema rejection, and same-version no-op.
2579
3038
  - [`tests/src/core/DatabaseTransaction.test.ts`](../tests/src/core/DatabaseTransaction.test.ts) — direct transaction-view coverage: the typed table `table()` builds over the scoped driver, its writes landing straight on that driver, the scope `CONFLICT` after settlement, the `NOT_FOUND` refusal for an undeclared table, a per-table primary override, a scoped table refusing work started after settlement, and the configured generator minting a key for a keyless write.
2580
3039
  - [`tests/src/server/factories.test.ts`](../tests/src/server/factories.test.ts) — `createJSONDriver` / `createSQLiteDriver` each return a working `DriverInterface` instance (a round-trip end to end), drive the core `createDatabase` stack, and persist across a reopen; `createSQLiteDriver` requires a path and opens an in-memory database only with `path: ':memory:'`.
2581
- - [`tests/src/server/drivers/JSONDriver.test.ts`](../tests/src/server/drivers/JSONDriver.test.ts) — `JSONDriver` persistence plus atomic insert and the exclusive point-mutation queue: queued abort/no late start, active staging restoration, cleanup-success error precedence, deterministic real-filesystem persistence-plus-cleanup dual failure with exact evidence and queue recovery, read isolation, concurrent-writer ordering, fail-closed real-filesystem coverage for non-absence reads, invalid syntax/documents/table sets/containers/rows/metadata, byte preservation, no partial publication, application-invalid row retention, payload-safe rejection, strict stream paging, and same-instance external-repair retry; synchronous root/scoped stamp and migration ownership, deeply frozen distinct copy-out, deployed-schema-first open, isolated callback/root-migration candidates whose rows/schema/metadata publish only after file replacement succeeds, transaction-time root scan/stream continuation conflicts with terminal cleanup, and post-native-rollback rejection replacement.
2582
- - [`tests/src/server/drivers/SQLiteDriver.test.ts`](../tests/src/server/drivers/SQLiteDriver.test.ts) — `SQLiteDriver`'s native surface: deployed-metadata-first open and reconciliation; fail-closed malformed metadata, physical schema disagreement, and persisted-table loss before DDL, including deterministic first-loss evidence, physical non-recreation, external repair, and same-driver retry; root/scoped stamp/migration ownership and distinct deeply frozen copy-out; atomic insert/duplicate `CONFLICT`; point-mutation abort boundaries; strict direct records/aggregate/stream paging; native planned query and aggregate paths, the paging readings, the operator matrix, and `EXPLAIN QUERY PLAN` of the native plan; repeatable schema-aware snapshot capture/replay plus real dropped-table and exclusive-lock failure containment/recovery; atomic `MigrationInput` schema/rows/metadata at the root; fixed-literal savepoint containment for a caught migration failure while its callback transaction remains active; candidate-schema publication only after commit; callback transaction barriers/invalidation including root continuation cleanup; payload-safe rejection; post-native-rollback rejection replacement; backend-fault mapping; and engine parity.
3040
+ - [`tests/src/server/drivers/JSONDriver.test.ts`](../tests/src/server/drivers/JSONDriver.test.ts) — `JSONDriver` persistence plus atomic insert and the exclusive point-mutation queue: an empty list that leaves the file in place, a failed clear flush that leaves every row in memory, queued abort/no late start, active staging restoration, cleanup-success error precedence, deterministic real-filesystem persistence-plus-cleanup dual failure with exact evidence and queue recovery, read isolation, concurrent-writer ordering, fail-closed real-filesystem coverage for non-absence reads, invalid syntax/documents/table sets/containers/rows/metadata, byte preservation, no partial publication, application-invalid row retention, payload-safe rejection, strict stream paging, and same-instance external-repair retry; synchronous root/scoped stamp and migration ownership, deeply frozen distinct copy-out, deployed-schema-first open, isolated callback/root-migration candidates whose rows/schema/metadata publish only after file replacement succeeds, transaction-time root scan/stream continuation conflicts with terminal cleanup, and post-native-rollback rejection replacement.
3041
+ - [`tests/src/server/drivers/SQLiteDriver.test.ts`](../tests/src/server/drivers/SQLiteDriver.test.ts) — `SQLiteDriver`'s native surface: deployed-metadata-first open and reconciliation; fail-closed malformed metadata, physical schema disagreement, and persisted-table loss before DDL, including deterministic first-loss evidence, physical non-recreation, external repair, and same-driver retry; root/scoped stamp/migration ownership and distinct deeply frozen copy-out; atomic insert/duplicate `CONFLICT`; point-mutation abort boundaries; strict direct records/aggregate/stream paging; native planned query and aggregate paths, the paging readings, the operator matrix, and `EXPLAIN QUERY PLAN` of the native plan; list reads and deletes as one statement, a conflicting batch that applies no row outside a scope and rolls back to its savepoint inside one, and one commit per batch read through the file change counter under a rollback journal; atomic `MigrationInput` schema/rows/metadata at the root; fixed-literal savepoint containment for a caught migration failure while its callback transaction remains active; candidate-schema publication only after commit; callback transaction barriers/invalidation including root continuation cleanup; payload-safe rejection; post-native-rollback rejection replacement; backend-fault mapping, `SQLITE_LOCKED` without `retryable` included; the rows-read tripwire `plantTripwire` plants beyond each page; `BEGIN IMMEDIATE` across two drivers on one thread and against a worker-thread holder under a `timeout`; the WAL default; statistics at a writable open; `pragma` and its name door; the index reconcile at open; native orders on a column with both flags; the nested-path prefilters per operator and scalar class; an integer `sum` as `TOTAL`; and engine parity.
3042
+ - [`tests/src/server/SQLiteConnection.test.ts`](../tests/src/server/SQLiteConnection.test.ts) — the per-connection statement cache: one cached statement per text, least-recently-used eviction past `STATEMENT_LIMIT` with a text used since kept.
3043
+ - [`tests/src/server/drivers/SQLiteDriver.bench.ts`](../tests/src/server/drivers/SQLiteDriver.bench.ts) — run by `npm run test:bench`, outside every gate: the point read, a 100-key list, an `any` of 100 keys beside a tenant, a page, a count, and a 100-row batch through `Table` beside the wrapper alone, on 80646 narrow and mixed rows.
2583
3044
  - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) — the SQLite bridge: `quoteIdentifier`, codecs, row extraction, `deriveSQLiteIndexName` exact bytes, the planner `planSQLiteQuery` and its `matchesSQLiteCondition` / `computeSuccessor` predicates, `validatePragmas`, strict decode, and `matchesSQLiteAffinity`.
2584
3045
  - [`tests/src/server/compilers.test.ts`](../tests/src/server/compilers.test.ts) — the coherent SQL-emitter cluster: column/field/aggregate compilation, table/index/migration DDL, and the strict-page `QueryInput` → SQL pipeline with exact statements and parameters.
2585
- - [`tests/src/server/inferers.test.ts`](../tests/src/server/inferers.test.ts) — `inferValueStorage`'s nested-operand storage inference: the `ColumnStorage` a `json_extract` operand must encode as, over booleans, integral and fractional numbers, bigints, objects and arrays, strings, `null`, and `undefined`.
2586
- - [`tests/src/server/integration.test.ts`](../tests/src/server/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `SQLiteDriver` (native and residual reads) produce identical rows/counts/aggregates, and the text-order exemption names the ids SQLite returns under its binary order.
2587
- - [`tests/src/browser/drivers/IndexedDBDriver.test.ts`](../tests/src/browser/drivers/IndexedDBDriver.test.ts) — `IndexedDBDriver` against real IndexedDB: metadata-only bootstrap and deployed-schema-first reopen, one-transaction `has`/`get` absence discrimination, fail-closed malformed-metadata preservation (including stored `undefined`) and persisted-store loss with deterministic first-loss evidence, physical non-recreation, extra-store retention, external repair, and same-driver retry; bootstrap-lifetime store/version capture and a competing versionchange proving the persisted final open is pinned and retryable; payload-safe errors and table rejection, closed failed state, reserved-store validation, atomic `add` insertion and duplicate `CONFLICT`, active/pre-dispatch/late abort boundaries, strict direct records/stream paging, the plan, the rows read per conformance read against 0.0.23, snapshot capture-replay, schema/rows/metadata in one versionchange migration, metadata-only migration input, failed-upgrade reconnection to the old schema, metadata persistence, backend-fault mapping, and confirmation that callback `transaction` / native `aggregate` are absent.
2588
- - [`tests/src/browser/helpers.test.ts`](../tests/src/browser/helpers.test.ts) — the planner: `conditionToRange` over every comparison operator, `findAccessCondition` / `deriveAccessPlan` index and primary selection, `planIndexedDBQuery`, backend-error mapping, and exact `deriveIndexedDBIndexName` bytes.
3046
+ - [`tests/src/server/inferers.test.ts`](../tests/src/server/inferers.test.ts) — `inferValueStorage`'s nested-operand storage inference: the `ColumnStorage` a `json_extract` operand must encode as, over booleans, integral and fractional numbers, bigints, objects and arrays, strings, `null`, and `undefined`; and `inferSentinelType`'s class per storage, read against a declared table and through the `encodeValue` and `decodeValue` sentinel round trip.
3047
+ - [`tests/src/server/integration.test.ts`](../tests/src/server/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `SQLiteDriver` (native and residual reads) produce identical rows/counts/aggregates, and the text-order exemption names the ids SQLite returns under its binary order. Each wrong-class read in its refused-parity table raises the same `VALIDATION` refusal on both engines.
3048
+ - [`tests/src/browser/drivers/IndexedDBDriver.test.ts`](../tests/src/browser/drivers/IndexedDBDriver.test.ts) — `IndexedDBDriver` against real IndexedDB: metadata-only bootstrap and deployed-schema-first reopen, one-transaction `has`/`get` absence discrimination, fail-closed malformed-metadata preservation (including stored `undefined`) and persisted-store loss with deterministic first-loss evidence, physical non-recreation, extra-store retention, external repair, and same-driver retry; bootstrap-lifetime store/version capture and a competing versionchange proving the persisted final open is pinned and retryable; payload-safe errors and table rejection, closed failed state, reserved-store validation, atomic `add` insertion and duplicate `CONFLICT`, active/pre-dispatch/late abort boundaries, strict direct records/stream paging, the plan, the rows read per conformance read, list reads, inserts, and deletes in one transaction each, a journal scope whose native reads see its writes, schema/rows/metadata in one versionchange migration, metadata-only migration input, failed-upgrade reconnection to the old schema, metadata persistence, backend-fault mapping, confirmation that callback `transaction` is absent, a tripwire beyond each plan class's bound that the read never reaches, the differential of every plan class against the core engine, native counts and index extremes that return no row, streams that read one batch at a time, no index entry for a row missing its field, the index reconcile at open with its retryable concurrent bump, and `DRIVER` for a stored non-record.
3049
+ - [`tests/src/browser/drivers/IndexedDBDriver.bench.ts`](../tests/src/browser/drivers/IndexedDBDriver.bench.ts) — a bench no gate collects: the key-list, `any`, ordered page, `equals` page, `any` count, `equals` count, and batch cells over one client-shaped store, each beside the wrapper alone; run it with `vitest bench --config vite.config.ts --project src:browser --mode benchmark`.
3050
+ - [`tests/src/browser/IndexedDBBatchIterator.test.ts`](../tests/src/browser/IndexedDBBatchIterator.test.ts) — `IndexedDBBatchIterator` over a real store: each batch resumes from the position the previous batch reports, a short batch ends the stream, and an empty batch ends it too.
3051
+ - [`tests/src/browser/helpers.test.ts`](../tests/src/browser/helpers.test.ts) — the planner: `conditionToRange` over every comparison operator and `starts`, `findAccessPlan` ranking and its required-column rule, `deriveConditionPlan`, `deriveCompoundPlan`, `buildCompoundRange`, `rankAccessPlan`, `deriveOrderPlan`, `matchesAccessOrder`, `narrowRange`, `planIndexedDBQuery`, backend-error mapping with `RECORD`, and exact `deriveIndexedDBIndexName` bytes.
2589
3052
  - [`tests/src/browser/factories.test.ts`](../tests/src/browser/factories.test.ts) — `createIndexedDBDriver` returns a working `DriverInterface` instance (a round-trip end to end).
2590
- - [`tests/src/browser/integration.test.ts`](../tests/src/browser/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `IndexedDBDriver` produce identical rows/counts, including pushdown edge cases (`below`/`to` on a secondary-indexed column, a reversed `between`).
3053
+ - [`tests/src/browser/integration.test.ts`](../tests/src/browser/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `IndexedDBDriver` produce identical rows/counts, including pushdown edge cases (`below`/`to` on a secondary-indexed column, a reversed `between`). Each wrong-class read in its refused-parity table raises the same `VALIDATION` refusal on both engines.
2591
3054
 
2592
3055
  ## See also
2593
3056