@orkestrel/scaffold 0.0.134 → 0.0.136

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 (53) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +777 -83
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +327 -21
  3. package/dist/bin/main.js +254 -36
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/AGENTS.md +2 -2
  6. package/dist/host/agents/orchestration.md +2 -2
  7. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +983 -123
  9. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  10. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +22 -5
  11. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +403 -32
  12. package/dist/host/claude/agents/orkestrel.md +17 -17
  13. package/dist/host/claude/agents/reviewer.md +1 -1
  14. package/dist/host/claude/rules/architecture.md +1 -1
  15. package/dist/host/claude/rules/documentation.md +1 -1
  16. package/dist/host/claude/rules/patterns.md +4 -2
  17. package/dist/host/claude/rules/workspace.md +73 -67
  18. package/dist/host/configs/helpers.ts +109 -73
  19. package/dist/host/dotfiles/oxlintrc.json +1 -57
  20. package/dist/host/guides/agent.md +989 -395
  21. package/dist/host/guides/contract.md +198 -163
  22. package/dist/host/guides/database.md +978 -503
  23. package/dist/host/guides/indexeddb.md +80 -66
  24. package/dist/host/guides/middleware.md +5 -5
  25. package/dist/host/guides/ollama.md +41 -42
  26. package/dist/host/guides/relation.md +56 -32
  27. package/dist/host/guides/scaffold.md +185 -107
  28. package/dist/host/guides/sqlite.md +44 -23
  29. package/dist/host/guides/study.md +12 -12
  30. package/dist/host/guides/test.md +163 -47
  31. package/dist/host/guides/toolbox.md +127 -81
  32. package/dist/host/guides/workspace.md +21 -14
  33. package/dist/host/manifest.json +30 -30
  34. package/dist/host/scripts/browsers.sh +0 -0
  35. package/dist/host/scripts/codex.sh +0 -0
  36. package/dist/host/scripts/cursor.sh +0 -0
  37. package/dist/host/scripts/deps.sh +0 -0
  38. package/dist/host/scripts/npm.sh +0 -0
  39. package/dist/host/scripts/ollama.sh +0 -0
  40. package/dist/host/tests/config.test.ts +237 -115
  41. package/dist/src/core/index.cjs +591 -218
  42. package/dist/src/core/index.cjs.map +1 -1
  43. package/dist/src/core/index.d.cts +248 -29
  44. package/dist/src/core/index.d.ts +248 -29
  45. package/dist/src/core/index.js +581 -216
  46. package/dist/src/core/index.js.map +1 -1
  47. package/dist/src/server/index.cjs +18 -8
  48. package/dist/src/server/index.cjs.map +1 -1
  49. package/dist/src/server/index.d.cts +4 -3
  50. package/dist/src/server/index.d.ts +4 -3
  51. package/dist/src/server/index.js +19 -9
  52. package/dist/src/server/index.js.map +1 -1
  53. package/package.json +3 -3
@@ -1,20 +1,19 @@
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,
9
9
  JSON-Schema introspection, and seed data all flow from that one
10
10
  declaration — no separate schema, no annotations, no `as`.
11
11
 
12
- The design stance is one engine, thin drivers. A backend implements only an
13
- irreducible storage primitive — keyed read/write/insert/delete, an ordered
14
- `scan`, key listing, and a `snapshot` — and inherits the entire WHERE / order /
15
- page / aggregate surface from a single pure query engine in the core. A backend
16
- that can go faster (a SQL `WHERE`, an index range) implements the optional
17
- native hooks the engine falls back from; it never re-derives query semantics.
12
+ The design stance is native first, under the rule Contract invariant 3 places. A backend
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
+ core's engine runs only the residual. A backend without `plan` inherits the whole WHERE /
16
+ order / page / aggregate surface from that engine over `scan`.
18
17
  So this is deliberately not an ORM and not a query abstraction layer: there is
19
18
  no entity graph, no migration runner, and no raw-SQL escape hatch — only the
20
19
  smallest cross-environment core that earns its keep.
@@ -22,12 +21,11 @@ smallest cross-environment core that earns its keep.
22
21
  Source: [`src/core`](../src/core), published through `@orkestrel/database`. The
23
22
  persistent drivers ship alongside it: a trusted-mode SQLite driver in
24
23
  [`src/server`](../src/server) (surfaced through `@orkestrel/database/server`)
25
- with native querying, paging, aggregation, transactions, and atomic migration,
26
- and a narrow-then-refine IndexedDB driver in [`src/browser`](../src/browser)
27
- (surfaced through `@orkestrel/database/browser`) that pushes a key-range
28
- candidate set down to the index and lets the core engine refine it to the exact
29
- result — beside the I/O-free `MemoryDriver` and the file-persisted
30
- `JSONDriver`.
24
+ with native querying, paging, counting, aggregation, transactions, and atomic migration,
25
+ and an IndexedDB driver in [`src/browser`](../src/browser)
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
+ file-persisted `JSONDriver`, whose reads the core answers over `scan`.
31
29
 
32
30
  ## Surface
33
31
 
@@ -73,41 +71,49 @@ produces the JSON Schema, and seeds fixtures.
73
71
 
74
72
  ### Factories
75
73
 
76
- | Name | Kind | Signature | Summary |
77
- | ----------------------- | -------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
78
- | `createDatabase` | function | `<const T extends TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Creates a database over a driver and a declared `tables` schema. |
79
- | `createMemoryDriver` | function | `() => DriverInterface` | Creates the in-memory reference `DriverInterface`. |
80
- | `createJSONDriver` | function | `(path: string) => DriverInterface` | Creates a persistent JSON-file `DriverInterface` for a given path. |
81
- | `createSQLiteDriver` | function | `(options: SQLiteDriverOptions) => DriverInterface` | Creates a trusted-mode, server-native SQLite `DriverInterface` for a database path, or for `:memory:` when explicitly requested. |
82
- | `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. |
83
81
 
84
82
  ### Classes
85
83
 
86
- | Name | Kind | Signature | Summary |
87
- | ------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
88
- | `Database` | class | `new <T extends TableMap = TableMap>(options: DatabaseOptions<T>) => DatabaseInterface<T>` | Exposes a typed view over one shared internal lifecycle and storage context. |
89
- | `DriverIterator` | class | `new <T>(source: AsyncIterator<T>, guard: () => void) => AsyncIterableIterator<T>` | Forms the internal continuation boundary for a root driver async iterator. |
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) => DriverInterface` | Implements the `DriverInterface` 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
- | `StreamPage` | class | `new (offset: number) => StreamPage` | Tracks the matching-row position of one streaming page. |
95
- | `JSONTransaction` | class | `new (memory: MemoryDriver, schema: readonly TableSchema[], identities: ReadonlyMap<string, object>) => JSONTransaction` | Owns the isolated memory store and schema of one JSON transaction. |
96
- | `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. |
97
99
 
98
100
  ### Server
99
101
 
100
- | Name | Kind | Signature | Summary |
101
- | ---------------------------- | -------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
102
- | `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. |
103
- | `matchesConditionExactly` | function | `(condition: Condition, schema: TableSchema) => boolean` | Reports whether one `Condition` compiles to SQL that is provably identical to the core engine's `matchesCondition` for every value its column's declared type can store. |
104
- | `matchesOrderExactly` | function | `(order: Order, schema: TableSchema) => boolean` | Reports whether one `Order` term's column compiles to an `ORDER BY` that matches the engine's `sortRows` exactly. |
105
- | `matchesQueryExactly` | function | `(input: QueryInput, schema: TableSchema) => boolean` | Reports whether a whole `QueryInput` is exact — every condition and every order term is exact. `limit` / `offset` never affect exactness (SQL `LIMIT` / `OFFSET` are always engine-identical). |
106
- | `matchesDeclaredStorage` | function | `(value: unknown, storage: ColumnStorage) => boolean` | Reports whether a value's runtime type matches a column's declared exact type — the operand side of the declared-type-trust proof. |
107
- | `EXACT_COLUMN_STORAGE` | const | `readonly ColumnStorage[]` | Lists the declared `ColumnStorage`s whose SQL equality comparisons (`equals` / `not` / `any` / `none`) and `starts` / `ends` compiles are provably engine-exact under declared-type trust — `text` / `integer` / `real` / `boolean`; a `json` or `blob` column always refines instead. |
108
- | `EXACT_RANGE_COLUMN_STORAGE` | const | `readonly ColumnStorage[]` | Lists the declared `ColumnStorage`s whose SQL range comparisons (`above` / `below` / `from` / `to` / `between`) and `ORDER BY` compiles are provably engine-exact — `integer` / `real` / `boolean` only. `text` is excluded: see `EXACT_COLUMN_STORAGE`'s remarks for the BINARY-collation (code-point) vs. JS `<` (code-unit) divergence on supplementary-plane characters. |
109
- | `extractValues` | function | `(row: SQLiteRow, names: readonly string[], table: string) => readonly SQLiteValue[]` | Extracts a stored row's values in a declared positional order. |
110
- | `deriveSQLiteIndexName` | function | `(table: string, columns: readonly string[]) => string` | Builds a collision-free SQL index name for a table + column-group index — shared by the compiler module's `schemaToIndexes` and `stepToSQL`, so a plan-built index name always matches one `open` would have created. |
102
+ | Name | Kind | Signature | Summary |
103
+ | ------------------------ | -------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
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. |
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. |
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`. |
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`. |
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. |
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. |
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. |
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. |
114
+ | `matchesDeclaredStorage` | function | `(value: unknown, storage: ColumnStorage) => boolean` | Reports whether an operand has the storage class a declared column stores, so a bound operand compares as the stored values do. |
115
+ | `extractValues` | function | `(row: SQLiteRow, names: readonly string[], table: string) => readonly SQLiteValue[]` | Extracts a stored row's values in a declared positional order. |
116
+ | `deriveSQLiteIndexName` | function | `(table: string, columns: readonly string[]) => string` | Builds a collision-free SQL index name for a table + column-group index — shared by the compiler module's `schemaToIndexes` and `stepToSQL`, so a plan-built index name always matches one `open` would have created. |
111
117
 
112
118
  ### SQL compilation
113
119
 
@@ -115,47 +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) => CompiledSQL` | Compiles one condition to its `<column> <operator>` SQL fragment and the parameters it binds — engine-exact 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) => string` | Compiles the ORDER BY clause from the order terms, always ending with the primary key as the final determinant. |
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
- | `matchesAggregateExactly` | function | `(operation: AggregateOperation, column: FieldPath, schema: TableSchema) => boolean` | Reports whether SQLite can execute an aggregate exactly like the core engine. |
132
- | `matchesSQLiteAffinity` | function | `(declared: unknown, storage: ColumnStorage) => boolean` | Checks a declared SQLite type against a portable storage affinity. |
133
- | `matchesAbsentPath` | function | `(error: unknown) => boolean` | Reports whether a caught filesystem error says that nothing is there to read. |
134
- | `encodeValue` | function | `(value: unknown, column: ColumnSchema) => SQLiteValue` | Encodes a JS value to its stored `SQLiteValue` for a declared column. |
135
- | `decodeValue` | function | `(value: SQLiteValue, column: ColumnSchema) => unknown` | Decodes a stored `SQLiteValue` back to its JS value for a declared column — the exact inverse of `encodeValue`. |
136
- | `encodeRow` | function | `(row: Row, schema: TableSchema) => SQLiteRow` | Encodes a whole `Row` to a `SQLiteRow` by its table's schema. |
137
- | `decodeRow` | function | `(row: SQLiteRow, schema: TableSchema) => Row` | Decodes a stored `SQLiteRow` back to a `Row` by its table's schema. |
138
- | `schemaToTable` | function | `(schema: TableSchema) => string` | Projects a `TableSchema` to its `CREATE TABLE IF NOT EXISTS` statement. |
139
- | `schemaToIndexes` | function | `(schema: TableSchema) => readonly string[]` | Projects a `TableSchema` to its declared SQLite indexes. |
140
- | `stepToSQL` | function | `(step: MigrationStep) => readonly string[]` | Projects one `MigrationStep` to SQLite DDL. |
141
- | `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. |
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. |
142
155
 
143
156
  ### Browser
144
157
 
145
- Pure functions behind the IndexedDB driver's key-range pushdown planner — a
146
- candidate superset the core engine then refines to the exact result, never
147
- lossy.
148
-
149
- | Name | Kind | Signature | Summary |
150
- | -------------------------- | -------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
151
- | `selectPlan` | function | `(input: QueryInput \| undefined, schema: TableSchema, available: readonly string[]) => QueryPlan` | Plans an IndexedDB read for a `QueryInput` — picks the index (or the primary store) and `IDBKeyRange` to narrow by, falling back to a full scan. |
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
- | `INDEXABLE_STORAGE` | const | `readonly ColumnStorage[]` | Lists the declared `ColumnStorage`s that are valid, orderable IndexedDB keys. |
154
- | `METADATA_STORE` | const | `"__metadata__"` | Names the reserved out-of-line store `__metadata__` the `IndexedDBDriver` stamps its `DriverMetadata` into. |
155
- | `mapIndexedDBError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy — the default mapping used everywhere except inside `migrate()`. |
156
- | `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. |
157
- | `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. |
158
- | `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. |
159
185
 
160
186
  ### Errors
161
187
 
@@ -178,29 +204,75 @@ whose every entry passes Contract's `isAuditFault` function.
178
204
  The portable semantics every backend shares — pure, total functions the
179
205
  driver never re-implements.
180
206
 
181
- | Name | Kind | Signature | Summary |
182
- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
183
- | `compareValues` | function | `(left: unknown, right: unknown) => number` | Compares two arbitrary values under one total order — the comparator behind sorting and the range operators. |
184
- | `matchesCondition` | function | `(row: Row, condition: Condition) => boolean` | Evaluates one `Condition` against a row — the per-operator predicate. |
185
- | `matchesQuery` | function | `(row: Row, conditions: readonly Condition[]) => boolean` | Folds a row through a list of conditions, joining each by its connector. |
186
- | `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]` | Sorts rows by an ordering specification, leaving the input untouched. |
187
- | `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]` | Applies a `QueryInput` to rows — filter, then sort, then page. |
188
- | `validatePage` | function | `(input?: QueryInput) => void` | Validates the paging fields of a portable query. |
189
- | `computeAggregate` | function | `(rows: readonly unknown[], operation: AggregateOperation, column: FieldPath) => number \| undefined` | Computes an aggregate over a column across rows. |
190
- | `extractKey` | function | `(row: Row, column: string) => Key \| undefined` | Reads a row's primary key from a column, when it is a usable `Key`. |
191
- | `bindRowKey` | function | `(row: Row, primary: string, key: Key) => Row` | Returns a fresh row whose primary column is authoritatively bound to its storage key. |
192
- | `shapeToColumnSchema` | function | `(name: string, shape: ContractShape) => ColumnSchema` | Projects one contract shape into a portable column schema. |
193
- | `findColumn` | function | `(name: string, schema: TableSchema) => ColumnSchema \| undefined` | Reads one flat column's declaration out of a table schema. |
194
- | `resolvePrimary` | function | `(primary: PrimaryMap, name: string) => string` | Resolves the primary-key column one table keys its rows by. |
195
- | `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. |
196
- | `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. |
197
- | `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`). |
198
- | `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". |
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
+ | `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]` | Sorts rows by an ordering specification, leaving the input untouched. |
213
+ | `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]` | Applies a `QueryInput` to rows — filter, then sort, then page. |
214
+ | `validatePage` | function | `(input?: QueryInput) => void` | Validates the paging fields of a portable query. |
215
+ | `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. |
216
+ | `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. |
217
+ | `computeFirstIndexes` | function | `(keys: readonly unknown[]) => ReadonlyMap<unknown, number>` | Computes the position of each key's first occurrence in a batch. |
218
+ | `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. |
219
+ | `computeAggregate` | function | `(rows: readonly unknown[], operation: AggregateOperation, column: FieldPath) => number \| undefined` | Computes an aggregate over a column across rows. |
220
+ | `extractKey` | function | `(row: Row, column: string) => Key \| undefined` | Reads a row's primary key from a column, when it is a usable `Key`. |
221
+ | `bindRowKey` | function | `(row: Row, primary: string, key: Key) => Row` | Returns a fresh row whose primary column is authoritatively bound to its storage key. |
222
+ | `shapeToColumnSchema` | function | `(name: string, shape: ContractShape) => ColumnSchema` | Projects one contract shape into a portable column schema. |
223
+ | `findColumn` | function | `(name: string, schema: TableSchema) => ColumnSchema \| undefined` | Reads one flat column's declaration out of a table schema. |
224
+ | `resolvePrimary` | function | `(primary: PrimaryMap, name: string) => string` | Resolves the primary-key column one table keys its rows by. |
225
+ | `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. |
226
+ | `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. |
227
+ | `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`). |
228
+ | `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". |
229
+ | `collectScalars` | function | `(values: readonly unknown[]) => ReadonlySet<unknown>` | Collects the scalar operands of a membership list into one set. |
230
+ | `matchesListed` | function | `(value: unknown, values: readonly unknown[], scalars?: ReadonlySet<unknown>) => boolean` | Checks whether a value equals one operand of a membership list. |
231
+ | `prepareScalars` | function | `(conditions: readonly Condition[]) => ReadonlyArray<ReadonlySet<unknown>>` | Collects one scalar set per condition, by position — the `scalars` argument of `matchesQuery`. |
232
+ | `normalizeReadInput` | function | `(input: ReadInput) => ReadInput` | Drops each clause a read does not hold, so an absent clause is an absent key. |
233
+ | `planRead` | function | `(storage: StorageInterface, table: string, input: ReadInput) => ReadPlan` | Asks a storage for its plan of a read, with the read normalized first. |
234
+ | `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. |
199
235
 
200
236
  For `minimum` and `maximum`, `computeAggregate` compares each numeric value
201
237
  with a scalar `Math.min` or `Math.max` call. The helper never passes a
