@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
@@ -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
@@ -129,7 +129,7 @@ The `triage` role sends System One requests to `/v1/systemone`. Its `StudySystem
129
129
 
130
130
  A provider declares `triage` and `digest.triage` together. Both metadata passes verify the pin through tags and show, configuration identity retains it, and a declared daemon includes it in its verified maintenance population. A transport fault on this leg fails the trial even if the consumer catches it; it cannot produce successful recording completion. A well-transported answer the consumer semantically refuses remains the consumer's decision to refer onward. Study chooses no model name or probability cutoff.
131
131
 
132
- Recording reads version and optional procedure from the exchange sink's opening declaration. The transport refuses metadata or model pins that differ from that row. Preflight and postflight verify version, tags, and show for each distinct pinned model. Ordered exact steps compare UTF-8 bytes and verify their declared SHA-256 receipt; capture steps require their declared positive safe byte length and forbid body or input members. Goal, role, route, policy, and order are checked before sending. A second request and verification during request admission refuse. The sink supplies each HTTP ordinal, which joins dispatch and wire evidence even without passive observation. An attempt retains request bytes before sending. A validated response retains native status, selected headers, exact bytes, and chunk lengths; a failure retains bounded partial bytes and cannot produce completion. Successful postflight appends completion after the admitted execution sequence; a declared procedure also requires every step to finish. The parent composes the declaration, and the worker retains that row after verifying any maintenance prefix.
132
+ Recording reads the optional procedure from the exchange sink's opening declaration. The transport refuses metadata or model pins that differ from that row. Preflight and postflight each fetch the serving version, then verify tags and show for each distinct pinned model. The version is an observation for debugging: each pass appends a `version` evidence row to its goal, `{ version }` with the reply's nonempty string or `null` when the reply names none, and Study compares it with nothing, so no recording, replay, or continuation refuses because of a version. The sidecar retains each version reply's exact bytes. Ordered exact steps compare UTF-8 bytes and verify their declared SHA-256 receipt; capture steps require their declared positive safe byte length and forbid body or input members. Goal, role, route, policy, and order are checked before sending. A second request and verification during request admission refuse. The sink supplies each HTTP ordinal, which joins dispatch and wire evidence even without passive observation. An attempt retains request bytes before sending. A validated response retains native status, selected headers, exact bytes, and chunk lengths; a failure retains bounded partial bytes and cannot produce completion. Successful postflight appends completion after the admitted execution sequence; a declared procedure also requires every step to finish. The parent composes the declaration, and the worker retains that row after verifying any maintenance prefix.
133
133
 
134
134
  The transport owns its configuration before validation and snapshots each outbound URL, settings, headers, and request correlation before awaiting admission. Later caller mutation cannot change the admitted request. Cancellation signals, the timing callback, and the optional fetch collaborator retain their live identity.
135
135
 
@@ -216,9 +216,9 @@ The Ollama transport appends a `stop` evidence row after its `wire` row when com
216
216
 
217
217
  ## Native command
218
218
 
219
- Recording declares positive safe `record.bytes`, `record.calls`, and `record.duration` allowances on the profile. The manifest retains the same declaration, and the parent reserves that complete allowance separately for each trial before starting workers. The allowance covers every serialized sidecar byte, including base64 expansion, opening and terminal rows, and LF framing. It consumes series custody without consuming goal evidence or model quota. Recording profiles explicitly supply `settings.version` and `settings.metadata`. Omitting `settings.procedure` selects open recording; supplying it keeps ordered exact or capture admission. The parent calls `buildStudyExchangeDeclaration` with the profile, trial, scenario, and whether it owns a daemon session. Each destination carries that declaration, and the driver, session, and worker check its members against the profile and trial they hold before constructing the adapter driver. The transport takes version and procedure from the sink, with no duplicate options.
219
+ Recording declares positive safe `record.bytes`, `record.calls`, and `record.duration` allowances on the profile. The manifest retains the same declaration, and the parent reserves that complete allowance separately for each trial before starting workers. The allowance covers every serialized sidecar byte, including base64 expansion, opening and terminal rows, and LF framing. It consumes series custody without consuming goal evidence or model quota. Recording profiles explicitly supply `settings.metadata`, and name no serving version. Omitting `settings.procedure` selects open recording; supplying it keeps ordered exact or capture admission. The parent calls `buildStudyExchangeDeclaration` with the profile, trial, scenario, and whether it owns a daemon session. Each destination carries that declaration, and the driver, session, and worker check its members against the profile and trial they hold before constructing the adapter driver. The transport takes the procedure from the sink, with no duplicate options.
220
220
 
221
- The declaration retains `record`, the ordered `goals`, and a `configuration` digest alongside version, pinned models, metadata bounds, maintenance, and optional procedure. Configuration hashes canonical room, settings, and daemon configuration with the daemon executable path omitted. Profile record and elapsed bounds stay outside that digest. Maintenance lists the daemon's declared models when the parent owns a daemon session for this execution, and is empty otherwise.
221
+ The declaration retains `record`, the ordered `goals`, and a `configuration` digest alongside pinned models, metadata bounds, maintenance, and optional procedure. It holds no version, and a declaration that carries one refuses. Configuration hashes canonical room, settings, and daemon configuration with the daemon executable path omitted; the daemon declaration holds no executable digest, so an updated executable leaves configuration unchanged. Profile record and elapsed bounds stay outside that digest. Maintenance lists the daemon's declared models when the parent owns a daemon session for this execution, and is empty otherwise.
222
222
 
223
223
  The `record.calls` allowance counts execution attempts retained by the sidecar, including replayed exchanges. A request past the cap refuses before append or send with CAPACITY and the scope stop Recording calls. The `record.duration` allowance sums execution send-to-settlement milliseconds; metadata retains its independent budget. When the remaining model time binds a request, its recording deadline starts immediately before send and expires with DEADLINE and the scope stop Recording duration. An exhausted allowance refuses before append or send. A refusal keeps prior charges and prevents completion; an admitted attempt retains its failure terminal, including any bounded partial reply. Such a result stays interrupted.
224
224
 
@@ -238,11 +238,11 @@ The `StudyIdentity` interface retains location-independent runtime and content d
238
238
 
239
239
  The replay manifest's ancestor retains the source result id, seal, and complete source identity. The replay sidecar's ancestor also retains its source file identity and exchange prefix. The manifest's own identity describes the executing build, so both contents remain available. The worker rechecks the ancestor and recorded goal prefix. The `scanStudyDivergence` function accepts a strictly read history and strictly read replay rows, aligns non-maintenance attempts by position, and returns the first differing or unmatched request. It performs no second validation. An extra request pairs with the recorded attempt at its position; after the last recorded execution, that is the first postflight request; an early end has no actual attempt. An attempt past the complete recording has no expected attempt and uses the recording's completion count plus one as its ordinal.
240
240
 
241
- Continuation selects `--extend <result>` on check or execute and refuses a simultaneous replay selection. The ancestor must be sealed, recorded in open form, and complete without operational failures or partial products. The executing profile must declare open recording and a dedicated daemon. The definition, driver, ordered trials, runtime, content, version, models, and configuration must match. Every scenario keeps its id and strictly extends its ancestor's goals, including their canonical input values. Fixture identity changes with the grown scenario. Recording and elapsed bounds may rise because they stay outside configuration; no bound rises automatically.
241
+ Continuation selects `--extend <result>` on check or execute and refuses a simultaneous replay selection. The ancestor must be sealed, recorded in open form, and complete without operational failures or partial products. The executing profile must declare open recording, and it can declare a dedicated daemon or none, with empty maintenance. The definition, driver, ordered trials, runtime, content, models, and configuration must match; the serving version and the daemon executable can differ, so a recording continues under a later Ollama. Every scenario keeps its id and strictly extends its ancestor's goals, including their canonical input values. Fixture identity changes with the grown scenario. Recording and elapsed bounds may rise because they stay outside configuration; no bound rises automatically.
242
242
 
243
- The parent derives a live replay prefix ending immediately before each ancestor's postflight. It starts and verifies the daemon, then records live unloads before opening the worker. The worker reconstructs state through the real adapter with exact recorded preflight and execution responses, sending no prefix request to the daemon. It checks the consumed prefix at the ancestor's last goal. An extra request in that goal refuses before forwarding and retains its attempt and failure. The first request in a later goal goes live; postflight verifies the live daemon at the extended horizon's last goal. Each segment's first live goal starts cold, so its timing and cache state can differ from a continuous execution.
243
+ The parent derives a live replay prefix ending immediately before each ancestor's postflight. With a declared daemon, it starts and verifies the daemon, then records live unloads before opening the worker; without one, it records no maintenance and live requests go to the external daemon at the provider URL. The worker reconstructs state through the real adapter with exact recorded preflight and execution responses, sending no prefix request to the daemon. It checks the consumed prefix at the ancestor's last goal. An extra request in that goal refuses before forwarding and retains its attempt and failure. The first request in a later goal goes live; postflight verifies the live daemon at the extended horizon's last goal. With a declared daemon, each segment's first live goal starts cold, so its timing and cache state can differ from a continuous execution; an external daemon keeps whatever models it holds.
244
244
 
245
- The descendant retains a complete flat sidecar: its extended declaration and ancestor prefix, live maintenance, replayed request and response bytes with recorded chunk lengths, live execution, live postflight, and completion. Its manifest links the immediate ancestor, so a later segment needs only that complete descendant. Replayed goals emit their evidence again and count against recording calls; their send-to-settlement time follows the executing recording duration allowance.
245
+ The descendant retains a complete flat sidecar: its extended declaration and ancestor prefix, any live maintenance, replayed request and response bytes with recorded chunk lengths, live execution, live postflight, and completion. Its manifest links the immediate ancestor, so a later segment needs only that complete descendant. Replayed goals emit their evidence again and count against recording calls; their send-to-settlement time follows the executing recording duration allowance.
246
246
 
247
247
  Triage participates in open recording and in exact or capture procedures using its System One route and policy. Strict sidecar reading checks the same identity, ordering, receipts, and completion as for other roles. Prefix and keyed replay retain original response bytes and chunk lengths. An offline replay sends nothing, and a keyed triage miss cannot borrow another role's recorded answer. Replayed triage usage still charges admission budgets, while progress and reports attribute it to `triage`, count it as replayed, and exclude it from live spending. Continuation requires open recording, replays the ancestor goals, and sends only the grown horizon's suffix live. Keyed replay remains exclusive with `--extend`, and every keyed execution still requires recording.
248
248
 
@@ -300,9 +300,9 @@ isStudyExchangeAncestor(reference)
300
300
 
301
301
  The process driver accepts `StudyProcessDriverOptions`. Its optional `prepare` callback runs in the parent before session construction, preserves the reserved destination and allowance, and never crosses structured cloning or IPC. Offline replay refuses a preparation callback. A worker verifies any retained maintenance prefix before resuming the sidecar and projects those ordinals into its first goal's evidence.
302
302
 
303
- A provider's optional `daemon` declaration makes live execution own a dedicated Ollama session at the provider URL. The declaration pins a canonical absolute executable, its SHA-256 digest, the exact version, explicit environment overrides, and distinct model names and inventory digests equal to the provider's model, judge, and triage pins. Shared pins require one entry. A maintenance-only model, a relative executable, port 11434, a missing model digest, or conflicting environment-name casing refuses at profile load. The daemon owns the effective OLLAMA_HOST value. Without this declaration, the provider URL selects an external daemon.
303
+ A provider's optional `daemon` declaration makes live execution own a dedicated Ollama session at the provider URL. The declaration names a canonical absolute executable, explicit environment overrides, and distinct model names and inventory digests equal to the provider's model, judge, and triage pins. It names no executable digest and no version, and a declaration that carries either refuses. Shared pins require one entry. A maintenance-only model, a relative executable, port 11434, a missing model digest, or conflicting environment-name casing refuses at profile load. The daemon owns the effective OLLAMA_HOST value. Without this declaration, the provider URL selects an external daemon.
304
304
 
305
- The `StudyDaemonSession` class starts and verifies the daemon before trial execution. The manifest's `host.daemon` string retains the verified startup identity; startup version and inventory probes belong to no trial sidecar. Before each trial worker opens, preparation unloads the declared models in order. The `StudyDaemonTrial` class synchronizes each maintenance attempt before sending, retains status, allowed headers, original sender chunk lengths, and exact body bytes, and closes the prefix after daemon validation. A failed exchange retains a failure row. The worker joins the maintenance ordinals to the scenario's first declared goal. Every execution ending awaits daemon stop and process-tree join; an unconfirmed cleanup refuses completion. Offline replay constructs no daemon or preparation callback and sends no maintenance request.
305
+ The `StudyDaemonSession` class starts and verifies the daemon before trial execution. Each start reads the executable's SHA-256 and hands it to the daemon as the identity to start. The manifest's `host.daemon` string retains the verified startup identity, including that digest and the version the daemon reported. Study compares neither with an earlier reading, so an updated executable or version never refuses a run. Startup version and inventory probes belong to no trial sidecar. Before each trial worker opens, preparation unloads the declared models in order. The `StudyDaemonTrial` class synchronizes each maintenance attempt before sending, retains status, allowed headers, original sender chunk lengths, and exact body bytes, and closes the prefix after daemon validation. A failed exchange retains a failure row. The worker joins the maintenance ordinals to the scenario's first declared goal. Every execution ending awaits daemon stop and process-tree join; an unconfirmed tree stop refuses completion, and an executable that changed or became unreadable while the daemon ran refuses nothing. Offline replay constructs no daemon or preparation callback and sends no maintenance request.
306
306
 
307
307
  Install the package in the consumer workspace, then run the study executable from that workspace. The selected declaration lives at studies/<name>/study.json, and its declared rubric path resolves inside that same directory. Its driver field selects a bundle at studies/<driver>/ containing scenarios/<scenario>.json, profiles/<profile>.json, and the adapter module index.ts. Several declarations can share one driver bundle while each keeps its own rubric. The profile defaults to local. JSON declarations use the public definition, scenario, profile, and rubric contracts.
308
308
 
@@ -405,7 +405,7 @@ The following declarations describe this concept.
405
405
  | `STUDY_CHECKPOINT_EVENT` | const | `"checkpoint"` | Names the evidence event whose row a seeded execution hands its trial at open. |
406
406
  | `STUDY_COMMAND_DURATION` | const | `86400000` | Caps declared execution duration at the native supervisor's host ceiling. |
407
407
  | `STUDY_COMMAND_GRADER` | const | `"consumer-adapter"` | Names the trusted command's independent offline predicate. |
408
- | `STUDY_COMMAND_HELP` | const | `"study check <study> [--profile <name>] [--closure <directory>] [--extend <result>] [--trial <name>] [--goals <first>..<last>] [--seed <result>:<trial>:<goal>]\nstudy freeze <study> --profile <name> --to <directory>\nstudy execute <study> [--profile <name>] [--out <path>] [--expected <sha256>] [--closure <directory>] [--extend <result> \| --replay <result> --prefix <JSON trial counts> --offline <true\|false> \| --replay <result> --roles <JSON roles> --offline <true\|false>] [--trial <name>] [--goals <first>..<last>] [--seed <result>:<trial>:<goal>]\nstudy grade <result> --rubric <path>\nstudy label <result> --assessment <sha256> --labels <path>\nstudy report <result> --assessment <sha256>\nstudy progress <result> [--from <goal>]\nstudy --help\nstudy --version\n\nProfiles default to local; freeze requires --profile. Flags require values and may appear only once.\nResults default to tmp/studies/<result>; scratch also uses tmp/studies.\nA result is its id under tmp/studies, a root-relative path, or an absolute path.\nRelative paths, including --out, must stay inside the consumer working directory.\nOutput directories must be new; existing results are never overwritten.\n--expected pins the fingerprint returned by check. --assessment selects an exact assessment.\n--rubric selects independent criteria. --labels imports caller-supplied semantic labels.\n--closure selects retained artifacts. Replay requires explicit prefix counts or roles, and offline behavior.\n--roles serves a listed role's request whose path, method, and body bytes equal a recorded attempt's.\n--extend continues a sealed open recording with further goals and requires a declared daemon.\ncheck carries --extend into next and binds the ancestor seal into its fingerprint.\ncheck binds --trial, --goals, and --seed into its fingerprint and carries them into next.\nSuccess writes one JSON document; next contains suggested argv, never executed automatically.\ncheck, freeze, grade, label, report and progress have a fixed allowance of 60 seconds.\nexecute checks first, then uses the declared series duration plus 15 seconds for cleanup.\nExit codes: 0 success, 64 invalid input, 124 deadline, 130 interruption, 1 operational failure.\n"` | Defines the complete public CLI reference shared by help and grammar diagnostics. |
408
+ | `STUDY_COMMAND_HELP` | const | `"study check <study> [--profile <name>] [--closure <directory>] [--extend <result>] [--trial <name>] [--goals <first>..<last>] [--seed <result>:<trial>:<goal>]\nstudy freeze <study> --profile <name> --to <directory>\nstudy execute <study> [--profile <name>] [--out <path>] [--expected <sha256>] [--closure <directory>] [--extend <result> \| --replay <result> --prefix <JSON trial counts> --offline <true\|false> \| --replay <result> --roles <JSON roles> --offline <true\|false>] [--trial <name>] [--goals <first>..<last>] [--seed <result>:<trial>:<goal>]\nstudy grade <result> --rubric <path>\nstudy label <result> --assessment <sha256> --labels <path>\nstudy report <result> --assessment <sha256>\nstudy progress <result> [--from <goal>]\nstudy --help\nstudy --version\n\nProfiles default to local; freeze requires --profile. Flags require values and may appear only once.\nResults default to tmp/studies/<result>; scratch also uses tmp/studies.\nA result is its id under tmp/studies, a root-relative path, or an absolute path.\nRelative paths, including --out, must stay inside the consumer working directory.\nOutput directories must be new; existing results are never overwritten.\n--expected pins the fingerprint returned by check. --assessment selects an exact assessment.\n--rubric selects independent criteria. --labels imports caller-supplied semantic labels.\n--closure selects retained artifacts. Replay requires explicit prefix counts or roles, and offline behavior.\n--roles serves a listed role's request whose path, method, and body bytes equal a recorded attempt's.\n--extend continues a sealed open recording with further goals; the profile can omit a daemon.\ncheck carries --extend into next and binds the ancestor seal into its fingerprint.\ncheck binds --trial, --goals, and --seed into its fingerprint and carries them into next.\nSuccess writes one JSON document; next contains suggested argv, never executed automatically.\ncheck, freeze, grade, label, report and progress have a fixed allowance of 60 seconds.\nexecute checks first, then uses the declared series duration plus 15 seconds for cleanup.\nExit codes: 0 success, 64 invalid input, 124 deadline, 130 interruption, 1 operational failure.\n"` | Defines the complete public CLI reference shared by help and grammar diagnostics. |
409
409
  | `STUDY_COMMAND_OPERATION` | const | `"study-command"` | Names the command route beneath the native supervisor. |
410
410
  | `STUDY_CUSTODY_BYTES` | const | `number` | Limits untrusted metadata before JSON parsing or file allocation. |
411
411
  | `STUDY_DRAIN_DURATION` | const | `1000` | Bounds how long inherited output handles stay open after native exit, in milliseconds. |
@@ -749,7 +749,7 @@ The following declarations describe this concept.
749
749
  | `readStudyDeclarationBytes` | function | `(root: string, path: string) => Promise<Uint8Array>` | Reads one declaration file and refuses a missing or linked path with its root-relative path. |
750
750
  | `readStudyVersion` | function | `(entry: string) => string` | Reads the version of the study package that owns an executable entry. |
751
751
  | `matchesSystemError` | function | `(value: unknown, code: string) => boolean` | Reports whether a caught value is a Node error carrying the given system code. |
752
- | `StudyDaemon` | interface | `{ executable, digest, version, environment?, models }` | Pins an executable and the model population an execution owns until cleanup. |
752
+ | `StudyDaemon` | interface | `{ executable, environment?, models }` | Pins an executable and the model population an execution owns until cleanup. |
753
753
  | `StudyDaemonModel` | interface | `{ name, digest }` | Pins one model the declared daemon verifies and unloads before each trial. |
754
754
  | `StudyRecord` | interface | `{ bytes, calls, duration }` | Bounds serialized exchange bytes, execution calls and summed model time for each trial. |
755
755
  | `ArtifactErrorCode` | type | `'ARTIFACT' \| 'TRAVERSAL' \| 'REDIRECT' \| 'ALIAS' \| 'NAME' \| 'DUPLICATE' \| 'OCCUPIED' \| 'OVERLAP' \| 'PARENT' \| 'STALE' \| 'VOLUME' \| 'DRIFT' \| 'LIMIT'` | Names the refused boundary of a captured or materialized artifact graph. |
@@ -782,7 +782,7 @@ The following declarations describe this concept.
782
782
  | `StudyExchangeDestination` | interface | `{ path, declaration, retained? }` | Holds the parent-reserved destination of one trial's exchange sidecar. |
783
783
  | `StudyExchangeBytes` | interface | `{ body, digest, size }` | Retains an application HTTP body's exact bytes independently of text decoding. |
784
784
  | `StudyExchangeIdentity` | interface | `{ ordinal, goal, role, path, method, stage, step? }` | Binds one HTTP exchange to its trial-local position and declared execution stage. |
785
- | `StudyExchangeDeclaration` | interface | `{ phase, trial, version, models, metadata, record, goals, configuration, procedure?, maintenance, ancestor?, keyed? }` | Declares a bounded trial horizon and serving identities before any exchange attempt. |
785
+ | `StudyExchangeDeclaration` | interface | `{ phase, trial, models, metadata, record, goals, configuration, procedure?, maintenance, ancestor?, keyed? }` | Declares a bounded trial horizon and serving identities before any exchange attempt. |
786
786
  | `StudyExchangeAttempt` | interface | `{ phase }` | Retains admitted request bytes durably before the corresponding send begins. |
787
787
  | `StudyExchangeReply` | interface | `{ status, headers, chunks }` | Retains response status, headers, and original application-body chunk lengths. |
788
788
  | `StudyExchangeResponse` | interface | `{ phase }` | Retains a fully consumed response only after status and terminal validation succeed. |
@@ -3346,7 +3346,7 @@ try {
3346
3346
 
3347
3347
  ## Tests
3348
3348
 
3349
- The staging proofs drive the real command and worker over a Node protocol daemon on an ephemeral loopback port. The daemon records whether each unload's attempt was already readable on disk. The source suite proves repeated maintenance prefixes, exact ordinal joins, offline replay without a daemon or request, and startup, trial, unload, and cancellation cleanup while an unrelated sentinel survives. Setup proofs validate fixture declarations without starting a child.
3349
+ The staging proofs drive the real command and worker over a Node protocol daemon on an ephemeral loopback port. The daemon records whether each unload's attempt was already readable on disk. The source suite proves repeated maintenance prefixes, exact ordinal joins, offline replay without a daemon or request, startup, trial, unload, and cancellation cleanup while an unrelated sentinel survives, and a stop that completes after the executable changed under the running daemon. Setup proofs validate fixture declarations without starting a child.
3350
3350
 
3351
3351
  ### Call exchange and replay helpers
3352
3352