@orkestrel/scaffold 0.0.133 → 0.0.135

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 (92) hide show
  1. package/dist/agents/skills/orkestrel-dispatch/scripts/bench.js +61 -96
  2. package/dist/agents/skills/orkestrel-dispatch/scripts/brief.js +48 -76
  3. package/dist/agents/skills/orkestrel-dispatch/scripts/chain.js +27 -66
  4. package/dist/agents/skills/orkestrel-dispatch/scripts/cite.js +31 -64
  5. package/dist/agents/skills/orkestrel-dispatch/scripts/launch.js +43 -57
  6. package/dist/agents/skills/orkestrel-dispatch/scripts/login.js +43 -86
  7. package/dist/agents/skills/orkestrel-dispatch/scripts/patch.js +68 -104
  8. package/dist/agents/skills/orkestrel-dispatch/scripts/result.js +35 -69
  9. package/dist/agents/skills/orkestrel-dispatch/scripts/sweep.js +47 -84
  10. package/dist/agents/skills/orkestrel-falsify/scripts/mutate.js +134 -116
  11. package/dist/agents/skills/orkestrel-harden/scripts/discovery.js +38 -90
  12. package/dist/agents/skills/orkestrel-harden/scripts/interleave.js +39 -103
  13. package/dist/agents/skills/orkestrel-harden/scripts/measure.js +40 -89
  14. package/dist/agents/skills/orkestrel-harden/scripts/titles.js +41 -87
  15. package/dist/agents/skills/orkestrel-parallel/scripts/cases.js +43 -88
  16. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +1568 -213
  17. package/dist/agents/skills/orkestrel-publish/scripts/compare.js +40 -60
  18. package/dist/agents/skills/orkestrel-publish/scripts/pins.js +47 -81
  19. package/dist/agents/skills/orkestrel-publish/scripts/steps.js +66 -104
  20. package/dist/agents/skills/orkestrel-publish/scripts/swap.js +74 -88
  21. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +387 -109
  22. package/dist/agents/skills/orkestrel-publish/scripts/window.js +55 -96
  23. package/dist/agents/skills/orkestrel-scout/scripts/map.js +54 -101
  24. package/dist/bin/main.js +275 -33
  25. package/dist/bin/main.js.map +1 -1
  26. package/dist/host/AGENTS.md +1 -1
  27. package/dist/host/agents/skills/orkestrel-dispatch/scripts/bench.ts +81 -97
  28. package/dist/host/agents/skills/orkestrel-dispatch/scripts/brief.ts +64 -72
  29. package/dist/host/agents/skills/orkestrel-dispatch/scripts/chain.ts +41 -63
  30. package/dist/host/agents/skills/orkestrel-dispatch/scripts/cite.ts +56 -79
  31. package/dist/host/agents/skills/orkestrel-dispatch/scripts/launch.ts +61 -74
  32. package/dist/host/agents/skills/orkestrel-dispatch/scripts/login.ts +59 -89
  33. package/dist/host/agents/skills/orkestrel-dispatch/scripts/patch.ts +87 -106
  34. package/dist/host/agents/skills/orkestrel-dispatch/scripts/result.ts +57 -76
  35. package/dist/host/agents/skills/orkestrel-dispatch/scripts/sweep.ts +73 -88
  36. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +2 -2
  37. package/dist/host/agents/skills/orkestrel-falsify/scripts/mutate.ts +167 -119
  38. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +1 -1
  39. package/dist/host/agents/skills/orkestrel-harden/scripts/discovery.ts +58 -75
  40. package/dist/host/agents/skills/orkestrel-harden/scripts/interleave.ts +55 -99
  41. package/dist/host/agents/skills/orkestrel-harden/scripts/measure.ts +59 -90
  42. package/dist/host/agents/skills/orkestrel-harden/scripts/titles.ts +60 -80
  43. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +4 -4
  44. package/dist/host/agents/skills/orkestrel-parallel/scripts/cases.ts +71 -108
  45. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +1990 -274
  46. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  47. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +28 -7
  48. package/dist/host/agents/skills/orkestrel-publish/scripts/compare.ts +58 -79
  49. package/dist/host/agents/skills/orkestrel-publish/scripts/pins.ts +66 -87
  50. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +84 -102
  51. package/dist/host/agents/skills/orkestrel-publish/scripts/swap.ts +92 -99
  52. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +483 -127
  53. package/dist/host/agents/skills/orkestrel-publish/scripts/window.ts +82 -120
  54. package/dist/host/agents/skills/orkestrel-scout/SKILL.md +3 -3
  55. package/dist/host/agents/skills/orkestrel-scout/scripts/map.ts +85 -112
  56. package/dist/host/claude/agents/orkestrel.md +16 -16
  57. package/dist/host/claude/rules/architecture.md +1 -1
  58. package/dist/host/claude/rules/documentation.md +1 -1
  59. package/dist/host/claude/rules/patterns.md +7 -4
  60. package/dist/host/claude/rules/styles.md +1 -1
  61. package/dist/host/claude/rules/tests.md +3 -3
  62. package/dist/host/claude/rules/workspace.md +50 -37
  63. package/dist/host/configs/helpers.ts +117 -71
  64. package/dist/host/dotfiles/oxlintrc.json +6 -0
  65. package/dist/host/guides/agent.md +989 -395
  66. package/dist/host/guides/database.md +357 -342
  67. package/dist/host/guides/form.md +79 -4
  68. package/dist/host/guides/middleware.md +5 -5
  69. package/dist/host/guides/ollama.md +41 -42
  70. package/dist/host/guides/scaffold.md +170 -70
  71. package/dist/host/guides/study.md +12 -12
  72. package/dist/host/guides/table.md +20 -6
  73. package/dist/host/guides/test.md +166 -52
  74. package/dist/host/guides/toolbox.md +127 -81
  75. package/dist/host/guides/workspace.md +21 -14
  76. package/dist/host/manifest.json +54 -54
  77. package/dist/host/tests/config.test.ts +251 -7
  78. package/dist/host/tests/policy.test.ts +14 -21
  79. package/dist/host/tests/setupPolicy.ts +43 -36
  80. package/dist/src/core/index.cjs +533 -139
  81. package/dist/src/core/index.cjs.map +1 -1
  82. package/dist/src/core/index.d.cts +223 -16
  83. package/dist/src/core/index.d.ts +223 -16
  84. package/dist/src/core/index.js +524 -139
  85. package/dist/src/core/index.js.map +1 -1
  86. package/dist/src/server/index.cjs +23 -14
  87. package/dist/src/server/index.cjs.map +1 -1
  88. package/dist/src/server/index.d.cts +3 -2
  89. package/dist/src/server/index.d.ts +3 -2
  90. package/dist/src/server/index.js +24 -15
  91. package/dist/src/server/index.js.map +1 -1
  92. package/package.json +2 -2
@@ -9,12 +9,11 @@ A table is a contract. Declare a `tables` map of
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, an ordered `scan`, key listing, and a
14
+ `snapshot`, 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 condition with a
27
+ key range over the primary key or an index — 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
 
@@ -97,17 +95,19 @@ produces the JSON Schema, and seeds fixtures.
97
95
 
98
96
  ### Server