202
238
  row-sized argument list.
203
239
 
240
+ ### Query door
241
+
242
+ Every read of a table passes this door before any driver call: the shape-derived guard of
243
+ `queryInputContract`, then a pass over the table's columns; see [The query door](#the-query-door)
244
+ for each refusal.
245
+
246
+ | Name | Kind | Signature | Summary |
247
+ | -------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
248
+ | `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. |
249
+ | `queryInputContract` | const | `ContractInterface<QueryInput>` | Holds the compiled contract of a portable read, which a table admits every read through. |
250
+ | `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. |
251
+ | `restoreUndefinedOperands` | function | `(masked: QueryInput, source: unknown) => QueryInput` | Puts back the operands of a read whose masked form `maskUndefinedOperands` built and the query contract admitted. |
252
+ | `matchesIllFormedText` | function | `(value: unknown) => boolean` | Checks whether a value is a string holding a lone surrogate, which has no UTF-8 form. |
253
+ | `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. |
254
+ | `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. |
255
+ | `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. |
256
+ | `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. |
257
+ | `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. |
258
+ | `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. |
259
+ | `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`. |
260
+ | `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. |
261
+ | `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. |
262
+ | `collectColumns` | function | `(columns: ColumnMap) => ReadonlyMap<string, ColumnSchema>` | Collects a table's column map into each column's portable schema, by name, in declaration order. |
263
+
264
+ ### Recording
265
+
266
+ The rows-read instrument: a recorder wraps a real driver and counts the keys each storage call
267
+ addresses and the rows it returns or yields. A call log records calls; this counts rows too.
268
+
269
+ | Name | Kind | Signature | Summary |
270
+ | -------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
271
+ | `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. |
272
+ | `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. |
273
+ | `tallyCalls` | function | `(calls: readonly StorageCall[], member: StorageMember) => StorageTally` | Totals the calls, addressed keys, and returned rows of one member across recorded calls. |
274
+ | `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. |
275
+
204
276
  ### Abort
205
277
 
206
278
  | Name | Kind | Signature | Summary |
@@ -222,90 +294,118 @@ transform. Versioning drivers persist reconciliation metadata through the paired
222
294
 
223
295
  ### Conformance
224
296
 
225
- | Name | Kind | Signature | Summary |
226
- | --------------- | -------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
227
- | `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. |
228
- | `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`. |
229
- | `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. |
297
+ | Name | Kind | Signature | Summary |
298
+ | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
299
+ | `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. |
300
+ | `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`. |
301
+ | `buildFailureFinding` | function | `(check: string, error: unknown) => ConformanceFinding` | Builds the finding a conformance phase yields when it throws, naming the phase. |
302
+ | `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. |
303
+ | `findPlanFaults` | function | `(input: ReadInput, plan: ReadPlan) => readonly string[]` | Lists the invariants a `ReadPlan` breaks for the read it splits. |
304
+ | `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. |
305
+ | `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. |
306
+ | `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. |
230
307
 
231
308
  ### Helpers & guards
232
309
 
233
310
  Pure helpers behind the query engine's pattern matching.
234
311
 
235
- | Name | Kind | Signature | Summary |
236
- | ------------------------ | -------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
237
- | `cloneDriverMetadata` | function | `(value: unknown) => DriverMetadata` | Clones unknown driver metadata into a distinct deeply frozen snapshot. |
238
- | `matchesWildcardPattern` | function | `(value: string, pattern: string, any: string, single: string, fold: boolean) => boolean` | Matches a value against a wildcard pattern in linear time — the shared, ReDoS-safe engine behind `matchesLikePattern` and `matchesGlobPattern`. |
239
- | `matchesWildcardSegment` | function | `(value: string, segment: string, at: number, single: string) => boolean` | Checks whether a fixed-length wildcard segment matches a value at an offset. |
240
- | `matchesLikePattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a SQL `LIKE` pattern, folding case. |
241
- | `matchesGlobPattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a `GLOB` pattern, preserving case. |
242
- | `isDriverMetadata` | function | `(value: unknown) => value is DriverMetadata` | Checks whether a value is persisted driver metadata. |
243
- | `isDriverSchema` | function | `(value: unknown) => value is readonly TableSchema[]` | Checks whether a value is a complete portable driver schema. |
244
- | `isColumnSchema` | function | `(value: unknown) => value is ColumnSchema` | Checks whether a value is a portable column schema. |
245
- | `isTableSchema` | function | `(value: unknown) => value is TableSchema` | Checks whether a value is a portable table schema. |
246
- | `isMigrationStep` | function | `(value: unknown) => value is MigrationStep` | Checks whether a value is one ordered migration step. |
247
- | `isMigration` | function | `(value: unknown) => value is Migration` | Checks whether a value is an ordered migration plan. |
248
- | `isMigrationInput` | function | `(value: unknown) => value is MigrationInput` | Checks whether a value is one atomic migration request. |
249
- | `isKey` | function | `(value: unknown) => value is Key` | Checks whether a value is a usable database key. |
250
- | `cloneDriverSchema` | function | `(value: unknown) => readonly TableSchema[]` | Clones unknown driver schema into a distinct deeply frozen snapshot. |
251
- | `cloneMigrationInput` | function | `(value: unknown) => MigrationInput` | Clones unknown migration input into a distinct deeply frozen snapshot. |
252
- | `captureFailure` | function | `(operation: () => Promise<unknown>) => Promise<unknown>` | Captures the exact rejection or synchronous throw from a driver conformance operation. |
312
+ | Name | Kind | Signature | Summary |
313
+ | ------------------------ | -------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
314
+ | `cloneDriverMetadata` | function | `(value: unknown) => DriverMetadata` | Clones unknown driver metadata into a distinct deeply frozen snapshot. |
315
+ | `matchesWildcardPattern` | function | `(value: string, pattern: string, any: string, single: string, fold: boolean) => boolean` | Matches a value against a wildcard pattern in linear time — the shared, ReDoS-safe engine behind `matchesLikePattern` and `matchesGlobPattern`. |
316
+ | `matchesWildcardSegment` | function | `(value: readonly string[], segment: readonly string[], at: number, single: string) => boolean` | Checks whether a fixed-length wildcard segment matches a value at an offset. |
317
+ | `matchesLikePattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a SQL `LIKE` pattern, folding ASCII case. |
318
+ | `matchesGlobPattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a `GLOB` pattern, preserving case. |
319
+ | `foldASCII` | function | `(text: string) => string` | Folds the ASCII letters of a text to lower case, leaving every other character unchanged. |
320
+ | `isDriverMetadata` | function | `(value: unknown) => value is DriverMetadata` | Checks whether a value is persisted driver metadata. |
321
+ | `isDriverSchema` | function | `(value: unknown) => value is readonly TableSchema[]` | Checks whether a value is a complete portable driver schema. |
322
+ | `isColumnSchema` | function | `(value: unknown) => value is ColumnSchema` | Checks whether a value is a portable column schema. |
323
+ | `isTableSchema` | function | `(value: unknown) => value is TableSchema` | Checks whether a value is a portable table schema. |
324
+ | `isMigrationStep` | function | `(value: unknown) => value is MigrationStep` | Checks whether a value is one ordered migration step. |
325
+ | `isMigration` | function | `(value: unknown) => value is Migration` | Checks whether a value is an ordered migration plan. |
326
+ | `isMigrationInput` | function | `(value: unknown) => value is MigrationInput` | Checks whether a value is one atomic migration request. |
327
+ | `isKey` | function | `(value: unknown) => value is Key` | Checks whether a value is a usable database key. |
328
+ | `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. |
329
+ | `isAggregateOperation` | const | `Guard<AggregateOperation>` | Checks whether a value is one of `AGGREGATE_OPERATIONS`. |
330
+ | `isScalar` | function | `(value: unknown) => value is Scalar` | Checks whether a value is a scalar: not an object and not a function. |
331
+ | `cloneDriverSchema` | function | `(value: unknown) => readonly TableSchema[]` | Clones unknown driver schema into a distinct deeply frozen snapshot. |
332
+ | `cloneMigrationInput` | function | `(value: unknown) => MigrationInput` | Clones unknown migration input into a distinct deeply frozen snapshot. |
333
+ | `captureFailure` | function | `(operation: () => Promise<unknown>) => Promise<unknown>` | Captures the exact rejection or synchronous throw from a driver conformance operation. |
253
334
 
254
335
  ### Constants
255
336
 
256
- | Name | Kind | Signature | Summary |
257
- | -------------------------- | ----- | ------------------------ | ------------------------------------------------------------------------------------------------------------- |
258
- | `DEFAULT_PRIMARY` | const | `"id"` | Supplies the primary-key column, `'id'`, assumed when `PrimaryMap` does not name one. |
259
- | `MAX_PATTERN_LENGTH` | const | `1024` | Sets the longest `LIKE` / `GLOB` pattern the wildcard matcher accepts, 1024 characters, before rejecting it. |
260
- | `CONFORMANCE_USERS_SCHEMA` | const | `TableSchema` | Describes the `users` table the driver-conformance battery opens — keyed by the default `id` primary column. |
261
- | `CONFORMANCE_POSTS_SCHEMA` | const | `TableSchema` | Describes the `posts` table the driver-conformance battery opens — keyed by a non-`id` `slug` primary column. |
262
- | `CONFORMANCE_SCHEMA` | const | `readonly TableSchema[]` | Holds the fixed `users` and `posts` schema every driver-conformance phase opens. |
337
+ | Name | Kind | Signature | Summary |
338
+ | -------------------------- | ----- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
339
+ | `DEFAULT_PRIMARY` | const | `"id"` | Supplies the primary-key column, `'id'`, assumed when `PrimaryMap` does not name one. |
340
+ | `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`. |
341
+ | `AGGREGATE_OPERATIONS` | const | `readonly AggregateOperation[]` | Lists the aggregates a read can compute: `count`, `sum`, `average`, `minimum`, and `maximum`. |
342
+ | `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`. |
343
+ | `MAX_PATTERN_LENGTH` | const | `1024` | Sets the longest `LIKE` / `GLOB` pattern the wildcard matcher accepts, 1024 characters, before rejecting it. |
344
+ | `CONFORMANCE_USERS_SCHEMA` | const | `TableSchema` | Describes the `users` table the driver-conformance battery opens — keyed by the default `id` primary column. |
345
+ | `CONFORMANCE_POSTS_SCHEMA` | const | `TableSchema` | Describes the `posts` table the driver-conformance battery opens — keyed by a non-`id` `slug` primary column. |
346
+ | `CONFORMANCE_SCHEMA` | const | `readonly TableSchema[]` | Holds the fixed `users` and `posts` schema every driver-conformance phase opens. |
347
+ | `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 `[`. |
348
+ | `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. |
263
349
 
264
350
  ### Types
265
351
 
266
- | Name | Kind | Signature | Summary |
267
- | -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
268
- | `Key` | type | `string \| number` | Represents a primary key — the value identifying a row within its table. |
269
- | `KeyFunction` | type | `() => Key` | Represents a key-generating function. |
270
- | `Row` | type | `Record<string, unknown>` | Represents a table row — a plain record of column values keyed by column name. |
271
- | `ConditionOperator` | type | `'equals' \| 'not' \| 'above' \| 'below' \| 'from' \| 'to' \| 'between' \| 'like' \| 'glob' \| 'starts' \| 'ends' \| 'any' \| 'none' \| 'absent' \| 'present'` | Represents a WHERE operator — the comparison a single `Condition` applies. |
272
- | `ConditionConnector` | type | `'and' \| 'or'` | Names how a `Condition` joins to the running result of the conditions before it. |
273
- | `Condition` | interface | `{ column, operator, values, connector }` | Represents one compiled WHERE condition. |
274
- | `OrderDirection` | type | `'ascending' \| 'descending'` | Names a sort direction. |
275
- | `Order` | interface | `{ column, direction }` | Represents one ordering term — a column (`FieldPath`, flat or nested) and its direction. |
276
- | `QueryInput` | interface | `{ conditions?, order?, limit?, offset? }` | Represents a serializable read specification — everything a backend needs to compile one read, free of JS callbacks so any backend can honor it. |
277
- | `AggregateOperation` | type | `'count' \| 'sum' \| 'average' \| 'minimum' \| 'maximum'` | Names an aggregate computed over a numeric column. |
278
- | `OperationOptions` | interface | `{ signal? }` | Options for an abortable operation. |
279
- | `DatabaseStatus` | type | `'idle' \| 'open' \| 'closed'` | Names the lifecycle state of a `DatabaseInterface`. |
280
- | `AdmissionInterface` | interface | `{ accepting, track() }` | Represents the admission boundary a scoped operation enters before it runs. |
281
- | `DatabaseErrorCode` | type | `'CLOSED' \| 'NOT_FOUND' \| 'CONFLICT' \| 'VALIDATION' \| 'ABORTED' \| 'MIGRATION' \| 'CONFORMANCE' \| 'DRIVER'` | Names a machine-readable `DatabaseError` code. |
282
- | `ConformanceFinding` | interface | `{ check, message, context }` | Represents one violated invariant from the driver-conformance battery. |
283
- | `DatabaseEventMap` | type | `{ readonly open: readonly []; readonly close: readonly []; readonly transaction: readonly []; readonly commit: readonly []; readonly rollback: readonly [error: unknown]; readonly migrate: readonly [migration: Migration]; }` | Describes the push observation surface of a `DatabaseInterface` — the connection + transaction lifecycle a fire-and-forget observer (logging, metrics, tracing, cache invalidation) subscribes to. |
284
- | `TableEventMap` | type | `{ readonly write: readonly [key: Key]; readonly remove: readonly [key: Key]; readonly clear: readonly []; }` | Describes the push observation surface of a `TableInterface` — the per-row mutation moments a fire-and-forget observer (cache invalidation, sync, an audit log) subscribes to, alongside the database-level `DatabaseEventMap`. |
285
- | `ColumnMap` | type | `Readonly<Record<string, ContractShape>>` | Represents one table's columns — a map of column name to its value `ContractShape`. |
286
- | `TableMap` | type | `Readonly<Record<string, ColumnMap>>` | Represents a database's table schema — a map of table name to its `ColumnMap`. |
287
- | `RowOf` | type | `Infer<{ readonly category: 'object'; readonly properties: C; }>` | Represents the row type a table's `ColumnMap` describe — `Infer` of the `objectShape` the database wraps them in. |
288
- | `PrimaryMap` | type | `Readonly<Record<string, string>>` | Holds per-table primary-key column overrides — `{ [table]: column }`. |
289
- | `IndexMap` | type | `Readonly<Record<string, ReadonlyArray<readonly string[]>>>` | Holds per-table secondary indexes — `{ [table]: groups }`, each group one (possibly compound) index of column names. |
290
- | `ColumnStorage` | type | `'text' \| 'integer' \| 'real' \| 'boolean' \| 'json' \| 'blob'` | Names a portable storage type for a column — the backend maps it to its native type (SQLite affinity, an IndexedDB value). Derived from a column's `ContractShape` by `shapeToColumnStorage`; `json` covers object/array/union/raw values a backend stores as JSON text and can `json_extract` for nested-field queries. |
291
- | `ColumnSchema` | interface | `{ name, storage, optional, nullable }` | Represents one column of a `TableSchema` — its name, portable `ColumnStorage`, and whether it independently accepts absence (`optional`) and explicit `null` (`nullable`). |
292
- | `TableSchema` | interface | `{ name, primary, columns, indexes }` | Represents a backend-agnostic description of one table — what `open` hands each driver so a native backend can create real tables and indexes. |
293
- | `MigrationStep` | type | `{ readonly operation: 'table.add'; readonly table: TableSchema; } \| { readonly operation: 'table.remove'; readonly table: string; } \| { readonly operation: 'column.add'; readonly table: string; readonly column: ColumnSchema; } \| { readonly operation: 'column.remove'; readonly table: string; readonly column: string; } \| { readonly operation: 'index.add'; readonly table: string; readonly index: readonly string[]; } \| { readonly operation: 'index.remove'; readonly table: string; readonly index: readonly string[]; }` | Represents one step of a `Migration` plan — a single schema change applied to one table. |
294
- | `Migration` | interface | `{ from, to, steps }` | Represents a schema migration plan — an ordered set of `MigrationStep`s moving a database from one schema version to another. |
295
- | `MigrationInput` | interface | `{ plan, metadata? }` | Represents one atomic migration request. |
296
- | `StorageInterface` | interface | `{ read(), write(), insert(), delete(), keys(), scan(), clear(), records?(), aggregate?(), stream?(), migrate?(), metadata?(), stamp?() }` | Declares the storage operations available only inside a driver's transaction scope. |
297
- | `DriverMetadata` | interface | `{ version, schema }` | Represents persisted schema metadata a versioning driver owns as an immutable snapshot. |
298
- | `DriverInterface` | interface | `{ open(), close(), snapshot(), transaction?() }` | Declares the storage primitive every backend implements — the whole of the bridge. |
299
- | `DatabaseOptions` | interface | `{ on?, error?, driver, tables, primary?, indexes?, name?, generator?, version? }` | Options for `createDatabase`. |
300
- | `CompiledSQL` | interface | `{ sql, parameters }` | Represents a parameterized SQL fragment or statement plus its bind values. The `@orkestrel/database/server` entry point exports this type. |
301
- | `SQLiteDriverOptions` | interface | `{ path, readonly?, timeout?, references?, pragmas? }` | Configures `createSQLiteDriver`. The `@orkestrel/database/server` entry point exports this type. |
302
- | `QueryPlan` | interface | `{ index?, range? }` | Represents a pushdown plan — an optional index and optional `IDBKeyRange` used to narrow a read. An omitted `index` selects the primary store; an omitted `range` performs a full scan. The plan is always a superset of the matching rows; the core engine refines it to the exact result. An empty plan (`{}`) is a primary-store full scan. The `@orkestrel/database/browser` entry point exports this type. |
303
- | `TableDefinition` | interface | `{ primary, columns, schema }` | Represents one table's portable definition, produced by `export` — the unit of schema / migration exchange across environments. |
304
- | `DatabaseStorageInterface` | interface | `{ table() }` | Represents a table-only database view. |
305
- | `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. |
306
- | `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. |
307
- | `QueryInterface` | interface | `{ condition(), order(), filter(), limit(), offset(), collect(), find(), count(), stream(), aggregate() }` | Builds a read through a fluent chain. |
308
- | `CursorInterface` | interface | `{ value, index, done, next(), update(), remove(), close() }` | Walks a table's rows forward for bulk in-place mutation. |
352
+ | Name | Kind | Signature | Summary |
353
+ | -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
354
+ | `Key` | type | `string \| number` | Represents a primary key — the value identifying a row within its table. |
355
+ | `KeyFunction` | type | `() => Key` | Represents a key-generating function. |
356
+ | `Row` | type | `Record<string, unknown>` | Represents a table row — a plain record of column values keyed by column name. |
357
+ | `Scalar` | type | `null \| undefined \| boolean \| number \| bigint \| string \| symbol` | Represents a value that is not an object and not a function: `null` or a primitive. |
358
+ | `ConditionOperator` | type | `'equals' \| 'not' \| 'above' \| 'below' \| 'from' \| 'to' \| 'between' \| 'like' \| 'glob' \| 'starts' \| 'ends' \| 'any' \| 'none' \| 'absent' \| 'present'` | Represents a WHERE operator — the comparison a single `Condition` applies. |
359
+ | `ConditionConnector` | type | `'and' \| 'or'` | Names how a `Condition` joins to the running result of the conditions before it. |
360
+ | `Condition` | interface | `{ column, operator, values, connector }` | Represents one compiled WHERE condition. |
361
+ | `OrderDirection` | type | `'ascending' \| 'descending'` | Names a sort direction. |
362
+ | `Order` | interface | `{ column, direction }` | Represents one ordering term — a column (`FieldPath`, flat or nested) and its direction. |
363
+ | `QueryInput` | interface | `{ conditions?, order?, limit?, offset? }` | Represents a serializable read specification — everything a backend needs to compile one read, free of JS callbacks so any backend can honor it. |
364
+ | `Aggregate` | interface | `{ operation, column }` | Represents one aggregate a read reduces its rows to. |
365
+ | `ReadInput` | interface | `{ aggregate? }` | Represents a read as a driver plans it: a query, and the aggregate over its rows when the read computes one. |
366
+ | `ReadPlan` | interface | `{ native, residual }` | Represents the split of one read between the engine and the core. |
367
+ | `AggregateOperation` | type | `'count' \| 'sum' \| 'average' \| 'minimum' \| 'maximum'` | Names an aggregate computed over a numeric column. |
368
+ | `OperationOptions` | interface | `{ signal? }` | Options for an abortable operation. |
369
+ | `DatabaseStatus` | type | `'idle' \| 'open' \| 'closed'` | Names the lifecycle state of a `DatabaseInterface`. |
370
+ | `AdmissionInterface` | interface | `{ accepting, track() }` | Represents the admission boundary a scoped operation enters before it runs. |
371
+ | `DatabaseErrorCode` | type | `'CLOSED' \| 'NOT_FOUND' \| 'CONFLICT' \| 'VALIDATION' \| 'ABORTED' \| 'MIGRATION' \| 'CONFORMANCE' \| 'DRIVER'` | Names a machine-readable `DatabaseError` code. |
372
+ | `ConformanceFinding` | interface | `{ check, message, context }` | Represents one violated invariant from the driver-conformance battery. |
373
+ | `DatabaseEventMap` | type | `{ readonly open: readonly []; readonly close: readonly []; readonly transaction: readonly []; readonly commit: readonly []; readonly rollback: readonly [error: unknown]; readonly migrate: readonly [migration: Migration]; }` | Describes the push observation surface of a `DatabaseInterface` — the connection + transaction lifecycle a fire-and-forget observer (logging, metrics, tracing, cache invalidation) subscribes to. |
374
+ | `TableEventMap` | type | `{ readonly write: readonly [key: Key]; readonly remove: readonly [key: Key]; readonly clear: readonly []; }` | Describes the push observation surface of a `TableInterface` — the per-row mutation moments a fire-and-forget observer (cache invalidation, sync, an audit log) subscribes to, alongside the database-level `DatabaseEventMap`. |
375
+ | `ColumnMap` | type | `Readonly<Record<string, ContractShape>>` | Represents one table's columns — a map of column name to its value `ContractShape`. |
376
+ | `TableMap` | type | `Readonly<Record<string, ColumnMap>>` | Represents a database's table schema — a map of table name to its `ColumnMap`. |
377
+ | `RowOf` | type | `Infer<{ readonly category: 'object'; readonly properties: C; }>` | Represents the row type a table's `ColumnMap` describe — `Infer` of the `objectShape` the database wraps them in. |
378
+ | `PrimaryMap` | type | `Readonly<Record<string, string>>` | Holds per-table primary-key column overrides — `{ [table]: column }`. |
379
+ | `IndexMap` | type | `Readonly<Record<string, ReadonlyArray<readonly string[]>>>` | Holds per-table secondary indexes — `{ [table]: groups }`, each group one (possibly compound) index of column names. |
380
+ | `ColumnStorage` | type | `'text' \| 'integer' \| 'real' \| 'boolean' \| 'json' \| 'blob'` | Names a portable storage type for a column — the backend maps it to its native type (SQLite affinity, an IndexedDB value). Derived from a column's `ContractShape` by `shapeToColumnStorage`; `json` covers object/array/union/raw values a backend stores as JSON text and can `json_extract` for nested-field queries. |
381
+ | `ColumnSchema` | interface | `{ name, storage, optional, nullable }` | Represents one column of a `TableSchema` — its name, portable `ColumnStorage`, and whether it independently accepts absence (`optional`) and explicit `null` (`nullable`). |
382
+ | `TableSchema` | interface | `{ name, primary, columns, indexes }` | Represents a backend-agnostic description of one table — what `open` hands each driver so a native backend can create real tables and indexes. |
383
+ | `MigrationStep` | type | `{ readonly operation: 'table.add'; readonly table: TableSchema; } \| { readonly operation: 'table.remove'; readonly table: string; } \| { readonly operation: 'column.add'; readonly table: string; readonly column: ColumnSchema; } \| { readonly operation: 'column.remove'; readonly table: string; readonly column: string; } \| { readonly operation: 'index.add'; readonly table: string; readonly index: readonly string[]; } \| { readonly operation: 'index.remove'; readonly table: string; readonly index: readonly string[]; }` | Represents one step of a `Migration` plan — a single schema change applied to one table. |
384
+ | `Migration` | interface | `{ from, to, steps }` | Represents a schema migration plan — an ordered set of `MigrationStep`s moving a database from one schema version to another. |
385
+ | `MigrationInput` | interface | `{ plan, metadata? }` | Represents one atomic migration request. |
386
+ | `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. |
387
+ | `DriverMetadata` | interface | `{ version, schema }` | Represents persisted schema metadata a versioning driver owns as an immutable snapshot. |
388
+ | `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. |
389
+ | `StorageMember` | type | `'read' \| 'write' \| 'insert' \| 'delete' \| 'keys' \| 'scan' \| 'clear' \| 'plan' \| 'records' \| 'stream' \| 'aggregate'` | Names a `StorageInterface` member a `StorageRecorder` observes. |
390
+ | `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. |
391
+ | `StorageTally` | interface | `{ calls, keys, rows }` | Represents the calls, addressed keys, and returned rows of one member across recorded calls. |
392
+ | `StorageResult` | interface | `{ value, calls }` | Represents one measured operation's value and the storage calls it made. |
393
+ | `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. |
394
+ | `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. |
395
+ | `DatabaseOptions` | interface | `{ on?, error?, driver, tables, primary?, indexes?, name?, generator?, version? }` | Options for `createDatabase`. |
396
+ | `CompiledSQL` | interface | `{ sql, parameters }` | Represents a parameterized SQL fragment or statement plus its bind values. The `@orkestrel/database/server` entry point exports this type. |
397
+ | `SQLiteDriverOptions` | interface | `{ path, readonly?, timeout?, references?, pragmas? }` | Configures `createSQLiteDriver`. The `@orkestrel/database/server` entry point exports this type. |
398
+ | `SQLiteDriverInterface` | interface | `{ pragma() }` | Represents the SQLite driver: the storage contract plus a read of one connection pragma. |
399
+ | `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. |
400
+ | `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. |
401
+ | `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. |
402
+ | `TableDefinition` | interface | `{ primary, columns, schema }` | Represents one table's portable definition, produced by `export` — the unit of schema / migration exchange across environments. |
403
+ | `DatabaseStorageInterface` | interface | `{ table() }` | Represents a table-only database view. |
404
+ | `DatabaseTableOptions` | interface | `{ on?, error? }` | Options for one table handle that `table` returns. |
405
+ | `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. |
406
+ | `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. |
407
+ | `QueryInterface` | interface | `{ condition(), order(), filter(), limit(), offset(), collect(), find(), count(), stream(), aggregate() }` | Builds a read through a fluent chain. |
408
+ | `CursorInterface` | interface | `{ value, index, done, next(), update(), remove(), close() }` | Walks a table's rows forward for bulk in-place mutation. |
309
409
 
310
410
  ### Operation state
311
411
 
@@ -366,56 +466,121 @@ method below runs inside that scope, and each carries the same contract its
366
466
  `StorageInterface` and `DriverInterface` tables share one description per
367
467
  method.
368
468
 
369
- | Method | Returns | Summary |
370
- | ----------- | -------------------------------------- | -------------------------------------------------------------------------------- |
371
- | `read` | `Promise<Row \| undefined>` | Reads one row by key. |
372
- | `write` | `Promise<void>` | Writes one row at a key. |
373
- | `insert` | `Promise<void>` | Inserts one row atomically, rejecting `CONFLICT` when its key already exists. |
374
- | `delete` | `Promise<boolean>` | Deletes one row by key. |
375
- | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
376
- | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
377
- | `clear` | `Promise<void>` | Empties a table. |
378
- | `records` | `Promise<readonly Row[]>` | Reads the rows matching a `QueryInput` natively — an optional hook. |
379
- | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over a column natively — an optional hook. |
380
- | `stream` | `AsyncIterable<Row>` | Iterates the natively filtered rows lazily — an optional hook. |
381
- | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
382
- | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
383
- | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
469
+ | Method | Returns | Summary |
470
+ | ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
471
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
472
+ | `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. |
473
+ | `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. |
474
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
475
+ | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
476
+ | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
477
+ | `clear` | `Promise<void>` | Empties a table. |
478
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
479
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
480
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
481
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
482
+ | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
483
+ | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
484
+ | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
384
485
 
385
486
  #### `DriverInterface`
386
487
 
387
- The complete backend extends `StorageInterface` with lifecycle, the
388
- snapshot floor, and an optional native transaction callback. The inherited
488
+ The complete backend extends `StorageInterface` with lifecycle and an optional native
489
+ transaction callback. The inherited
389
490
  storage/query/migration/metadata methods carry the same contract they carry on
390
491
  `StorageInterface`, addressed against the whole backend rather than one
391
492
  transaction scope. `open` receives the derived `TableSchema` list: a native
392
493
  backend builds real tables and indexes from it, a scan-only backend reads
393
- `name` alone. `snapshot` with no `tables` captures the whole store, while a
394
- list scopes capture and restore to those tables. An omitted optional hook
395
- costs nothing — the core query engine answers `records`, `aggregate`, and
396
- `stream` over `scan` instead, and a driver without `transaction` runs a scope
397
- on the snapshot floor (see [Native transactions](#native-transactions)).
494
+ `name` alone. Each keyed member takes one key, or a list that one call applies whole: a
495
+ list `write` or `insert` pairs `keys[i]` with `rows[i]` and applies every row or none, and
496
+ a list `delete` reports, per key, whether the call removed its row: it is the storage contract,
497
+ not a manager verb, and `Table.remove` emits `remove` for each removed key before it folds the
498
+ list into one answer. A driver without
499
+ `plan` answers nothing natively — the core runs the whole read over `scan` — and a driver
500
+ without `transaction` runs a scope on the core's journal (see
501
+ [Transactions](#transactions)).
398
502
 
399
503
  | Method | Returns | Summary |
400
504
  | ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
401
505
  | `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
