@orkestrel/scaffold 0.0.125 → 0.0.127

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 (35) hide show
  1. package/dist/bin/main.js +50 -14
  2. package/dist/bin/main.js.map +1 -1
  3. package/dist/host/AGENTS.md +1 -1
  4. package/dist/host/agents/orchestration.md +5 -4
  5. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +1 -1
  6. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +2 -2
  7. package/dist/host/agents/skills/orkestrel-journey/SKILL.md +18 -19
  8. package/dist/host/agents/skills/orkestrel-parallel/references/codex.md +2 -1
  9. package/dist/host/claude/AGENTS.md +2 -2
  10. package/dist/host/claude/agents/orkestrel.md +18 -18
  11. package/dist/host/claude/agents/planner.md +2 -2
  12. package/dist/host/claude/rules/quality.md +3 -0
  13. package/dist/host/claude/rules/tests.md +3 -0
  14. package/dist/host/claude/rules/workspace.md +11 -5
  15. package/dist/host/codex/agents/planner.toml +2 -2
  16. package/dist/host/guides/agent.md +285 -161
  17. package/dist/host/guides/capture.md +123 -123
  18. package/dist/host/guides/database.md +18 -7
  19. package/dist/host/guides/ndjson.md +4 -3
  20. package/dist/host/guides/ollama.md +2 -2
  21. package/dist/host/guides/program.md +3 -3
  22. package/dist/host/guides/qualifier.md +1 -1
  23. package/dist/host/guides/relation.md +71 -31
  24. package/dist/host/guides/scaffold.md +101 -64
  25. package/dist/host/guides/study.md +22 -12
  26. package/dist/host/guides/toolbox.md +9 -2
  27. package/dist/host/manifest.json +26 -26
  28. package/dist/host/tests/config.test.ts +24 -6
  29. package/dist/src/core/index.cjs +134 -79
  30. package/dist/src/core/index.cjs.map +1 -1
  31. package/dist/src/core/index.d.cts +30 -7
  32. package/dist/src/core/index.d.ts +30 -7
  33. package/dist/src/core/index.js +134 -80
  34. package/dist/src/core/index.js.map +1 -1
  35. package/package.json +4 -4
@@ -299,8 +299,8 @@ Pure helpers behind the query engine's pattern matching.
299
299
  | `SQLiteDriverOptions` | interface | `{ path, readonly?, timeout?, references?, pragmas? }` | Configures `createSQLiteDriver`. The `@orkestrel/database/server` entry point exports this type. |
300
300
  | `QueryPlan` | interface | `{ index?, range? }` | Represents a pushdown plan — an optional index and optional `IDBKeyRange` used to narrow a read. An omitted `index` selects the primary store; an omitted `range` performs a full scan. The plan is always a superset of the matching rows; the core engine refines it to the exact result. An empty plan (`{}`) is a primary-store full scan. The `@orkestrel/database/browser` entry point exports this type. |
301
301
  | `TableDefinition` | interface | `{ primary, columns, schema }` | Represents one table's portable definition, produced by `export` — the unit of schema / migration exchange across environments. |
302
- | `DatabaseStorageInterface` | interface | `{ table() }` | Represents a database view valid only inside one `DatabaseInterface.transaction` scope. |
303
- | `DatabaseInterface` | interface | `{ emitter, name, status, table(), import(), export(), open(), close(), transaction(), migrate() }` | Represents a database — the ergonomic entry point that owns the driver and its tables. |
302
+ | `DatabaseStorageInterface` | interface | `{ table() }` | Represents a table-only database view. |
303
+ | `DatabaseInterface` | interface | `{ emitter, name, status, import(), export(), open(), close(), transaction(), migrate() }` | Represents a database — the ergonomic entry point that owns the driver and its tables. |
304
304
  | `TableInterface` | interface | `{ emitter, name, primary, contract, get(), resolve(), has(), keys(), records(), count(), aggregate(), scan(), set(), add(), update(), remove(), clear(), query(), cursor() }` | Exposes typed keyed CRUD plus fluent query and cursor access. |