99
97
 
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. |
98
+ | Name | Kind | Signature | Summary |
99
+ | ------------------------ | -------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
100
+ | `METADATA_TABLE` | const | `"_metadata"` | Names the reserved metadata table the `SQLiteDriver` creates on `open` to persist its stamped `DriverMetadata` (`version` + declared schema JSON) — the SQLite realization of the `metadata` / `stamp` driver hooks. |
101
+ | `PRAGMA_NAMES` | const | `readonly string[]` | Lists the PRAGMA names the `SQLiteDriver` admits in its `pragmas` option, each matched exactly; it refuses every other name, because one can change a read result the planner assumes. |
102
+ | `validatePragmas` | function | `(pragmas: Readonly<Record<string, string \| number>> \| undefined) => void` | Validates the `pragmas` option of the SQLite driver: each name must be one of `PRAGMA_NAMES`, matched exactly, and each value a finite number or a bare keyword. |
103
+ | `planSQLiteQuery` | function | `(input: ReadInput, schema: TableSchema) => ReadPlan` | Splits a read into the part SQLite answers natively and the residual the core runs — the SQLite driver's `plan`. |
104
+ | `matchesSQLiteCondition` | function | `(condition: Condition, schema: TableSchema) => boolean` | Reports whether SQLite answers one `Condition` with the core engine's meaning. |
105
+ | `findSQLiteColumn` | function | `(path: FieldPath, schema: TableSchema) => ColumnSchema \| undefined` | Resolves the declared column a field path names when SQLite answers it natively: a flat path to a declared `text`, `integer`, `real`, or `boolean` column. |
106
+ | `matchesPrimaryPin` | function | `(conditions: readonly Condition[], schema: TableSchema) => boolean` | Reports whether a WHERE fold pins its column references: every connector is `and` and one condition is `any` on the primary key. |
107
+ | `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. |
108
+ | `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. |
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. |
111
111
 
112
112
  ### SQL compilation
113
113
 
@@ -115,47 +115,50 @@ Pure, server-only functions that turn a core `QueryInput` / `TableSchema` into
115
115
  parameterized SQL text — the native-query payoff for a SQLite-backed driver.
116
116
  None of these import a SQLite package; they speak strings and values only.
117
117
 
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. |
118
+ | Name | Kind | Signature | Summary |
119
+ | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
+ | `inferValueStorage` | function | `(value: unknown) => ColumnStorage` | Reads the storage type a nested (`json_extract`) operand encodes as from its runtime value, never as `json`. |
121
+ | `compileJSONTypeSQL` | function | `(path: readonly string[]) => string` | Compiles a nested `FieldPath` to the `json_type(<col>, <path>)` SQL expression — the `compileFieldSQL` `json_extract` sibling used to tell a present JSON `null` apart from an absent path (both read back as SQL `NULL` through `json_extract`, but `json_type` reports `'null'` for the former and SQL `NULL` for the latter). |
122
+ | `compileConditionSQL` | function | `(condition: Condition, schema: TableSchema, pinned?: boolean) => CompiledSQL` | Compiles one condition to its SQL fragment and the parameters it binds, with the core engine's meaning under SQL's three-valued `NULL` logic. |
123
+ | `compileWhereSQL` | function | `(conditions: readonly Condition[], schema: TableSchema) => CompiledSQL` | Folds the conditions into one WHERE clause, parenthesizing progressively left-to-right so the grouping matches the engine's `matchesQuery` fold. |
124
+ | `compileOrderSQL` | function | `(order: readonly Order[] \| undefined, schema: TableSchema, pinned?: boolean) => string` | Compiles the ORDER BY clause from the order terms, ending with the primary key in the direction of the final term. |
125
+ | `compilePageSQL` | function | `(limit: number \| undefined, offset: number \| undefined) => CompiledSQL` | Compiles the LIMIT / OFFSET clause. |
126
+ | `compileQuerySQL` | function | `(input: QueryInput \| undefined, schema: TableSchema) => CompiledSQL` | Compiles a `QueryInput` into the SQL clause that follows a table name, with its bound parameters in clause order. |
127
+ | `quoteIdentifier` | function | `(identifier: string) => string` | Quotes a SQL identifier (a table or column name) so any characters are literal. |
128
+ | `compileFieldSQL` | function | `(path: FieldPath) => string` | Compiles a `FieldPath` to the SQL expression that reads it. |
129
+ | `compileColumnSQL` | function | `(storage: ColumnStorage) => string` | Maps a portable `ColumnStorage` to its SQLite column type. |
130
+ | `compileAggregateSQL` | function | `(operation: AggregateOperation, column: FieldPath) => string` | Compiles an `AggregateOperation` over a `FieldPath`. |
131
+ | `matchesSQLiteAffinity` | function | `(declared: unknown, storage: ColumnStorage) => boolean` | Checks a declared SQLite type against a portable storage affinity. |
132
+ | `matchesAbsentPath` | function | `(error: unknown) => boolean` | Reports whether a caught filesystem error says that nothing is there to read. |
133
+ | `encodeValue` | function | `(value: unknown, column: ColumnSchema) => SQLiteValue` | Encodes a JS value to its stored `SQLiteValue` for a declared column. |
134
+ | `decodeValue` | function | `(value: SQLiteValue, column: ColumnSchema, context?: Readonly<Record<string, unknown>>) => unknown` | Decodes a stored `SQLiteValue` back to its JS value for a declared column — the exact inverse of `encodeValue`. |
135
+ | `encodeRow` | function | `(row: Row, schema: TableSchema) => SQLiteRow` | Encodes a whole `Row` to a `SQLiteRow` by its table's schema. |
136
+ | `decodeRow` | function | `(row: SQLiteRow, schema: TableSchema) => Row` | Decodes a stored `SQLiteRow` back to a `Row` by its table's schema. |
137
+ | `schemaToTable` | function | `(schema: TableSchema) => string` | Projects a `TableSchema` to its `CREATE TABLE IF NOT EXISTS` statement. |
138
+ | `schemaToIndexes` | function | `(schema: TableSchema) => readonly string[]` | Projects a `TableSchema` to its declared SQLite indexes. |
139
+ | `stepToSQL` | function | `(step: MigrationStep) => readonly string[]` | Projects one `MigrationStep` to SQLite DDL. |
140
+ | `compileBoundSQL` | function | `(sql: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Encodes condition operands for a SQL fragment using their declared or inferred storage. |
141
+ | `compileListSQL` | function | `(head: string, tail: string, values: readonly unknown[], nested: boolean, declared: ColumnSchema \| undefined) => CompiledSQL` | Compiles a membership list as one bound JSON parameter read through `json_each`, or as one parameter per operand when an encoded operand has no JSON form. |
142
+ | `compileGuardedSQL` | function | `(fragment: string, guard: string) => string` | Parenthesizes a fragment when a guard term joins it, and leaves a bare fragment bare. |
143
+ | `compileJoinedSQL` | function | `(parts: readonly CompiledSQL[], connective: string, empty: string) => CompiledSQL` | Joins SQL fragments with one connective, parenthesizing two or more, and returns a constant for none. |
142
144
 
143
145
  ### Browser
144
146
 
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. |
147
+ Pure functions behind the IndexedDB driver's planner — the one condition a key range
148
+ answers stays native, and the core engine runs the rest.
149
+
150
+ | Name | Kind | Signature | Summary |
151
+ | -------------------------- | -------- | --------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
152
+ | `conditionToRange` | function | `(condition: Condition) => IDBKeyRange \| undefined` | Translates one `Condition` to the `IDBKeyRange` it maps to, when its operator is one of the exact key comparisons over scalar operands; otherwise returns `undefined`. |
153
+ | `planIndexedDBQuery` | function | `(input: ReadInput, schema: TableSchema, available: readonly string[]) => ReadPlan` | Splits a read into the part IndexedDB answers natively and the residual the core runs — the IndexedDB driver's `plan`. |
154
+ | `findAccessCondition` | function | `(input: QueryInput \| undefined, schema: TableSchema, available: readonly string[]) => Condition \| undefined` | Finds the condition an IndexedDB read narrows on: the first one an index or the primary key answers with an exact key range. |
155
+ | `deriveAccessPlan` | function | `(condition: Condition \| undefined, schema: TableSchema) => AccessPlan` | Derives the key-range read for the condition an IndexedDB read narrows on. |
156
+ | `INDEXABLE_STORAGE` | const | `readonly ColumnStorage[]` | Lists the declared `ColumnStorage`s that are valid, orderable IndexedDB keys. |
157
+ | `METADATA_STORE` | const | `"__metadata__"` | Names the reserved out-of-line store `__metadata__` the `IndexedDBDriver` stamps its `DriverMetadata` into. |
158
+ | `mapIndexedDBError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy — the default mapping used everywhere except inside `migrate()`. |
159
+ | `mapMigrationError` | function | `(error: IndexedDBError) => DatabaseError` | Maps a backend `IndexedDBError` to the portable `DatabaseError` taxonomy for use inside `migrate()` — the one context where `UPGRADE` means the migration itself failed, not a generic driver fault. |
160
+ | `deriveIndexedDBIndexName` | function | `(columns: readonly string[]) => string` | Derives an IndexedDB index name for a declared column group — a bare column name for a single-column index, a deterministic collision-free encoding for a compound one. |
161
+ | `schemaToStore` | function | `(schema: TableSchema) => StoreDefinition` | Projects a table schema into the IndexedDB wrapper's store definition. |
159
162
 