402
506
  | `close` | `Promise<void>` | Releases the backend. |
403
- | `snapshot` | `Promise<() => Promise<void>>` | Captures table rows and returns a repeatable thunk that restores those rows — the primitive transactions are built on. |
404
- | `read` | `Promise<Row \| undefined>` | Reads one row by key. |
405
- | `write` | `Promise<void>` | Writes one row at a key. |
406
- | `insert` | `Promise<void>` | Inserts one row atomically, rejecting `CONFLICT` when its key already exists. |
407
- | `delete` | `Promise<boolean>` | Deletes one row by key. |
507
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
508
+ | `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. |
509
+ | `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. |
510
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
408
511
  | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
409
512
  | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
410
513
  | `clear` | `Promise<void>` | Empties a table. |
411
- | `records` | `Promise<readonly Row[]>` | Reads the rows matching a `QueryInput` natively — an optional hook. |
412
- | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over a column natively — an optional hook. |
413
- | `stream` | `AsyncIterable<Row>` | Iterates the natively filtered rows lazily — an optional hook. |
514
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
515
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
516
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
517
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
414
518
  | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
415
519
  | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
416
520
  | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
417
521
  | `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. |
418
522
 
523
+ #### `StorageJournalInterface`
524
+
525
+ `StorageJournalInterface` extends `StorageInterface`. Each inherited member forwards to the
526
+ storage the journal wraps, and a write, insert, delete, or clear first records the prior rows
527
+ it would change.
528
+
529
+ | Method | Returns | Summary |
530
+ | ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
531
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
532
+ | `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. |
533
+ | `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. |
534
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
535
+ | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
536
+ | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
537
+ | `clear` | `Promise<void>` | Empties a table. |
538
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
539
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
540
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
541
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
542
+ | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
543
+ | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
544
+ | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
545
+ | `restore` | `Promise<void>` | Restores every key and table the journal recorded to its prior rows. |
546
+
547
+ #### `StreamPageInterface`
548
+
549
+ The matching-row position of one streaming page; its `count` data member stays in the Surface
550
+ row.
551
+
552
+ | Method | Returns | Summary |
553
+ | ------ | --------- | ------------------------------- |
554
+ | `next` | `boolean` | Advances past one matching row. |
555
+
556
+ #### `SQLiteDriverInterface`
557
+
558
+ `SQLiteDriverInterface` extends `DriverInterface`, and `createSQLiteDriver` returns it. Each
559
+ inherited member carries its `DriverInterface` contract. `pragma` is a root member: the scoped
560
+ capability a transaction passes does not declare it, and a call while a transaction is active
561
+ raises `CONFLICT`.
562
+
563
+ | Method | Returns | Summary |
564
+ | ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
565
+ | `open` | `Promise<void>` | Readies the tables from a derived `TableSchema` list. |
566
+ | `close` | `Promise<void>` | Releases the backend. |
567
+ | `read` | `Promise<Row \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
568
+ | `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. |
569
+ | `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. |
570
+ | `delete` | `Promise<boolean>` (or array) | Deletes one row by key, or each listed row, reporting whether each row existed. |
571
+ | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
572
+ | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
573
+ | `clear` | `Promise<void>` | Empties a table. |
574
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
575
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
576
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
577
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
578
+ | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
579
+ | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
580
+ | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
581
+ | `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. |
582
+ | `pragma` | `SQLiteValue \| undefined` | Runs `PRAGMA name` with no value and returns the first value the engine answers. |
583
+
419
584
  #### `DatabaseInterface`
420
585
 
421
586
  `DatabaseInterface` extends `DatabaseStorageInterface` and inherits its `table` method.
@@ -445,6 +610,11 @@ for work started after the transaction settles.
445
610
  | ------- | ----------------------------- | ---------------------------------------------- |
446
611
  | `table` | `TableInterface<RowOf<T[K]>>` | Returns the typed handle for a declared table. |
447
612
 
613
+ `table(name, options)` takes `DatabaseTableOptions`: `on` registers initial `TableEventMap` listeners
614
+ on the handle's emitter, and `error` routes their throws instead of the database's `error` option.
615
+ A handle has no lifecycle verb: its emitter ends with the handle, and after the database closes
616
+ no operation runs, so no handle emits.
617
+
448
618
  #### `AdmissionInterface`
449
619
 
450
620
  The admission boundary the root database context and a transaction scope both
@@ -457,34 +627,33 @@ expose; its `accepting` data member stays in the Surface row above.
457
627
  #### `TableInterface`
458
628
 
459
629
  The keyed methods batch by overload (one in → one out; array in → array
460
- out) — a single verb, never `getMany` / `setAll`. `records()` / `scan()`
461
- narrow every row through the table's contract guard, so a non-conforming
462
- stored row (legacy data, a row from before a migration) never appears in
463
- their results. `count()` uses the same contract-valid candidate semantics as
464
- `records()` while ignoring paging, so invalid stored rows do not consume the
465
- count. `aggregate()` remains a stored-row operation; its `count` aggregate may
466
- therefore include a row that `TableInterface.count()` excludes. `records`,
630
+ out) — a single verb, never `getMany` / `setAll`. `get()`, `records()`, and `scan()`
631
+ narrow every returned row through the table's contract guard, and a stored row that fails
632
+ it raises `DRIVER` with `table`, `key`, and the contract's `faults`. `count()` is
633
+ `aggregate('count')`, which reads the stored set `records()` reads while ignoring paging,
634
+ so the two agree. `records`,
467
635
  `count`, `aggregate`, `scan`, `set`, `add`, `update`, and `remove` each take an
468
- optional `OperationOptions`: its `signal` reaches every backend commit point,
469
- and an aborted batch keeps the items already committed.
470
-
471
- | Method | Returns | Summary |
472
- | ----------- | ------------------------------------ | ------------------------------------------------------------------------------------ |
473
- | `get` | `Promise<T \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
474
- | `resolve` | `Promise<T>` (or array) | Reads one row by key, or one row per key for a list, throwing `NOT_FOUND` on a miss. |
475
- | `has` | `Promise<boolean>` (or array) | Reports whether one key exists, or one result per key for a list. |
476
- | `keys` | `Promise<readonly Key[]>` | Lists every primary key in order. |
477
- | `records` | `Promise<readonly T[]>` | Reads the contract-valid rows matching an optional `QueryInput`. |
478
- | `count` | `Promise<number>` | Counts contract-valid rows matching `input`'s conditions. |
479
- | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over `column` across rows matching `input`'s conditions. |
480
- | `scan` | `AsyncIterable<T>` | Iterates the table's rows lazily with filtering. |
481
- | `set` | `Promise<Key>` (or array) | Upserts one or more rows. |
482
- | `add` | `Promise<Key>` (or array) | Inserts one or more rows, throwing `CONFLICT` on a duplicate key. |
483
- | `update` | `Promise<boolean>` (or array) | Applies a partial change to one or more rows. |
484
- | `remove` | `Promise<boolean>` (or array) | Deletes one or more rows. |
485
- | `clear` | `Promise<void>` | Empties the table. |
486
- | `query` | `QueryInterface<T>` | Opens a fluent query builder over the table. |
487
- | `cursor` | `Promise<CursorInterface<T>>` | Opens a forward row cursor for bulk mutation. |
636
+ optional `OperationOptions`: its `signal` reaches every backend commit point. A list form
637
+ is one driver call that admits every row first and applies every row or none; `update`
638
+ of a list is one list `read` and one list `write`.
639
+
640
+ | Method | Returns | Summary |
641
+ | ----------- | ------------------------------------ | ----------------------------------------------------------------------------------------- |
642
+ | `get` | `Promise<T \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
643
+ | `resolve` | `Promise<T>` (or array) | Reads one row by key, or one row per key for a list, throwing `NOT_FOUND` on a miss. |
644
+ | `has` | `Promise<boolean>` (or array) | Reports whether one key exists, or one result per key for a list. |
645
+ | `keys` | `Promise<readonly Key[]>` | Lists every primary key in order. |
646
+ | `records` | `Promise<readonly T[]>` | Reads the rows matching an optional `QueryInput`. |
647
+ | `count` | `Promise<number>` | Counts the stored rows matching `input`'s conditions. |
648
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over `column` across the stored rows matching `input`'s conditions. |
649
+ | `scan` | `AsyncIterable<T>` | Iterates the table's rows lazily with filtering. |
650
+ | `set` | `Promise<Key>` (or array) | Upserts one or more rows. |
651
+ | `add` | `Promise<Key>` (or array) | Inserts one or more rows, throwing `CONFLICT` on a duplicate key. |
652
+ | `update` | `Promise<boolean>` (or array) | Applies a partial change to one or more rows. |
653
+ | `remove` | `Promise<boolean>` | Deletes one or more rows. |
654
+ | `clear` | `Promise<void>` | Empties the table. |
655
+ | `query` | `QueryInterface<T>` | Opens a fluent query builder over the table. |
656
+ | `cursor` | `Promise<CursorInterface<T>>` | Opens a forward row cursor for bulk mutation. |
488
657
 
489
658
  #### `QueryInterface`
490
659
 
@@ -529,45 +698,60 @@ These invariants hold across the core database source tree ↔ this guide:
529
698
  an entry barrel remain internal.
530
699
  2. **A table is a contract.** Every write is admitted whole through the
531
700
  table's compiled contract — `set` / `add` / `update` run the row through
532
- Contract's `admitValue`, which admits a lossless repair such as `'36'` to
533
- `36` for a number column and enforces constraints such as `min` /
534
- `pattern`. A row that carries an undeclared top-level column, omits a
535
- required column, or needs a lossy repair such as `'036'` to `36` throws
536
- `VALIDATION`; the table never removes a column to admit the rest. A
701
+ Contract's `admitValue`, which enforces types and constraints such as
702
+ `min` / `pattern` and repairs nothing. A row that carries an undeclared
703
+ top-level column, omits a required column, or holds a mistyped value such
704
+ as `'36'` for an integer column throws `VALIDATION`; the table never
705
+ removes a column to admit the rest. A caller that wants a lossless repair
706
+ runs `repairValue(table.contract, row)` before the write. A
537
707
  `rawShape` column admits any defined value, so the nested keys of a JSON
538
708
  column never refuse. Reads are narrowed back to the table's row type
539
709
  through the guard — never an `as` (see `AGENTS.md` § Non-negotiable
540
710
  rules). The row type is the shape's `Infer`, so a `tables` map types every
541
711
  table from one declaration. A refusal's context carries `table` and
542
712
  `faults`, the `AuditFault` list `admitValue` returned, and its message
543
- names the table and the first fault through Contract's `describeFaultLine`
544
- function. A fault's `received` member and the message carry Contract's
713
+ names the table and every fault through Contract's `describeFaults`
714
+ function, bounded by `FAULT_TEXT_LIMIT`. A fault's `received` member and the message carry Contract's
545
715
  JSON-encoded, length-capped rendering of the received value; the rejected
546
716
  row and the parser cause never enter the message, context, serialized
547
717
  error, or table events.
548
- 3. **Thin driver, one engine, native overrides.** The required
549
- `DriverInterface` surface is the irreducible storage primitive — keyed
550
- read/write/atomic-insert/delete, an ordered `scan`, key listing, and `snapshot`. `open`
551
- hands the driver a derived `TableSchema[]` (each table's `columns`, their
552
- portable `ColumnStorage` through `shapeToColumnStorage`, the `primary` key, and declared
553
- `indexes`) so a native backend can build real tables and indexes; a
554
- scan-only backend reads only `name`. The pure, total query engine
555
- (`applyQuery` / `matchesQuery` / `computeAggregate` / …) over `scan`
556
- is the default and the only required path. A backend can implement the
557
- optional native `records?` / `aggregate?` / `transaction?` /
558
- `stream?` / `migrate?` where it has a faster or more native path, and the
559
- engine prefers each when present — falling back to the portable path
560
- otherwise (see `.claude/rules/architecture.md` § System constraints).
561
- Because `aggregate?` legitimately resolves to
562
- `undefined` (a sum over zero rows), `Table.aggregate` decides the hook ran
563
- by its **presence** (a present method returns a Promise; `?.()` is
564
- `undefined` only when the method is absent), never by the resolved value.
565
- Neither reference driver implements `records?` / `aggregate?`,
566
- so every query runs the engine over key-ordered `scan`; both do implement
567
- `stream?` and `migrate?` (`MemoryDriver.stream` lazily filters `scan` through
568
- the engine; `JSONDriver.stream` delegates to its inner `MemoryDriver`).
569
- `MemoryDriver` still lacks a native `transaction?`, so its transactions
570
- always use the snapshot floor; `JSONDriver` does implement
718
+ 3. **Native first.** A driver answers every part of a read or a write with its engine's
719
+ native operation wherever the engine has one, and the core runs its own engine only over
720
+ the residual a driver's plan returns. The rule's home is the `DriverInterface` doc block,
721
+ which also states the plan invariants; this guide states it nowhere else. `open` hands the
722
+ driver a derived `TableSchema[]` (each table's `columns`, their portable `ColumnStorage`
723
+ through `shapeToColumnStorage`, the `primary` key, and declared `indexes`) so a native
724
+ backend can build real tables and indexes; a scan-only backend reads only `name`. A
725
+ driver declares its native coverage per read through `plan`, which returns a `ReadPlan`;
726
+ `Table` calls `records`, `stream`, and `aggregate` with `plan.native` only, and runs the
727
+ residual through `applyQuery`, `matchesQuery`, `sortRows`, and `computeAggregate`. A read
728
+ is wholly native when `residual` equals `{}`. `scanDriver` checks every plan's invariants,
729
+ the transaction capability's mirror of the native members, and a differential of each
730
+ planned driver against the core engine over `scan`. The following table rules where
731
+ each clause runs in this release:
732
+
733
+ | Clause | `SQLiteDriver` | `IndexedDBDriver` | `MemoryDriver`, `JSONDriver` |
734
+ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
735
+ | 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` |
736
+ | 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` |
737
+ | An `or` fold | Native when every condition is; otherwise wholly residual | Residual | Residual over `scan` |
738
+ | 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` |
739
+ | 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` |
740
+ | `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` |
741
+ | `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` |
742
+ | 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 |
743
+
744
+ The rule fixes these semantics on every driver: text order and text ranges are the
745
+ engine's binary order, so SQLite orders by code point where the core orders by UTF-16
746
+ code unit, and the two differ only between a supplementary-plane character and one in
747
+ U+E000 to U+FFFF; `like` folds ASCII letters only, and `_` and `?` match one code point;
748
+ ties resolve by primary key in the direction of the final order term; `sum` and
749
+ `average` on a numeric column are the engine's arithmetic, and SQLite's `sum` is its
750
+ floating-point `TOTAL`, which an integer sum past 2^53 reads as without raising. Every write is admitted
751
+ through the contract, so every stored row conforms; a returned stored row that fails the
752
+ contract raises `DRIVER`, and SQLite raises `DRIVER` for a stored value that does not
753
+ match its column's declaration. `MemoryDriver` lacks a native `transaction?`, so the
754
+ core's journal carries its transactions; `JSONDriver` does implement
571
755
  `transaction?` — it clones the committed memory/schema/metadata into an
572
756
  isolated candidate, passes only that candidate's capability to the callback,
573
757
  and publishes it with one atomic file replacement only when the callback
@@ -580,7 +764,7 @@ These invariants hold across the core database source tree ↔ this guide:
580
764
  exactly once, and terminalizes the iterator; the transaction and driver
581
765
  remain usable. Memory and IndexedDB need no equivalent root wrapper because
582
766
  neither exposes a callback transaction. `Database.transaction` over a `JSONDriver`
583
- therefore prefers this native path over the snapshot floor. Both reference drivers also
767
+ therefore prefers this native path over the journal. Both reference drivers also
584
768
  implement the paired `metadata?` / `stamp?` — `MemoryDriver` in-process only
585
769
  (the owned `DriverMetadata` snapshot lives in instance memory), `JSONDriver` persisted:
586
770
  the file is `{ metadata?: DriverMetadata, tables }`, with `metadata` present only
@@ -601,63 +785,18 @@ These invariants hold across the core database source tree ↔ this guide:
601
785
  `DatabaseError('DRIVER', 'Stored SQLite table is missing')` before any DDL in its
602
786
  open transaction, and IndexedDB throws
603
787
  `DatabaseError('DRIVER', 'Stored IndexedDB store is missing')` before its final
604
- open. Extra physical objects remain allowed, and SQLite may reconstruct a
605
- missing declared index because the table and its records still exist. IndexedDB
788
+ open. Extra tables and stores remain allowed, apart from an IndexedDB index the deployed
789
+ schema does not declare, which open drops; SQLite may reconstruct a missing declared index
790
+ because the table and its records still exist, and a writable SQLite open also drops each
791
+ created index of a deployed table that the deployed schema no longer declares. IndexedDB
606
792
  captures the bootstrap connection's exact stores and version in the same
607
- lifetime, then pins the persisted final open to that version; a concurrent
608
- versionchange makes the stale open reject instead of silently bumping and
609
- recreating storage. Existing unreadable, malformed, structurally incompatible,
793
+ lifetime, then pins the persisted final open to that version, or to the next one when
794
+ it drops an undeclared index; a concurrent versionchange makes the stale open reject
795
+ instead of silently bumping and recreating storage. Existing unreadable, malformed, structurally incompatible,
610
796
  or physically incomplete state throws `DRIVER` without publishing a handle or
611
797
  attempting table/store repair; after external repair, the same driver instance
612
798
  may retry `open`.
613
- `SQLiteDriver` and `IndexedDBDriver` complete the native-override
614
- picture from opposite ends, each earning trust its own way (see
615
- `.claude/rules/architecture.md` § System constraints).
616
- `SQLiteDriver` is **prove-exactness-or-refine**: real `CREATE TABLE` /
617
- `CREATE INDEX` DDL backs every table, but `records?` /
618
- `aggregate?` / `stream?` compile a `QueryInput` straight to SQL
619
- (`compileQuerySQL`, `compileAggregateSQL`) and run it natively only when
620
- `matchesQueryExactly` (built from `matchesConditionExactly` / `matchesOrderExactly`) first
621
- proves the SQL and the engine's semantics are identical for every
622
- condition and order term — otherwise the driver falls back to a full
623
- `scan` refined through the same core engine every scan-only driver uses
624
- (`applyQuery` / `filterRows` / `computeAggregate` / `matchesQuery`).
625
- Refine, not native SQL, is the path for: `like` / `glob` patterns (SQL
626
- `LIKE`/`GLOB` semantics can diverge from the engine's `matchesWildcardPattern`),
627
- every scalar condition over a column that is optional or nullable,
628
- `absent` / `present` only when the column is optional and nullable, a `null`
629
- or `undefined` scalar operand, an empty `any` / `none` operand list,
630
- mismatched operand types, `json` / `blob` columns, and any nested
631
- `FieldPath` — and a
632
- range operator (`above` / `below` / `from` / `to` / `between`) or an
633
- `ORDER BY` term over a `text` column: SQLite's default BINARY collation
634
- orders `TEXT` by Unicode code point while the core engine's `compareValues`
635
- orders JS strings by UTF-16 code unit, and the two diverge on
636
- supplementary-plane characters (code points ≥ U+10000, for example many emoji) —
637
- so text ranges and text ordering always refine through the engine, even
638
- though text equality (`equals`/`not`/`any`/`none`) and `starts`/`ends` stay
639
- native on a required non-null text column. `starts` / `ends` compile
640
- case-sensitively (a `substr` comparison plus a
641
- `typeof text === 'string'` guard; an empty operand falls back to a
642
- `typeof` check) when they do qualify as exact. `IndexedDBDriver` is **narrow-then-refine**:
643
- `records?` / `stream?` first ask `selectPlan` for a key-range pushdown over
644
- the primary key or a single-column secondary index — a candidate superset,
645
- never lossy — then hands that superset to the same core engine
646
- (`applyQuery` / `matchesQuery`) every scan-only driver uses, which
647
- refines it to the exact result; a plan that cannot prove itself range-exact
648
- (a nested path, a non-orderable column type, an `or`-joined condition, a
649
- non-comparison operator) falls back to a full scan. `below` / `to` push
650
- down only onto the primary store, never a secondary index — a secondary
651
- index has no entry for a row whose indexed column is absent or `null`,
652
- while the engine's total order (`compareValues`) lets those rows match a
653
- `below` / `to` bound; `equals` / `above` / `from` / `between` remain
654
- index-eligible on either. `conditionToRange` returns `undefined` for a `between`
655
- whose bounds are reversed (`compareValues(first, second) > 0`), so
656
- `selectPlan` falls back to a full scan instead of handing a raw
657
- backwards `IDBKeyRange` to the store (which would throw a `DataError`).
658
- `IndexedDBDriver.snapshot()` captures every store in one read transaction,
659
- so the capture is point-in-time consistent across stores even under
660
- concurrent writers; `restore` was already atomic. `SQLiteDriver` and
799
+ `SQLiteDriver` and
661
800
  `IndexedDBDriver` each implement `migrate?` natively and treat `MigrationInput` as one commit unit:
662
801
  `SQLiteDriver` applies schema, rows, and optional metadata inside one native
663
802
  SQLite transaction (`stepToSQL` projects each step's DDL), while a migration
@@ -673,20 +812,20 @@ These invariants hold across the core database source tree ↔ this guide:
673
812
  nothing is rewritten. Both implement the paired `metadata?` /
674
813
  `stamp?` into a reserved store name a user table must avoid:
675
814
  `SQLiteDriver` uses a single-row `_metadata` table (`METADATA_TABLE`), and
676
- `IndexedDBDriver` uses an out-of-line `__metadata__` store (`METADATA_STORE`), both
677
- excluded from a whole-store `snapshot`. `SQLiteDriver` implements
678
- `transaction?` as a callback-scoped real `BEGIN` / `COMMIT` / `ROLLBACK`;
815
+ `IndexedDBDriver` uses an out-of-line `__metadata__` store (`METADATA_STORE`), which no
816
+ table reaches. `SQLiteDriver` implements
817
+ `transaction?` as a callback-scoped real `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`;
679
818
  the capability performs reads, writes, migration, and metadata work inside
680
819
  that one native transaction, then becomes invalid. `IndexedDBDriver`
681
820
  deliberately omits `transaction?`: an `IDBTransaction` can auto-commit when
682
821
  control yields to a non-IDB `await`, so arbitrary callback awaits cannot
683
- truthfully remain inside one native transaction. It also omits `aggregate?`
684
- because IndexedDB has no native SUM/AVG/MIN/MAX; the engine over the narrowed
685
- `records?` covers it. A new backend implements a handful of small methods and
686
- inherits the entire query surface unchanged.
822
+ truthfully remain inside one native transaction. It also omits `aggregate?`, so every
823
+ aggregate it plans stays residual.
824
+
687
825
  4. **Total query helpers; the equality family is structural, not ranked.**
688
826
  `compareValues`, `matchesCondition`, and `matchesQuery` never throw — a
689
- type mismatch is a non-match and the comparator is a total order (it
827
+ type mismatch is a non-match there, which invariant 15 keeps from any read of a table,
828
+ and the comparator is a total order (it
690
829
  never returns `NaN`), mirroring the contracts guards' totality (see
691
830
  `.claude/rules/patterns.md` § Validation and contracts). The range
692
831
  operators (`above` / `below` / `from` / `to` /
@@ -716,9 +855,10 @@ These invariants hold across the core database source tree ↔ this guide:
716
855
  tables, queries, cursors, and streams also throw `CONFLICT` after settlement.
717
856
  When the driver implements `transaction?(scope)`, the driver owns
718
857
  acquisition, commit on fulfillment, rollback on rejection, release, and
719
- invalidation. Otherwise the universal single-writer floor snapshots the
720
- whole store, runs the same scoped callback, and restores the snapshot on
721
- rejection. Either path emits the identical `transaction` / `commit`
858
+ invalidation. Otherwise the core's before-image journal records the prior row of each
859
+ key the scope writes or deletes, on its first touch, and restores those keys on
860
+ rejection; a `clear` journals its table alone, and reads go to the driver, so a native
861
+ read sees the scope's writes. It gives rollback on rejection and no crash atomicity. Either path emits the identical `transaction` / `commit`
722
862
  lifecycle; `rollback(error)` is emitted only when rollback completed and the
723
863
  original scope/drain error remains the propagated rejection, never when
724
864
  cleanup itself replaced that error.
@@ -740,7 +880,14 @@ These invariants hold across the core database source tree ↔ this guide:
740
880
  restores, and the original transaction error still propagates (proven by
741
881
  the emit-safety tests). Reads / queries / counts are not emitted (a
742
882
  reader does not mutate, and those paths are too hot). The observation
743
- lives in the core layer; the drivers stay storage primitives.
883
+ lives in the core layer; the drivers stay storage primitives. `close`
884
+ destroys the database emitter last, after its `close` event and even when
885
+ the driver refuses to close, so a listener registered before `close`
886
+ receives nothing after it. `table(name, options)` takes `DatabaseTableOptions`:
887
+ `on` registers initial listeners on that handle's emitter, and `error`
888
+ routes their throws instead of the database's `error` option. A handle has no
889
+ lifecycle verb: its emitter ends with the handle, and after the database closes
890
+ no operation runs, so no handle emits.
744
891
  7. **Views share a driver.** A database is a typed view over a set of tables
745
892
  on one driver. `import(tables)` returns a new view of only those tables
746
893
  over the **same** driver (sharing storage and transactions); `export()`
@@ -757,13 +904,13 @@ These invariants hold across the core database source tree ↔ this guide:
757
904
  `migrate?` / `metadata?` / `stamp?` may be omitted). `MemoryDriver` and
758
905
  `JSONDriver` both omit `records?` / `aggregate?`, and both
759
906
  implement `stream?` / `migrate?` / `metadata?` / `stamp?`; `MemoryDriver` still
760
- omits `transaction?` (snapshot floor only) while `JSONDriver`
907
+ omits `transaction?` (the core's journal carries its scopes) while `JSONDriver`
761
908
  implements `transaction?` too (isolated candidate state plus one atomic
762
909
  publish on callback fulfillment). `SQLiteDriver` implements every optional hook — `records?` /
763
910
  `aggregate?` / `transaction?` / `stream?` / `migrate?` / `metadata?`
764
911
  / `stamp?` — the fully-native backend. `IndexedDBDriver` implements
765
- `records?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
766
- omits `transaction?` and `aggregate?` by IndexedDB's nature, not by
912
+ `records?` / `aggregate?` / `stream?` / `migrate?` / `metadata?` / `stamp?` but
913
+ omits `transaction?` by IndexedDB's nature, not by
767
914
  choice (see `.claude/rules/documentation.md` § Parity). A renamed / added /
