@orkestrel/scaffold 0.0.134 → 0.0.136

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +777 -83
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +327 -21
  3. package/dist/bin/main.js +254 -36
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/AGENTS.md +2 -2
  6. package/dist/host/agents/orchestration.md +2 -2
  7. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +983 -123
  9. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  10. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +22 -5
  11. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +403 -32
  12. package/dist/host/claude/agents/orkestrel.md +17 -17
  13. package/dist/host/claude/agents/reviewer.md +1 -1
  14. package/dist/host/claude/rules/architecture.md +1 -1
  15. package/dist/host/claude/rules/documentation.md +1 -1
  16. package/dist/host/claude/rules/patterns.md +4 -2
  17. package/dist/host/claude/rules/workspace.md +73 -67
  18. package/dist/host/configs/helpers.ts +109 -73
  19. package/dist/host/dotfiles/oxlintrc.json +1 -57
  20. package/dist/host/guides/agent.md +989 -395
  21. package/dist/host/guides/contract.md +198 -163
  22. package/dist/host/guides/database.md +978 -503
  23. package/dist/host/guides/indexeddb.md +80 -66
  24. package/dist/host/guides/middleware.md +5 -5
  25. package/dist/host/guides/ollama.md +41 -42
  26. package/dist/host/guides/relation.md +56 -32
  27. package/dist/host/guides/scaffold.md +185 -107
  28. package/dist/host/guides/sqlite.md +44 -23
  29. package/dist/host/guides/study.md +12 -12
  30. package/dist/host/guides/test.md +163 -47
  31. package/dist/host/guides/toolbox.md +127 -81
  32. package/dist/host/guides/workspace.md +21 -14
  33. package/dist/host/manifest.json +30 -30
  34. package/dist/host/scripts/browsers.sh +0 -0
  35. package/dist/host/scripts/codex.sh +0 -0
  36. package/dist/host/scripts/cursor.sh +0 -0
  37. package/dist/host/scripts/deps.sh +0 -0
  38. package/dist/host/scripts/npm.sh +0 -0
  39. package/dist/host/scripts/ollama.sh +0 -0
  40. package/dist/host/tests/config.test.ts +237 -115
  41. package/dist/src/core/index.cjs +591 -218
  42. package/dist/src/core/index.cjs.map +1 -1
  43. package/dist/src/core/index.d.cts +248 -29
  44. package/dist/src/core/index.d.ts +248 -29
  45. package/dist/src/core/index.js +581 -216
  46. package/dist/src/core/index.js.map +1 -1
  47. package/dist/src/server/index.cjs +18 -8
  48. package/dist/src/server/index.cjs.map +1 -1
  49. package/dist/src/server/index.d.cts +4 -3
  50. package/dist/src/server/index.d.ts +4 -3
  51. package/dist/src/server/index.js +19 -9
  52. package/dist/src/server/index.js.map +1 -1
  53. package/package.json +3 -3
@@ -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