160
163
  ### Errors
161
164
 
@@ -178,24 +181,30 @@ whose every entry passes Contract's `isAuditFault` function.
178
181
  The portable semantics every backend shares — pure, total functions the
179
182
  driver never re-implements.
180
183
 
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". |
184
+ | Name | Kind | Signature | Summary |
185
+ | ---------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
186
+ | `compareValues` | function | `(left: unknown, right: unknown) => number` | Compares two arbitrary values under one total order — the comparator behind sorting and the range operators. |
187
+ | `matchesCondition` | function | `(row: Row, condition: Condition, scalars?: ReadonlySet<unknown>) => boolean` | Evaluates one `Condition` against a row — the per-operator predicate. |
188
+ | `matchesQuery` | function | `(row: Row, conditions: readonly Condition[], scalars?: ReadonlyArray<ReadonlySet<unknown>>) => boolean` | Folds a row through a list of conditions, joining each by its connector. |
189
+ | `sortRows` | function | `(rows: readonly Row[], order: readonly Order[]) => readonly Row[]` | Sorts rows by an ordering specification, leaving the input untouched. |
190
+ | `applyQuery` | function | `(rows: readonly Row[], input?: QueryInput) => readonly Row[]` | Applies a `QueryInput` to rows — filter, then sort, then page. |
191
+ | `validatePage` | function | `(input?: QueryInput) => void` | Validates the paging fields of a portable query. |
192
+ | `computeAggregate` | function | `(rows: readonly unknown[], operation: AggregateOperation, column: FieldPath) => number \| undefined` | Computes an aggregate over a column across rows. |
193
+ | `extractKey` | function | `(row: Row, column: string) => Key \| undefined` | Reads a row's primary key from a column, when it is a usable `Key`. |
194
+ | `bindRowKey` | function | `(row: Row, primary: string, key: Key) => Row` | Returns a fresh row whose primary column is authoritatively bound to its storage key. |
195
+ | `shapeToColumnSchema` | function | `(name: string, shape: ContractShape) => ColumnSchema` | Projects one contract shape into a portable column schema. |
196
+ | `findColumn` | function | `(name: string, schema: TableSchema) => ColumnSchema \| undefined` | Reads one flat column's declaration out of a table schema. |
197
+ | `resolvePrimary` | function | `(primary: PrimaryMap, name: string) => string` | Resolves the primary-key column one table keys its rows by. |
198
+ | `requireColumns` | function | `(<T extends TableMap, K extends keyof T & string>(tables: T, name: K) => T[K]) & ((tables: TableMap, name: string) => ColumnMap)` | Requires one declared table's columns out of a table map. |
199
+ | `shapeToColumnStorage` | function | `(shape: ContractShape) => ColumnStorage` | Maps a column's `ContractShape` to its portable `ColumnStorage` — the value a `TableSchema` carries so a native backend can declare a real column. |
200
+ | `filterRows` | function | `(rows: readonly Row[], conditions: readonly Condition[]) => readonly Row[]` | Filters rows by a list of conditions — the shared basis for a table's count and aggregate paths (no sort/page, unlike `applyQuery`). |
201
+ | `equalsValue` | function | `(left: unknown, right: unknown) => boolean` | Compares two values structurally by SameValueZero leaves — the comparator behind conformance checks and any test/fixture that needs "same data", not "same reference". |
202
+ | `collectScalars` | function | `(values: readonly unknown[]) => ReadonlySet<unknown>` | Collects the scalar operands of a membership list into one set. |
203
+ | `matchesListed` | function | `(value: unknown, values: readonly unknown[], scalars?: ReadonlySet<unknown>) => boolean` | Checks whether a value equals one operand of a membership list. |
204
+ | `prepareScalars` | function | `(conditions: readonly Condition[]) => ReadonlyArray<ReadonlySet<unknown>>` | Collects one scalar set per condition, by position — the `scalars` argument of `matchesQuery`. |
205
+ | `normalizeReadInput` | function | `(input: ReadInput) => ReadInput` | Drops each clause a read does not hold, so an absent clause is an absent key. |
206
+ | `planRead` | function | `(storage: StorageInterface, table: string, input: ReadInput) => ReadPlan` | Asks a storage for its plan of a read, with the read normalized first. |
207
+ | `streamPlannedRows` | function | `(storage: StorageInterface, table: string, native: ReadInput, residual: ReadInput, step?: () => Promise<void>) => AsyncIterable<Row>` | Streams the native side of a plan and applies residual conditions and a residual page, stopping at `offset + limit` matches — step 3 of the read procedure. |
199
208
 
200
209
  For `minimum` and `maximum`, `computeAggregate` compares each numeric value
201
210
  with a scalar `Math.min` or `Math.max` call. The helper never passes a
@@ -222,90 +231,102 @@ transform. Versioning drivers persist reconciliation metadata through the paired
222
231
 
223
232
  ### Conformance
224
233
 
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. |
234
+ | Name | Kind | Signature | Summary |
235
+ | ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
236
+ | `conformDriver` | function | `(factory: () => DriverInterface) => Promise<void>` | Runs the driver-conformance battery, throwing on the first violated invariant — the fail-fast entry point most callers (test setup, CI smoke checks) want. |
237
+ | `scanDriver` | function | `(factory: () => DriverInterface) => AsyncIterable<ConformanceFinding>` | Walks the driver-conformance battery against a fresh `DriverInterface` per phase, yielding one `ConformanceFinding` per violated invariant — the shared invariant suite every backend (in-memory, SQLite, IndexedDB) must uphold to be a drop-in `DriverInterface`. |
238
+ | `auditDriver` | function | `(factory: () => DriverInterface) => Promise<readonly ConformanceFinding[]>` | Runs the full driver-conformance battery and collects every violation — the audit entry point for a driver author who wants a complete report rather than a single fail-fast throw. |
239
+ | `findPlanFaults` | function | `(input: ReadInput, plan: ReadPlan) => readonly string[]` | Lists the invariants a `ReadPlan` breaks for the read it splits. |
240
+ | `readPlannedRows` | function | `(storage: StorageInterface, table: string, input: QueryInput, step?: () => Promise<void>) => Promise<readonly Row[]>` | Reads the rows of a read through a storage's plan — the read procedure `Table.records` runs and the conformance differential checks. |
241
+ | `readPlannedAggregate` | function | `(storage: StorageInterface, table: string, input: QueryInput, aggregate: Aggregate, step?: () => Promise<void>) => Promise<number \| undefined>` | Computes an aggregate read through a storage's plan — the read procedure `Table.count` and `Table.aggregate` run and the conformance differential checks. |
242
+ | `scanPlans` | function | `(storage: StorageInterface, check: string) => AsyncIterable<ConformanceFinding>` | Compares a storage's planned answer to every conformance read against the core engine's answer over its `scan`, and checks each plan's invariants. |
230
243
 
231
244
  ### Helpers & guards
232
245
 
233
246
  Pure helpers behind the query engine's pattern matching.