768
915
  removed method breaks the gate
769
916
  until the table is reconciled.
@@ -789,9 +936,8 @@ These invariants hold across the core database source tree ↔ this guide:
789
936
  the temp file before rejection, and reads wait behind that unit. Once an
790
937
  commit point that cannot be aborted (`SQLite` call entry, IndexedDB transaction
791
938
  completion, JSON `rename` dispatch) has won, the operation awaits and reports its real
792
- result; a late signal cannot convert success to `ABORTED`. Batch items remain
793
- sequential and independent: earlier committed items survive an abort of a
794
- later item.
939
+ result; a late signal cannot convert success to `ABORTED`. A batch is one driver call,
940
+ so an abort ahead of its commit point applies no row of it.
795
941
  10. **Key generation is host-neutral and overridable.** When an optional
796
942
  primary column is omitted, a table uses global `crypto.randomUUID()`.
797
943
  `DatabaseOptions.generator` (a `KeyFunction`) authoritatively replaces
@@ -862,16 +1008,17 @@ These invariants hold across the core database source tree ↔ this guide:
862
1008
  README all call it the same way. It opens the fixed `users` and `posts`
863
1009
  schema per phase (calling `factory()` fresh each time so failures stay
864
1010
  isolated) and verifies the required surface's invariants (copy-in/copy-out