305
305
  | `QueryInterface` | interface | `{ condition(), order(), filter(), limit(), offset(), collect(), find(), count(), stream(), aggregate() }` | Builds a read through a fluent chain. |
306
306
  | `CursorInterface` | interface | `{ value, index, done, next(), update(), remove(), close() }` | Walks a table's rows forward for bulk in-place mutation. |
@@ -416,6 +416,9 @@ on the snapshot floor (see [Native transactions](#native-transactions)).
416
416
 
417
417
  #### `DatabaseInterface`
418
418
 
419
+ `DatabaseInterface` extends `DatabaseStorageInterface` and inherits its `table` method.
420
+ The database is accepted wherever table-only storage is accepted.
421
+
419
422
  `transaction` and `migrate` each take an optional `OperationOptions`, whose
420
423
  `signal` is checked once, at entry.
421
424
 
@@ -431,12 +434,14 @@ on the snapshot floor (see [Native transactions](#native-transactions)).
431
434
 
432
435
  #### `DatabaseStorageInterface`
433
436
 
434
- The scoped view and every table taken from it throw `CONFLICT` for work started
435
- after the transaction settles.
437
+ A root database presents this table-only view for its lifetime. A transaction
438
+ scope presents a view that cannot open, close, import, migrate, or nest a
439
+ transaction. The scoped view and every table taken from it throw `CONFLICT`
440
+ for work started after the transaction settles.
436
441
 
437
- | Method | Returns | Summary |
438
- | ------- | ----------------------------- | ------------------------------------------------------ |
439
- | `table` | `TableInterface<RowOf<T[K]>>` | Returns a table bound to the active transaction scope. |
442
+ | Method | Returns | Summary |
443
+ | ------- | ----------------------------- | ---------------------------------------------- |
444
+ | `table` | `TableInterface<RowOf<T[K]>>` | Returns the typed handle for a declared table. |
440
445
 
441
446
  #### `AdmissionInterface`
442
447
 
@@ -1481,6 +1486,12 @@ publish cursor state or restore `value` after close.
1481
1486
 
1482
1487
  ### Transactions
1483
1488
 
1489
+ `DatabaseInterface` extends `DatabaseStorageInterface`, so a root database and
1490
+ a transaction callback's storage both satisfy the table-only contract. The root
1491
+ presents that view for its lifetime. The transaction supplies a scoped view
1492
+ that cannot open, close, import, migrate, or nest a transaction; the view and
1493
+ every table captured from it throw `CONFLICT` after the scope settles.
1494
+
1484
1495
  Runs a scoped callback across two tables that commits on success and rolls every table back when the scope throws:
1485
1496
 
1486
1497
  ```ts
@@ -7,15 +7,16 @@
7
7
  `parse(chunk)` appends `chunk` to an internal buffer and splits it on `\n`: every
8
8
  line before the last is `\n`-terminated, hence complete, and is parsed to a record,
9
9
  while the final segment is held back for the next call, so a line split across chunk
10
- boundaries is reassembled the moment its closing `\n` arrives. Each trimmed line is
10
+ boundaries is reassembled the moment its closing `\n` arrives. Each complete line is
11
+ trimmed with the `String.prototype.trim` method, then
11
12
  filtered — a blank or whitespace-only line (including one whose only content was a
12
13
  CRLF's trailing `\r`) is skipped — so only plain records come back, and a line the
13
14
  stream never terminates is never emitted even when the buffered text already happens
14
15
  to be valid JSON. By default the parser refuses a line it cannot return: `parse`
15
16
  throws an `NDJSONError` with code `'SYNTAX'` for a complete line that is not valid
16
17
  JSON and `'RECORD'` for a complete line that is not a plain record. The throwing call
17
- returns no record, discards the lines after the refused line in the same call too, and
18
- leaves the parser cleared, as `clear()` leaves it. With `strict: false` the parser
18
+ returns no records, discards every held line, including earlier complete lines and
19
+ the trailing partial line, and leaves the parser cleared, as `clear()` leaves it. With `strict: false` the parser
19
20
  skips such a line instead, for a caller that prefers the records it can read over a
20
21
  refusal. Blank lines are skipped, and lines are split and trimmed, the same way in both
21
22
  modes. A chunk that is not a string throws `'SYNTAX'` in both modes, because joining it
@@ -379,7 +379,7 @@ else console.log(result.refusals?.deletion?.missing)
379
379
 
380
380
  ### Ask a native decision model
381
381
 
382
- For a model that Ollama serves on the System One endpoint, use the agent package's factory. A request carries the choice, noul, and score together. Ollama 0.40.0 serves the `tev1:0.8b` model on this path and refuses Mica with HTTP 400; the package makes no capability check.
382
+ For a model that Ollama serves on the System One endpoint, use the agent package's factory. A request carries the choice, noul, and score together. The wire keys are zero-based positions in question entry order; the judge maps the positional answers back to the caller's ids. Ollama 0.40.0 serves the `tev1:0.8b` model on this path and refuses Mica with HTTP 400; the package makes no capability check.
383
383
 
384
384
  ```ts
385
385
  import { measureAnswer, createSystemOneJudge } from '@orkestrel/agent'
@@ -846,7 +846,7 @@ The daemon session proofs run in the `src:server` project against `tests/src/ser
846
846
  - [`tests/src/server/OllamaDaemon.test.ts`](../tests/src/server/OllamaDaemon.test.ts) drives the lifecycle over the fake daemon: a shared startup behind a delayed version reply, verification before any model request, retained maintenance including a refused unload, an overlapping unload, and a refused restart; ordered requests through an optional transport and its global control, exact maintenance bytes across re-chunked replies, a retained transport reference after caller mutation, and transport refusals at each send boundary, with startup joining the child before rejecting and unload leaving it running until `stop`; a mismatched inventory digest refused with `model`, metadata-only requests, and the owned child joined before startup rejects; a stale executable digest and an occupied port, each refused before a child exists; silence, an exit before listening, a bind failure, and an exit before answering, each refused with the owned child gone; executable bytes replaced through the declared path during use, which `stop` reports as `false` with a `digest` error; and a stop and an abort that each end the daemon and its runner while an unrelated process survives.
847
847
  - [`tests/src/server/helpers.test.ts`](../tests/src/server/helpers.test.ts) proves the environment merge by case-folded name, the listen announcement match, the version and model comparisons, the bounded metadata exchange and its refusals, the retained bytes and their digests, the exact unload body, and the terminal reply check, over an in-process peer that answers the metadata routes.
848
848
  - [`tests/src/server/validators.test.ts`](../tests/src/server/validators.test.ts), [`tests/src/server/factories.test.ts`](../tests/src/server/factories.test.ts), and [`tests/src/server/errors.test.ts`](../tests/src/server/errors.test.ts) prove the declaration refusals before any spawn, the undeclared keys by path, the guards in lockstep with the shape, an unstarted session's release without a spawn, and the error brand, its context copy, its cause, and the guard's refusals.
849
- - [`tests/service/OllamaDaemon.test.ts`](../tests/service/OllamaDaemon.test.ts) starts a dedicated real daemon, verifies its receipt, unloads every declared model with the exact request body, and requires a confirmed stop without generation. An explicit `OLLAMA_DAEMON_DECLARATION` JSON value wins. Otherwise the proof resolves `OLLAMA_DAEMON_EXECUTABLE` or the `ollama` executable on `PATH` to its canonical path, computes its SHA-256, reads the provisioned service at `OLLAMA_HOST` for its version and the selected model's `/api/tags` digest, and chooses an ephemeral loopback port apart from 11434 and the provisioned service port. It runs only in the `service` project.
849
+ - [`tests/service/OllamaDaemon.test.ts`](../tests/service/OllamaDaemon.test.ts) starts a dedicated real daemon, verifies its receipt, unloads every declared model with the exact request body, and requires a confirmed stop without generation. An explicit `OLLAMA_DAEMON_DECLARATION` JSON value wins. Otherwise the proof resolves `OLLAMA_DAEMON_EXECUTABLE` or the `ollama` executable on `PATH` to its canonical path, computes its SHA-256, reads the provisioned service at `OLLAMA_HOST` for its version and the selected model's `/api/tags` digest, and chooses an ephemeral loopback port apart from 11434 and the provisioned service port. The executable must be the build the provisioned service runs, because the proof compares their versions: when `OLLAMA_HOST` names a held runner, set `OLLAMA_DAEMON_EXECUTABLE` to that runner's executable, or the proof takes the `ollama` on `PATH` and refuses with `Executable version differs`. It runs only in the `service` project.
850
850
 
851
851
  The hermetic projects — `src:core`, `src:server`, `setup`, `guides`, `conformance`, `policy`, and `config` — run with no Ollama daemon and no network beyond loopback. The `src:server` project starts no Ollama executable: its lifecycle proofs spawn the fake daemon and bind loopback ports only. The `service` project requires a warm local Ollama and, for the page proof, a Chromium-family browser and a built `dist`, and for the daemon session proof an executable on `PATH`, an `OLLAMA_DAEMON_EXECUTABLE` path, or an explicit `OLLAMA_DAEMON_DECLARATION` value; `distribution` packs and installs the artifact. The import guard reads `distribution` with the hermetic projects, because it never reaches the daemon; it leaves out `probe` and `service` alone, the two projects that may.
852
852
 
@@ -713,9 +713,9 @@ allowed.
713
713
  An `AggregateResult` gathers its subjects' `faults`, `repairs`, and `defaulted`, each once by path, and
714
714
  each subject keeps its own. A result crosses a boundary as `projectProgramResult` or
715
715
  `projectAggregateResult`, which `programResultContract` and `aggregateResultContract` admit. A
716
- definition crosses on `createProgramDefinitionContract().is`, never `parse`. `is` reads a nested
717
- `shape` as any JSON value and the guard reads it as a shape, so `shape: 42` passes `is` and
718
- `isProgramDefinition` refuses it: a definition crossing a boundary goes through the guard as well.
716
+ definition crosses on `createProgramDefinitionContract().is`, never `parse`. The contract validates
717
+ a nested `shape` through `shapeShape`, so both its `is` method and the `isProgramDefinition` guard
718
+ refuse a malformed declaration such as `shape: 42`.
719
719
 
720
720
  ### Success
721
721
 
@@ -555,7 +555,7 @@ eligible and contributes evidence a later consumer may act on.
555
555
 
556
556
  ### Publishing definitions and results
557
557
 
558
- `createQualificationDefinitionContract()` publishes a definition, its `schema` for an LLM, a tool, or MCP. Cross a definition on `is`, never `parse`, and hold the result, because building it walks the recursive expressions of its logical passes. `is` reads a nested `shape` as any JSON value and the guard reads it as a shape, so `shape: 42` passes `is` and `isQualificationDefinition` refuses it: a definition crossing a boundary goes through the guard as well. A result crosses as `projectQualificationResult`, which `qualificationResultContract` admits, because a premise's `actual` holds whatever the subject held and a derivation's `value` may be `NaN`.
558
+ `createQualificationDefinitionContract()` publishes a definition, its `schema` for an LLM, a tool, or MCP. Cross a definition on `is`, never `parse`, and hold the result, because building it walks the recursive expressions of its logical passes. The contract validates a nested `shape` through `shapeShape`, so both its `is` method and the `isQualificationDefinition` guard refuse a malformed declaration such as `shape: 42`. A result crosses as `projectQualificationResult`, which `qualificationResultContract` admits, because a premise's `actual` holds whatever the subject held and a derivation's `value` may be `NaN`.
559
559
 
560
560
  ### Validation
561
561
 
@@ -9,13 +9,13 @@ The relationships (`belongs` / `many` / `one` / `through` / `morph`) cover the f
9
9
 
10
10
  ## Surface
11
11
 
12
- Create a manager over a database and its relation map, then reach a typed model and load with relations attached:
12
+ Create a manager over storage and its relation map, then reach a typed model and load with relations attached. In root examples, `TABLES` names the table map passed to `createDatabase`, and `db` is its returned `DatabaseInterface<typeof TABLES>`:
13
13
 
14
14
  ```ts
15
15
  import { createRelationManager, belongsTo, hasMany, hasThrough } from '@orkestrel/relation'
16
16
 
17
- const manager = createRelationManager({
18
- database: db, // a typed DatabaseInterface from createDatabase(...)
17
+ const manager = createRelationManager<typeof TABLES>({
18
+ storage: db, // the DatabaseInterface<typeof TABLES> returned by createDatabase(...)
19
19
  relations: {
20
20
  accounts: {
21
21
  classification: belongsTo('classificationId', 'classifications'), // foreign key on accounts → one classification
@@ -37,11 +37,11 @@ acme?.contacts // the relation property — broad (Row | readonly Row[] | undefi
37
37
 
38
38
  ### Factory & manager
39
39
 
40
- | Name | Kind | Signature | Summary |
41
- | ----------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
42
- | `createRelationManager` | function | `<T extends TableMap>(options: RelationManagerOptions<T>) => RelationManagerInterface<T>` | Creates a `RelationManagerInterface` over a database 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. |
44
- | `Model` | class | `new <T = Row>(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext \| undefined, database: DatabaseInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler) => ModelInterface<T>` | Pairs a typed table with relation-aware `load` / `find` and junction management. |
40
+ | Name | Kind | Signature | Summary |
41
+ | ----------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
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. |
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
47
47
 
@@ -55,20 +55,21 @@ 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). |
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. |
63
64
 
64
65
  ### Row helpers
65
66
 
66
- | Name | Kind | Signature | Summary |
67
- | --------------- | -------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
68
- | `readColumn` | function | `(record: unknown, column: string) => unknown` | Reads one column off any record, whatever its declared type. |
69
- | `countAttached` | function | `(values: ReadonlyArray<Row \| readonly Row[] \| undefined>) => number` | Counts the related rows one relation attached across a record set. |
70
- | `indexRows` | function | `(rows: readonly Row[], column: string) => ReadonlyMap<string, Row>` | Indexes rows by the string form of one column, for keyed lookups. |
71
- | `groupRows` | function | `(rows: readonly Row[], column: string) => ReadonlyMap<string, readonly Row[]>` | Groups rows by the string form of one column, for one-to-many lookups. |
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. |
72
73
 
73
74
  ### Errors
74
75
 
@@ -104,7 +105,7 @@ transparent proxies, unbranded look-alikes, and plain branded objects.
104
105
  | `FindOptions` | interface | `{ limit?, offset?, sort?, direction? }` | Configures pagination, ordering, and cancellation for `find`. |
105
106
  | `ModelEventMap` | type | `{ readonly load: readonly [name: string, count: number]; readonly link: readonly [key: Key, relation: string]; readonly unlink: readonly [key: Key, relation: string]; }` | Declares the push observation surface of a `ModelInterface` — the eager-load + junction-management moments a fire-and-forget observer (logging, metrics, a sync layer) subscribes to. |
106
107
  | `ModelInterface` | interface | `{ emitter, name, table, relations, load(), find(), link(), unlink(), links() }` | Represents a typed table paired with relation-aware loading and junction management. |
107
- | `RelationManagerOptions` | interface | `{ database, relations?, model? }` | Configures `createRelationManager`. |
108
+ | `RelationManagerOptions` | interface | `{ storage, relations?, model? }` | Configures `createRelationManager`. |
108
109
  | `RelationManagerInterface` | interface | `{ count, model(), names(), has() }` | Vends a typed `ModelInterface` per table. |
109
110
 
110
111
  ## Methods
@@ -120,7 +121,7 @@ The public methods of each behavioral interface — one table per type, keyed by
120
121
  | `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. |
121
122
  | `find` | `Promise<readonly Loaded<T>[]>` | Finds many records, paged and sorted through `FindOptions`, with the chosen relations populated. |
122
123
  | `link` | `Promise<void>` | Inserts a missing junction row for a `through` relation. |
123
- | `unlink` | `Promise<void>` | Removes every matching junction row for a `through` relation inside one transaction. |
124
+ | `unlink` | `Promise<void>` | Removes every matching junction row for a `through` relation through the bound storage. |
124
125
  | `links` | `Promise<readonly Key[]>` | Lists the related keys reachable through a `through` relation. |
125
126
 
126
127
  #### `RelationManagerInterface`
@@ -138,16 +139,18 @@ The public methods of each behavioral interface — one table per type, keyed by
138
139
  These invariants hold across `src/core` ↔ `relation.md`:
139
140
 
140
141
  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).
141
- 2. **Layered on the typed database and validated at construction.** A manager is built over a `DatabaseInterface`; `model(name)` is checked against the database's declared tables and returns a model whose `table` is that table's typed `TableInterface` (a declared table with no relation entry yields a relation-less model — still fully usable for typed CRUD). Related tables are fetched by runtime name at the broad `Row` type. Every resolved target table and `through` junction must appear in `database.export()`; an undeclared table throws `RelationError('INVALID', ...)` when the manager is created, before any operation runs.
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.
142
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.
143
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.
144
- 5. **Total, loose `Loaded`.** `Loaded<T>` is the base row (the table's row type) intersected with the broad relation bag `Readonly<LoadedMap>` (`Row | readonly Row[] | undefined` per relation); a missed `belongs` / `one` is `undefined`, a missed `many` / `through` / `morph` is `[]`. Through-only operations (`link` / `unlink` / `links`) throw `NOT_THROUGH` on any other relationship and `UNKNOWN_RELATION` for a relation the model never declared. `link` is idempotent for sequential calls: an existing `(key, target)` pair causes no write and no event. Concurrent `link` calls for the same pair may each insert. `unlink` removes all matching rows inside one database transaction, so a fault rolls the whole removal back. On a driver without a native transaction the database's floor snapshots the whole store, so a rollback restores every table to the scope's start.
145
- 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.
146
- 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 database mutation or transaction. An aborted signal surfaces unchanged as the database package's `ABORTED` error.
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.
147
+ 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.
147
148
  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.
148
149
 
149
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.
150
151
 
152
+ 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
+
151
154
  ## Patterns
152
155
 
153
156
  ### Defining relations
@@ -165,8 +168,8 @@ import {
165
168
  hasMorph,
166
169
  } from '@orkestrel/relation'
167
170
 
168
- const manager = createRelationManager({
169
- database: db,
171
+ const manager = createRelationManager<typeof TABLES>({
172
+ storage: db,
170
173
  relations: {
171
174
  accounts: {
172
175
  classification: belongsTo('classificationId', 'classifications'), // foreign key on accounts
@@ -244,6 +247,14 @@ try {
244
247
  }
245
248
  ```
246
249
 
250
+ Validate a target through a bound storage view; an undeclared target throws `INVALID` with its model, relation, and table context:
251
+
252
+ ```ts
253
+ import { validateRelationTable } from '@orkestrel/relation'
254
+
255
+ validateRelationTable(storage, 'accounts', 'contacts', 'contacts')
256
+ ```
257
+
247
258
  ### The registry surface
248
259
 
249
260
  Beyond `model(name)`, a `RelationManager` exposes `names()` (every table name with resolved relations) and `has(name)` (whether a given table has any):
@@ -298,7 +309,7 @@ A `through` relation's junction rows are managed by key — no need to model the
298
309
  ```ts
299
310
  await accounts.link('acc1', 'representatives', 'rep3') // insert a junction row (accountId=acc1, repId=rep3)
300
311
  await accounts.link('acc1', 'representatives', 'rep3') // already linked, sequential call: no write and no event
301
- await accounts.unlink('acc1', 'representatives', 'rep1') // remove all matches atomically
312
+ await accounts.unlink('acc1', 'representatives', 'rep1') // remove every match through the bound storage
302
313
  const repIds = await accounts.links('acc1', 'representatives') // the related keys reachable through the junction
303
314
  ```
304
315
 
@@ -317,6 +328,35 @@ controller.abort('stop loading')
317
328
  await pending
318
329
  ```
319
330
 
331
+ ### Transactions
332
+
333
+ Construct the manager inside the transaction callback so its tables and relation operations share that scope. Retain the manager only within the callback; models and tables reject work after settlement with `CONFLICT`. This example reads the contact written in its scope and asserts its count:
334
+
335
+ ```ts
336
+ import { createDatabase, createMemoryDriver } from '@orkestrel/database'
337
+ import { isArray, stringShape } from '@orkestrel/contract'
338
+ import { createRelationManager, hasMany } from '@orkestrel/relation'
339
+
340
+ const TABLES = {
341
+ accounts: { id: stringShape(), name: stringShape() },
342
+ contacts: { id: stringShape(), accountId: stringShape() },
343
+ }
344
+ const database = createDatabase({ driver: createMemoryDriver(), tables: TABLES })
345
+ const count = await database.transaction(async (storage) => {
346
+ const manager = createRelationManager({
347
+ storage,
348
+ relations: { accounts: { contacts: hasMany('accountId') } },
349
+ })
350
+ await manager.model('accounts').table.set({ id: 'a1', name: 'Acme' })
351
+ await storage.table('contacts').set({ id: 'c1', accountId: 'a1' })
352
+ const account = await manager.model('accounts').load('a1', { contacts: true })
353
+ return isArray(account?.contacts) ? account.contacts.length : 0
354
+ })
355
+ if (count !== 1) throw new Error('Expected one related contact')
356
+ ```
357
+
358
+ An uncaught scope failure rolls its writes back. Model `link` and `unlink` events fire after their junction operation completes in scope and before the outer commit. Publish effects that require committed data after `database.transaction()` resolves.
359
+
320
360
  ### Observing
321
361
 
322
362
  Each `Model` exposes a typed `emitter` carrying its eager-load + junction moments for fire-and-forget observers — logging, metrics, a sync layer. Subscribe through `model.emitter.on(...)`. **Emitting is observation-only**: every event fires strictly after the load resolves and after the junction operation completes, so a listener can never change what a load does (and a throwing one can't corrupt it). The `RelationManager` is event-free by design — a stateless registry that merely vends models has no observable lifecycle of its own; observe the per-model handle instead.
@@ -330,8 +370,8 @@ accounts.emitter.on('link', (key, relation) => sync.push(key, relation))
330
370
  `model(name)` returns a fresh handle on every call, and each handle owns its own emitter. Retain the handle you subscribed to; a later `manager.model('accounts')` is a different observer surface. To observe every handle a manager vends, pass the listeners once as the manager's `model` option:
331
371
 
332
372
  ```ts
333
- const manager = createRelationManager({
334
- database: db,
373
+ const manager = createRelationManager<typeof TABLES>({
374
+ storage: db,
335
375
  relations: { accounts: { contacts: hasMany('accountId') } },
336
376
  model: {
337
377
  on: { load: (name, count) => metrics.record(`relation.${name}`, count) },
@@ -365,7 +405,7 @@ The event vocabulary:
365
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`.
366
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.
367
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.
368
- - [`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`, atomic `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).
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).
369
409
  - [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — `createRelationManager` wires up a working, typed manager end to end.
370
410
 
371
411
  ## See also