234
247
 
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. |
248
+ | Name | Kind | Signature | Summary |
249
+ | ------------------------ | -------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
250
+ | `cloneDriverMetadata` | function | `(value: unknown) => DriverMetadata` | Clones unknown driver metadata into a distinct deeply frozen snapshot. |
251
+ | `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`. |
252
+ | `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. |
253
+ | `matchesLikePattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a SQL `LIKE` pattern, folding ASCII case. |
254
+ | `matchesGlobPattern` | function | `(value: string, pattern: string) => boolean` | Matches a value against a `GLOB` pattern, preserving case. |
255
+ | `foldASCII` | function | `(text: string) => string` | Folds the ASCII letters of a text to lower case, leaving every other character unchanged. |
256
+ | `isDriverMetadata` | function | `(value: unknown) => value is DriverMetadata` | Checks whether a value is persisted driver metadata. |
257
+ | `isDriverSchema` | function | `(value: unknown) => value is readonly TableSchema[]` | Checks whether a value is a complete portable driver schema. |
258
+ | `isColumnSchema` | function | `(value: unknown) => value is ColumnSchema` | Checks whether a value is a portable column schema. |
259
+ | `isTableSchema` | function | `(value: unknown) => value is TableSchema` | Checks whether a value is a portable table schema. |
260
+ | `isMigrationStep` | function | `(value: unknown) => value is MigrationStep` | Checks whether a value is one ordered migration step. |
261
+ | `isMigration` | function | `(value: unknown) => value is Migration` | Checks whether a value is an ordered migration plan. |
262
+ | `isMigrationInput` | function | `(value: unknown) => value is MigrationInput` | Checks whether a value is one atomic migration request. |
263
+ | `isKey` | function | `(value: unknown) => value is Key` | Checks whether a value is a usable database key. |
264
+ | `isScalar` | function | `(value: unknown) => value is Scalar` | Checks whether a value is a scalar: not an object and not a function. |
265
+ | `cloneDriverSchema` | function | `(value: unknown) => readonly TableSchema[]` | Clones unknown driver schema into a distinct deeply frozen snapshot. |
266
+ | `cloneMigrationInput` | function | `(value: unknown) => MigrationInput` | Clones unknown migration input into a distinct deeply frozen snapshot. |
267
+ | `captureFailure` | function | `(operation: () => Promise<unknown>) => Promise<unknown>` | Captures the exact rejection or synchronous throw from a driver conformance operation. |
253
268
 
254
269
  ### Constants
255
270
 
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. |
271
+ | Name | Kind | Signature | Summary |
272
+ | -------------------------- | ----- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
273
+ | `DEFAULT_PRIMARY` | const | `"id"` | Supplies the primary-key column, `'id'`, assumed when `PrimaryMap` does not name one. |
274
+ | `MAX_PATTERN_LENGTH` | const | `1024` | Sets the longest `LIKE` / `GLOB` pattern the wildcard matcher accepts, 1024 characters, before rejecting it. |
275
+ | `CONFORMANCE_USERS_SCHEMA` | const | `TableSchema` | Describes the `users` table the driver-conformance battery opens — keyed by the default `id` primary column. |
276
+ | `CONFORMANCE_POSTS_SCHEMA` | const | `TableSchema` | Describes the `posts` table the driver-conformance battery opens — keyed by a non-`id` `slug` primary column. |
277
+ | `CONFORMANCE_SCHEMA` | const | `readonly TableSchema[]` | Holds the fixed `users` and `posts` schema every driver-conformance phase opens. |
278
+ | `CONFORMANCE_ROWS` | const | `readonly Row[]` | Holds the `users` rows the conformance differential seeds: ties, an absent `age`, ASCII and non-ASCII case variants, a supplementary-plane character, an empty name, and a `[`. |
279
+ | `CONFORMANCE_READS` | const | `readonly ReadInput[]` | Holds the reads the conformance differential runs over `CONFORMANCE_ROWS`: every operator on a required text column and an optional integer column, `null` operands, `or` folds, a nested path, orders with ties, a page, and every aggregate. |
263
280
 
264
281
  ### Types
265
282
 
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. |
283
+ | Name | Kind | Signature | Summary |
284
+ | -------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
285
+ | `Key` | type | `string \| number` | Represents a primary key — the value identifying a row within its table. |
286
+ | `KeyFunction` | type | `() => Key` | Represents a key-generating function. |
287
+ | `Row` | type | `Record<string, unknown>` | Represents a table row — a plain record of column values keyed by column name. |
288
+ | `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. |
289
+ | `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. |
290
+ | `ConditionConnector` | type | `'and' \| 'or'` | Names how a `Condition` joins to the running result of the conditions before it. |
291
+ | `Condition` | interface | `{ column, operator, values, connector }` | Represents one compiled WHERE condition. |
292
+ | `OrderDirection` | type | `'ascending' \| 'descending'` | Names a sort direction. |
293
+ | `Order` | interface | `{ column, direction }` | Represents one ordering term — a column (`FieldPath`, flat or nested) and its direction. |
294
+ | `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. |
295
+ | `Aggregate` | interface | `{ operation, column }` | Represents one aggregate a read reduces its rows to. |
296
+ | `ReadInput` | interface | `{ aggregate? }` | Represents a read as a driver plans it: a query, and the aggregate over its rows when the read computes one. |
297
+ | `ReadPlan` | interface | `{ native, residual }` | Represents the split of one read between the engine and the core. |
298
+ | `AggregateOperation` | type | `'count' \| 'sum' \| 'average' \| 'minimum' \| 'maximum'` | Names an aggregate computed over a numeric column. |
299
+ | `OperationOptions` | interface | `{ signal? }` | Options for an abortable operation. |
300
+ | `DatabaseStatus` | type | `'idle' \| 'open' \| 'closed'` | Names the lifecycle state of a `DatabaseInterface`. |
301
+ | `AdmissionInterface` | interface | `{ accepting, track() }` | Represents the admission boundary a scoped operation enters before it runs. |
302
+ | `DatabaseErrorCode` | type | `'CLOSED' \| 'NOT_FOUND' \| 'CONFLICT' \| 'VALIDATION' \| 'ABORTED' \| 'MIGRATION' \| 'CONFORMANCE' \| 'DRIVER'` | Names a machine-readable `DatabaseError` code. |
303
+ | `ConformanceFinding` | interface | `{ check, message, context }` | Represents one violated invariant from the driver-conformance battery. |
304
+ | `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. |
305
+ | `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`. |
306
+ | `ColumnMap` | type | `Readonly<Record<string, ContractShape>>` | Represents one table's columns — a map of column name to its value `ContractShape`. |
307
+ | `TableMap` | type | `Readonly<Record<string, ColumnMap>>` | Represents a database's table schema — a map of table name to its `ColumnMap`. |
308
+ | `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. |
309
+ | `PrimaryMap` | type | `Readonly<Record<string, string>>` | Holds per-table primary-key column overrides — `{ [table]: column }`. |
310
+ | `IndexMap` | type | `Readonly<Record<string, ReadonlyArray<readonly string[]>>>` | Holds per-table secondary indexes — `{ [table]: groups }`, each group one (possibly compound) index of column names. |
311
+ | `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. |
312
+ | `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`). |
313
+ | `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. |
314
+ | `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. |
315
+ | `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. |
316
+ | `MigrationInput` | interface | `{ plan, metadata? }` | Represents one atomic migration request. |
317
+ | `StorageInterface` | interface | `{ read(), write(), insert(), delete(), keys(), scan(), clear(), plan?(), records?(), aggregate?(), stream?(), migrate?(), metadata?(), stamp?() }` | Declares the storage operations available only inside a driver's transaction scope. |
318
+ | `DriverMetadata` | interface | `{ version, schema }` | Represents persisted schema metadata a versioning driver owns as an immutable snapshot. |
319
+ | `DriverInterface` | interface | `{ open(), close(), snapshot(), transaction?() }` | Declares the storage contract a backend implements: its engine's native operations first, and the core's engine only for the residual its plan returns. |
320
+ | `DatabaseOptions` | interface | `{ on?, error?, driver, tables, primary?, indexes?, name?, generator?, version? }` | Options for `createDatabase`. |
321
+ | `CompiledSQL` | interface | `{ sql, parameters }` | Represents a parameterized SQL fragment or statement plus its bind values. The `@orkestrel/database/server` entry point exports this type. |
322
+ | `SQLiteDriverOptions` | interface | `{ path, readonly?, timeout?, references?, pragmas? }` | Configures `createSQLiteDriver`. The `@orkestrel/database/server` entry point exports this type. |
323
+ | `AccessPlan` | interface | `{ index?, range? }` | Represents the key-range read behind a plan's native side — an optional index and an optional `IDBKeyRange`. An omitted `index` selects the primary store; an omitted `range` reads the whole store, so `{}` is a whole-store read. The `@orkestrel/database/browser` entry point exports this type. |
324
+ | `TableDefinition` | interface | `{ primary, columns, schema }` | Represents one table's portable definition, produced by `export` — the unit of schema / migration exchange across environments. |
325
+ | `DatabaseStorageInterface` | interface | `{ table() }` | Represents a table-only database view. |
326
+ | `DatabaseInterface` | interface | `{ emitter, name, status, import(), export(), open(), close(), transaction(), migrate() }` | Represents a database — the ergonomic entry point that owns the driver and its tables. |
327
+ | `TableInterface` | interface | `{ emitter, name, primary, contract, get(), resolve(), has(), keys(), records(), count(), aggregate(), scan(), set(), add(), update(), remove(), clear(), query(), cursor() }` | Exposes typed keyed CRUD plus fluent query and cursor access. |
328
+ | `QueryInterface` | interface | `{ condition(), order(), filter(), limit(), offset(), collect(), find(), count(), stream(), aggregate() }` | Builds a read through a fluent chain. |
329
+ | `CursorInterface` | interface | `{ value, index, done, next(), update(), remove(), close() }` | Walks a table's rows forward for bulk in-place mutation. |
309
330
 
310
331
  ### Operation state
311
332
 
@@ -366,21 +387,22 @@ method below runs inside that scope, and each carries the same contract its
366
387
  `StorageInterface` and `DriverInterface` tables share one description per
367
388
  method.
368
389
 
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. |
390
+ | Method | Returns | Summary |
391
+ | ----------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
392
+ | `read` | `Promise<Row \| undefined>` | Reads one row by key. |
393
+ | `write` | `Promise<void>` | Writes one row at a key. |
394
+ | `insert` | `Promise<void>` | Inserts one row atomically, rejecting `CONFLICT` when its key already exists. |
395
+ | `delete` | `Promise<boolean>` | Deletes one row by key. |
396
+ | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
397
+ | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
398
+ | `clear` | `Promise<void>` | Empties a table. |
399
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
400
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
401
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
402
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
403
+ | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
404
+ | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
405
+ | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
384
406
 
385
407
  #### `DriverInterface`
386
408
 
@@ -391,10 +413,10 @@ storage/query/migration/metadata methods carry the same contract they carry on
391
413
  transaction scope. `open` receives the derived `TableSchema` list: a native
392
414
  backend builds real tables and indexes from it, a scan-only backend reads
393
415
  `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)).
