@orkestrel/scaffold 0.0.135 → 0.0.137

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +167 -4
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +20 -5
  3. package/dist/bin/main.js +12 -12
  4. package/dist/host/AGENTS.md +1 -1
  5. package/dist/host/agents/orchestration.md +2 -2
  6. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +201 -8
  7. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +24 -5
  8. package/dist/host/claude/agents/orkestrel.md +52 -52
  9. package/dist/host/claude/agents/reviewer.md +1 -1
  10. package/dist/host/claude/rules/documentation.md +1 -1
  11. package/dist/host/claude/rules/patterns.md +2 -2
  12. package/dist/host/claude/rules/workspace.md +9 -4
  13. package/dist/host/configs/helpers.ts +21 -6
  14. package/dist/host/guides/agent.md +3 -1
  15. package/dist/host/guides/brief.md +16 -16
  16. package/dist/host/guides/browser.md +1 -1
  17. package/dist/host/guides/contract.md +198 -163
  18. package/dist/host/guides/database.md +773 -310
  19. package/dist/host/guides/indexeddb.md +80 -66
  20. package/dist/host/guides/reason.md +1 -1
  21. package/dist/host/guides/relation.md +56 -32
  22. package/dist/host/guides/scaffold.md +8 -2
  23. package/dist/host/guides/sqlite.md +44 -23
  24. package/dist/host/guides/test.md +7 -3
  25. package/dist/host/guides/tool.md +2 -1
  26. package/dist/host/guides/toolbox.md +44 -44
  27. package/dist/host/guides/workflow.md +2 -2
  28. package/dist/host/manifest.json +26 -26
  29. package/dist/host/tests/config.test.ts +71 -3
  30. package/dist/src/core/index.cjs +112 -35
  31. package/dist/src/core/index.cjs.map +1 -1
  32. package/dist/src/core/index.d.cts +31 -5
  33. package/dist/src/core/index.d.ts +31 -5
  34. package/dist/src/core/index.js +112 -36
  35. package/dist/src/core/index.js.map +1 -1
  36. package/package.json +12 -12
@@ -5,7 +5,7 @@
5
5
  > attached, batched so a direct relation costs one query across the whole record set and
6
6
  > a `through` relation two.
7
7
 