865
- isolation, upsert-overwrite, key-ordered `keys`/`scan`, `snapshot` rollback, a
866
- non-`id` primary key, structural round-tripping through `equalsValue`), then
1011
+ isolation, upsert-overwrite, key-ordered `keys`/`scan`, the batch invariants (a list
1012
+ read in key order, a list write that applies every row, a list insert with a conflicting
1013
+ final member and a mismatched batch that apply none, a list delete that reports each key
1014
+ once), the journal's round trip of prior rows, a non-`id` primary key, structural round-tripping through `equalsValue`), then
867
1015
  presence-gates the optional `migrate?` / `stream?` / `transaction?`
868
1016
  hooks when the driver implements them. The battery's `write-read` phase
869
1017
  is deepened with nested-field checks (a written row's nested object/array
870
1018
  fields must copy-in/copy-out isolated, not only its top-level fields),
871
- and a dedicated `snapshot-nested` phase asserts the same nested isolation
872
- across a `snapshot()` capture/restore round-trip — a driver that
873
- shallow-copies anywhere in its write/read/scan/snapshot boundary
874
- fails conformance (`MemoryDriver` passes by deep-copying through
1019
+ and the journal phase asserts the same nested isolation for a list read whose rows the
1020
+ journal restores — a driver that shallow-copies anywhere in its write/read/scan
1021
+ boundary fails conformance (`MemoryDriver` passes by deep-copying through
875
1022
  `structuredClone` at every one of those boundaries). The first violated
876
1023
  invariant throws a `CONFORMANCE` `DatabaseError` naming the failed check.
877
1024
  13. **Backend faults surface as `DatabaseError`, never raw.** No native
@@ -881,16 +1028,14 @@ These invariants hold across the core database source tree ↔ this guide:
881
1028
  (`#guard` internally on the SQLite side; `mapIndexedDBError` /
882
1029
  `mapMigrationError` on the IndexedDB side), preserving the original
883
1030
  error as `context.cause`. `SQLiteDriver`: a constraint violation maps to
884
- `CONFLICT`, a closed-connection fault to `CLOSED`, a busy/locked database
885
- to `DRIVER` with a `retryable` context flag, anything else to `DRIVER`.
886
- Snapshot capture puts the open gate, every prepare/read, and captured-map
887
- population inside one `#guard`; replay likewise contains the open gate,
888
- native transaction, deletes, prepares, and reinserts in one `#guard`.
889
- Public `close()` crosses that same boundary. A physically dropped declared
890
- table therefore rejects capture as top-level `DRIVER`, and a zero-timeout
891
- exclusive lock rejects replay as retryable `DRIVER` with
892
- `context.code === 'BUSY'`; both retain the actual `SQLiteError` only at
893
- `context.cause`.
1031
+ `CONFLICT`, a closed-connection fault to `CLOSED`, a busy database (`SQLITE_BUSY`, another
1032
+ connection's lock) to `DRIVER` with a `retryable` context flag, and anything else to
1033
+ `DRIVER`, `SQLITE_LOCKED` included: a lock the same connection holds, such as an open
1034
+ stream under a `migrate` that drops an index, carries no `retryable` flag, and its
1035
+ `context.cause.context.errcode` is 6.
1036
+ Public `close()` crosses that same boundary, and a zero-timeout exclusive lock rejects a
1037
+ write as retryable `DRIVER` with `context.code === 'BUSY'`, retaining the actual
1038
+ `SQLiteError` only at `context.cause`.
894
1039
  `IndexedDBDriver`: a constraint violation maps to `CONFLICT`; a
895
1040
  closed/not-open/invalid-state fault to `CLOSED`; a quota fault to
896
1041
  `DRIVER` with `code: 'QUOTA'`; `migrate`'s versionchange path remaps an
@@ -905,11 +1050,43 @@ These invariants hold across the core database source tree ↔ this guide:
905
1050
  as corrupted metadata. Because both drivers derive their index names from
906
1051
  a length-prefixed scheme (`deriveSQLiteIndexName` for SQLite,
907
1052
  `deriveIndexedDBIndexName` for IndexedDB) to stay collision-free across
908
- compound indexes, a database
909
- file/store created under an older naming scheme leaves its old-named
910
- indexes orphaned (unreferenced, harmless) on reopen under the new scheme —
911
- they are never queried and never collide, but a storage audit may notice
912
- them.
1053
+ compound indexes. A writable SQLite open drops every created index of a deployed table
1054
+ whose name its deployed schema does not derive, an old-named index included; an IndexedDB
1055
+ store created under an older naming scheme leaves its old-named indexes orphaned
1056
+ (unreferenced, harmless) on reopen — they are never queried and never collide, but a
1057
+ storage audit may notice them.
1058
+
1059
+ 15. **Every read passes the query door.** `records`, `count`, `aggregate`, `scan`, and each
1060
+ `query()` terminal, a filtered `aggregate` included, admit a copy of their read after the
1061
+ driver is ready and before any driver call, and read only that copy, so a change the
1062
+ caller makes afterward never reaches the read. Only an absent read (`undefined`) skips
1063
+ the door; `null` refuses. The shape-derived guard of `queryInputContract` holds the
1064
+ structure: each condition is a union keyed on `operator` that fixes the arity of
1065
+ `values`, `like`, `glob`, `starts`, and `ends` take a string operand, a column is a name
1066
+ or a non-empty list of strings, `connector` and `direction` are their literals, `limit`
1067
+ and `offset` are nonnegative integers, and every object refuses an undeclared key. A pass
1068
+ over the table's columns holds the schema facts: the leading column of a condition, an
1069
+ ordering term, and the aggregate column is declared; a nested path descends only a
1070
+ `json` column; an operand matches its column's storage class (a string for `text`, a
1071
+ number for `integer` and `real`, a boolean for `boolean`, any value on `json`); `null`
1072
+ stands only on a nullable column and `undefined` only on an optional one, each for
1073
+ `equals`, `not`, `any`, and `none`, never under a range operator; `like`, `glob`,
1074
+ `starts`, and `ends` read a `text` or `json` column; the aggregate operation is one of
1075
+ `AGGREGATE_OPERATIONS`; and every string operand is well-formed UTF-16, on a `json`
1076
+ column and under a nested path too. The pass reads no refinement: integer-ness, bounds,
1077
+ patterns, and literal membership stay the contract's. A literal whose members span more
1078
+ than one class is `json` storage, as a union is. A refusal is `VALIDATION` whose context
1079
+ carries `table` and `faults`: the guard's `admitValue` faults, computed only after the
1080
+ guard refuses, then the faults of the column pass, which also runs when the guard refuses
1081
+ and skips each condition and ordering term a guard fault names, so one refusal names every
1082
+ fault once. The message is a header and the contract's `describeFaults` rendering, bounded
1083
+ by `FAULT_TEXT_LIMIT`. When the column pass reports, the header and the context add the
1084
+ `column` its first fault names, and the `operator` when the guard admitted the read, and
1085
+ the header lists the declared columns. An aggregate is admitted as a copy with its read, and
1086
+ the table computes from that copy. A lone surrogate in a written `text` value or in a key
1087
+ is `VALIDATION` with `table` and `column` on every driver, because SQLite stores it as
1088
+ U+FFFD and reads back a changed value; a `json` cell holding one round-trips, because
1089
+ `JSON.stringify` escapes it.
913
1090
 
914
1091
  What ships is the **core in-between** (schema-aware: `open` receives a
915
1092
  derived `TableSchema[]`, with `shapeToColumnStorage` mapping each column's shape), its
@@ -917,7 +1094,7 @@ reference `MemoryDriver`, and the persistent `JSONDriver`, `SQLiteDriver`, and
917
1094
  `IndexedDBDriver` backends. `JSONDriver` in `src/server` is a decorator over
918
1095
  `MemoryDriver` that loads/flushes a single JSON file — every primitive
919
1096
  delegates to the inner memory driver, so querying, key-order `scan` / `keys`,
920
- and capture-replay `snapshot` are inherited unchanged; `JSONDriver.migrate`
1097
+ and the all-or-nothing batches are inherited unchanged; `JSONDriver.migrate`
921
1098
  additionally persists the migrated state, and every flush is atomic — written
922
1099
  to a sibling temp file and `rename`d onto the target path, so a crash mid-flush
923
1100
  can never truncate or corrupt the previous good file. Outside a `transaction`,
@@ -932,7 +1109,7 @@ active, and a captured capability used after settlement throw `CONFLICT`.
932
1109
  fully-native, **trusted-mode** backend on the published `@orkestrel/sqlite`
933
1110
  wrapper — real typed `CREATE TABLE` / `CREATE INDEX` DDL, native
934
1111
  `records?` / `aggregate?` / `stream?` compiled straight to SQL,
935
- real `BEGIN` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
1112
+ real `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK` transactions, atomic DDL migration
936
1113
  (`stepToSQL`; a root input uses one native transaction, while an input inside
937
1114
  an existing callback transaction uses the guarded fixed internal savepoint
938
1115
  literal for caught-inner-failure containment while the outer transaction stays
@@ -941,15 +1118,13 @@ and a reserved
941
1118
  `_metadata` table (`METADATA_TABLE`) for `metadata?` / `stamp?` versioning — every
942
1119
  optional `DriverInterface` hook, none skipped. `IndexedDBDriver` in
943
1120
  `src/browser`, on the published `@orkestrel/indexeddb` wrapper, is the
944
- **narrow-then-refine** persistent browser backend — `selectPlan` turns a
945
- `QueryInput` into a key-range pushdown over the primary key or a single-column
946
- secondary index (a candidate superset, never lossy) that the same core
947
- engine then refines to the exact result; `migrate?` applies a non-empty plan
1121
+ persistent browser backend — `planIndexedDBQuery` keeps native the one access path
1122
+ `findAccessPlan` ranks first, with the order, page, `count`, `minimum`, and `maximum` that
1123
+ path serves, and leaves the rest of the read residual for the core engine; `migrate?` applies a non-empty plan
948
1124
  and its metadata in one versionchange transaction, and `metadata?` / `stamp?`
949
1125
  persist into a reserved
950
1126
  `__metadata__` store (`METADATA_STORE`) — it omits `transaction?` because arbitrary
951
- callback awaits outlive an auto-committing `IDBTransaction`, and
952
- `aggregate?` (no native SUM/AVG/MIN/MAX) by IndexedDB's own nature. The core
1127
+ callback awaits outlive an auto-committing `IDBTransaction`. The core
953
1128
  `Database` / `Table` are also **observable** — each owns a typed `emitter`
954
1129
  (`DatabaseEventMap` / `TableEventMap`) carrying the transaction +
955
1130
  per-row lifecycle (see [Observing](#observing)); a driver stays a storage
@@ -992,9 +1167,8 @@ posts.primary // 'slug' — the declared override
992
1167
 
993
1168
  Each `indexes` entry is one (possibly compound) index of column names; they
994
1169
  flow into each table's derived `TableSchema`. Neither driver here declares a
995
- native index, so both ignore them; SQLite and IndexedDB use supported
996
- declarations for native indexes and still refine through the shared engine when
997
- required.
1170
+ native index, so both ignore them; SQLite and IndexedDB build a native index from each
1171
+ supported declaration, and IndexedDB drops at open an index the declaration no longer names.
998
1172
 
999
1173
  ### Swapping the driver
1000
1174
 
@@ -1089,6 +1263,47 @@ await users.count() // every row, unfiltered
1089
1263
  await users.aggregate('average', 'age') // number | undefined
1090
1264
  ```
1091
1265
 
1266
+ ### The query door
1267
+
1268
+ A table admits each read before any driver call, so a malformed read raises in place of an
1269
+ empty or a whole-table answer. The refusal names the table, and the key path and expected class
1270
+ of each fault; when the column pass reports, it also names the column and operator of its first
1271
+ fault and lists the declared columns:
1272
+
1273
+ ```ts
1274
+ import { createDatabase, createMemoryDriver } from '@orkestrel/database'
1275
+ import { integerShape, optionalShape, stringShape } from '@orkestrel/contract'
1276
+
1277
+ const items = createDatabase({
1278
+ driver: createMemoryDriver(),
1279
+ tables: {
1280
+ items: { id: stringShape(), rank: integerShape(), note: optionalShape(stringShape()) },
1281
+ },
1282
+ }).table('items')
1283
+ await items.set([
1284
+ { id: 'a', rank: 5 },
1285
+ { id: 'b', rank: 7, note: 'kept' },
1286
+ ])
1287
+
1288
+ await items.count({
1289
+ conditions: [{ column: 'note', operator: 'equals', values: [undefined], connector: 'and' }],
1290
+ }) // 1 — `undefined` stands on an optional column
1291
+ await items
1292
+ .count({ conditions: [{ column: 'rank', operator: 'equals', values: ['5'], connector: 'and' }] })
1293
+ .catch((error: unknown) => error)
1294
+ // DatabaseError VALIDATION, context { table: 'items', column: 'rank', operator: 'equals', faults: [
1295
+ // { reason: 'type', path: ['conditions', '0', 'values', '0'], expected: 'number', received: '"5"' }] }
1296
+ await items
1297
+ .records({ conditions: [{ column: 'rnk', operator: 'absent', values: [], connector: 'and' }] })
1298
+ .catch((error: unknown) => error)
1299
+ // DatabaseError VALIDATION; the message lists the declared columns: id text, rank integer, note text optional
1300
+ await items.get('a\uD800').catch((error: unknown) => error)
1301
+ // DatabaseError VALIDATION, context { table: 'items', column: 'id' } — a lone surrogate in a key
1302
+ ```
1303
+
1304
+ `queryInputContract` is the same door for a caller that admits a read before it reaches a
1305
+ table, such as a server that takes a read from a client.
1306
+
1092
1307
  ### Streaming with early exit
1093
1308
 
1094
1309
  `scan` (on a table) and `stream` (on a query) are lazy — rows are yielded one
@@ -1179,8 +1394,8 @@ write. Memory and SQLite check immediately before their synchronous mutation;
1179
1394
  IndexedDB aborts its explicit readwrite transaction while active; JSON aborts
1180
1395
  staging, cleans its temp file, and restores the preimage before rejecting. If
1181
1396
  the native commit has already been dispatched, the method ignores a late abort
1182
- and awaits the real success or failure. A batch passes the same signal to each
1183
- sequential item, so already-committed earlier items remain committed.
1397
+ and awaits the real success or failure. A batch is one driver call with one commit point,
1398
+ so an abort applies every row of it or none.
1184
1399
 
1185
1400
  ### Batch operations
1186
1401
 
@@ -1214,33 +1429,46 @@ await users.get(['u1', 'u2']) // → readonly (Row | undefined)[]
1214
1429
  await users.resolve(['u1', 'u2']) // → readonly Row[] (NOT_FOUND on any miss)
1215
1430
  await users.has(['u1', 'u2']) // → readonly boolean[]
1216
1431
  await users.update(['u1', 'u2'], { role: 'member' }) // same changes to each → readonly boolean[]
1217
- await users.remove(['u1', 'u2']) // → readonly boolean[]
1432
+ await users.remove(['u1', 'u2']) // → boolean, true only when every distinct listed key held a row and was removed
1218
1433
  ```
1219
1434
 
1220
- A batch runs as independent sequential operations; wrap it in `transaction`
1221
- when it must be atomic.
1435
+ A batch is one driver call that applies every row or none. The table admits every row through
1436
+ the contract ahead of that call, so a refused row applies none of the batch, and a conflicting
1437
+ `add` member does the same. SQLite runs the batch as one transaction, or as one savepoint
1438
+ inside a scope; IndexedDB runs it in one `database.write` scope; `MemoryDriver` and
1439
+ `JSONDriver` check every row ahead of the first change. `get`, `resolve`, and `has` of a key
1440
+ list are one list `read`, and `update` of a key list is one list `read` and one list
1441
+ `write`.
1222
1442
 
1223
1443
  ### Admission through the contract
1224
1444
 
1225
- Admits a numeric string against the table's contract, stores the repaired number, and refuses an undeclared column:
1445
+ Repairs a numeric string through the table's contract before the write, stores the number, and refuses the bare write and an undeclared column:
1226
1446
 
1227
1447
  ```ts
1228
1448
  import { createDatabase, createMemoryDriver, isDatabaseError } from '@orkestrel/database'
1229
- import { admitValue, integerShape, stringShape } from '@orkestrel/contract'
1449
+ import type { DatabaseInterface } from '@orkestrel/database'
1450
+ import { integerShape, repairValue, stringShape } from '@orkestrel/contract'
1230
1451
 
1231
- const users = createDatabase({
1452
+ // A DatabaseInterface hands out untyped rows, as a boundary that holds loose data needs.
1453
+ const db: DatabaseInterface = createDatabase({
1232
1454
  driver: createMemoryDriver(),
1233
1455
  tables: {
1234
1456
  users: { id: stringShape(), name: stringShape(), age: integerShape(), role: stringShape() },
1235
1457
  },
1236
- }).table('users')
1458
+ })
1459
+ const users = db.table('users')
1237
1460
 
1238
- // A numeric string is a lossless repair, so admitValue admits it as the number.
1239
- const admitted = admitValue(users.contract, { id: 'u2', name: 'Bo', age: '41', role: 'member' })
1240
- if (!admitted.success) throw new Error('Expected the row to admit')
1241
- await users.set(admitted.value.value)
1461
+ // A numeric string is a lossless repair, so repairValue admits it as the number before the write.
1462
+ const loose = { id: 'u2', name: 'Bo', age: '41', role: 'member' }
1463
+ const repaired = repairValue(users.contract, loose)
1464
+ if (!repaired.success) throw new Error('Expected the row to repair')
1465
+ await users.set(repaired.value.value)
1242
1466
  ;(await users.get('u2'))?.age // 41 (a number)
1243
1467
 
1468
+ // The bare write refuses the same row with DatabaseError('VALIDATION') and the type fault.
1469
+ const bare = await users.set({ ...loose, id: 'u4' }).catch((error: unknown) => error)
1470
+ if (isDatabaseError(bare)) bare.message // contains 'age: type; expected integer; received "41"'
1471
+
1244
1472
  // An undeclared column refuses with DatabaseError('VALIDATION') and the contract's faults.
1245
1473
  const imported = { id: 'u3', name: 'Cy', age: 29, role: 'member', nickname: 'Cy' }
1246
1474
  const refused = await users.set(imported).catch((error: unknown) => error)
@@ -1377,9 +1605,10 @@ await users
1377
1605
  .collect()
1378
1606
  ```
1379
1607
 
1380
- The condition operators map to familiar SQL operators. The engine
1381
- evaluates every one of them in JS over `scan`; SQLite and IndexedDB push down
1382
- provably exact candidate work and refine through these same semantics:
1608
+ The condition operators map to familiar SQL operators. The core engine evaluates each one
1609
+ over a residual; SQLite answers each natively on a flat declared column, and IndexedDB
1610
+ answers the conditions of one access path with a key range or a key list, under these same
1611
+ semantics:
1383
1612
 
1384
1613
  | Operator | SQL |
1385
1614
  | --------- | ------------- |
@@ -1558,6 +1787,35 @@ error. `rollback(error)` reports only a completed rollback whose original
1558
1787
  scope/drain error is still being propagated — a cleanup failure is never
1559
1788
  reported as a successful rollback.
1560
1789
 
1790
+ On a driver without `transaction?` (`MemoryDriver`, `IndexedDBDriver`, a custom backend), the
1791
+ core runs the scope through its before-image journal, `StorageJournal`: each write, insert,
1792
+ or delete reads the prior rows of its untouched keys in one list `read` ahead of the write,
1793
+ and a `clear` reads its table's keys and rows ahead of emptying it. On rejection the journal
1794
+ writes back each cleared table and each recorded row and deletes each recorded key that held
1795
+ no row, so the cost of a scope follows the keys it touched rather than the store's size.
1796
+ Reads go to the driver, so a native read inside the scope sees the scope's writes. The
1797
+ journal gives rollback on rejection and no crash atomicity:
1798
+
1799
+ ```ts
1800
+ import { createMemoryDriver, StorageJournal } from '@orkestrel/database'
1801
+
1802
+ const driver = createMemoryDriver()
1803
+ await driver.open([
1804
+ {
1805
+ name: 'users',
1806
+ primary: 'id',
1807
+ columns: [{ name: 'id', storage: 'text', optional: false, nullable: false }],
1808
+ indexes: [],
1809
+ },
1810
+ ])
1811
+ await driver.write('users', 'u1', { id: 'u1', name: 'Ada' })
1812
+ const journal = new StorageJournal(driver)
1813
+ await journal.write('users', 'u1', { id: 'u1', name: 'Grace' })
1814
+ await journal.insert('users', 'u2', { id: 'u2', name: 'Alan' })
1815
+ await journal.restore()
1816
+ await driver.read('users', ['u1', 'u2']) // [{ id: 'u1', name: 'Ada' }, undefined]
1817
+ ```
1818
+
1561
1819
  Root promise operations enter the shared admission ledger synchronously, before
1562
1820
  their first `await`. `transaction()` closes root admission before it drains that
1563
1821
  ledger, so work accepted immediately before the transaction is included and work
@@ -1586,7 +1844,7 @@ await boundary.track(async () => 42) // 42
1586
1844
  ### Native transactions
1587
1845
 
1588
1846
  `transaction` uses a driver's optional native `transaction?(scope)` hook
1589
- instead of the snapshot floor. The driver passes a `StorageInterface`
1847
+ instead of the core's journal. The driver passes a `StorageInterface`
1590
1848
  capability to the callback, commits when it fulfills, rolls back when it
1591
1849
  rejects, and invalidates the capability after settlement. The database-level
1592
1850
  `transaction` / `commit` / `rollback` events fire the same either way:
@@ -1830,10 +2088,10 @@ schemaToStore(table)
1830
2088
 
1831
2089
  The helper delegates exact JSON ownership to Contract 0.0.9's
1832
2090
  `cloneJSONRecord`, then validates the owned output as `DriverMetadata`. A malformed
1833
- shape, cycle, function, accessor, or hostile/revoked proxy throws
2091
+ shape, cycle, function, accessor, or throwing/revoked proxy throws
1834
2092
  `DatabaseError('VALIDATION')` with `context.path === 'metadata'`; clone/traversal
1835
2093
  failures are retained only as `context.cause`, so no raw Contract or caller
1836
- error crosses the Database surface. Hostile values are never stringified or
2094
+ error crosses the Database surface. Untrusted values are never stringified or
1837
2095
  embedded in the diagnostic.
1838
2096
 
1839
2097
  `JSONDriver` applies that ownership rule at every file-backed seam: valid parsed
@@ -1848,7 +2106,7 @@ structured-clone behavior and are not forced through the JSON metadata cloner.
1848
2106
 
1849
2107
  `SQLiteDriver` applies the same boundary at persisted-row ingress, every
1850
2108
  root/scoped `stamp` and `migrate` ingress, and every `metadata()` copy-out.
1851
- Root lifecycle and scoped token gates run before hostile metadata traversal;
2109
+ Root lifecycle and scoped token gates run before untrusted metadata traversal;
1852
2110
  valid migration metadata is cloned before its first DDL statement. Malformed
1853
2111
  stored metadata fails closed with `DRIVER`, while valid copy-outs are distinct
1854
2112
  and deeply frozen. General SQLite rows continue through
@@ -1939,8 +2197,9 @@ const db = createDatabase({
1939
2197
  on: { commit: () => console.log('transaction committed') },
1940
2198
  })
1941
2199
 
1942
- const users = db.table('users') // hold the handle (the documented practice) and observe it
1943
- users.emitter.on('write', (key) => console.log('invalidate users', key))
2200
+ const users = db.table('users', {
2201
+ on: { write: (key) => console.log('invalidate users', key) },
2202
+ }) // hold the handle (the documented practice) and observe it
1944
2203
  users.emitter.on('remove', (key) => console.log('invalidate users', key))
1945
2204
  db.emitter.on('rollback', (error) => console.warn('transaction rolled back', error))
1946
2205
  ```
@@ -1955,7 +2214,7 @@ The event vocabulary:
1955
2214
  `open` fires once when the handle's driver connects (an explicit `open()`, or
1956
2215
  the lazy first-use connect); `close`
1957
2216
  when the driver is released; `transaction` when a scope begins after its
1958
- native boundary or fallback snapshot is acquired; `commit` only after a scope
2217
+ native boundary is acquired or its journal is created; `commit` only after a scope
1959
2218
  succeeds; `rollback` only after a throwing scope's tables are all restored;
1960
2219
  `migrate` after a migration commits. A `Table` fires `write` after any
1961
2220
  row put (set / add / update — re-read by key if you need the new value),
@@ -1963,7 +2222,12 @@ row put (set / add / update — re-read by key if you need the new value),
1963
2222
  and `clear` after the table is emptied. Reads / queries / counts are **not**
1964
2223
  emitted — a reader does not mutate, and those paths are too hot. Each
1965
2224
  `db.table(name)` returns a fresh handle with its own emitter, so subscribe
1966
- on the handle you hold and operate on that same handle.
2225
+ on the handle you hold and operate on that same handle, or pass initial
2226
+ listeners through the handle's `on` option. `close` destroys the database
2227
+ emitter after its `close` event, so a database listener receives nothing after
2228
+ `close`. A table handle has no lifecycle verb: its emitter ends with the handle, and
2229
+ after `close` every table operation refuses with `CLOSED`, so a table listener
2230
+ receives nothing after it either.
1967
2231
 
1968
2232
  **Listener isolation.** A listener throw never escapes
1969
2233
  into the engine: the emitter isolates it and routes it to
@@ -1980,8 +2244,8 @@ propagates, the tables still roll back), and a throwing `write` observer
1980
2244
  leaves the written row intact — proven by the per-entity emit-safety tests.
1981
2245
  (A `Table` reached through the `Database` receives the same `error` handler
1982
2246
  the `DatabaseOptions.error` option supplies, so a `Table` listener throw
1983
- routes there; with no `error` handler configured, the throw is swallowed
1984
- silently.)
2247
+ routes there unless the handle's own `DatabaseTableOptions.error` option supplies one;
2248
+ with no `error` handler configured, the throw is swallowed silently.)
1985
2249
 
1986
2250
  ### Importing and exporting schemas
1987
2251
 
@@ -2097,17 +2361,18 @@ await driver.write('users', 'u1', { id: 'u1', name: 'Ada Lovelace' }) // upsert
2097
2361
  await driver.read('users', 'u1') // { id: 'u1', name: 'Ada' } | undefined
2098
2362
  for await (const row of driver.scan('users')) row // every row, key order
2099
2363
  await driver.keys('users') // readonly Key[]
2100
- const rollback = await driver.snapshot() // capture, then...
2101
- await driver.delete('users', 'u1') // boolean
2102
- await rollback() // ...restore the captured state
2364
+ await driver.write('users', ['u2', 'u3'], [{ id: 'u2' }, { id: 'u3' }]) // every row or none
2365
+ await driver.read('users', ['u1', 'missing']) // [{ id: 'u1', name: 'Ada Lovelace' }, undefined]
2366
+ await driver.delete('users', ['u2', 'u2']) // [true, false]
2367
+ await driver.delete('users', 'u1') // true
2103
2368
  await driver.clear('users')
2104
2369
  await driver.close()
2105
2370
  ```
2106
2371
 
2107
2372
  ### Query engine helpers
2108
2373
 
2109
- The pure functions behind `TableInterface` and `QueryInterface` — useful
2110
- directly when building a new driver's native `records` / `aggregate` hook:
2374
+ The pure functions of the core's engine, which runs the residual of a driver's plan
2375
+ behind `TableInterface` and `QueryInterface`:
2111
2376
 
2112
2377
  ```ts
2113
2378
  import type { Condition } from '@orkestrel/database'
@@ -2131,7 +2396,7 @@ import {
2131
2396
 
2132
2397
  compareValues(1, 2) // -1 — a total order over mixed types
2133
2398
  matchesWildcardPattern('hello', 'h%o', '%', '_', true) // true — the shared LIKE/GLOB engine
2134
- matchesLikePattern('hello', 'h%o') // true — case-insensitive
2399
+ matchesLikePattern('Hello', 'h%o') // true — ASCII letters fold
2135
2400
  matchesGlobPattern('hello', 'h*o') // true — case-sensitive
2136
2401
 
2137
2402
  const condition: Condition = {
@@ -2154,6 +2419,36 @@ shapeToColumnStorage(integerShape()) // 'integer' — the type `open` hands a dr
2154
2419
  equalsValue({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }) // true — structural, not reference, equality
2155
2420
  ```
2156
2421
 
2422
+ ### Recording driver calls
2423
+
2424
+ `StorageRecorder` wraps a real driver and counts the keys each call addresses and the rows it
2425
+ returns or yields; `tallyCalls` totals one member. Its `driver` declares exactly the members
2426
+ its source declares, so a read plans as it would on the source:
2427
+
2428
+ ```ts
2429
+ import { integerShape, stringShape } from '@orkestrel/contract'
2430
+ import {
2431
+ createDatabase,
2432
+ createMemoryDriver,
2433
+ StorageRecorder,
2434
+ tallyCalls,
2435
+ } from '@orkestrel/database'
2436
+
2437
+ const recorder = new StorageRecorder(createMemoryDriver())
2438
+ const users = createDatabase({
2439
+ driver: recorder.driver,
2440
+ tables: { users: { id: stringShape(), age: integerShape() } },
2441
+ }).table('users')
2442
+ await users.set([
2443
+ { id: 'u1', age: 36 },
2444
+ { id: 'u2', age: 7 },
2445
+ ])
2446
+
2447
+ const { value, calls } = await recorder.measure(() => users.count())
2448
+ value // 2
2449
+ tallyCalls(calls, 'scan') // { calls: 1, keys: 0, rows: 2 } — the Memory driver answers over scan
2450
+ ```
2451
+
2157
2452
  ### Persistence with the JSON driver
2158
2453
 
2159
2454
  Opens a database over the JSON driver and writes one row, persisted to the backing file:
@@ -2206,19 +2501,19 @@ restored before that error leaves the exclusive queue, so the next operation
2206
2501
  can proceed after the temporary obstruction is removed. A successful staging
2207
2502
  write requests native `flush: true` before the same-directory atomic rename.
2208
2503
 
2209
- `JSONDriver.snapshot()` captures owned row data together with the table schema
2210
- needed to decode that capture. Its rollback thunk is repeatable and restores
2211
- data only into the driver's current schema: current metadata is never rewound,
2212
- a captured table removed after capture is skipped, and a table added later is
2213
- preserved. Replaying the same thunk again produces the same row result without
2214
- replacing the current schema or metadata.
2504
+ Each root write, insert, or delete, a list included, records its prior rows in a
2505
+ `StorageJournal` over the driver's memory, applies the change, and flushes the whole store
2506
+ once; a failed flush restores the journaled rows before the error leaves the queue, so memory
2507
+ and the file hold the same rows. An empty list changes no row and leaves the file in place.
2508
+ `clear` flushes the table as empty ahead of emptying memory, so a failed flush leaves memory
2509
+ holding every row it held.
2215
2510
 
2216
2511
  ### Compiling input to SQL
2217
2512
 
2218
2513
  The server's pure `compilers.ts` turns a core `QueryInput` (the same one
2219
2514
  `applyQuery` folds) into the `WHERE` / `ORDER BY` / `LIMIT` tail of a
2220
- `SELECT`, with `?`-bound parameters in clause order — the payload a native SQLite
2221
- driver's `records` hook runs directly:
2515
+ `SELECT`, with `?`-bound parameters in clause order — the native side of a plan that a
2516
+ SQLite driver's `records` hook runs:
2222
2517
 
2223
2518
  ```ts
2224
2519
  import {
@@ -2227,8 +2522,8 @@ import {
2227
2522
  compileFieldSQL,
2228
2523
  compileQuerySQL,
2229
2524
  deriveSQLiteIndexName,
2230
- matchesAggregateExactly,
2231
2525
  matchesSQLiteAffinity,
2526
+ planSQLiteQuery,
2232
2527
  quoteIdentifier,
2233
2528
  schemaToIndexes,
2234
2529
  schemaToTable,
@@ -2249,14 +2544,14 @@ const schema: TableSchema = {
2249
2544
  compileQuerySQL(
2250
2545
  { conditions: [{ column: 'age', operator: 'from', values: [18], connector: 'and' }] },
2251
2546
  schema,
2252
- ) // { sql: 'WHERE "age" >= ? ORDER BY "id"', parameters: [18] }
2547
+ ) // { sql: 'WHERE "age" >= ? ORDER BY "id" ASC', parameters: [18] }
2253
2548
 
2254
2549
  quoteIdentifier('order') // '"order"'
2255
2550
  deriveSQLiteIndexName('users', ['age']) // 'idx_5_users_3_age'
2256
2551
  compileColumnSQL('integer') // 'INTEGER'
2257
- compileFieldSQL(['profile', 'score']) // 'json_extract("profile", \'$.score\')'
2552
+ compileFieldSQL(['profile', 'score']) // `json_extract(CASE WHEN typeof("profile") = 'text' THEN "profile" END, '$."score"')`
2258
2553
  compileAggregateSQL('average', 'age') // 'AVG("age")'
2259
- matchesAggregateExactly('minimum', 'age', schema) // true
2554
+ planSQLiteQuery({ aggregate: { operation: 'minimum', column: 'age' } }, schema).residual // {}
2260
2555
  matchesSQLiteAffinity('INTEGER', 'integer') // true
2261
2556
  schemaToTable(schema) // CREATE TABLE IF NOT EXISTS …
2262
2557
  schemaToIndexes(schema) // []
@@ -2266,31 +2561,36 @@ stepToSQL({ operation: 'index.add', table: 'users', index: ['age'] })
2266
2561
  // db.prepare(`SELECT * FROM "users" ${sql}`).all(...parameters)
2267
2562
  ```
2268
2563
 
2269
- ### Exact-or-refine vs. narrow-then-refine native reads
2270
-
2271
- A native override earns the engine's trust by proving exactness or by
2272
- narrowing then refining (see `.claude/rules/architecture.md` § System
2273
- constraints).
2274
- **Prove-exactness-or-refine** (`SQLiteDriver`): the backend has real typed
2275
- columns and indexes, so it compiles the `QueryInput` straight to SQL and runs
2276
- it natively only when `matchesQueryExactly` first proves the SQL and the engine
2277
- agree on every condition/order term for that schema — otherwise it falls
2278
- back to a full scan refined through the same core engine (never a "trust
2279
- blindly" path). **Narrow-then-refine**
2280
- (`IndexedDBDriver`): the backend can only prove a candidate superset range-exact
2281
- (a key-range pushdown), so it fetches that superset and hands it to the same
2282
- core engine every scan-only driver uses (`applyQuery` / `matchesQuery`),
2283
- which refines it down to the exact result — conformance is earned by "never
2284
- under-fetch," not by native filtering. Both are indistinguishable from the
2285
- caller's side: `Table.records` / `count` / `stream` return identical rows
2286
- either way; only the path to get there differs.
2564
+ ### Plans and residual work
2565
+
2566
+ A driver's `plan` splits each read into the part its engine answers and the residual the
2567
+ core runs, under the native-first rule the `DriverInterface` doc block states. A read is
2568
+ wholly native when `residual` equals `{}`. `planSQLiteQuery` is the SQLite driver's plan,
2569
+ and `compileQuerySQL` compiles its native side; `planIndexedDBQuery` is the IndexedDB
2570
+ driver's plan, which keeps one ranked access path native with the order, page, and count it
2571
+ serves. A driver without `plan`, such as
2572
+ `MemoryDriver` and `JSONDriver`, answers the whole read as residual over `scan`. `Table` runs
2573
+ every read through `readPlannedRows`, `readPlannedAggregate`, and `streamPlannedRows`, the one
2574
+ read procedure `scanDriver`'s differential checks.
2575
+
2576
+ Two SQLite forms keep a read native where a flag or a path would otherwise send it to the
2577
+ core. An order on a column that is both optional and nullable compiles a rank ahead of the
2578
+ column term, in the term's direction: absence ranks 0, the column's `null` sentinel ranks 1,
2579
+ and a value ranks 2, so the engine returns the core's total order, and the page stays native
2580
+ beside it. When every connector is `and`, `matchesSQLitePrefilter` admits `equals`, `not`,
2581
+ `any`, and `none` with scalar operands on a nested path under a `json` head, and the plan puts
2582
+ the condition on both sides: `compileNestedSQL` tests the JSON type at the path beside its
2583
+ value, so the engine keeps a superset of the rows and the core rechecks each one. A key that
2584
+ can name an array member, a canonical index such as `0` or `length`, keeps the condition
2585
+ residual alone, because a JSON path label names an object member only. A prefilter holds the
2586
+ page on the residual side, so the core still stops at `offset + limit` matches.
2287
2587
 
2288
2588
  ```ts
2289
2589
  import type { Condition, TableSchema } from '@orkestrel/database'
2290
2590
  import {
2291
- matchesConditionExactly,
2292
- matchesQueryExactly,
2293
- matchesOrderExactly,
2591
+ compileQuerySQL,
2592
+ matchesSQLiteCondition,
2593
+ planSQLiteQuery,
2294
2594
  } from '@orkestrel/database/server'
2295
2595
 
2296
2596
  const schema: TableSchema = {
@@ -2303,28 +2603,29 @@ const schema: TableSchema = {
2303
2603
  indexes: [],
2304
2604
  }
2305
2605
 
2306
- const exact: Condition = {
2606
+ const native: Condition = {
2307
2607
  column: 'age',
2308
2608
  operator: 'above',
2309
2609
  values: [18],
2310
2610
  connector: 'and',
2311
2611
  }
2312
- matchesConditionExactly(exact, schema) // true — a plain comparison over a typed column
2612
+ matchesSQLiteCondition(native, schema) // true — a comparison over a typed column
2313
2613
 
2314
- const notExact: Condition = {
2614
+ const residual: Condition = {
2315
2615
  column: 'age',
2316
2616
  operator: 'above',
2317
2617
  values: [null],
2318
2618
  connector: 'and',
2319
2619
  }
2320
- matchesConditionExactly(notExact, schema) // false — a null operand refines instead
2620
+ matchesSQLiteCondition(residual, schema) // false — a null range operand stays residual
2321
2621
 
2322
- matchesOrderExactly({ column: 'age', direction: 'ascending' }, schema) // true — a flat, orderable column
2323
-
2324
- matchesQueryExactly(
2325
- { conditions: [exact], order: [{ column: 'age', direction: 'ascending' }] },
2622
+ const plan = planSQLiteQuery(
2623
+ { conditions: [native], order: [{ column: 'age', direction: 'ascending' }], limit: 10 },
2326
2624
  schema,
2327
- ) // true
2625
+ ) // { native: { conditions: [ … ], order: [ … ], limit: 10 }, residual: {} }
2626
+
2627
+ compileQuerySQL(plan.native, schema)
2628
+ // { sql: 'WHERE "age" > ? ORDER BY "age" ASC, "id" ASC LIMIT ?', parameters: [18, 10] }
2328
2629
  ```
2329
2630
 
2330
2631
  ### Persistence with the SQLite driver
@@ -2358,15 +2659,18 @@ await db
2358
2659
  // Real transactions and atomic migration ship with it:
2359
2660
  await db.transaction(async (transaction) => {
2360
2661
  await transaction.table('users').update('u1', { age: 37 })
2361
- }) // real BEGIN/COMMIT/ROLLBACK, not the snapshot floor
2662
+ }) // real BEGIN IMMEDIATE/COMMIT/ROLLBACK, not the core's journal
2362
2663
 
2363
- // createSQLiteDriver accepts a SQLiteDriverOptions bag:
2364
- createSQLiteDriver({
2365
- path: 'data/app.sqlite',
2366
- timeout: 5000,
2664
+ // createSQLiteDriver accepts a SQLiteDriverOptions bag and returns a SQLiteDriverInterface:
2665
+ const driver = createSQLiteDriver({
2666
+ path: 'data/reports.sqlite',
2367
2667
  references: true,
2368
- pragmas: { journal_mode: 'WAL' }, // applied through pragma() right after connect(), in order
2668
+ pragmas: { synchronous: 'FULL' }, // applied after the WAL default, in order
2369
2669
  })
2670
+ const reports = createDatabase({ driver, tables: { reports: { id: stringShape() } } })
2671
+ await reports.table('reports').set({ id: 'r1' })
2672
+ driver.pragma('journal_mode') // 'wal'
2673
+ driver.pragma('synchronous') // 2
2370
2674
  ```
2371
2675
 
2372
2676
  `SQLiteDriver` is the fully-native backend — it implements every optional
@@ -2385,17 +2689,72 @@ metadata. The same call inside a callback transaction uses a SQLite savepoint:
2385
2689
  the wrapper deliberately provides raw `execute`, not a savepoint manager, so the
2386
2690
  driver owns one guarded fixed internal SQL literal. If caller code catches its
2387
2691
  failure, the failed inner migration is rolled back to that savepoint while the
2388
- surrounding transaction remains active and may continue safely. Snapshot
2389
- capture and replay, plus public `close()`, contain their complete native bodies
2390
- inside `#guard`; no raw SQLite fault crosses the driver boundary. Candidate
2692
+ surrounding transaction remains active and may continue safely. A list write or insert
2693
+ uses one prepared statement per row, as one transaction outside a scope and inside the same
2694
+ savepoint form within one, so a conflicting row applies none of the batch; a list read and a
2695
+ list delete are each one statement with the keys bound as one JSON parameter. Public
2696
+ `close()` contains its complete native body inside `#guard`; no raw SQLite fault crosses the driver boundary. Candidate
2391
2697
  schema state becomes live only after the native commit. Point `write` / `insert` /
2392
2698
  `delete` check `OperationOptions.signal`
2393
2699
  immediately before the synchronous SQLite call; that call entry is the commit
2394
2700
  point, so there is no post-check that could relabel a completed commit.
2395
2701
 
2702
+ A writable file opens under `journal_mode = WAL`, issued ahead of the `pragmas` entries, unless
2703
+ `pragmas` names `journal_mode`; a `':memory:'` database and a `readonly`
2704
+ open keep their journal. The driver issues no other pragma: `synchronous` keeps the engine
2705
+ build's default, which is `FULL` on the SQLite that Node 22.23.5 bundles, and the busy timeout
2706
+ stays 0 unless the application sets `timeout`. A refused journal mode raises nothing, so an
2707
+ application that requires WAL reads `journal_mode` back through the `pragma` method.
2708
+
2709
+ Every driver transaction opens with `BEGIN IMMEDIATE`: a scope, a list write's commit, a root
2710
+ `migrate`, and the open's schema transaction. A contended writer is refused at its start,
2711
+ ahead of any work, and a set busy timeout applies there. One driver per file is the supported
2712
+ shape. Two connections on one thread never resolve by waiting, because the holder cannot
2713
+ advance while the waiter blocks the thread: with no `timeout`, the waiter's scope is refused at
2714
+ once as `DRIVER` with `context.retryable`, a read on it returns, and its scope runs after the
2715
+ holder settles, so share one driver instead. Set `timeout` only when another process or a
2716
+ worker thread opens the file; the wait blocks the event loop for up to its length, and the
2717
+ waiting scope runs after the holder commits. A copy of the main file alone misses the WAL.
2718
+ The application decides whether to retry a refusal.
2719
+
2720
+ The `pragma` method of the `SQLiteDriverInterface` that `createSQLiteDriver` returns runs
2721
+ `PRAGMA name` with no value and returns the first value the engine answers, or `undefined`
2722
+ when it answers no row. A name the engine treats as an action runs that action. A name that
2723
+ fails `isPragmaName` from `@orkestrel/sqlite` raises `VALIDATION` ahead of any SQL, and a call
2724
+ while a transaction is active raises `CONFLICT`. The `pragmas` option is the one place a
2725
+ setting is written: each name passes `isPragmaName` and is one of `PRAGMA_NAMES`, and each
2726
+ value passes `isPragmaValue`, a 32-bit signed integer or a keyword of ASCII letters and
2727
+ underscores, at construction.
2728
+
2729
+ A writable open runs `PRAGMA optimize = 0x10002` after its schema transaction, so an index the
2730
+ open created is analyzed too, and the `close` method runs nothing. Statistics are exact at a
2731
+ writable open of a table that holds none or whose row count changed tenfold since its
2732
+ statistics, and the prior statistics stand in between. The analysis reads every row of such a
2733
+ table, so its cost grows with the table. A busy refusal of it leaves the open in place, because
2734
+ it changes cost only and the next writable open analyzes again; any other refusal fails the
2735
+ open as `DRIVER`, so a file whose index is corrupt never opens. The busy path is unproven by
2736
+ test: the schema transaction takes the same write lock on the same thread immediately before the
2737
+ analysis, so nothing can stage the refusal between them without a seam, and a seam there
2738
+ would reopen it. The `pragma` method with
2739
+ `optimize` runs the engine's default mask, whose bounded statistics a following open keeps
2740
+ until the row count changes tenfold.
2741
+
2742
+ Inside the open transaction, after validation, a writable open drops every index created on
2743
+ a deployed table (`origin` `c` in `pragma_index_list`) whose name the deployed schema does not
2744
+ derive, so the file's created indexes equal the deployed schema's; an index is derived data,
2745
+ so a drop loses no row. A `readonly` open drops nothing, and an undeclared unique index still
2746
+ raises `DRIVER`.
2747
+
2748
+ Each open connection is a `SQLiteConnection`, which keeps up to `STATEMENT_LIMIT` prepared
2749
+ statements keyed by SQL text and evicts the least recently used. Point and list reads, list
2750
+ deletes, writes, pages, counts, and aggregates reuse them; a stream prepares its own statement,
2751
+ because a statement with an open iterator cannot run again. The `close` method and the next
2752
+ `open` drop the cache with the connection. A cached point read skips the statement's compile,
2753
+ which `tests/src/server/drivers/SQLiteDriver.bench.ts` reads beside the wrapper alone.
2754
+
2396
2755
  ### Persistence with the IndexedDB driver
2397
2756
 
2398
- Feature-detects `indexedDB`, opens a database over the IndexedDB driver, writes one row, and runs a query pushed down to a key range:
2757
+ Feature-detects `indexedDB`, opens a database over the IndexedDB driver, writes one row, and runs a query the driver answers with a key range:
2399
2758
 
2400
2759
  ```ts
2401
2760
  import { createDatabase } from '@orkestrel/database'
@@ -2413,7 +2772,7 @@ if (typeof indexedDB !== 'undefined') {
2413
2772
  .table('users')
2414
2773
  .query()
2415
2774
  .condition({ column: 'id', operator: 'equals', values: ['u1'], connector: 'and' })
2416
- .collect() // pushed down to a key range
2775
+ .collect() // answered by a key range on the primary key
2417
2776
  }
2418
2777
  ```
2419
2778
 
@@ -2425,48 +2784,82 @@ publishing schema/identity/connection state or changing the record. The
2425
2784
  bootstrap closes in every outcome, so external repair or version activity is
2426
2785
  not blocked and the same driver may retry. It then connects the deployed
2427
2786
  `DriverMetadata.schema` plus `__metadata__`; it does not create the target declaration
2428
- before reconciliation. The driver narrows a `QueryInput` to a key-range candidate over the
2429
- primary key or a single-column secondary index (`selectPlan`), then lets the
2430
- core engine refine it to the exact result — see
2431
- [Exact-or-refine vs. narrow-then-refine native reads](#exact-or-refine-vs-narrow-then-refine-native-reads).
2432
- It implements `records?` / `stream?` / `migrate?` / `metadata?` /
2433
- `stamp?` (persisted into a reserved `__metadata__` store, `METADATA_STORE` —
2787
+ before reconciliation.
2788
+
2789
+ `open()` drops every index of a deployed table that the deployed schema does not declare: the
2790
+ stored schema of a versioned database, and the declared schema of an unversioned one. It
2791
+ drops them on its own connection at the next version, then makes its final open pinned for
2792
+ a versioned database and unpinned for an unversioned one, and a dropped index loses no row.
2793
+ When another connection bumps the version between the driver's read of it and that
2794
+ upgrade, `open()` rejects with `DRIVER` whose `context.retryable` is `true`; call
2795
+ `open()` again. Two builds that declare different indexes on one unversioned database name
2796
+ each drop the other's index at their `open()`, and the other's next open creates it again,
2797
+ so give each build its own database name.
2798
+
2799
+ The plan keeps native the one access path `findAccessPlan` ranks first, with the order, the
2800
+ page, `count`, `minimum`, and `maximum` that path serves (`planIndexedDBQuery`), and the
2801
+ core engine runs the rest — see [Plans and residual work](#plans-and-residual-work) and
2802
+ [IndexedDB planning](#indexeddb-planning). A stream and `scan` read at most
2803
+ `STREAM_BATCH_SIZE` rows per transaction and resume after the final key of each batch,
2804
+ because a transaction cannot stay open across your awaits. A native page reads no row past
2805
+ `offset + limit`; a page with residual conditions stops after the batch that holds its last
2806
+ match. A stream walking the primary key or an index
2807
+ holds one batch; a listed stream, an `any` or an index range read out of its index order,
2808
+ holds its sorted primary keys plus one batch. A direct stream applies a residual condition
2809
+ and page to each batch as it arrives, and only a residual order holds every match. The
2810
+ stream reads each batch at its own moment, so a row another write moves past the stream's
2811
+ position can appear twice or not at all. A stored value that is no record raises `DRIVER` with `context.code` `'RECORD'`
2812
+ from a read, `MIGRATION` inside `migrate()`, and the payload-safe metadata refusal from
2813
+ `open()` and `metadata()`; none of them carries the stored value.
2814
+ `IndexedDBDriver` implements `plan?` / `records?` / `aggregate?` / `stream?` / `migrate?` /
2815
+ `metadata?` / `stamp?` (persisted into a reserved `__metadata__` store, `METADATA_STORE` —
2434
2816
  `open()` throws `DatabaseError('VALIDATION')` if a declared table is
2435
2817
  literally named `__metadata__`), but omits `transaction?` (the underlying
2436
2818
  `IDBTransaction` auto-commits the moment control yields to a non-IDB
2437
- `await`) and `aggregate?` (IndexedDB has no native SUM/AVG/MIN/MAX) by
2438
- IndexedDB's own nature. A non-empty `migrate({ plan, metadata })` performs DDL,
2819
+ `await`) by IndexedDB's own nature. A non-empty `migrate({ plan, metadata })` performs DDL,
2439
2820
  row transformations, and the metadata write in the same versionchange
2440
2821
  transaction; a metadata-only input uses one ordinary `__metadata__` write
2441
- transaction. A failed upgrade reconnects the old deployed schema. Each point
2822
+ transaction. A failed upgrade reconnects the old deployed schema, pinned at the stored version
2823
+ when metadata is stored, so `migrate()` raises `MIGRATION` and leaves the driver usable. Each point
2442
2824
  `write` / `insert` / `delete` still uses one explicit
2443
2825
  wrapper `database.write(table, scope)` transaction: the signal aborts it only
2444
2826
  while active, a signal-driven rollback maps to `DatabaseError('ABORTED')`, and
2445
2827
  native transaction completion is the commit boundary a late abort cannot
2446
2828
  rewrite.
2447
- Every public `QueryInput` boundary also calls `validatePage`: `limit` and
2448
- `offset`, when present, must be finite nonnegative integers. Validation is
2449
- deterministic (`limit` before `offset`), non-finite diagnostics retain
2450
- `'NaN'` / `'Infinity'` rather than JSON-coercing to `null`, and zero is
2451
- legal. Return kind determines timing: `Query.limit` / `Query.offset` and
2452
- `AsyncIterable` factories (`Table.scan` and every direct driver `stream`)
2453
- throw synchronously, while Promise terminals (`Table.records` / `count` /
2454
- `aggregate` and native Promise hooks) return rejected promises. Every path
2455
- reports identical `VALIDATION` evidence and applies the same page predicate.
2456
- Failed query-builder validation does not mutate builder state. `count` and
2457
- `aggregate` validate paging even though valid paging remains intentionally
2458
- ignored by their unpaged semantics.
2459
-
2460
- ### IndexedDB pushdown planning
2461
-
2462
- The pure planner behind `IndexedDBDriver`'s native `records?` /
2463
- `stream?` — useful directly to see what a `QueryInput` pushes down to before it
2464
- ever touches a browser database:
2829
+ A table checks paging inside the query door: `limit` and `offset`, when present, must be
2830
+ nonnegative integers, and zero is legal. Every table and query path refuses with one evidence
2831
+ shape, `VALIDATION` with `table` and `faults`, a fault at `['limit']` or `['offset']`.
2832
+ `Query.limit` and `Query.offset` refuse synchronously through the same door and leave the
2833
+ builder unchanged; `Table.records`, `count`, and `aggregate` return a rejected promise; and
2834
+ `Table.scan` raises at its first step. `count` and `aggregate` check paging even though their
2835
+ unpaged semantics ignore it. A driver's own hooks (`records`, `stream`, `aggregate`, and the
2836
+ SQL compilers) keep `validatePage`, whose `VALIDATION` context names the `field` and its
2837
+ `value`, rendering `NaN` and infinity as strings.
2838
+
2839
+ ### IndexedDB planning
2840
+
2841
+ The pure planner behind `IndexedDBDriver`'s `plan` shows which access path a read takes
2842
+ before the read touches a browser database. When every connector is `and`, it ranks the
2843
+ paths the conditions admit by a fixed rule, because IndexedDB has no statistics and reads
2844
+ one index per read: primary-key `equals` or `any` first, then a compound index matched on
2845
+ two or more columns, then a single-column index with `equals` or `any` beside a compound index
2846
+ whose leading column alone an `equals` binds, then a range or `starts` on the primary key or
2847
+ an index. An index holds no entry for a row whose field is
2848
+ absent or `null`, so `below`, `to`, an order, `minimum`, and `maximum` read an index only
2849
+ for a column declared required. `any` reads one `get(keys)` on the primary key, or one
2850
+ `only` range per value on an index sorted into primary-key order, and its page reads the
2851
+ listed keys first and only the page's rows. When the access path and the order's path
2852
+ differ, the access path wins and the order sorts as residual:
2465
2853
 
2466
2854
  ```ts
2467
2855
  import type { Condition, TableSchema } from '@orkestrel/database'
2468
2856
  import { isKey } from '@orkestrel/database'
2469
- import { conditionToRange, deriveIndexedDBIndexName, selectPlan } from '@orkestrel/database/browser'
2857
+ import {
2858
+ conditionToRange,
2859
+ deriveIndexedDBIndexName,
2860
+ findAccessPlan,
2861
+ planIndexedDBQuery,
2862
+ } from '@orkestrel/database/browser'
2470
2863
 
2471
2864
  const schema: TableSchema = {
2472
2865
  name: 'users',
@@ -2474,8 +2867,9 @@ const schema: TableSchema = {
2474
2867
  columns: [
2475
2868
  { name: 'id', storage: 'text', optional: false, nullable: false },
2476
2869
  { name: 'age', storage: 'integer', optional: false, nullable: false },
2870
+ { name: 'city', storage: 'text', optional: true, nullable: false },
2477
2871
  ],
2478
- indexes: [['age']],
2872
+ indexes: [['age'], ['city']],
2479
2873
  }
2480
2874
 
2481
2875
  isKey('u1') // true — a string is a usable IndexedDB key
@@ -2490,16 +2884,21 @@ const equalsAge: Condition = {
2490
2884
  }
2491
2885
  conditionToRange(equalsAge) // an IDBKeyRange.only(30) — an exact comparison operator
2492
2886
 
2493
- // A full scan (no condition qualifies for pushdown) returns an empty plan —
2494
- // the driver then reads every row and lets the core engine filter it exactly:
2495
- selectPlan(undefined, schema, ['age']) // {}
2496
-
2497
- // A comparison over the indexed `age` column narrows to that index's range:
2498
- selectPlan(
2499
- { conditions: [{ column: 'age', operator: 'from', values: [18], connector: 'and' }] },
2500
- schema,
2501
- ['age'],
2502
- ) // { index: 'age', range: an IDBKeyRange bounding age >= 18 }
2887
+ // No condition narrows, so the plan reads the whole store; the page is native:
2888
+ planIndexedDBQuery({ limit: 10 }, schema, ['age', 'city']) // { native: { limit: 10 }, residual: {} }
2889
+
2890
+ // A range over the required `age` index is the access path, and it serves an order on age:
2891
+ const fromAge: Condition = { column: 'age', operator: 'from', values: [18], connector: 'and' }
2892
+ const byAge = [{ column: 'age', direction: 'descending' as const }]
2893
+ planIndexedDBQuery({ conditions: [fromAge], order: byAge, limit: 10 }, schema, ['age', 'city'])
2894
+ // { native: { conditions: [fromAge], order: byAge, limit: 10 }, residual: {} }
2895
+
2896
+ // `below` on the optional `city` column would miss rows without a city, so it stays residual:
2897
+ const belowCity: Condition = { column: 'city', operator: 'below', values: ['m'], connector: 'and' }
2898
+ planIndexedDBQuery({ conditions: [belowCity] }, schema, ['age', 'city'])
2899
+ // { native: {}, residual: { conditions: [belowCity] } }
2900
+ findAccessPlan({ conditions: [fromAge] }, schema, ['age', 'city'])
2901
+ // { conditions: [fromAge], columns: ['age'], prefix: 0, index: 'age', range: an IDBKeyRange bounding age >= 18 }
2503
2902
  ```
2504
2903
 
2505
2904
  ### IndexedDB error mapping
@@ -2515,15 +2914,15 @@ import { mapIndexedDBError, mapMigrationError } from '@orkestrel/database/browse
2515
2914
  declare const fault: IndexedDBError // a caught backend fault
2516
2915
 
2517
2916
  mapIndexedDBError(fault) // → DatabaseError('CONFLICT' | 'CLOSED' | 'DRIVER', ...)
2518
- mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATION'
2917
+ mapMigrationError(fault) // → the same, but an UPGRADE or a RECORD fault becomes 'MIGRATION'
2519
2918
  ```
2520
2919
 
2521
2920
  ### Practices
2522
2921
 
2523
2922
  - **Declare tables in `createDatabase({ tables })` and hold the handles** —
2524
2923
  `const users = db.table('users')`; reuse them rather than re-resolving.
2525
- - **Writes admit whole, reads narrow.** At an unknown-input boundary, admit
2526
- loose data (`'41'`) through `admitValue(table.contract, input)` and write
2924
+ - **Writes admit whole, reads narrow.** At an unknown-input boundary, repair
2925
+ loose data (`'41'`) through `repairValue(table.contract, input)` and write
2527
2926
  its value; a refusal carries the faults to report. Trust `get` / `records`
2528
2927
  to return the row type.
2529
2928
  - **Use `resolve` when absence is an error**, `get` when it is expected —
@@ -2545,34 +2944,110 @@ mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATIO
2545
2944
  - **Use `MemoryDriver` for tests and ephemeral data** — no I/O, and
2546
2945
  `JSONDriver` swaps in unchanged when writes need to survive a restart.
2547
2946
 
2947
+ ## Migrating from 0.0.24
2948
+
2949
+ The coverage wave changes these exports and behaviors; each consumer changes in the release
2950
+ that adopts it. A name in this section that the package no longer exports is written plain.
2951
+
2952
+ | 0.0.24 | This release |
2953
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2954
+ | 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 |
2955
+ | 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 |
2956
+ | 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 |
2957
+ | 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 |
2958
+ | `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 |
2959
+ | 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 |
2960
+ | 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 |
2961
+ | A non-string operand of `like`, `glob`, `starts`, or `ends`, or a `null` read, matching no row | `VALIDATION` |
2962
+ | An unknown aggregate operation answering a maximum, or a missing column raising a raw `TypeError` | `VALIDATION` naming `aggregate.operation` or `aggregate.column` |
2963
+ | `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` |
2964
+ | 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 |
2965
+ | A `literalShape` column whose members span more than one class, stored as `text` | `json` storage, as a union is |
2966
+ | 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` |
2967
+ | `AccessPlan` as `{ index?, range? }` | `{ conditions, columns, prefix, index?, range?, keys? }`; `{}` as a whole-store read is `{ conditions: [], columns: [primary], prefix: 0 }` |
2968
+ | `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` |
2969
+ | An undeclared index surviving `IndexedDBDriver.open()` | `open()` drops it on a connection at the next version; a concurrent bump raises `DRIVER` with `context.retryable` |
2970
+ | 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 |
2971
+ | 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 |
2972
+ | `createSQLiteDriver` returning `DriverInterface` | It returns `SQLiteDriverInterface`, which adds the `pragma` method; `SQLiteDriver` implements it |
2973
+ | 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 |
2974
+ | 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 |
2975
+ | A SQLite open that analyzed nothing | A writable open runs `PRAGMA optimize = 0x10002` after its schema transaction; the `close` method runs nothing |
2976
+ | 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 |
2977
+ | A `pragmas` value that is any finite number | A value is a 32-bit signed integer or a bare keyword, through `isPragmaValue` |
2978
+ | An integer `sum` past 2^53 on SQLite raising `DRIVER` | `sum` compiles to `TOTAL`, the engine's float sum, with `undefined` over no value |
2979
+ | 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 |
2980
+
2981
+ The paging wave changes these exports and behaviors; under the no-shim law, each consumer
2982
+ changes in the release that adopts it. A name in this section that the package no longer
2983
+ exports is written plain, without code formatting.
2984
+
2985
+ | 0.0.23 | This release |
2986
+ | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2987
+ | matchesQueryExactly(input, schema) | `planSQLiteQuery(input, schema)`, which returns a `ReadPlan`; a read is wholly native when `residual` equals `{}` |
2988
+ | `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 |
2989
+ | matchesConditionExactly | `matchesSQLiteCondition(condition, schema)` |
2990
+ | matchesOrderExactly, matchesAggregateExactly, EXACT_COLUMN_STORAGE, EXACT_RANGE_COLUMN_STORAGE | Removed; `planSQLiteQuery` answers each question |
2991
+ | selectPlan(input, schema, indexes) | `findAccessPlan(input, schema, indexes)` for the access path, and `planIndexedDBQuery(input, schema, indexes)` for the split |
2992
+ | QueryPlan | `AccessPlan` |
2993
+ | `MemoryDriver.stream`, `JSONDriver.stream` | Removed; call `Table.scan`, or `streamPlannedRows` over the driver |
2994
+ | `matchesWildcardSegment(value: string, segment: string, …)` | `matchesWildcardSegment(value: readonly string[], segment: readonly string[], …)`, over code points |
2995
+ | `decodeValue` and `decodeRow` returning absence for a malformed cell | Both raise `DRIVER` with `table`, `column`, and `key` |
2996
+ | `compileOrderSQL` ending with a bare primary-key term | The primary-key term always carries `ASC` or `DESC`, in the direction of the final term |
2997
+ | A read that skipped a nonconforming stored row | `get`, `records`, and `scan` raise `DRIVER` with `table`, `key`, and `faults` |
2998
+ | `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 |
2999
+ | 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 |
3000
+ | 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 |
3001
+ | `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 |
3002
+
3003
+ The paging wave added names that its review then renamed or folded before release:
3004
+ compactReadInput is `normalizeReadInput`; comparePlans is `scanPlans`; containsValue is
3005
+ `matchesListed`; matchesNativeCondition is `matchesSQLiteCondition`; findNativeColumn is
3006
+ `findSQLiteColumn`; wrapValued is `compileGuardedSQL`; REFUSED_PRAGMAS is `PRAGMA_NAMES`, an allowlist; collectRows is removed in favor of
3007
+ `Array.fromAsync`; matchesNativeOrder and matchesNativeAggregate fold into
3008
+ `planSQLiteQuery`; classifyAbsence and the ColumnAbsence type fold into
3009
+ `compileConditionSQL`; decodeStoredValue folds into `decodeValue`; and `isScalar` narrows
3010
+ to `Scalar`.
3011
+
2548
3012
  ## Tests
2549
3013
 
2550
3014
  - [`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.
2551
- - [`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.
3015
+ - [`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.
3016
+ - [`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.
2552
3017
  - [`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.
2553
- - [`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).
2554
- - [`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.
3018
+ - [`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.
3019
+ - [`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.
2555
3020
  - [`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.
2556
3021
  - [`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.
2557
3022
  - [`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.
2558
- - [`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.
3023
+ - [`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.
2559
3024
  - [`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.
3025
+ - [`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.
3026
+ - [`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.
3027
+ - [`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.
3028
+ - [`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.
3029
+ - [`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).
3030
+ - [`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.
2560
3031
  - [`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.
2561
3032
  - [`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).
2562
3033
  - [`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.
2563
3034
  - [`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.
2564
3035
  - [`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.
2565
3036
  - [`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:'`.
2566
- - [`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.
2567
- - [`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 exact-or-refine query and aggregate paths; 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.
2568
- - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) — the SQLite bridge: `quoteIdentifier`, codecs, row extraction, `deriveSQLiteIndexName` exact bytes, and the `matchesConditionExactly` / `matchesOrderExactly` / `matchesQueryExactly` / `matchesAggregateExactly` / `matchesSQLiteAffinity` predicates.
3037
+ - [`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.
3038
+ - [`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.
3039
+ - [`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.
3040
+ - [`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.
3041
+ - [`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`.
2569
3042
  - [`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.
2570
- - [`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`.
2571
- - [`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` (both exact-path and refine-path queries) produce identical rows/counts/aggregates.
2572
- - [`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, native narrow-then-refine queries, 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.
2573
- - [`tests/src/browser/helpers.test.ts`](../tests/src/browser/helpers.test.ts) — the pushdown planner: `conditionToRange` over every comparison operator, `selectPlan` index/primary selection and lossless fallbacks, backend-error mapping, and exact `deriveIndexedDBIndexName` bytes.
3043
+ - [`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.
3044
+ - [`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.
3045
+ - [`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.
3046
+ - [`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`.
3047
+ - [`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.
3048
+ - [`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.
2574
3049
  - [`tests/src/browser/factories.test.ts`](../tests/src/browser/factories.test.ts) — `createIndexedDBDriver` returns a working `DriverInterface` instance (a round-trip end to end).
2575
- - [`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`).
3050
+ - [`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.
2576
3051
 
2577
3052
  ## See also
2578
3053