416
+ list scopes capture and restore to those tables. A driver without `plan` answers
417
+ nothing natively — the core runs the whole read over `scan` — and a driver without
418
+ `transaction` runs a scope on the snapshot floor (see
419
+ [Native transactions](#native-transactions)).
398
420
 
399
421
  | Method | Returns | Summary |
400
422
  | ------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -408,9 +430,10 @@ on the snapshot floor (see [Native transactions](#native-transactions)).
408
430
  | `keys` | `Promise<readonly Key[]>` | Lists a table's keys. |
409
431
  | `scan` | `AsyncIterable<Row>` | Iterates a table's rows in ascending key order. |
410
432
  | `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. |
433
+ | `plan` | `ReadPlan` | Splits a read into the part the engine answers natively and the residual the core runs — an optional hook. |
434
+ | `records` | `Promise<readonly Row[]>` | Reads the rows matching the native side of a plan — an optional hook. |
435
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over the rows matching the native side of a plan — an optional hook. |
436
+ | `stream` | `AsyncIterable<Row>` | Iterates the rows matching the native side of a plan lazily — an optional hook. |
414
437
  | `migrate` | `Promise<void>` | Applies one atomic `MigrationInput` — an optional hook. |
415
438
  | `metadata` | `Promise<DriverMetadata \| undefined>` | Reads the persisted `DriverMetadata` as a deeply frozen copy — an optional hook. |
416
439
  | `stamp` | `Promise<void>` | Writes the persisted `DriverMetadata`, snapshot at entry — an optional hook. |
@@ -457,34 +480,32 @@ expose; its `accepting` data member stays in the Surface row above.
457
480
  #### `TableInterface`
458
481
 
459
482
  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`,
483
+ out) — a single verb, never `getMany` / `setAll`. `get()`, `records()`, and `scan()`
484
+ narrow every returned row through the table's contract guard, and a stored row that fails
485
+ it raises `DRIVER` with `table`, `key`, and the contract's `faults`. `count()` is
486
+ `aggregate('count')`, which reads the stored set `records()` reads while ignoring paging,
487
+ so the two agree. `records`,
467
488
  `count`, `aggregate`, `scan`, `set`, `add`, `update`, and `remove` each take an
468
489
  optional `OperationOptions`: its `signal` reaches every backend commit point,
469
490
  and an aborted batch keeps the items already committed.
470
491
 
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. |
492
+ | Method | Returns | Summary |
493
+ | ----------- | ------------------------------------ | ----------------------------------------------------------------------------------------- |
494
+ | `get` | `Promise<T \| undefined>` (or array) | Reads one row by key, or one row per key for a list — `undefined` for each miss. |
495
+ | `resolve` | `Promise<T>` (or array) | Reads one row by key, or one row per key for a list, throwing `NOT_FOUND` on a miss. |
496
+ | `has` | `Promise<boolean>` (or array) | Reports whether one key exists, or one result per key for a list. |
497
+ | `keys` | `Promise<readonly Key[]>` | Lists every primary key in order. |
498
+ | `records` | `Promise<readonly T[]>` | Reads the rows matching an optional `QueryInput`. |
499
+ | `count` | `Promise<number>` | Counts the stored rows matching `input`'s conditions. |
500
+ | `aggregate` | `Promise<number \| undefined>` | Computes an aggregate over `column` across the stored rows matching `input`'s conditions. |
501
+ | `scan` | `AsyncIterable<T>` | Iterates the table's rows lazily with filtering. |
502
+ | `set` | `Promise<Key>` (or array) | Upserts one or more rows. |
503
+ | `add` | `Promise<Key>` (or array) | Inserts one or more rows, throwing `CONFLICT` on a duplicate key. |
504
+ | `update` | `Promise<boolean>` (or array) | Applies a partial change to one or more rows. |
505
+ | `remove` | `Promise<boolean>` (or array) | Deletes one or more rows. |
506
+ | `clear` | `Promise<void>` | Empties the table. |
507
+ | `query` | `QueryInterface<T>` | Opens a fluent query builder over the table. |
508
+ | `cursor` | `Promise<CursorInterface<T>>` | Opens a forward row cursor for bulk mutation. |
488
509
 
489
510
  #### `QueryInterface`
490
511
 
@@ -545,29 +566,42 @@ These invariants hold across the core database source tree ↔ this guide:
545
566
  JSON-encoded, length-capped rendering of the received value; the rejected
546
567
  row and the parser cause never enter the message, context, serialized
547
568
  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
569
+ 3. **Native first.** A driver answers every part of a read or a write with its engine's
570
+ native operation wherever the engine has one, and the core runs its own engine only over
571
+ the residual a driver's plan returns. The rule's home is the `DriverInterface` doc block,
572
+ which also states the plan invariants; this guide states it nowhere else. `open` hands the
573
+ driver a derived `TableSchema[]` (each table's `columns`, their portable `ColumnStorage`
574
+ through `shapeToColumnStorage`, the `primary` key, and declared `indexes`) so a native
575
+ backend can build real tables and indexes; a scan-only backend reads only `name`. A
576
+ driver declares its native coverage per read through `plan`, which returns a `ReadPlan`;
577
+ `Table` calls `records`, `stream`, and `aggregate` with `plan.native` only, and runs the
578
+ residual through `applyQuery`, `matchesQuery`, `sortRows`, and `computeAggregate`. A read
579
+ is wholly native when `residual` equals `{}`. `scanDriver` checks every plan's invariants,
580
+ the transaction capability's mirror of the native members, and a differential of each
581
+ planned driver against the core engine over `scan`. The following table rules where
582
+ each clause runs in this release:
583
+
584
+ | Clause | `SQLiteDriver` | `IndexedDBDriver` | `MemoryDriver`, `JSONDriver` |
585
+ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- |
586
+ | Every operator on a flat `text`, `integer`, `real`, or `boolean` column | Native under every flag combination, with the null forms chosen from the column's flags; `starts` is an index range and `any` / `none` bind one `json_each` parameter | The first `and`-joined `equals`, `above`, `from`, or `between` over an index, or a comparison over the primary key | Residual over `scan` |
587
+ | A nested path; a `json` or `blob` column | Residual | Residual | Residual over `scan` |
588
+ | An `or` fold | Native when every condition is; otherwise wholly residual | Residual | Residual over `scan` |
589
+ | Order | Native on a flat column that is not both optional and nullable | Residual | Residual over `scan` |
590
+ | Page | `LIMIT` and `OFFSET` when the residual holds no condition and no order | Residual, stopping the stream at `offset + limit` matches | Residual over `scan` |
591
+ | `count` | `COUNT(*)` when the residual holds no condition | Residual | Residual over `scan` |
592
+ | `sum`, `average`, `minimum`, `maximum` | Native on an `integer` or `real` column that is not both optional and nullable | Residual | Residual over `scan` |
593
+ | Transaction | `BEGIN` / `COMMIT` / `ROLLBACK`; the scoped capability declares `plan`, `records`, `stream`, and `aggregate` | The snapshot floor | `JSONDriver`: native; `MemoryDriver`: the snapshot floor |
594
+
595
+ The rule fixes these semantics on every driver: text order and text ranges are the
596
+ engine's binary order, so SQLite orders by code point where the core orders by UTF-16
597
+ code unit, and the two differ only between a supplementary-plane character and one in
598
+ U+E000 to U+FFFF; `like` folds ASCII letters only, and `_` and `?` match one code point;
599
+ ties resolve by primary key in the direction of the final order term; `sum` and
600
+ `average` on a numeric column are the engine's arithmetic. Every write is admitted
601
+ through the contract, so every stored row conforms; a returned stored row that fails the
602
+ contract raises `DRIVER`, and SQLite raises `DRIVER` for a stored value that does not
603
+ match its column's declaration. `MemoryDriver` still lacks a native `transaction?`, so its
604
+ transactions always use the snapshot floor; `JSONDriver` does implement
571
605
  `transaction?` — it clones the committed memory/schema/metadata into an
572
606
  isolated candidate, passes only that candidate's capability to the callback,
573
607
  and publishes it with one atomic file replacement only when the callback
@@ -610,51 +644,6 @@ These invariants hold across the core database source tree ↔ this guide:
610
644
  or physically incomplete state throws `DRIVER` without publishing a handle or
611
645
  attempting table/store repair; after external repair, the same driver instance
612
646
  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
647
  `IndexedDBDriver.snapshot()` captures every store in one read transaction,
659
648
  so the capture is point-in-time consistent across stores even under
660
649
  concurrent writers; `restore` was already atomic. `SQLiteDriver` and
@@ -680,10 +669,9 @@ These invariants hold across the core database source tree ↔ this guide:
680
669
  that one native transaction, then becomes invalid. `IndexedDBDriver`
681
670
  deliberately omits `transaction?`: an `IDBTransaction` can auto-commit when
682
671
  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.
672
+ truthfully remain inside one native transaction. It also omits `aggregate?`, so every
673
+ aggregate it plans stays residual.
674
+
687
675
  4. **Total query helpers; the equality family is structural, not ranked.**
688
676
  `compareValues`, `matchesCondition`, and `matchesQuery` never throw — a
689
677
  type mismatch is a non-match and the comparator is a total order (it
@@ -941,10 +929,9 @@ and a reserved
941
929
  `_metadata` table (`METADATA_TABLE`) for `metadata?` / `stamp?` versioning — every
942
930
  optional `DriverInterface` hook, none skipped. `IndexedDBDriver` in
943
931
  `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
932
+ persistent browser backend — `planIndexedDBQuery` keeps native the one condition a
933
+ key range over the primary key or a single-column secondary index answers, and leaves the
934
+ rest of the read residual for the core engine; `migrate?` applies a non-empty plan
948
935
  and its metadata in one versionchange transaction, and `metadata?` / `stamp?`
949
936
  persist into a reserved
950
937
  `__metadata__` store (`METADATA_STORE`) — it omits `transaction?` because arbitrary
@@ -992,9 +979,8 @@ posts.primary // 'slug' — the declared override
992
979
 
993
980
  Each `indexes` entry is one (possibly compound) index of column names; they
994
981
  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.
982
+ native index, so both ignore them; SQLite and IndexedDB build a native index from each
983
+ supported declaration.
998
984
 
999
985
  ### Swapping the driver
1000
986
 
@@ -1377,9 +1363,9 @@ await users
1377
1363
  .collect()
1378
1364
  ```
1379
1365
 
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:
1366
+ The condition operators map to familiar SQL operators. The core engine evaluates each one
1367
+ over a residual; SQLite answers each natively on a flat declared column, and IndexedDB
1368
+ answers one comparison with a key range, under these same semantics:
1383
1369
 
1384
1370
  | Operator | SQL |
1385
1371
  | --------- | ------------- |
@@ -2106,8 +2092,8 @@ await driver.close()
2106
2092
 
2107
2093
  ### Query engine helpers
2108
2094
 
2109
- The pure functions behind `TableInterface` and `QueryInterface` — useful
2110
- directly when building a new driver's native `records` / `aggregate` hook:
2095
+ The pure functions of the core's engine, which runs the residual of a driver's plan
2096
+ behind `TableInterface` and `QueryInterface`:
2111
2097
 
2112
2098
  ```ts
2113
2099
  import type { Condition } from '@orkestrel/database'
@@ -2131,7 +2117,7 @@ import {
2131
2117
 
2132
2118
  compareValues(1, 2) // -1 — a total order over mixed types
2133
2119
  matchesWildcardPattern('hello', 'h%o', '%', '_', true) // true — the shared LIKE/GLOB engine
2134
- matchesLikePattern('hello', 'h%o') // true — case-insensitive
2120
+ matchesLikePattern('Hello', 'h%o') // true — ASCII letters fold
2135
2121
  matchesGlobPattern('hello', 'h*o') // true — case-sensitive
2136
2122
 
2137
2123
  const condition: Condition = {
@@ -2217,8 +2203,8 @@ replacing the current schema or metadata.
2217
2203
 
2218
2204
  The server's pure `compilers.ts` turns a core `QueryInput` (the same one
2219
2205
  `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:
2206
+ `SELECT`, with `?`-bound parameters in clause order — the native side of a plan that a
2207
+ SQLite driver's `records` hook runs:
2222
2208
 
2223
2209
  ```ts
2224
2210
  import {
@@ -2227,8 +2213,8 @@ import {
2227
2213
  compileFieldSQL,
2228
2214
  compileQuerySQL,
2229
2215
  deriveSQLiteIndexName,
2230
- matchesAggregateExactly,
2231
2216
  matchesSQLiteAffinity,
2217
+ planSQLiteQuery,
2232
2218
  quoteIdentifier,
2233
2219
  schemaToIndexes,
2234
2220
  schemaToTable,
@@ -2249,14 +2235,14 @@ const schema: TableSchema = {
2249
2235
  compileQuerySQL(
2250
2236
  { conditions: [{ column: 'age', operator: 'from', values: [18], connector: 'and' }] },
2251
2237
  schema,
2252
- ) // { sql: 'WHERE "age" >= ? ORDER BY "id"', parameters: [18] }
2238
+ ) // { sql: 'WHERE "age" >= ? ORDER BY "id" ASC', parameters: [18] }
2253
2239
 
2254
2240
  quoteIdentifier('order') // '"order"'
2255
2241
  deriveSQLiteIndexName('users', ['age']) // 'idx_5_users_3_age'
2256
2242
  compileColumnSQL('integer') // 'INTEGER'
2257
2243
  compileFieldSQL(['profile', 'score']) // 'json_extract("profile", \'$.score\')'
2258
2244
  compileAggregateSQL('average', 'age') // 'AVG("age")'
2259
- matchesAggregateExactly('minimum', 'age', schema) // true
2245
+ planSQLiteQuery({ aggregate: { operation: 'minimum', column: 'age' } }, schema).residual // {}
2260
2246
  matchesSQLiteAffinity('INTEGER', 'integer') // true
2261
2247
  schemaToTable(schema) // CREATE TABLE IF NOT EXISTS …
2262
2248
  schemaToIndexes(schema) // []
@@ -2266,31 +2252,23 @@ stepToSQL({ operation: 'index.add', table: 'users', index: ['age'] })
2266
2252
  // db.prepare(`SELECT * FROM "users" ${sql}`).all(...parameters)
2267
2253
  ```
2268
2254
 
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.
2255
+ ### Plans and residual work
2256
+
2257
+ A driver's `plan` splits each read into the part its engine answers and the residual the
2258
+ core runs, under the native-first rule the `DriverInterface` doc block states. A read is
2259
+ wholly native when `residual` equals `{}`. `planSQLiteQuery` is the SQLite driver's plan,
2260
+ and `compileQuerySQL` compiles its native side; `planIndexedDBQuery` is the IndexedDB
2261
+ driver's plan, which keeps one key-range condition native. A driver without `plan`, such as
2262
+ `MemoryDriver` and `JSONDriver`, answers the whole read as residual over `scan`. `Table` runs
2263
+ every read through `readPlannedRows`, `readPlannedAggregate`, and `streamPlannedRows`, the one
2264
+ read procedure `scanDriver`'s differential checks.
2287
2265
 
2288
2266
  ```ts
2289
2267
  import type { Condition, TableSchema } from '@orkestrel/database'
2290
2268
  import {
2291
- matchesConditionExactly,
2292
- matchesQueryExactly,
2293
- matchesOrderExactly,
2269
+ compileQuerySQL,
2270
+ matchesSQLiteCondition,
2271
+ planSQLiteQuery,
2294
2272
  } from '@orkestrel/database/server'
2295
2273
 
2296
2274
  const schema: TableSchema = {
@@ -2303,28 +2281,29 @@ const schema: TableSchema = {
2303
2281
  indexes: [],
2304
2282
  }
2305
2283
 
2306
- const exact: Condition = {
2284
+ const native: Condition = {
2307
2285
  column: 'age',
2308
2286
  operator: 'above',
2309
2287
  values: [18],
2310
2288
  connector: 'and',
2311
2289
  }
2312
- matchesConditionExactly(exact, schema) // true — a plain comparison over a typed column
2290
+ matchesSQLiteCondition(native, schema) // true — a comparison over a typed column
2313
2291
 
2314
- const notExact: Condition = {
2292
+ const residual: Condition = {
2315
2293
  column: 'age',
2316
2294
  operator: 'above',
2317
2295
  values: [null],
2318
2296
  connector: 'and',
2319
2297
  }
2320
- matchesConditionExactly(notExact, schema) // false — a null operand refines instead
2298
+ matchesSQLiteCondition(residual, schema) // false — a null range operand stays residual
2321
2299
 
2322
- matchesOrderExactly({ column: 'age', direction: 'ascending' }, schema) // true — a flat, orderable column
2323
-
2324
- matchesQueryExactly(
2325
- { conditions: [exact], order: [{ column: 'age', direction: 'ascending' }] },
2300
+ const plan = planSQLiteQuery(
2301
+ { conditions: [native], order: [{ column: 'age', direction: 'ascending' }], limit: 10 },
2326
2302
  schema,
2327
- ) // true
2303
+ ) // { native: { conditions: [ … ], order: [ … ], limit: 10 }, residual: {} }
2304
+
2305
+ compileQuerySQL(plan.native, schema)
2306
+ // { sql: 'WHERE "age" > ? ORDER BY "age" ASC, "id" ASC LIMIT ?', parameters: [18, 10] }
2328
2307
  ```
2329
2308
 
2330
2309
  ### Persistence with the SQLite driver
@@ -2425,11 +2404,10 @@ publishing schema/identity/connection state or changing the record. The
2425
2404
  bootstrap closes in every outcome, so external repair or version activity is
2426
2405
  not blocked and the same driver may retry. It then connects the deployed
2427
2406
  `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?` /
2407
+ before reconciliation. Its plan keeps native the one condition a key range over the
2408
+ primary key or a single-column secondary index answers (`planIndexedDBQuery`), and the core
2409
+ engine runs the rest — see [Plans and residual work](#plans-and-residual-work).
2410
+ It implements `plan?` / `records?` / `stream?` / `migrate?` / `metadata?` /
2433
2411
  `stamp?` (persisted into a reserved `__metadata__` store, `METADATA_STORE` —
2434
2412
  `open()` throws `DatabaseError('VALIDATION')` if a declared table is
2435
2413
  literally named `__metadata__`), but omits `transaction?` (the underlying
@@ -2457,16 +2435,21 @@ Failed query-builder validation does not mutate builder state. `count` and
2457
2435
  `aggregate` validate paging even though valid paging remains intentionally
2458
2436
  ignored by their unpaged semantics.
2459
2437
 
2460
- ### IndexedDB pushdown planning
2438
+ ### IndexedDB planning
2461
2439
 
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:
2440
+ The pure planner behind `IndexedDBDriver`'s `plan` — useful directly to see which condition
2441
+ a key range answers before a read touches a browser database:
2465
2442
 
2466
2443
  ```ts
2467
2444
  import type { Condition, TableSchema } from '@orkestrel/database'
2468
2445
  import { isKey } from '@orkestrel/database'
2469
- import { conditionToRange, deriveIndexedDBIndexName, selectPlan } from '@orkestrel/database/browser'
2446
+ import {
2447
+ conditionToRange,
2448
+ deriveAccessPlan,
2449
+ deriveIndexedDBIndexName,
2450
+ findAccessCondition,
2451
+ planIndexedDBQuery,
2452
+ } from '@orkestrel/database/browser'
2470
2453
 
2471
2454
  const schema: TableSchema = {
2472
2455
  name: 'users',
@@ -2490,16 +2473,15 @@ const equalsAge: Condition = {
2490
2473
  }
2491
2474
  conditionToRange(equalsAge) // an IDBKeyRange.only(30) — an exact comparison operator
2492
2475
 
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']) // {}
2476
+ // No condition narrows, so the plan reads the whole store and leaves the read residual:
2477
+ planIndexedDBQuery({}, schema, ['age']) // { native: {}, residual: {} }
2496
2478
 
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 }
2479
+ // A comparison over the indexed `age` column stays native as that index's range:
2480
+ const fromAge: Condition = { column: 'age', operator: 'from', values: [18], connector: 'and' }
2481
+ planIndexedDBQuery({ conditions: [fromAge], limit: 10 }, schema, ['age'])
2482
+ // { native: { conditions: [fromAge] }, residual: { limit: 10 } }
2483
+ deriveAccessPlan(findAccessCondition({ conditions: [fromAge] }, schema, ['age']), schema)
2484
+ // { index: 'age', range: an IDBKeyRange bounding age >= 18 }
2503
2485
  ```
2504
2486
 
2505
2487
  ### IndexedDB error mapping
@@ -2545,6 +2527,39 @@ mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATIO
2545
2527
  - **Use `MemoryDriver` for tests and ephemeral data** — no I/O, and
2546
2528
  `JSONDriver` swaps in unchanged when writes need to survive a restart.
2547
2529
 
2530
+ ## Migrating from 0.0.23
2531
+
2532
+ The paging wave changes these exports and behaviors; under the no-shim law, each consumer
2533
+ changes in the release that adopts it. A name in this section that the package no longer
2534
+ exports is written plain, without code formatting.
2535
+
2536
+ | 0.0.23 | This release |
2537
+ | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2538
+ | matchesQueryExactly(input, schema) | `planSQLiteQuery(input, schema)`, which returns a `ReadPlan`; a read is wholly native when `residual` equals `{}` |
2539
+ | `compileQuerySQL(input, schema)` | Same name and signature; pass it `planSQLiteQuery(input, schema).native`. Its SQL changes: `starts` compiles to an index range, `any` and `none` bind one `json_each` parameter, every condition beside an `any` on the primary key is pinned behind unary `+`, and the primary-key tie term carries the final order term's direction |
2540
+ | matchesConditionExactly | `matchesSQLiteCondition(condition, schema)` |
2541
+ | matchesOrderExactly, matchesAggregateExactly, EXACT_COLUMN_STORAGE, EXACT_RANGE_COLUMN_STORAGE | Removed; `planSQLiteQuery` answers each question |
2542
+ | selectPlan(input, schema, indexes) | `deriveAccessPlan(findAccessCondition(input, schema, indexes), schema)` for the key-range read, and `planIndexedDBQuery(input, schema, indexes)` for the split |
2543
+ | QueryPlan | `AccessPlan` |
2544
+ | `MemoryDriver.stream`, `JSONDriver.stream` | Removed; call `Table.scan`, or `streamPlannedRows` over the driver |
2545
+ | `matchesWildcardSegment(value: string, segment: string, …)` | `matchesWildcardSegment(value: readonly string[], segment: readonly string[], …)`, over code points |
2546
+ | `decodeValue` and `decodeRow` returning absence for a malformed cell | Both raise `DRIVER` with `table`, `column`, and `key` |
2547
+ | `compileOrderSQL` ending with a bare primary-key term | The primary-key term always carries `ASC` or `DESC`, in the direction of the final term |
2548
+ | A read that skipped a nonconforming stored row | `get`, `records`, and `scan` raise `DRIVER` with `table`, `key`, and `faults` |
2549
+ | `count` skipping a nonconforming stored row | `count` is `aggregate('count')`: it counts every stored row its conditions match, a nonconforming row included, and raises nothing, because it returns no row |
2550
+ | A driver with `records`, `stream`, or `aggregate` and no `plan` | The core never calls those hooks and reads the driver over `scan`; a custom driver adds `plan` to keep its pushdown |
2551
+ | Any `pragmas` entry on `createSQLiteDriver` | Each name must be one of `PRAGMA_NAMES`, matched exactly, and each value a finite number or a bare keyword; anything else throws `VALIDATION` from `validatePragmas` |
2552
+ | `compileConditionSQL` and `compileQuerySQL` leaving `equals` / `not` with `undefined`, and lists holding `null` or `undefined`, to the core | Each compiles natively: `undefined` to `IS NULL` / `IS NOT NULL` on a column that stores absence, and a list to `IN (…)` joined with the null and absence tests its flags define, the `none` complement included |
2553
+
2554
+ The paging wave added names that its review then renamed or folded before release:
2555
+ compactReadInput is `normalizeReadInput`; comparePlans is `scanPlans`; containsValue is
2556
+ `matchesListed`; matchesNativeCondition is `matchesSQLiteCondition`; findNativeColumn is
2557
+ `findSQLiteColumn`; wrapValued is `compileGuardedSQL`; REFUSED_PRAGMAS is `PRAGMA_NAMES`, an allowlist; collectRows is removed in favor of
2558
+ `Array.fromAsync`; matchesNativeOrder and matchesNativeAggregate fold into
2559
+ `planSQLiteQuery`; classifyAbsence and the ColumnAbsence type fold into
2560
+ `compileConditionSQL`; decodeStoredValue folds into `decodeValue`; and `isScalar` narrows
2561
+ to `Scalar`.
2562
+
2548
2563
  ## Tests
2549
2564
 
2550
2565
  - [`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.
@@ -2564,13 +2579,13 @@ mapMigrationError(fault) // → the same, but an UPGRADE fault becomes 'MIGRATIO
2564
2579
  - [`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
2580
  - [`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
2581
  - [`tests/src/server/drivers/JSONDriver.test.ts`](../tests/src/server/drivers/JSONDriver.test.ts) — `JSONDriver` persistence plus atomic insert and the exclusive point-mutation queue: queued abort/no late start, active staging restoration, cleanup-success error precedence, deterministic real-filesystem persistence-plus-cleanup dual failure with exact evidence and queue recovery, read isolation, concurrent-writer ordering, fail-closed real-filesystem coverage for non-absence reads, invalid syntax/documents/table sets/containers/rows/metadata, byte preservation, no partial publication, application-invalid row retention, payload-safe rejection, strict stream paging, and same-instance external-repair retry; synchronous root/scoped stamp and migration ownership, deeply frozen distinct copy-out, deployed-schema-first open, isolated callback/root-migration candidates whose rows/schema/metadata publish only after file replacement succeeds, transaction-time root scan/stream continuation conflicts with terminal cleanup, and post-native-rollback rejection replacement.
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.
2582
+ - [`tests/src/server/drivers/SQLiteDriver.test.ts`](../tests/src/server/drivers/SQLiteDriver.test.ts) — `SQLiteDriver`'s native surface: deployed-metadata-first open and reconciliation; fail-closed malformed metadata, physical schema disagreement, and persisted-table loss before DDL, including deterministic first-loss evidence, physical non-recreation, external repair, and same-driver retry; root/scoped stamp/migration ownership and distinct deeply frozen copy-out; atomic insert/duplicate `CONFLICT`; point-mutation abort boundaries; strict direct records/aggregate/stream paging; native planned query and aggregate paths, the paging readings, the operator matrix, and `EXPLAIN QUERY PLAN` of the native plan; repeatable schema-aware snapshot capture/replay plus real dropped-table and exclusive-lock failure containment/recovery; atomic `MigrationInput` schema/rows/metadata at the root; fixed-literal savepoint containment for a caught migration failure while its callback transaction remains active; candidate-schema publication only after commit; callback transaction barriers/invalidation including root continuation cleanup; payload-safe rejection; post-native-rollback rejection replacement; backend-fault mapping; and engine parity.
2583
+ - [`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
2584
  - [`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
2585
  - [`tests/src/server/inferers.test.ts`](../tests/src/server/inferers.test.ts) — `inferValueStorage`'s nested-operand storage inference: the `ColumnStorage` a `json_extract` operand must encode as, over booleans, integral and fractional numbers, bigints, objects and arrays, strings, `null`, and `undefined`.
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.
2586
+ - [`tests/src/server/integration.test.ts`](../tests/src/server/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `SQLiteDriver` (native and residual reads) produce identical rows/counts/aggregates, and the text-order exemption names the ids SQLite returns under its binary order.
2587
+ - [`tests/src/browser/drivers/IndexedDBDriver.test.ts`](../tests/src/browser/drivers/IndexedDBDriver.test.ts) — `IndexedDBDriver` against real IndexedDB: metadata-only bootstrap and deployed-schema-first reopen, one-transaction `has`/`get` absence discrimination, fail-closed malformed-metadata preservation (including stored `undefined`) and persisted-store loss with deterministic first-loss evidence, physical non-recreation, extra-store retention, external repair, and same-driver retry; bootstrap-lifetime store/version capture and a competing versionchange proving the persisted final open is pinned and retryable; payload-safe errors and table rejection, closed failed state, reserved-store validation, atomic `add` insertion and duplicate `CONFLICT`, active/pre-dispatch/late abort boundaries, strict direct records/stream paging, the plan, the rows read per conformance read against 0.0.23, snapshot capture-replay, schema/rows/metadata in one versionchange migration, metadata-only migration input, failed-upgrade reconnection to the old schema, metadata persistence, backend-fault mapping, and confirmation that callback `transaction` / native `aggregate` are absent.
2588
+ - [`tests/src/browser/helpers.test.ts`](../tests/src/browser/helpers.test.ts) — the planner: `conditionToRange` over every comparison operator, `findAccessCondition` / `deriveAccessPlan` index and primary selection, `planIndexedDBQuery`, backend-error mapping, and exact `deriveIndexedDBIndexName` bytes.
2574
2589
  - [`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
2590
  - [`tests/src/browser/integration.test.ts`](../tests/src/browser/integration.test.ts) — cross-backend behavioral parity: the same `QueryInput` set run against `MemoryDriver` and `IndexedDBDriver` produce identical rows/counts, including pushdown edge cases (`below`/`to` on a secondary-indexed column, a reversed `between`).
2576
2591