8
- The relationships (`belongs` / `many` / `one` / `through` / `morph`) cover the foreign-key shapes; nested includes recurse through the registry; `link` / `unlink` / `links` manage a many-to-many junction without hand-writing join rows. The layer stays thin above the typed store: resolution is define-time — each relation is precomputed once into a flat `ResolvedRelation`, and nothing is inferred while loading — and the loaded relation properties are deliberately loose (`Row | readonly Row[] | undefined`) rather than typed to each exact target row. The typed half is the table reached through `model.table`, and relation loading is the looser convenience on top. No write-cascades, no lazy proxies, no query builder of its own. Source: [`src/core`](../src/core). Surfaced through the `@src/core` barrel.
8
+ The relationships (`belongs` / `many` / `one` / `through` / `morph`) cover the foreign-key shapes; nested includes recurse through the registry; `link` / `unlink` / `links` manage a many-to-many junction without hand-writing join rows. The layer stays thin above the typed store: resolution is define-time — each relation is precomputed once into a flat `ResolvedRelation`, and nothing is inferred while loading — and the loaded relation properties are deliberately loose (`Row | readonly Row[] | undefined`) rather than typed to each exact target row. The typed half is the table reached through `model.table`, and relation loading is the looser convenience on top. No write-cascades, no lazy proxies, no query builder of its own; [Limits](#limits) states each refusal and what reopens it. Source: [`src/core`](../src/core). Surfaced through the `@src/core` barrel.
9
9
 
10
10
  ## Surface
11
11
 
@@ -40,7 +40,7 @@ acme?.contacts // the relation property — broad (Row | readonly Row[] | undefi
40
40
  | Name | Kind | Signature | Summary |
41
41
  | ----------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
42
42
  | `createRelationManager` | function | `<T extends TableMap>(options: RelationManagerOptions<T>) => RelationManagerInterface<T>` | Creates a `RelationManagerInterface` over storage and its relation map. |
43
- | `RelationManager` | class | `new <T extends TableMap = TableMap>(options: RelationManagerOptions<T>) => RelationManagerInterface<T>` | Resolves a `RelationsShape` once at construction and vends a typed `ModelInterface` per declared table. |
43
+ | `RelationManager` | class | `new <T extends TableMap = TableMap>(options: RelationManagerOptions<T>) => RelationManagerInterface<T>` | Resolves a `RelationSchema` once at construction and vends a typed `ModelInterface` per declared table. |
44
44
  | `Model` | class | `new <T = Row>(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext \| undefined, storage: DatabaseStorageInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler) => ModelInterface<T>` | Pairs a typed table with relation-aware `load` / `find` and junction management. |
45
45
 
46
46
  ### Builders
@@ -55,21 +55,32 @@ acme?.contacts // the relation property — broad (Row | readonly Row[] | undefi
55
55
 
56
56
  ### Resolution
57
57
 
58
- | Name | Kind | Signature | Summary |
59
- | ----------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
60
- | `resolveRelation` | function | `(name: string, value: Relation) => ResolvedRelation` | Resolves one raw `Relation` value into a flat `ResolvedRelation`. |
61
- | `resolveRelationMap` | function | `(relations: RelationMap) => ReadonlyMap<string, ResolvedRelation>` | Resolves every entry of a `RelationMap` into a name → `ResolvedRelation` map. |
62
- | `isRelationDescriptor` | function | `(value: unknown) => value is RelationDescriptor` | Narrows a value to a `RelationDescriptor` (the object form of a relation). |
63
- | `validateRelationTable` | function | `(storage: DatabaseStorageInterface, model: string, relation: string, table: string, junction?: boolean) => void` | Validates a relation table through its bound storage, translating only an undeclared table. |
58
+ | Name | Kind | Signature | Summary |
59
+ | -------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
60
+ | `resolveRelation` | function | `(name: string, value: Relation) => ResolvedRelation` | Resolves one raw `Relation` value into a flat `ResolvedRelation`. |
61
+ | `resolveRelationMap` | function | `(relations: RelationMap) => ReadonlyMap<string, ResolvedRelation>` | Resolves every entry of a `RelationMap` into a name → `ResolvedRelation` map. |
62
+ | `isRelationDescriptor` | const | `Guard<RelationDescriptor>` | Narrows a value to a `RelationDescriptor` (the object form of a relation). |
63
+ | `validateRelationTable` | function | `(storage: DatabaseStorageInterface, model: string, relation: string, table: string, junction?: boolean) => void` | Validates a relation table through its bound storage, translating only an undeclared table. |
64
+ | `validateRelationJunction` | function | `(model: string, resolved: ResolvedThrough, primary: string) => void` | Validates that a `through` relation's junction keys its rows by a column of its own. |
64
65
 
65
66
  ### Row helpers
66
67
 
67
- | Name | Kind | Signature | Summary |
68
- | --------------- | -------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
69
- | `readColumn` | function | `(record: unknown, column: string) => unknown` | Reads one column off any record, whatever its declared type. |
70
- | `countAttached` | function | `(values: ReadonlyArray<Row \| readonly Row[] \| undefined>) => number` | Counts the related rows one relation attached across a record set. |
71
- | `indexRows` | function | `(rows: readonly Row[], column: string, values?: readonly Row[]) => ReadonlyMap<string, Row>` | Indexes rows by the string form of one column, for keyed lookups. |
72
- | `groupRows` | function | `(rows: readonly Row[], column: string, values?: readonly Row[]) => ReadonlyMap<string, readonly Row[]>` | Groups rows by the string form of one column, for one-to-many lookups. |
68
+ | Name | Kind | Signature | Summary |
69
+ | ---------------- | -------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
70
+ | `computeLinkKey` | function | `(key: Key, target: Key) => string` | Computes the junction row's primary key for one pair of a `through` relation. |
71
+ | `readRow` | function | `<T>(table: string, row: T) => T & Row` | Reads one row a storage returned, refusing a value that is not a plain record. |
72
+ | `countAttached` | function | `(values: ReadonlyArray<Row \| readonly Row[] \| undefined>) => number` | Counts the related rows one relation attached across a record set. |
73
+ | `indexRows` | function | `(rows: readonly Row[], column: string, values?: readonly Row[]) => ReadonlyMap<string, Row>` | Indexes rows by the string form of one column, for keyed lookups. |
74
+ | `groupRows` | function | `(rows: readonly Row[], column: string, values?: readonly Row[]) => ReadonlyMap<string, readonly Row[]>` | Groups rows by the string form of one column, for one-to-many lookups. |
75
+
76
+ ### Contracts
77
+
78
+ The descriptor contract is one closed shape compiled once; `isRelationDescriptor` is its guard and `resolveRelation` admits through it, so a refusal carries the contract's faults.
79
+
80
+ | Name | Kind | Signature | Summary |
81
+ | ---------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
82
+ | `relationDescriptorShape` | const | `import("@orkestrel/contract").ObjectShape<{ relationship: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").LiteralShape<readonly ["belongs", "many", "one", "through", "morph"]>>; column: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; key: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; through: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; source: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; target: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; tag: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; label: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; model: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, false>` | Declares the object form of a relation as a closed contract shape. |
83
+ | `relationDescriptorContract` | const | `ContractInterface<RelationDescriptor>` | Holds the compiled contract of a relation descriptor, which `resolveRelation` admits through. |
73
84
 
74
85
  ### Errors
75
86
 
@@ -90,7 +101,7 @@ transparent proxies, unbranded look-alikes, and plain branded objects.
90
101
  | `RelationDescriptor` | interface | `{ relationship?, column?, key?, through?, source?, target?, tag?, label?, model? }` | Represents the object form of a relation. |
91
102
  | `Relation` | type | `string \| readonly string[] \| RelationDescriptor` | Represents a single relation definition. |
92
103
  | `RelationMap` | type | `Readonly<Record<string, Relation>>` | Holds a model's relations, keyed by relation name. |
93
- | `RelationsShape` | type | `{ readonly [K in keyof T]?: RelationMap; }` | Holds per-table relation maps — the declarative input to `createRelationManager`. |
104
+ | `RelationSchema` | type | `{ readonly [K in keyof T]?: RelationMap; }` | Holds per-table relation maps — the declarative input to `createRelationManager`. |
94
105
  | `ResolvedRelation` | type | `ResolvedBelongs \| ResolvedMany \| ResolvedOne \| ResolvedThrough \| ResolvedMorph` | Represents a relation resolved at define-time into a flat, ready-to-load form. |
95
106
  | `ResolvedBelongs` | interface | `{ relationship, name, model, column }` | Represents a `belongs` relation resolved at define-time — the foreign key sits on the owning table. |
96
107
  | `ResolvedMany` | interface | `{ relationship, name, model, key }` | Represents a `many` relation resolved at define-time — the foreign key sits on the related table. |
@@ -120,8 +131,8 @@ The public methods of each behavioral interface — one table per type, keyed by
120
131
  | -------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
121
132
  | `load` | `Promise<Loaded<T> \| undefined>` | Loads one record by key with the chosen relations populated, or a positional array of records for an array of keys. |
122
133
  | `find` | `Promise<readonly Loaded<T>[]>` | Finds many records, paged and sorted through `FindOptions`, with the chosen relations populated. |
123
- | `link` | `Promise<void>` | Inserts a missing junction row for a `through` relation. |
124
- | `unlink` | `Promise<void>` | Removes every matching junction row for a `through` relation through the bound storage. |
134
+ | `link` | `Promise<void>` | Inserts the junction row for a pair through a `through` relation. |
135
+ | `unlink` | `Promise<void>` | Removes the junction row for a pair through a `through` relation. |
125
136
  | `links` | `Promise<readonly Key[]>` | Lists the related keys reachable through a `through` relation. |
126
137
 
127
138
  #### `RelationManagerInterface`
@@ -139,15 +150,28 @@ The public methods of each behavioral interface — one table per type, keyed by
139
150
  These invariants hold across `src/core` ↔ `relation.md`:
140
151
 
141
152
  1. **Doc ↔ source bijection.** Every `function` / `class` / `interface` / `type` row in the `## Surface` tables is a real export of the relations source tree, and every export appears as a Surface row — exhaustive, both directions (`.claude/rules/documentation.md` § Parity).
142
- 2. **Layered on typed storage and validated at construction.** A manager binds to `DatabaseStorageInterface<T> & DatabaseStorageInterface`: the `DatabaseInterface<T>` returned by `createDatabase`, or transaction storage. At a typed root, pass the table map as the type argument; a transaction scope infers it. A `Database<T>` class expression is outside this option contract. `model(name)` preserves the declared table row type. Related tables are resolved by runtime name at the broad `Row` type. Construction resolves every target and junction through `storage.table(name)`. An undeclared target or junction throws `INVALID` with `{ model, relation, table }`; other database errors propagate unchanged, including `CLOSED` when construction resolves a relation on a closed root and `CONFLICT` for settled transaction storage.
143
- 3. **Batch loading — no N+1.** A direct included relation uses one query over the distinct foreign keys for the entire record set; a `through` relation uses two queries, one for the junction rows and one for the target rows. Related rows are grouped in memory and attached, so either query count is independent of how many parents were loaded. Nested includes recurse through the registry, and each nested level is batched again under the same rule.
144
- 4. **Resolution is define-time.** Each raw `Relation` is resolved once at construction into a flat `ResolvedRelation` — a union discriminated on `relationship` whose every arm declares its own columns required, so a loader reads them after one narrow and never against an absent member; nothing is inferred during loading. The builders set an explicit `relationship` (so `many` and `one`, otherwise identical as `{ key }`, are unambiguous); a hand-written descriptor with no `relationship` infers one from the fields present (`through` → `through`, `tag` → `morph`, `column` → `belongs`, else `key` → `one`), and a malformed one throws `INVALID` at define-time.
145
- 5. **Total, loose `Loaded`.** `Loaded<T>` intersects the base row with `Readonly<LoadedMap>` (`Row | readonly Row[] | undefined` per relation). A missed `belongs` / `one` is `undefined`; a missed `many` / `through` / `morph` is `[]`. Through-only operations throw `NOT_THROUGH` for another relationship and `UNKNOWN_RELATION` for an undeclared relation. Sequential `link` calls are idempotent; an existing pair writes and emits nothing. Concurrent calls may each insert. `unlink` removes every matching junction row through its bound storage and shares the fate of that scope. Enclose the call in `database.transaction()` for all-or-nothing removal. Outside a transaction, a fault propagates unchanged and leaves earlier removals committed. A failed removal emits no `unlink` event.
146
- 6. **Observation is a pure side-channel.** A `Model` owns a typed `emitter` (`ModelEventMap` — `load(name, count)` / `link(key, relation)` / `unlink(key, relation)`); `RelationManager` is event-free by design (a stateless registry has no observable lifecycle). Every event is emitted directly (the `.claude/rules/patterns.md` § Stateful emitters convention: the emitter isolates a listener throw, routing it to its own `error` handler — the `error` option, surfaced as `(error, event)`, never a domain event — itself re-entrancy-guarded) strictly after the load resolves and after the junction operation completes. `load` fires once per relation (carrying the count of rows attached across the record set — no N+1 in the events), so a buggy observer can corrupt neither the batched eager-load nor a junction write (proven by the emit-safety tests). An idempotent no-op `link` emits nothing. `link` and `unlink` report completion within the bound scope, before any outer commit; an event can therefore precede an outer rollback.
153
+ 2. **Layered on typed storage and validated at construction.** A manager binds to `DatabaseStorageInterface<T> & DatabaseStorageInterface`: the `DatabaseInterface<T>` returned by `createDatabase`, or transaction storage. At a typed root, pass the table map as the type argument; a transaction scope infers it. A `Database<T>` class expression is outside this option contract. `model(name)` preserves the declared table row type. Related tables are resolved by runtime name at the broad `Row` type. Construction resolves every target and junction through `storage.table(name)`. An undeclared target or junction throws `INVALID` with `{ model, relation, table }`; other database errors propagate unchanged, including `CLOSED` when construction resolves a relation on a closed root and `CONFLICT` for settled transaction storage. A `through` relation whose junction primary column is its `source` or `target` column throws `INVALID` with `{ model, relation, table, column }`, because that column cannot hold the pair's derived key.
154
+ 3. **Batch loading — no N+1.** A direct included relation uses one call over the distinct keys for the entire record set; a `through` relation uses two, one for the junction rows and one for the target rows. A load by primary key — a `belongs` load and a `through` target load — reads through the table's keyed `get`; a load by foreign key reads through `records` with `any`. Related rows are grouped in memory and attached, so either call count is independent of how many parents were loaded. Nested includes recurse through the registry, and each nested level is batched again under the same rule. `tests/guides.test.ts` asserts the exact calls per relationship and nesting level on a recording storage.
155
+ 4. **Resolution is define-time.** Each raw `Relation` is resolved once at construction into a flat `ResolvedRelation` — a union discriminated on `relationship` whose every arm declares its own columns required, so a loader reads them after one narrow and never against an absent member; nothing is inferred during loading. The builders set an explicit `relationship` (so `many` and `one`, otherwise identical as `{ key }`, are unambiguous); a hand-written descriptor with no `relationship` infers one from the fields present (`through` → `through`, `tag` → `morph`, `column` → `belongs`, else `key` → `one`), and a malformed one throws `INVALID` at define-time. A descriptor must pass `relationDescriptorContract`'s strict guard: an undeclared member, enumerable or not, a member holding another type, and a member present as `undefined` each throw `INVALID`, carrying the contract's audit faults described against its schema, and no lossless repair admits a descriptor.
156
+ 5. **Total, loose `Loaded`.** `Loaded<T>` intersects the base row with `Readonly<LoadedMap>` (`Row | readonly Row[] | undefined` per relation). A missed `belongs` / `one` is `undefined`; a missed `many` / `through` / `morph` is `[]`. Through-only operations throw `NOT_THROUGH` for another relationship and `UNKNOWN_RELATION` for an undeclared relation. `link` is one insert under the pair's derived key, `computeLinkKey(key, target)`, which the junction's primary column holds as text; a pair the junction already holds writes and emits nothing, so concurrent calls for one pair leave one row and one `link` event. Any other database error, a `CONFLICT` from a settled or busy scope included, propagates unchanged. `unlink` is one remove of that key; a failed remove propagates unchanged and emits no `unlink` event. A row a storage returns that is not a plain record throws `INVALID` naming its `table`; it never reads as a miss and is never dropped.
157
+ 6. **Observation is a pure side-channel.** A `Model` owns a typed `emitter` (`ModelEventMap` — `load(name, count)` / `link(key, relation)` / `unlink(key, relation)`); `RelationManager` is event-free by design (a stateless registry has no observable lifecycle). Every event is emitted directly (the `.claude/rules/patterns.md` § Stateful emitters convention: the emitter isolates a listener throw, routing it to its own `error` handler — the `error` option, surfaced as `(error, event)`, never a domain event — itself re-entrancy-guarded) strictly after the load resolves and after the junction operation completes. `load` fires once per relation (carrying the count of rows attached across the record set — no N+1 in the events), so a buggy observer can corrupt neither the batched eager-load nor a junction write (proven by the emit-safety tests). `link` fires only when it inserted a row and `unlink` only when it removed one. `link` and `unlink` report completion within the bound scope, before any outer commit; an event can therefore precede an outer rollback.
147
158
  7. **Cooperative cancellation.** Every model operation accepts the database package's abort option. Query reads pass the signal to `records`. The keyed `get` read takes no options in the database package, so `load` checks the signal before it and again before each relation in the population walk; a batched `get` already in flight runs to completion. Writes pass it to their bound storage mutation. An aborted signal surfaces unchanged as the database package's `ABORTED` error.
148
159
  8. **Doc ↔ source method bijection.** Every behavioral interface's `## Methods` table lists exactly its public methods (call-signature members) — exhaustive, both directions — and each implementing class (`Model` / `RelationManager`) exposes the same public methods, no more (`.claude/rules/documentation.md` § Parity). A renamed / added / removed method breaks the gate until the table is reconciled.
149
160
 
150
- Typing each loaded relation property to its exact target row (Prisma-style) is a deliberate, documented deferral — like the database guide's deferred pieces. The `Model` is **observable** — it owns a typed `emitter` (`ModelEventMap`) carrying its eager-load + junction moments (see [Observing](#observing)); `RelationManager` stays event-free by design (a stateless registry that merely vends models has no observable lifecycle of its own). Still out of scope: write-cascades; they are additive and leave the documented surface unchanged.
161
+ The `Model` is **observable** — it owns a typed `emitter` (`ModelEventMap`) carrying its eager-load + junction moments (see [Observing](#observing)); `RelationManager` stays event-free by design (a stateless registry that merely vends models has no observable lifecycle of its own).
162
+
163
+ ### Limits
164
+
165
+ Each refusal names what reopens it, and each requirement names its owner:
166
+
167
+ - **Typed loaded relations are refused.** A loaded relation property stays `Row | readonly Row[] | undefined`. A consumer that narrows a loaded relation property by hand reopens it.
168
+ - **Write-cascades belong to the database.** `Model` holds table-only storage and no transaction, so it writes no cascade. A release of that row's references reopens whether a relation declares its cascade there. The `@orkestrel/database` campaign's unique-index and references row owns it: the engine's `ON DELETE` on SQLite, and a check inside the transaction on IndexedDB.
169
+ - **The application declares the indexes.** Declare an index on each foreign-key column and each junction column a relation reads; the application owns these declarations.
170
+ - **An include returns every related row of every loaded parent.** `limit` on `find` bounds the parents, never the related rows, and a `one` relationship reads every match and keeps the first. A client page bar an include breaks, or an engine size refusal, reopens it.
171
+ - **A junction's primary column stores text, and `link` owns its value.** This requirement is the application's to meet: declare a text primary column apart from the `source` and `target` columns, because `link` writes the pair's derived key there. Each refusal that enforces it names what reopens it:
172
+ - A numeric junction primary column refuses the row with the database's `VALIDATION` error; a consumer that declares a numeric junction primary reopens it.
173
+ - Construction refuses a junction keyed by its `source` or `target` column with `INVALID`; a consumer whose junction must be keyed by one of those columns reopens it.
174
+ - Junction rows an earlier release wrote under generated keys are not migrated; a consumer holding such rows reopens it.
151
175
 
152
176
  Loaded relation properties replace same-named columns in returned rows. Grouping and indexing read the raw columns, so attachments survive that shadowing. Read an original column through `model.table` when a relation replaces it.
153
177
 
@@ -205,7 +229,7 @@ The relationships, and where each foreign key lives:
205
229
 
206
230
  ### Resolving relations directly
207
231
 
208
- `resolveRelation` / `resolveRelationMap` / `isRelationDescriptor` are what `createRelationManager` calls internally to turn a raw `RelationMap` into one `ResolvedRelation` per entry at construction — reach for them directly when validating a relation map before wiring a manager, or when testing a descriptor's inferred `relationship`:
232
+ `resolveRelationMap` and the `resolveRelation` it runs per entry are what `createRelationManager` calls at construction to turn a raw `RelationMap` into one `ResolvedRelation` per entry, and `isRelationDescriptor` is the strict guard `resolveRelation` gates each descriptor on — reach for them directly when validating a relation map before wiring a manager, or when testing a descriptor's inferred `relationship`:
209
233
 
210
234
  ```ts
211
235
  import { isRelationDescriptor, resolveRelation, resolveRelationMap } from '@orkestrel/relation'
@@ -307,9 +331,9 @@ await accounts.table
307
331
  A `through` relation's junction rows are managed by key — no need to model the junction table yourself or hand-write join rows. `link` / `unlink` / `links` resolve the relation's junction table + its source/target columns from the define-time `ResolvedRelation`, and throw `NOT_THROUGH` if pointed at a non-`through` relation.
308
332
 
309
333
  ```ts
310
- await accounts.link('acc1', 'representatives', 'rep3') // insert a junction row (accountId=acc1, repId=rep3)
311
- await accounts.link('acc1', 'representatives', 'rep3') // already linked, sequential call: no write and no event
312
- await accounts.unlink('acc1', 'representatives', 'rep1') // remove every match through the bound storage
334
+ await accounts.link('acc1', 'representatives', 'rep3') // one insert under computeLinkKey('acc1', 'rep3')
335
+ await accounts.link('acc1', 'representatives', 'rep3') // already linked: no write and no event
336
+ await accounts.unlink('acc1', 'representatives', 'rep1') // one remove; emits only when a row was removed
313
337
  const repIds = await accounts.links('acc1', 'representatives') // the related keys reachable through the junction
314
338
  ```
315
339
 
@@ -401,11 +425,11 @@ The event vocabulary:
401
425
 
402
426
  ## Tests
403
427
 
404
- - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` bijection (value + type exports), the `ModelInterface` / `RelationManagerInterface` ↔ `Model` / `RelationManager` method bijections, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Defining relations` 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 runs the guide's value-claiming fences and asserts the values their comments claim.
405
- - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — `resolveRelation` (shorthands, builders, inference, errors, a wrong-typed descriptor member), `resolveRelationMap`, `readColumn`, `countAttached`, `indexRows`, `groupRows`.
406
- - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — `isRelationDescriptor` over the object form, the builders' output, the string / array shorthands, a member holding the wrong type, and a `relationship` outside the union.
407
- - [`tests/src/core/RelationManager.test.ts`](../tests/src/core/RelationManager.test.ts) — the manager-level surface: the registry (`count` / `names` / `has`), the typed `model(name)` accessor, and construction-time `INVALID` errors for undeclared relation and junction tables.
408
- - [`tests/src/core/Model.test.ts`](../tests/src/core/Model.test.ts) — `Model` behavior: `load` / `find` populating each relationship (batched, no N+1), nested `includes`, the loaded relation accessors, idempotent `link`, scope-bound `unlink`, cooperative cancellation, `links`, and the `emitter` (`ModelEventMap`): `load(name, count)` fires once per relation (the attached count, including nested relations — not one per record), `link` / `unlink` carry the owning key + relation, `on?` wiring through the manager's `model` option, and emit safety (a throwing `load` / `link` observer can't corrupt the load or junction write — the emitter isolates it and routes it to the `model.error` handler when the manager carries one).
428
+ - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` bijection (value + type exports), the `ModelInterface` / `RelationManagerInterface` ↔ `Model` / `RelationManager` method bijections, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Defining relations` 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 runs the guide's value-claiming fences and asserts the values their comments claim, the exact table calls each relationship and nesting level makes on a recording storage with a per-parent control, and the include limits.
429
+ - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — `resolveRelation` (shorthands, builders, inference, errors, an undeclared descriptor member refused with its fault, a wrong-typed, padded, or present-`undefined` member refused rather than repaired, the declared members and relationship candidates named in the refusal, a bounded relation name and fault text), `resolveRelationMap`, `validateRelationJunction`, `readRow`, `computeLinkKey`, `countAttached`, `indexRows`, `groupRows`.
430
+ - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — `isRelationDescriptor` over the object form, the builders' output, the string / array shorthands, a member holding the wrong type, a member the descriptor does not declare, and a `relationship` outside the union.
431
+ - [`tests/src/core/RelationManager.test.ts`](../tests/src/core/RelationManager.test.ts) — the manager-level surface: the registry (`count` / `names` / `has`), the typed `model(name)` accessor, and construction-time `INVALID` errors for undeclared relation and junction tables, a descriptor contract repairs would admit, and a junction keyed by its `source` or `target` column.
432
+ - [`tests/src/core/Model.test.ts`](../tests/src/core/Model.test.ts) — `Model` behavior: `load` / `find` populating each relationship, nested `includes`, the loaded relation accessors, `link` as one `add` and `unlink` as one `remove` on a recording storage, two concurrent `link` calls leaving one row on MemoryDriver and on SQLite, an absent `unlink` emitting nothing, a `CONFLICT` from a busy or settled scope propagating, a numeric junction primary refused, a non-record row from a custom storage raising `INVALID` naming its table, cooperative cancellation (including an abort between a `through` junction read and its target read), `links`, and the `emitter` (`ModelEventMap`): `load(name, count)` fires once per relation, `link` / `unlink` carry the owning key + relation, `on?` wiring through the manager's `model` option, and emit safety.
409
433
  - [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — `createRelationManager` wires up a working, typed manager end to end.
410
434
 
411
435
  ## See also
@@ -314,6 +314,7 @@ Exported from `@orkestrel/scaffold`, and reachable from
314
314
  | `normalizePackagePath` | function | `(path: string) => string` | Returns the canonical form of a path a manifest names inside its package. |
315
315
  | `parseOwnedJSONValue` | function | `(value: unknown) => JSONValue \| undefined` | Snapshots an untrusted value into exact JSON data the caller owns. |
316
316
  | `planToSummary` | function | `(plan: Plan) => PlanSummary` | Projects a plan into its tally by artifact origin. |
317
+ | `projectsToBenches` | function | `(projects: readonly string[]) => readonly string[]` | Lists the bench globs of the browser-hosted projects among a workspace's project labels. |
317
318
  | `renderSkillPointer` | function | `(canonical: string, name: string) => string \| undefined` | Renders the `SKILL.md` pointer a target carries in place of a canonical skill. |
318
319
  | `scanManifestTokens` | function | `(text: string) => readonly ManifestToken[] \| undefined` | Scans manifest text for its strings and object braces, in order. |
319
320
  | `selectArtifactGroups` | function | `(groups?: readonly ArtifactGroup[]) => readonly ArtifactGroup[]` | Selects the groups a compile covers, in plan order. |
@@ -1026,8 +1027,13 @@ A selection that excludes `configs` proceeds. An advisory alone does not make an
1026
1027
  drift.
1027
1028
 
1028
1029
  The probe workbench separates ordinary probes from benchmarks by filename. `test:probe` collects
1029
- `tmp/probes/**/*.test.ts`. `test:bench` collects `tmp/probes/**/*.bench.ts` and `tests/**/*.bench.ts`
1030
- with the explicit `--mode benchmark` option. Neither script belongs to a gate. In a benchmark file,
1030
+ `tmp/probes/**/*.test.ts`. `test:bench` runs with the explicit `--mode benchmark` option. Its Node
1031
+ `probe` project collects `tmp/probes/**/*.bench.ts` and `tests/**/*.bench.ts` other than the browser
1032
+ benches: the `*.bench.ts` files beneath the test directory of each planned face that runs in
1033
+ Playwright Chromium, which `projectsToBenches` lists. Those faces are `src:browser`, `app:browser`,
1034
+ `src:vue`, `app:vue`, each sheet face, and the themes target. In a workspace with one, its
1035
+ `bench:browser` project runs those browser benches in Playwright Chromium.
1036
+ Neither script belongs to a gate. In a benchmark file,
1031
1037
  register a regular `it` or `test` callback that receives the context's `bench` fixture. Await
1032
1038
  `bench(name, options, fn).run()` or `bench.compare(...)`; options precede the benchmark function.
1033
1039
  The filename keeps the benchmark out of ordinary test runs, so no mode guard is required. The
@@ -51,14 +51,27 @@ db.prepare('SELECT name FROM users WHERE age >= ?').all([18]) // → [{ name: 'A
51
51
  | `SQLITE_CONSTRAINT` | const | `19` | Names the SQLite result code whose low byte, `19`, flags a constraint violation. |
52
52
  | `SQLITE_BUSY` | const | `5` | Names the SQLite result code whose low byte, `5`, flags a locked-database fault. |
53
53
 
54
+ ### Validators
55
+
56
+ | Name | Kind | Signature | Summary |
57
+ | ------------------- | ----- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
58
+ | `isPragmaName` | const | `Guard<string>` | Checks whether a value is a pragma name `pragma` can write into `PRAGMA` text: ASCII letters, digits, and underscores, opening with a letter or an underscore. |
59
+ | `isPragmaValue` | const | `Guard<string \| number>` | Checks whether a value is a pragma value `pragma` can write into `PRAGMA` text: a 32-bit signed integer, or a keyword of ASCII letters and underscores. |
60
+ | `isSQLiteErrorCode` | const | `Guard<"BUSY" \| "CLOSED" \| "CONSTRAINT" \| "INVALID" \| "UNKNOWN">` | Checks whether a value is a code a `SQLiteError` carries: `CLOSED`, `CONSTRAINT`, `BUSY`, `INVALID`, or `UNKNOWN`. |
61
+
62
+ Each pragma guard returns `false` for any input that is neither a string nor a number and never throws.
63
+ A name admits no schema prefix, quote, space, bracket, or `;`, so `main.journal_mode` and
64
+ `table_info(users)` are refused. A value admits an integer from `-2147483648` to `2147483647`, such as `-2000`, and
65
+ refuses every other number, such as `1.5`, `1e21`, and `2147483648`, as well as `NaN`, the infinities, a quoted literal, and a numeric string such as `'7'`.
66
+
54
67
  ### Helpers and errors
55
68
 
56
- | Name | Kind | Signature | Summary |
57
- | ---------------- | -------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
58
- | `wrapError` | function | `(error: unknown) => SQLiteError` | Converts a thrown native `node:sqlite` error into a typed `SQLiteError` at the wrapper's one boundary. |
59
- | `bindParameters` | function | `(parameters?: SQLiteParameters) => SQLiteBinding` | Normalizes `SQLiteParameters` to the binding shape a native `StatementSync` call expects — a positional spread, or a single named record. |
60
- | `SQLiteError` | class | `new (code: SQLiteErrorCode, message: string, context?: Readonly<Record<string, unknown>>) => SQLiteError` | Represents an error thrown by the SQLite wrapper, carrying a machine-readable `code` — `CLOSED`, `CONSTRAINT`, `BUSY`, `INVALID`, or `UNKNOWN`. |
61
- | `isSQLiteError` | function | `(value: unknown) => value is SQLiteError` | Checks whether a value is a `SQLiteError`. |
69
+ | Name | Kind | Signature | Summary |
70
+ | ---------------- | -------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
71
+ | `wrapError` | function | `(error: unknown) => SQLiteError` | Converts a thrown native `node:sqlite` error into a typed `SQLiteError` at the wrapper's one boundary. |
72
+ | `bindParameters` | function | `(parameters?: SQLiteParameterSet) => SQLiteBinding` | Normalizes a `SQLiteParameterSet` value to the binding shape a native `StatementSync` call expects — a positional spread, or a single named record. |
73
+ | `SQLiteError` | class | `new (code: SQLiteErrorCode, message: string, context?: Readonly<Record<string, unknown>>) => SQLiteError` | Represents an error thrown by the SQLite wrapper, carrying a machine-readable `code` — `CLOSED`, `CONSTRAINT`, `BUSY`, `INVALID`, or `UNKNOWN`. |
74
+ | `isSQLiteError` | function | `(value: unknown) => value is SQLiteError` | Checks whether a value is a `SQLiteError`. |
62
75
 
63
76
  `isSQLiteError` recognizes the own identity brand and declared members across package copies
64
77
  and module formats. It accepts subclass instances without requiring their name and refuses
@@ -72,8 +85,8 @@ non-writable own property.
72
85
  | -------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
73
86
  | `SQLiteValue` | type | `null \| number \| bigint \| string \| Uint8Array` | Represents a value SQLite stores and returns natively — the bridge between SQLite's storage classes and their JS types. |
74
87
  | `SQLiteRow` | type | `Record<string, SQLiteValue>` | Represents a result row — a record of column name to `SQLiteValue`. |
75
- | `SQLiteParameters` | type | `readonly SQLiteValue[] \| Readonly<Record<string, SQLiteValue>>` | Represents the bind parameters for a prepared statement — positional (an array, bound to `?`) or named (a record, bound to bare `:name` placeholders). |
76
- | `SQLiteBinding` | type | `{ readonly positional: readonly SQLiteValue[]; } \| { readonly named: Readonly<Record<string, SQLiteValue>>; }` | Represents the normalized binding shape a native `StatementSync` call expects — what `SQLiteParameters` become on the way into `node:sqlite`. |
88
+ | `SQLiteParameterSet` | type | `readonly SQLiteValue[] \| Readonly<Record<string, SQLiteValue>>` | Represents the bind values one prepared-statement call takes — positional (an array, bound to `?`) or named (a record, bound to bare `:name` placeholders). |
89
+ | `SQLiteBinding` | type | `{ readonly positional: readonly SQLiteValue[]; } \| { readonly named: Readonly<Record<string, SQLiteValue>>; }` | Represents the normalized binding shape a native `StatementSync` call expects — what a `SQLiteParameterSet` value becomes on the way into `node:sqlite`. |
77
90
  | `SQLiteExecuteResult` | interface | `{ changes, rowid }` | Represents the outcome of a non-query statement (`INSERT` / `UPDATE` / `DELETE` / DDL). |
78
91
  | `SQLiteErrorCode` | type | `'CLOSED' \| 'CONSTRAINT' \| 'BUSY' \| 'INVALID' \| 'UNKNOWN'` | Represents a machine-readable `SQLiteError` code. |
79
92
  | `SQLiteDatabaseOptions` | interface | `{ path?, readonly?, timeout?, foreignKeys?, bigints? }` | Represents the options for opening a SQLite connection, accepted by the `createSQLiteDatabase` function and the `SQLiteDatabase` constructor. |
@@ -94,17 +107,17 @@ The `transacting` member of `SQLiteDatabaseInterface` reports whether a transact
94
107
 
95
108
  #### `SQLiteDatabaseInterface`
96
109
 
97
- | Method | Returns | Summary |
98
- | ---------- | -------------------------- | ----------------------------------------------------------------------------------------------------------- |
99
- | `connect` | `void` | Opens the underlying connection — lazy and idempotent, so a second call is a no-op. |
100
- | `close` | `void` | Releases the connection; afterward every operation gates `CLOSED` until reconnect. |
101
- | `execute` | `void` | Runs one or more result-less SQL statements (DDL, pragmas) in a single call. |
102
- | `prepare` | `SQLiteStatementInterface` | Compiles SQL into a reusable prepared statement — the only path that runs queries. |
103
- | `transact` | `R` | Runs `scope` between `BEGIN` and `COMMIT`, rolling the whole scope back and rethrowing on a throw. |
104
- | `begin` | `void` | Opens a transaction (`BEGIN`); throws the native fault, a nested `BEGIN` included, as a `SQLiteError`. |
105
- | `commit` | `void` | Commits the open transaction (`COMMIT`); throws the native fault as a `SQLiteError` when none is open. |
106
- | `rollback` | `void` | Rolls back the open transaction (`ROLLBACK`); throws the native fault as a `SQLiteError` when none is open. |
107
- | `pragma` | `SQLiteValue \| undefined` | Reads a single PRAGMA, or sets then reads it when a `value` is passed. |
110
+ | Method | Returns | Summary |
111
+ | ---------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
112
+ | `connect` | `void` | Opens the underlying connection — lazy and idempotent, so a second call is a no-op. |
113
+ | `close` | `void` | Releases the connection; afterward every operation gates `CLOSED` until reconnect. |
114
+ | `execute` | `void` | Runs one or more result-less SQL statements (DDL, pragmas) in a single call. |
115
+ | `prepare` | `SQLiteStatementInterface` | Compiles SQL into a reusable prepared statement — the only path that runs queries. |
116
+ | `transact` | `R` | Runs `scope` between `BEGIN` and `COMMIT`, rolling the whole scope back and rethrowing on a throw. |
117
+ | `begin` | `void` | Opens a transaction (`BEGIN`); throws the native fault, a nested `BEGIN` included, as a `SQLiteError`. |
118
+ | `commit` | `void` | Commits the open transaction (`COMMIT`); throws the native fault as a `SQLiteError` when none is open. |
119
+ | `rollback` | `void` | Rolls back the open transaction (`ROLLBACK`); throws the native fault as a `SQLiteError` when none is open. |
120
+ | `pragma` | `SQLiteValue \| undefined` | Reads a single PRAGMA, or sets then reads it when a `value` is passed; throws `INVALID` before any SQL for a name or value the pragma guards refuse. |
108
121
 
109
122
  #### `SQLiteStatementInterface`
110
123
 
@@ -123,11 +136,12 @@ These invariants hold across `src/server` ↔ `sqlite.md`:
123
136
  2. **Synchronous.** Every operation runs synchronously, because `node:sqlite` does — no Promises. `@orkestrel/database`'s SQLite driver adapts it to that package's asynchronous driver contract, one layer up.
124
137
  3. **Native, not a second query engine.** The wrapper exposes only what `node:sqlite` offers natively — prepared statements, transactions, and pragmas. It has **no** `where` / `filter` / `order` / aggregate builder; that is the core database engine over `scan`, the same discipline as the IndexedDB wrapper.
125
138
  4. **`SQLiteValue` values, plain SQL.** Reads return `SQLiteRow`s of native `SQLiteValue`s; writes bind `SQLiteValue`s. Per-row typing belongs above this layer, in the core database's contracts.
126
- 5. **Native faults become `SQLiteError`.** Every native `node:sqlite` throw is mapped at the boundary to a `SQLiteError` carrying a machine-readable `code` — a constraint violation (a UNIQUE / PRIMARY KEY conflict) maps to `'CONSTRAINT'`, a locked-database fault to `'BUSY'`, a wrapper-lifecycle fault to `'CLOSED'`, the wrapper's own invalid-argument refusal to `'INVALID'`, and every unclassified native fault to `'UNKNOWN'`. This holds for `iterate` too: its lazy native iterator is stepped inside its own try/catch, so a fault surfacing mid-stream (for example an out-of-range integer on a later row) maps to a `SQLiteError` exactly like an eager fault, never escaping raw from the caller's `for...of`. Finalizing is the exception to that mapping: on every exit after the first step the wrapper finalizes the native iterator, and a fault from that finalize call is discarded rather than mapped, so leaving the loop never throws. Narrow a caught value with `isSQLiteError`.
139
+ 5. **Native faults become `SQLiteError`.** Every native `node:sqlite` throw is mapped at the boundary to a `SQLiteError` carrying a machine-readable `code` — a constraint violation (a UNIQUE / PRIMARY KEY conflict) maps to `'CONSTRAINT'`, a locked-database fault to `'BUSY'`, a wrapper-lifecycle fault to `'CLOSED'`, the wrapper's own invalid-argument refusal to `'INVALID'`, and every unclassified native fault to `'UNKNOWN'`. This holds for `iterate` too: its lazy native iterator is stepped inside `@orkestrel/contract`'s `attempt`, so a fault surfacing mid-stream (for example an out-of-range integer on a later row) maps to a `SQLiteError` exactly like an eager fault, never escaping raw from the caller's `for...of`. Finalizing is the exception to that mapping: on every exit after the first step the wrapper finalizes the native iterator, and a fault from that finalize call is discarded rather than mapped, so leaving the loop never throws. Narrow a caught value with `isSQLiteError`.
127
140
  6. **`CLOSED` before connect, and after close for any statement too.** The database connects lazily; an operation before `connect` (or after `close`) throws a `CLOSED` `SQLiteError`. `connect` is idempotent. A `SQLiteStatementInterface` retains a liveness check to its owning connection: after that connection is closed, every one of the statement's methods (`execute` / `get` / `all` / `iterate`) also throws `CLOSED` — even a statement prepared before the close and still held by the caller. Reconnecting afterward does not revive it: a statement prepared on the earlier connection stays `CLOSED` permanently; prepare a fresh statement on the new connection.
128
141
  7. **`BUSY` on lock contention — `SQLITE_LOCKED` is not `BUSY`.** A write that finds the database locked by another connection retries for `timeout` milliseconds (default `0` — fail immediately), then throws a `BUSY` `SQLiteError` — retryable, unlike the other codes. A `SQLITE_LOCKED` fault (result code `6`, a same-connection table-lock conflict, distinct from `SQLITE_BUSY`'s cross-connection database lock) is **not** mapped to `'BUSY'` — `wrapError` only recognizes `SQLITE_BUSY`, so a `SQLITE_LOCKED` fault surfaces as `'UNKNOWN'` and is not retryable the same way.
129
142
  8. **`transacting` mirrors native autocommit state.** `db.transacting` is `true` exactly while a transaction is open (inside `transact(scope)`, or between a manual `BEGIN` and its `COMMIT` / `ROLLBACK`) and `false` otherwise, including when disconnected.
130
143
  9. **`transact(scope)` requires a synchronous scope.** If `scope` returns a thenable (an `async` function or a function returning a `Promise`), the transaction is rolled back immediately and a `SQLiteError` with code `'INVALID'` is thrown — an async scope would otherwise return before its awaited work runs, letting `transact` commit prematurely. A transaction that must span async caller code uses `begin()` / `commit()` / `rollback()` directly instead.
144
+ 10. **`pragma` owns the syntax of its input.** A pragma name and value cannot be bound as parameters, so `pragma` writes them into the SQL text only after `isPragmaName` admits the name and `isPragmaValue` admits the value. Either refusal throws a `SQLiteError` with code `'INVALID'` before any SQL runs, on an open or a closed connection, and its `context` carries the refused input as `@orkestrel/contract`'s `preview` renders it. A string renders as a double-quoted JSON string, with a newline as `\n`, clipped to a trailing `…` when its quoted form passes 64 characters. Any other value renders without its content: a number as its text, an array as `array`, a plain or null-prototype record as `object`, and any other object, such as a class instance, a `Map`, or a `Date`, as `instance`. A numeric value is an integer from `-2147483648` to `2147483647`. SQLite misreads every other number without an error: an integer pragma keeps `2147483647`, sets `0` for `2147483648`, and sets `1` for `1e21`. The limit: a pragma that takes a 64-bit value above that range, such as `mmap_size` past 2 GiB, is refused until a consumer needs it, which reopens the bound. A keyword reads back as the engine reports it, so `'WAL'` reads `'wal'`. The guards check syntax, not whether the engine knows the name: an admitted name the engine does not know reads `undefined`.
131
145
 
132
146
  ## Patterns
133
147
 
@@ -231,6 +245,11 @@ db.pragma('user_version', 7) // set then read → 7 (a cheap on-disk schema-vers
231
245
  db.pragma('journal_mode', 'WAL') // set then read → 'wal' — durable write-ahead logging for a file db
232
246
  ```
233
247
 
248
+ A name outside `isPragmaName`, such as `main.journal_mode`, and a value outside `isPragmaValue`,
249
+ such as `'WAL; PRAGMA case_sensitive_like = ON'` or the fraction `1.5`, throw an `INVALID` `SQLiteError` and run no SQL. A numeric value is an integer from `-2147483648` to `2147483647`, because SQLite sets an integer pragma to `0` for `2147483648`; a pragma that takes a larger 64-bit value, such as `mmap_size` past 2 GiB, is refused. A keyword reads back as the engine reports it, so `'WAL'` reads `'wal'`.
250
+ Call either guard first when an input arrives from outside your code and you want a `false`
251
+ rather than a throw.
252
+
234
253
  ### Closing a connection
235
254
 
236
255
  Closes the connection and reads `connected` afterward:
@@ -307,7 +326,7 @@ try {
307
326
 
308
327
  ### Practices
309
328
 
310
- - **Use prepared statements with bound parameters**, never string-interpolated values — binding is the SQL-injection-safe path (pragmas, which can't bind, take trusted internal names only).
329
+ - **Use prepared statements with bound parameters**, never string-interpolated values — binding is the SQL-injection-safe path. A pragma can't bind, so `pragma` admits only the bare name `isPragmaName` accepts and the 32-bit integer or keyword `isPragmaValue` accepts.
311
330
  - **Keep a transaction scope synchronous and tight** — the wrapper is synchronous, so a scope is a plain function body that commits on return and rolls back on a throw.
312
331
  - **Branch on `error.code`** (through `isSQLiteError`) rather than parsing a message — `'CONSTRAINT'` distinguishes a key conflict from any other fault, and `'INVALID'` distinguishes the wrapper's own refusal from an unclassified native fault.
313
332
  - **Retry `'BUSY'`, not the others** — it is the one retryable code; back off briefly (or raise `timeout`) before retrying the same operation.
@@ -321,9 +340,11 @@ try {
321
340
  ## Tests
322
341
 
323
342
  - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/server` bijection, the `## Methods` ↔ interface/class method parity, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Connect, execute, and round-trip a row` 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 runs the flagship fences and asserts the values their comments claim.
324
- - [`tests/src/server/SQLiteDatabase.test.ts`](../tests/src/server/SQLiteDatabase.test.ts) — the database in a real `:memory:` SQLite: connect / close lifecycle, the `CLOSED` gate, execute DDL, prepare round-trip, transact commit and rollback, pragma get + set, and the production options — `readonly` rejecting a write, `foreignKeys` enforcing a real FK violation, `timeout` surfacing `BUSY` from a genuinely locked second connection, and `[Symbol.dispose]` closing inside a `using` block.
343
+ - [`tests/src/server/SQLiteDatabase.test.ts`](../tests/src/server/SQLiteDatabase.test.ts) — the database in a real `:memory:` SQLite: connect / close lifecycle, the `CLOSED` gate, execute DDL, prepare round-trip, transact commit and rollback, pragma get + set for a keyword and for a positive and a negative number, the `INVALID` refusal of each malformed pragma name and value before any SQL runs, and the production options — `readonly` rejecting a write, `foreignKeys` enforcing a real FK violation, `timeout` surfacing `BUSY` from a genuinely locked second connection, and `[Symbol.dispose]` closing inside a `using` block.
325
344
  - [`tests/src/server/SQLiteStatement.test.ts`](../tests/src/server/SQLiteStatement.test.ts) — prepared statements: `execute`'s result, positional and named binding, `get` / `all` / `iterate`, an abandoned `iterate` releasing its read lock and finalizing without throwing, and a `CONSTRAINT` violation.
326
- - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) — the wrapper's boundary helpers as pure units: `wrapError` mapping a thrown value to a typed `SQLiteError` (real constraint fault → `CONSTRAINT`, real locked-database fault → `BUSY`, non-error → `UNKNOWN`, pass-through) and `bindParameters` normalizing parameters to the native binding shape (array → positional, record → named).
345
+ - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) — the wrapper's boundary helpers as pure units: `wrapError` mapping a thrown value to a typed `SQLiteError` (real constraint fault → `CONSTRAINT`, real locked-database fault → `BUSY`, non-error → `UNKNOWN`, an `errcode` or `message` that cannot be read → `UNKNOWN` without a throw, an empty `Error` message → `unknown failure`, `errcode` read once, pass-through) and `bindParameters` normalizing parameters to the native binding shape (array → positional, record → named).
346
+ - [`tests/src/server/errors.test.ts`](../tests/src/server/errors.test.ts) — `isSQLiteError` over a class-instance and a callable `context`, its refusal of a branded error carrying an undeclared `code` or a `context` that is neither an object nor callable, and its reading of the global `Error` captured at load, so a replaced global changes neither the instance check nor the prototype comparison.
347
+ - [`tests/src/server/validators.test.ts`](../tests/src/server/validators.test.ts) — `isPragmaName` and `isPragmaValue` over tables of admitted and refused forms, and their totality over every input that is neither a string nor a number, a revoked proxy and a throwing getter included; `isSQLiteErrorCode` over each declared code and the adjacent refusals.
327
348
  - [`tests/src/server/factories.test.ts`](../tests/src/server/factories.test.ts) — `createSQLiteDatabase` returns a working `SQLiteDatabaseInterface` and defaults its path to `:memory:`.
328
349
 
329
350
  ## See also
@@ -69,7 +69,11 @@ and its reader, and the pure leaves they are built from. `@orkestrel/test/browse
69
69
  journey layer, which drives a real browser through the installed Vitest provider. Core touches
70
70
  neither `node:*` nor the DOM, so a browser test project imports it unchanged.
71
71
  `@orkestrel/test/reporter` is the runner entry Vitest's `--reporter` flag loads: its default
72
- export is `ProgressReporter`, and it ships ES only.
72
+ export is `ProgressReporter`, and it ships ES only. The entry lives at `src/bin/reporter.ts` and
73
+ builds to `dist/bin/reporter.js`; the specifier does not name that path. Use it for a run started
74
+ from the command line with a configuration you cannot edit, as `@orkestrel/capture` starts a
75
+ package's Vitest. In a package's own configuration, list `new ProgressReporter()` instead, as
76
+ § Read a long run while it runs shows.
73
77
 
74
78
  The browser face ships ES only. It is built on `vitest/browser`, which is an ES-only module, so no
75
79
  CommonJS consumer can reach it and no `.d.cts` is emitted for it.
@@ -3047,8 +3051,8 @@ Object.keys(
3047
3051
  Object.keys(
3048
3052
  readInventory(root, ['src'], { extensions: ['.ts'], exclude: ['src/server', 'src/browser'] }),
3049
3053
  )
3050
- // ['src/core/Production.ts', 'src/core/Teardown.ts', 'src/core/constants.ts', 'src/core/factories.ts', 'src/core/helpers.ts', 'src/core/index.ts',
3051
- // 'src/core/types.ts', 'src/core/validators.ts', 'src/reporter/main.ts']
3054
+ // ['src/bin/reporter.ts', 'src/core/Production.ts', 'src/core/Teardown.ts', 'src/core/constants.ts', 'src/core/factories.ts',
3055
+ // 'src/core/helpers.ts', 'src/core/index.ts', 'src/core/types.ts', 'src/core/validators.ts']
3052
3056
 
3053
3057
  // An exclusion also applies to a target you name, so naming one file below an excluded directory
3054
3058
  // does not reinstate it.
@@ -411,8 +411,9 @@ raw stay by reference. So `{ type: 'object' }` gives a null-prototype copy of th
411
411
  values by reference, and `parameters: {}` or a root `$ref` gives a plain top-level copy with nested
412
412
  values by reference.
413
413
 
414
- The shared lossless admission helper from `@orkestrel/contract` accepts `'30'` as `30`, `'true'`
414
+ The door admits through `repairValue` from `@orkestrel/contract`, which repairs a lossless leaf: it accepts `'30'` as `30`, `'true'`
415
415
  as `true`, and a finite number as its string. It refuses `'30.0'`, which changes the supplied text.
416
+ A model sends the arguments, so state the repair in the description of every tool that keeps the door, which every tool but a `strict: false` one does.
416
417
  The handler receives the admitted value without another parse. The argument snapshot remains
417
418
  in this package, and a union may retain that snapshot or its nested values by identity.
418
419
  `anyOf: [T, { type: 'null' }]` and `type: [T, 'null']` convert to a nullable rather than a union, so `'5'` reaches the handler