@orkestrel/scaffold 0.0.124 → 0.0.126

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-publish/scripts/steps.js +523 -0
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +70 -11
  3. package/dist/bin/main.js +51 -18
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/agents/orchestration.md +7 -2
  6. package/dist/host/agents/platforms/windows.md +9 -1
  7. package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +1 -1
  9. package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +1 -0
  10. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +32 -4
  11. package/dist/host/agents/skills/orkestrel-journey/SKILL.md +18 -19
  12. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -0
  13. package/dist/host/agents/skills/orkestrel-parallel/references/codex.md +2 -1
  14. package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +5 -1
  15. package/dist/host/agents/skills/orkestrel-publish/SKILL.md +1 -0
  16. package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
  17. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +23 -6
  18. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +654 -0
  19. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +79 -14
  20. package/dist/host/claude/agents/orkestrel.md +28 -28
  21. package/dist/host/claude/rules/patterns.md +1 -1
  22. package/dist/host/claude/rules/portability.md +2 -0
  23. package/dist/host/claude/rules/quality.md +6 -1
  24. package/dist/host/claude/rules/tests.md +6 -1
  25. package/dist/host/claude/rules/workspace.md +8 -3
  26. package/dist/host/guides/agent.md +575 -346
  27. package/dist/host/guides/brief.md +52 -48
  28. package/dist/host/guides/browser.md +2 -2
  29. package/dist/host/guides/interpret.md +531 -155
  30. package/dist/host/guides/mcp.md +183 -61
  31. package/dist/host/guides/ndjson.md +4 -3
  32. package/dist/host/guides/ollama.md +125 -68
  33. package/dist/host/guides/program.md +117 -39
  34. package/dist/host/guides/qualifier.md +110 -59
  35. package/dist/host/guides/rater.md +85 -32
  36. package/dist/host/guides/scaffold.md +49 -22
  37. package/dist/host/guides/study.md +596 -489
  38. package/dist/host/guides/toolbox.md +159 -80
  39. package/dist/host/guides/workflow.md +44 -25
  40. package/dist/host/manifest.json +41 -35
  41. package/dist/src/core/index.cjs +12 -10
  42. package/dist/src/core/index.cjs.map +1 -1
  43. package/dist/src/core/index.d.cts +3 -1
  44. package/dist/src/core/index.d.ts +3 -1
  45. package/dist/src/core/index.js +12 -10
  46. package/dist/src/core/index.js.map +1 -1
  47. package/dist/src/server/index.cjs +23 -11
  48. package/dist/src/server/index.cjs.map +1 -1
  49. package/dist/src/server/index.d.cts +10 -6
  50. package/dist/src/server/index.d.ts +10 -6
  51. package/dist/src/server/index.js +23 -11
  52. package/dist/src/server/index.js.map +1 -1
  53. package/package.json +7 -7
@@ -8,7 +8,7 @@ The runtime supplies `ToolInterface`, registry execution, and result isolation;
8
8
 
9
9
  `createPromptTool` / `createAnswerTool` are the ask and answer halves of a terminal-mediated human-in-the-loop seam over a live `TerminalManagerInterface` (`@orkestrel/terminal`). One call asks a whole multi-field form, not a single question. `createPromptTool` takes `{ to, schema }` per call, parses the model-supplied `schema` with `@orkestrel/form`'s `parseForm`, constructs the live form with `createForm`, and blocks the calling agent turn until the addressed terminal answers (`from` fixed at construction) — resolving with one `FormValues` record keyed by field name, re-surfacing a prompt cycle as `DEADLOCK` and an unanswered expiry as `EXPIRE`. `createAnswerTool` lists the forms addressed to a fixed `to` terminal as `{ id, from, schema }` records and answers one by `{ id, values }`, narrowing the model-supplied `values` with `@orkestrel/form`'s `isFormValues` before applying it, re-surfacing a failed apply as `ANSWER`. `createTerminalRoutes` ([`src/server`](../src/server), the `@src/server` barrel) is the wire bridge for the same manager — structural `{ method, path, handler }` route records, a GET SSE stream and a POST answer over one shared `:name`-templated path, carrying no dependency on `@orkestrel/router`'s own `Route` type so a consumer mounts them against any router accepting that two-arg handler shape, and byte-compatible with `@orkestrel/terminal`'s own `PromptClient` (same GET url streams, same POST url answers, same `{ id, values }` body, same JSON answer `Result` body, same `x-orkestrel-token` header).
10
10
 
11
- `createInferTool` / `createEndpointTool` bridge an existing API/DB surface into an LLM-callable `ToolInterface` over `@orkestrel/contract`'s sample-based schema inference — `createInferTool` a standalone utility a model calls to learn a JSON Schema from example values, `createEndpointTool` wrapping one concrete endpoint whose inferred `parameters` steer the model and, by default, are enforced at `execute` time (`EndpointToolOptions.validate`, default `true`; `validate: false` restores raw passthrough — see Contract invariant 23).
11
+ `createInferTool` / `createEndpointTool` bridge an existing API/DB surface into an LLM-callable `ToolInterface` over `@orkestrel/contract`'s sample-based schema inference — `createInferTool` a standalone utility a model calls to learn a JSON Schema from example values, `createEndpointTool` wrapping one concrete endpoint whose inferred `parameters` steer the model and, by default, are enforced at `execute` time (`EndpointToolOptions.strict`, default `true`; `strict: false` restores raw passthrough — see Contract invariant 23).
12
12
 
13
13
  Source: [`src/core`](../src/core) (the tool factories) and [`src/server`](../src/server) (the terminal-routes wire bridge). Surfaced through the `@src/core` and `@src/server` barrels respectively.
14
14
 
@@ -37,12 +37,12 @@ Source: [`src/core`](../src/core) (the tool factories) and [`src/server`](../src
37
37
 
38
38
  ### Stores
39
39
 
40
- Concrete `DefinitionStoreInterface` implementations (AGENTS' Stores rule, point-access mold): `MemoryDefinitionStore` the in-memory default, `DatabaseDefinitionStore` the driver-pluggable twin over one `@orkestrel/database` table. They implement the same `get` / `set` / `delete` contract over different backing storage, and differ within it: the memory store copies on write and on read, while the table-backed store narrows an untrusted stored blob and reports `undefined` for a malformed one.
40
+ Concrete `DefinitionStoreInterface` implementations (AGENTS' Stores rule, point-access mold): `MemoryDefinitionStore` the in-memory default, `DatabaseDefinitionStore` the driver-pluggable twin over one `@orkestrel/database` table. They implement the same `get` / `set` / `delete` contract over different backing storage, and differ within it: the memory store copies on write and on read, while the table-backed store narrows an untrusted stored blob and refuses a malformed one.
41
41
 
42
- | Name | Kind | Signature | Summary |
43
- | ------------------------- | ----- | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
44
- | `MemoryDefinitionStore` | class | `new () => DefinitionStoreInterface` | Represents the in-memory `DefinitionStoreInterface` — a process-lifetime `Map` of `DatabaseDefinition`s keyed by database id, the default store `createMemoryDefinitionStore` builds. It implements the same `DefinitionStoreInterface` contract as `DatabaseDefinitionStore`: this store copies on write and on read; the table-backed store narrows an untrusted stored blob and reports `undefined` for a malformed one. |
45
- | `DatabaseDefinitionStore` | class | `new (table: TableInterface<DatabaseDefinitionRow>) => DefinitionStoreInterface` | Represents a `DefinitionStoreInterface` backed by one table of the `@orkestrel/database` layer — a database's durable config state is a row, so persistence reduces to keyed point-access (`get` / `set` / `delete`) over a `TableInterface`, the driver-pluggable twin of the plain-`Map` `MemoryDefinitionStore`. |
42
+ | Name | Kind | Signature | Summary |
43
+ | ------------------------- | ----- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
44
+ | `MemoryDefinitionStore` | class | `new () => DefinitionStoreInterface` | Represents the in-memory `DefinitionStoreInterface` — a process-lifetime `Map` of `DatabaseDefinition`s keyed by database id, the default store `createMemoryDefinitionStore` builds. It implements the same `DefinitionStoreInterface` contract as `DatabaseDefinitionStore`: this store copies on write and on read; the table-backed store narrows an untrusted stored blob and refuses a malformed one. |
45
+ | `DatabaseDefinitionStore` | class | `new (table: TableInterface<DatabaseDefinitionRow>) => DefinitionStoreInterface` | Represents a `DefinitionStoreInterface` backed by one table of the `@orkestrel/database` layer — a database's durable config state is a row, so persistence reduces to keyed point-access (`get` / `set` / `delete`) over a `TableInterface`, the driver-pluggable twin of the plain-`Map` `MemoryDefinitionStore`. |
46
46
 
47
47
  ### Resolvers
48
48
 
@@ -64,40 +64,51 @@ Concrete `DefinitionStoreInterface` implementations (AGENTS' Stores rule, point-
64
64
 
65
65
  The total `(value: unknown) => value is T` guards this package applies at its untrusted boundaries — an authored lineage, a frozen agent adapter, the small-model column DSL, and a persisted database definition read back from a store.
66
66
 
67
- | Name | Kind | Signature | Summary |
68
- | ---------------------- | -------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
69
- | `isWorkflowLineage` | function | `(value: unknown) => value is WorkflowLineage` | Narrows an unknown value to a valid alternating workflow lineage. |
70
- | `isAgentFunction` | function | `(value: unknown) => value is AgentFunction` | Narrows an unknown callable to Toolbox's frozen contextual agent adapter metadata. |
71
- | `isColumnPrimitive` | const | `Guard<ColumnPrimitive>` | Narrows an unknown value to a `ColumnPrimitive`. |
72
- | `isColumnSpec` | function | `(value: unknown) => value is ColumnSpec` | Narrows an unknown value to a `ColumnSpec`. |
73
- | `isDatabaseDefinition` | function | `(value: unknown) => value is DatabaseDefinition` | Narrows an unknown value to a `DatabaseDefinition` — a non-empty `id` and `driver`, a `tables` record whose every value is `{ columns: record of valid ColumnSpec }`, plus optional `primary`, `indexes`, and finite `version` schema configuration. The boundary guard a `DefinitionStoreInterface` applies to an untrusted persisted blob before trusting it as a definition (never an `as`). |
67
+ | Name | Kind | Signature | Summary |
68
+ | ---------------------- | -------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
69
+ | `isWorkflowLineage` | function | `(value: unknown) => value is WorkflowLineage` | Narrows an unknown value to a valid alternating workflow lineage. |
70
+ | `isAgentFunction` | function | `(value: unknown) => value is AgentFunction` | Narrows an unknown callable to Toolbox's frozen contextual agent adapter metadata. |
71
+ | `isColumnPrimitive` | const | `Guard<ColumnPrimitive>` | Narrows an unknown value to a `ColumnPrimitive`. |
72
+ | `isColumnSpec` | const | `Guard<ColumnSpec>` | Narrows an unknown value to a `ColumnSpec` — a bare `ColumnPrimitive`, or exactly `{ primitive, optional? }`. |
73
+ | `isTableSpec` | function | `(value: unknown) => value is TableSpec` | Narrows an unknown value to a `TableSpec` — table name to exactly `{ columns }`, each column a valid `ColumnSpec`. |
74
+ | `isPrimaryMap` | function | `(value: unknown) => value is PrimaryMap` | Narrows an unknown value to a `PrimaryMap` (`@orkestrel/database`) — table name to a nonempty primary-key column name. |
75
+ | `isIndexMap` | function | `(value: unknown) => value is IndexMap` | Narrows an unknown value to an `IndexMap` (`@orkestrel/database`) — table name to its index groups, each group a nonempty list of nonempty column names. |
76
+ | `isDatabaseDefinition` | const | `Guard<DatabaseDefinition>` | Narrows an unknown value to exactly a `DatabaseDefinition` — a non-empty `id` and `driver`, a `TableSpec`, plus optional `primary`, `indexes`, and finite `version` schema configuration, refusing every other key. The boundary guard a `DefinitionStoreInterface` applies to an untrusted persisted blob before trusting it as a definition (never an `as`). |
74
77
 
75
78
  ### Helpers
76
79
 
77
80
  Pure, side-effect-free, exhaustively unit-tested under AGENTS' export-and-test-reusable-logic law and narrow-untrusted-input-with-guards rule — the lenient-authoring synthesis path and the ancestry tags `createAgentTool` and `createAgentFunction` share.
78
81
 
79
- | Name | Kind | Signature | Summary |
80
- | ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
81
- | `tagWorkflow` | function | `(id: string) => string` | Returns the ancestry identifier of a workflow in a run chain — `workflow:<id>`. |
82
- | `tagAgent` | function | `(name: string) => string` | Returns the ancestry identifier of an agent in a run chain — `agent:<name>`. |
83
- | `summarizeWorkflow` | function | `(result: WorkflowResult) => WorkflowToolResult` | Builds the plain success summary `createWorkflowTool` returns on a completed run — the universal tool-handler contract: return a plain value on success, appearing identically over both the agent loop and MCP. |
84
- | `extendLineage` | function | `(lineage: WorkflowLineage, tag: string) => WorkflowLineage` | Appends one tag to a workflow lineage and returns a frozen copy. |
85
- | `normalizeLineage` | function | `(lineage?: WorkflowLineage) => WorkflowLineage` | Returns the canonical workflow lineage — validated, copied, and frozen. |
86
- | `deriveWorkflowDepth` | function | `(lineage: WorkflowLineage) => number` | Derives the zero-based workflow nesting depth from a valid lineage. |
87
- | `resolveWorkflowTarget` | function | `(owned: JSONRecord, definition: WorkflowDefinition, steps: ContractInterface<WorkflowSteps>, draft: ContractInterface<WorkflowDraft>) => WorkflowDefinition \| undefined` | Resolves an owned workflow input through the supplied flat or draft contracts. |
88
- | `completeDraft` | function | `(draft: WorkflowDraft) => WorkflowDefinition` | Completes a `WorkflowDraft` into a strict `WorkflowDefinition` — synthesizes a missing `id` deterministically and positionally, and defaults a missing `name` to its resolved `id`. |
89
- | `completePhaseDraft` | function | `(phase: PhaseDraft, index: number) => WorkflowDefinition['phases'][number]` | Completes one `PhaseDraft` into a strict phase definition — the per-phase step of `completeDraft` (phase `index` → `phase-<index>` when its id is omitted). |
90
- | `completeTaskDraft` | function | `(task: TaskDraft, phaseId: string, index: number) => WorkflowDefinition['phases'][number]['tasks'][number]` | Completes one `TaskDraft` into a strict task definition — the per-task leaf step of `completeDraft` (task `index` of phase `<phaseId>` → `<phaseId>-task-<index>` when its id is omitted). |
91
- | `expandSteps` | function | `(flat: WorkflowSteps) => WorkflowDefinition` | Expands a flat `WorkflowSteps` blob into a strict `WorkflowDefinition` — each step becomes a one-task phase, in order. |
92
- | `inferTerminalCode` | function | `(error: unknown) => ToolboxErrorCode \| undefined` | Maps a caught error to the `ToolboxErrorCode` the terminal-tool factory throws with — the pure classification step of that factory's error handling. |
93
- | `inferDatabaseCode` | function | `(error: unknown) => DatabaseErrorCode \| undefined` | Maps a caught error to the granular `DatabaseErrorCode` (`@orkestrel/database`) the code `createDatabaseTool` throws with — the pure classification step of that factory's error handling, mirroring `inferTerminalCode`'s idiom for `@orkestrel/database`. |
94
- | `inferRelationCode` | function | `(error: unknown) => RelationErrorCode \| undefined` | Maps a caught error to the granular `RelationErrorCode` (`@orkestrel/relation`) the code `createRelationTool` throws with — the pure classification step of that factory's error handling, mirroring `inferTerminalCode`'s idiom for `@orkestrel/relation`. |
95
- | `expandInclude` | function | `(paths: readonly string[] \| undefined, depth: number) => Include` | Expands the relation tool's flat dot-path `include` list into a live `@orkestrel/relation` `Include` tree — the pure leaf `createRelationTool` calls before a `'load'` / `'find'` call. |
96
- | `resolveRelationManager` | function | `(managers: Readonly<Record<string, RelationManagerInterface>>, name: string \| undefined) => RelationManagerInterface` | Resolves which registered `RelationManagerInterface` a relation-tool call addresses — the pure manager-resolution leaf `createRelationTool` calls on every operation. |
97
- | `resolveRelationModel` | function | `(manager: RelationManagerInterface, name: string) => ModelInterface` | Resolves a `model` name against a live `RelationManagerInterface` — the pure model-lookup leaf `createRelationTool` calls on every operation, mirroring `resolveRelationManager`'s guard shape. |
98
- | `clampQuery` | function | `(query: QueryInput \| undefined, cap: number) => ClampedQuery` | Clamps a `'records'` call's query to a row cap, and builds the probe query the caller reads with — the pure leaf `createDatabaseTool`'s `'records'` operation uses to detect truncation without a separate `count` round trip. |
99
- | `resolveLimit` | function | `(requested: number \| undefined, cap: number) => number` | Picks the effective row limit a tool reads with — the requested count when it sits inside the cap, the cap when it exceeds it, and `0` when either falls below zero. |
100
- | `normalizeQuery` | function | `(query: DatabaseQueryInput \| undefined) => QueryInput \| undefined` | Returns the canonical live `@orkestrel/database` `QueryInput` for the database tool's parsed serialized query — each condition's omitted `connector` defaults to `'and'`. |
82
+ | Name | Kind | Signature | Summary |
83
+ | ---------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
84
+ | `tagWorkflow` | function | `(id: string) => string` | Returns the ancestry identifier of a workflow in a run chain — `workflow:<id>`. |
85
+ | `tagAgent` | function | `(name: string) => string` | Returns the ancestry identifier of an agent in a run chain — `agent:<name>`. |
86
+ | `summarizeWorkflow` | function | `(result: WorkflowResult) => WorkflowToolResult` | Builds the plain success summary `createWorkflowTool` returns on a completed run — the universal tool-handler contract: return a plain value on success, appearing identically over both the agent loop and MCP. |
87
+ | `extendLineage` | function | `(lineage: WorkflowLineage, tag: string) => WorkflowLineage` | Appends one tag to a workflow lineage and returns a frozen copy. |
88
+ | `normalizeLineage` | function | `(lineage?: WorkflowLineage) => WorkflowLineage` | Returns the canonical workflow lineage — validated, copied, and frozen. |
89
+ | `deriveWorkflowDepth` | function | `(lineage: WorkflowLineage) => number` | Derives the zero-based workflow nesting depth from a valid lineage. |
90
+ | `resolveWorkflowTarget` | function | `(owned: JSONRecord, definition: WorkflowDefinition, steps: ContractInterface<WorkflowSteps>, draft: ContractInterface<WorkflowDraft>) => WorkflowDefinition` | Resolves an owned workflow input through the supplied flat or draft contracts, or refuses it with what to send. |
91
+ | `renderCandidates` | function | `(names: readonly string[]) => string` | Renders the candidates a refusal offers, each encoded and length-capped and at most `REFUSAL_LIST_LIMIT` of them named, so a long or multiline name cannot fake or balloon the message. |
92
+ | `limitRefusal` | function | `(text: string) => string` | Caps the complete text of a refusal at `FAULT_TEXT_LIMIT` characters, saying where it stopped. |
93
+ | `describeDefinitionMismatch` | function | `(id: string, held: string) => string` | Describes a stored definition that names another id, naming the id it holds and the id it must hold. |
94
+ | `requireToolCall` | function | `<T>(contract: ContractInterface<T>, value: unknown) => T` | Reads a call's arguments through a compiled contract, or refuses them with what to send. |
95
+ | `buildArgumentRefusal` | function | `(schema: JSONSchema, value: unknown, faults: readonly AuditFault[]) => ToolError` | Builds an argument refusal from the supplied faults, auditing the schema when no faults were supplied. |
96
+ | `resolveBound` | function | `(value: number \| undefined, fallback: number, subject: string) => number` | Picks the effective value of a positive numeric tool option: the configured value when it is a positive safe integer, and the fallback when it is omitted. |
97
+ | `requireActiveWorkspace` | function | `(manager: WorkspaceManagerInterface, operation: string) => WorkspaceInterface` | Reads the active workspace for an operation that edits a file that must already exist, or refuses. |
98
+ | `describeDefinitionRefusal` | function | `(id: string, faults: readonly AuditFault[]) => string` | Describes a stored definition this package refuses to read, naming its first fault and the remedy. |
99
+ | `completeDraft` | function | `(draft: WorkflowDraft) => WorkflowDefinition` | Completes a `WorkflowDraft` into a strict `WorkflowDefinition` — synthesizes a missing `id` deterministically and positionally, and defaults a missing `name` to its resolved `id`. |
100
+ | `completePhaseDraft` | function | `(phase: PhaseDraft, index: number) => WorkflowDefinition['phases'][number]` | Completes one `PhaseDraft` into a strict phase definition — the per-phase step of `completeDraft` (phase `index` → `phase-<index>` when its id is omitted). |
101
+ | `completeTaskDraft` | function | `(task: TaskDraft, phaseId: string, index: number) => WorkflowDefinition['phases'][number]['tasks'][number]` | Completes one `TaskDraft` into a strict task definition — the per-task leaf step of `completeDraft` (task `index` of phase `<phaseId>` → `<phaseId>-task-<index>` when its id is omitted). |
102
+ | `expandSteps` | function | `(flat: WorkflowSteps) => WorkflowDefinition` | Expands a flat `WorkflowSteps` blob into a strict `WorkflowDefinition` — each step becomes a one-task phase, in order. |
103
+ | `inferTerminalCode` | function | `(error: unknown) => ToolboxErrorCode \| undefined` | Maps a caught error to the `ToolboxErrorCode` the terminal-tool factory throws with — the pure classification step of that factory's error handling. |
104
+ | `inferDatabaseCode` | function | `(error: unknown) => DatabaseErrorCode \| undefined` | Maps a caught error to the granular `DatabaseErrorCode` (`@orkestrel/database`) the code `createDatabaseTool` throws with — the pure classification step of that factory's error handling, mirroring `inferTerminalCode`'s idiom for `@orkestrel/database`. |
105
+ | `inferRelationCode` | function | `(error: unknown) => RelationErrorCode \| undefined` | Maps a caught error to the granular `RelationErrorCode` (`@orkestrel/relation`) the code `createRelationTool` throws with — the pure classification step of that factory's error handling, mirroring `inferTerminalCode`'s idiom for `@orkestrel/relation`. |
106
+ | `expandInclude` | function | `(paths: readonly string[] \| undefined, depth: number) => Include` | Expands the relation tool's flat dot-path `include` list into a live `@orkestrel/relation` `Include` tree — the pure leaf `createRelationTool` calls before a `'load'` / `'find'` call. |
107
+ | `resolveRelationManager` | function | `(managers: Readonly<Record<string, RelationManagerInterface>>, name: string \| undefined) => RelationManagerInterface` | Resolves which registered `RelationManagerInterface` a relation-tool call addresses — the pure manager-resolution leaf `createRelationTool` calls on every operation. |
108
+ | `resolveRelationModel` | function | `(manager: RelationManagerInterface, name: string) => ModelInterface` | Resolves a `model` name against a live `RelationManagerInterface` — the pure model-lookup leaf `createRelationTool` calls on every operation, mirroring `resolveRelationManager`'s guard shape. |
109
+ | `clampQuery` | function | `(query: QueryInput \| undefined, cap: number) => ClampedQuery` | Clamps a `'records'` call's query to a row cap, and builds the probe query the caller reads with — the pure leaf `createDatabaseTool`'s `'records'` operation uses to detect truncation without a separate `count` round trip. |
110
+ | `resolveLimit` | function | `(requested: number \| undefined, cap: number) => number` | Picks the effective row limit a tool reads with — the requested count when it sits inside the cap, the cap when it exceeds it, and `0` when either falls below zero. |
111
+ | `normalizeQuery` | function | `(query: DatabaseQueryInput \| undefined) => QueryInput \| undefined` | Returns the canonical live `@orkestrel/database` `QueryInput` for the database tool's parsed serialized query — each condition's omitted `connector` defaults to `'and'`. |
101
112
 
102
113
  ### Compilers
103
114
 
@@ -129,6 +140,10 @@ The shape values each `create*Tool` factory (and `createWorkflowDraftContract`)
129
140
  | `columnPrimitiveShape` | const | `import("@orkestrel/contract").LiteralShape<readonly ["string", "integer", "number", "boolean"]>` | Describes a `ColumnPrimitive` literal — the leaf `columnSpecShape` wraps. |
130
141
  | `columnSpecShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").LiteralShape<readonly ["string", "integer", "number", "boolean"]>, import("@orkestrel/contract").ObjectShape<{ primitive: import("@orkestrel/contract").LiteralShape<readonly ["string", "integer", "number", "boolean"]>; optional: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").BooleanShape>; }, false>]>` | Describes a `ColumnSpec` — a bare `columnPrimitiveShape`, or `{ primitive, optional }`. |
131
142
  | `tableSpecShape` | const | `import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").ObjectShape<{ columns: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").LiteralShape<readonly ["string", "integer", "number", "boolean"]>, import("@orkestrel/contract").ObjectShape<{ primitive: import("@orkestrel/contract").LiteralShape<readonly ["string", "integer", "number", "boolean"]>; optional: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").BooleanShape>; }, false>]>>; }, false>>` | Describes a `TableSpec` — table name to `{ columns }`, each column a `columnSpecShape`. |
143
+ | `primaryShape` | const | `import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").StringShape>` | Describes a `DatabaseDefinition`'s `primary` map — table name to its primary-key column. |
144
+ | `indexesShape` | const | `import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>>` | Describes a `DatabaseDefinition`'s `indexes` map — table name to its index column groups. |
145
+ | `definitionShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; driver: import("@orkestrel/contract").StringShape; tables: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").ObjectShape<{ columns: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").LiteralShape<readonly ["string", "integer", "number", "boolean"]>, import("@orkestrel/contract").ObjectShape<{ primitive: import("@orkestrel/contract").LiteralShape<readonly ["string", "integer", "number", "boolean"]>; optional: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").BooleanShape>; }, false>]>>; }, false>>; primary: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").StringShape>>; indexes: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>>>; version: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").NumberShape>; }, false>` | Describes a stored `DatabaseDefinition` exactly: the owned record `DatabaseDefinitionStore` reads and writes. |
146
+ | `definitionContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ id: string; driver: string; tables: { readonly [k: string]: Readonly<{ columns: { readonly [k: string]: "boolean" \| "integer" \| "number" \| "string" \| Readonly<{ primitive: "boolean" \| "integer" \| "number" \| "string"; } & { optional?: boolean; }>; }; } & {}>; }; } & { primary?: { readonly [k: string]: string; }; indexes?: { readonly [k: string]: readonly (readonly string[])[]; }; version?: number; }>>` | Holds the compiled `definitionShape`, whose `audit` fills the faults a refused stored definition carries. |
132
147
  | `keyShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").NumberShape]>>, import("@orkestrel/contract").StringShape, import("@orkestrel/contract").NumberShape]>` | Describes one key value for the database tool and the relation tool — a string or number; the array form (multiple keys, positional) resolves first, so an array argument is read as many keys rather than one. |
133
148
  | `rowShape` | const | `import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>` | Describes a loose row — a flat object of column name to JSON value. |
134
149
  | `rowsShape` | const | `import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>` | Describes one or many loose rows — the array form resolves first, so an array argument is read as many rows rather than one. |
@@ -199,7 +214,7 @@ The shape values each `create*Tool` factory (and `createWorkflowDraftContract`)
199
214
  | `WorkflowToolOptions` | interface | `{ lineage?, functions?, agents?, store? }` | Represents the options for `createWorkflowTool` and `createWorkflowFunctions` — lineage-aware composition of opaque leaves, raw agents, and native workflow persistence. |
200
215
  | `WorkspaceToolOptions` | interface | `{ name?, description?, manager?, store? }` | Represents the options for `createWorkspaceTool` — either a caller-built `WorkspaceManagerInterface` to drive directly, or a `WorkspaceStoreInterface` the tool constructs a fresh manager over; neither given constructs a manager over `@orkestrel/workspace`'s in-memory store. |
201
216
  | `WorkspaceOperation` | type | `{ readonly operation: 'read'; readonly path: string; } \| { readonly operation: 'list'; } \| { readonly operation: 'has'; readonly path: string; } \| { readonly operation: 'search'; readonly query: string; readonly regex?: boolean; readonly sensitive?: boolean; readonly limit?: number; } \| { readonly operation: 'replace'; readonly query: string; readonly replacement: string; readonly regex?: boolean; readonly sensitive?: boolean; readonly limit?: number; } \| { readonly operation: 'write'; readonly path: string; readonly content: string; } \| { readonly operation: 'splice'; readonly path: string; readonly content: string; readonly fromLine: number; readonly fromColumn: number; readonly toLine: number; readonly toColumn: number; } \| { readonly operation: 'prepend'; readonly path: string; readonly content: string; } \| { readonly operation: 'append'; readonly path: string; readonly content: string; } \| { readonly operation: 'move'; readonly from: string; readonly to: string; } \| { readonly operation: 'remove'; readonly path: string; } \| { readonly operation: 'workspaces'; } \| { readonly operation: 'switch'; readonly id: string; }` | Represents one operation an agent invokes through `createWorkspaceTool` — a flat, descriptive tagged union over the workspace edit, read, and navigation actions, discriminated by the `operation` literal (a discriminant is named for its axis — the action being performed — never `kind`). |
202
- | `AgentToolOptions` | interface | `{ name?, description?, provider?, tools?, system?, depth?, ancestry?, store? }` | Represents the options for `createAgentTool` — the sub-agent delegation defaults, the nesting-depth / cycle guard bookkeeping, and the advertised tool overrides. |
217
+ | `AgentToolOptions` | interface | `{ name?, description?, provider?, tools?, system?, authority?, depth?, ancestry?, store? }` | Represents the options for `createAgentTool` — the sub-agent delegation defaults, the nesting-depth / cycle guard bookkeeping, and the advertised tool overrides. |
203
218
  | `AgentToolArguments` | interface | `{ task, provider?, tools?, system? }` | Represents the flat args `createAgentTool` accepts — a delegated `task` plus the minimal optional `AgentJobInput` (`@orkestrel/agent`) fields a caller may override per-call. |
204
219
  | `ToolboxErrorCode` | type | `'TOOL' \| 'DEPTH' \| 'DEADLOCK' \| 'EXPIRE' \| 'ANSWER' \| 'DATABASE' \| 'RELATION'` | Represents the machine-readable code a thrown `ToolboxError` carries — a thrown, typed, code-bearing error, never a `{ error }` return. |
205
220
  | `DescribeToolArguments` | interface | `{ name }` | Represents the flat args `createDescribeTool` accepts — the registered tool `name` whose full `description` a model wants back. |
@@ -218,24 +233,27 @@ The shape values each `create*Tool` factory (and `createWorkflowDraftContract`)
218
233
  | `InferToolOptions` | interface | `{ name?, description? }` | Represents the options for `createInferTool` — advertised name and description overrides only; `format` and `enum` are runtime call arguments (see `inferToolShape`), not construction-time options, because a model chooses them per call. |
219
234
  | `EndpointHandler` | type | `(args: Readonly<Record<string, unknown>>, context: ToolContext) => Promise<unknown> \| unknown` | Represents the handler `EndpointDefinition.execute` implements — it mirrors `@orkestrel/tool`'s `ToolOptions.execute` signature exactly, so `createEndpointTool` forwards the execution context it receives to the handler unchanged and a handler that reads `context.signal` observes the caller's cancellation. |
220
235
  | `EndpointDefinition` | interface | `{ name, description, samples, execute }` | Represents one concrete endpoint `createEndpointTool` wraps as an LLM-callable `ToolInterface` — the advertised identity, a non-empty set of example values its `parameters` are inferred from, and the local handler that runs a call. |
221
- | `EndpointToolOptions` | interface | `{ format?, enum?, validate? }` | Represents the construction-time tuning for `createEndpointTool` — the inferred `parameters` schema's `format` and `enum` constraints, and whether that same schema is enforced at `execute` time. |
236
+ | `EndpointToolOptions` | interface | `{ format?, enum?, strict? }` | Represents the construction-time tuning for `createEndpointTool` — the inferred `parameters` schema's `format` and `enum` constraints, and whether that same schema is enforced at `execute` time. |
222
237
 
223
238
  ### Server routes
224
239
 
225
240
  The wire bridge for a `TerminalManagerInterface` — a GET SSE stream and a POST answer endpoint, both mounted on the same `:name`-templated path, returned as plain structural records carrying no dependency on `@orkestrel/router`'s own `Route` type ([`src/server`](../src/server), surfaced through `@src/server`).
226
241
 
227
- The POST endpoint takes `{ id, values }`, admits the body only when `id` is a nonempty string and `values` passes `@orkestrel/form`'s `isFormValues`, and returns the manager's own answer `Result` as a JSON body — `200` accepted, `422` an `'unknown'` / `'rejected'` outcome, `404` a `'target'` outcome. The body is what carries a rejection's per-field `errors` back to the answering client, so `PromptClient` can re-render the failed fields instead of guessing from a status code.
242
+ Construction refuses with a `TOOL` `ToolboxError` when `token` is missing or is neither a nonempty string nor a function, when `keepalive` is not a positive finite number, and when `limit` is not a positive safe integer. `token: () => true` is the explicit open, so routes never open by accident.
228
243
 
229
- | Name | Kind | Signature | Summary |
230
- | ----------------------- | --------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
231
- | `createTerminalRoutes` | function | `(manager: TerminalManagerInterface, options?: TerminalRoutesOptions) => readonly TerminalRoute[]` | Builds the GET SSE stream and POST answer routes that bridge a terminal manager onto the wire. |
232
- | `TerminalRouteMethod` | type | `'GET' \| 'POST' \| 'PUT' \| 'PATCH' \| 'DELETE' \| 'HEAD' \| 'OPTIONS'` | Represents the HTTP method literal a `TerminalRoute` declares — the same union `@orkestrel/router`'s `Method` type accepts. |
233
- | `TerminalRouteContext` | interface | `{ params }` | Represents the minimal route-dispatch context a `TerminalRoute` handler reads — exactly the frozen, URL-decoded `:name` path param slice a router hands a matched handler. |
234
- | `TerminalRoute` | interface | `{ method, path, handler }` | Represents one structural route record `createTerminalRoutes` returns — a plain `{ method, path, handler }` shape carrying no dependency on `@orkestrel/router`'s own `Route` type, so a consumer mounts it against any router that accepts a two-arg `(request, context) => Response \| Promise<Response>` handler keyed by `method` and `path`. |
235
- | `TerminalRoutesOptions` | interface | `{ path?, token?, keepalive?, timer?, limit? }` | Represents the options `createTerminalRoutes` takes — the shared route, authorization, keepalive, timer, and body-limit configuration both routes read. |
236
- | `TerminalToken` | type | `string \| ((value: string \| undefined) => boolean)` | Represents the `token` gate `TerminalRoutesOptions` may configure — a plain string compared for equality against the `x-orkestrel-token` header, or a validator function the consumer fully controls, enabling the expiry and rotation a fixed string cannot express (a JWT `exp` check, a revocation-list lookup, anything time-varying). `undefined` disables the auth check entirely. |
237
- | `TERMINAL_ROUTES_PATH` | const | `"/terminals/:name"` | Holds the default `:name`-templated path `createTerminalRoutes` mounts its GET (SSE) and POST (answer) routes under, `/terminals/:name`. |
238
- | `TERMINAL_KEEPALIVE_MS` | const | `15000` | Holds the default SSE keepalive interval `createTerminalRoutes` arms per open connection, `15_000` ms — a `:` comment ping a conforming SSE parser ignores, keeping intermediary proxies from timing out an otherwise-idle stream. |
244
+ The POST endpoint takes `{ id, values }` and holds the body exactly to `terminalAnswerShape`, as sent and with no leaf repair, then holds `values` to `@orkestrel/form`'s `isFormValues`. A refused body answers `422` with `{ success: false, error: { reason: 'malformed', message, faults } }`, whose `message` says what to send. An accepted body returns the manager's own answer `Result` as a JSON body — `200` accepted, `422` an `'unknown'` / `'rejected'` outcome, `404` a `'target'` outcome. The body is what carries a rejection's per-field `errors` back to the answering client, so `PromptClient` can re-render the failed fields instead of guessing from a status code.
245
+
246
+ | Name | Kind | Signature | Summary |
247
+ | ----------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
248
+ | `createTerminalRoutes` | function | `(manager: TerminalManagerInterface, options: TerminalRoutesOptions) => readonly TerminalRoute[]` | Builds the GET SSE stream and POST answer routes that bridge a terminal manager onto the wire. |
249
+ | `TerminalRouteMethod` | type | `'GET' \| 'POST' \| 'PUT' \| 'PATCH' \| 'DELETE' \| 'HEAD' \| 'OPTIONS'` | Represents the HTTP method literal a `TerminalRoute` declares — the same union `@orkestrel/router`'s `Method` type accepts. |
250
+ | `TerminalRouteContext` | interface | `{ params }` | Represents the minimal route-dispatch context a `TerminalRoute` handler reads — exactly the frozen, URL-decoded `:name` path param slice a router hands a matched handler. |
251
+ | `TerminalRoute` | interface | `{ method, path, handler }` | Represents one structural route record `createTerminalRoutes` returns — a plain `{ method, path, handler }` shape carrying no dependency on `@orkestrel/router`'s own `Route` type, so a consumer mounts it against any router that accepts a two-arg `(request, context) => Response \| Promise<Response>` handler keyed by `method` and `path`. |
252
+ | `TerminalRoutesOptions` | interface | `{ path?, token, keepalive?, timer?, limit? }` | Represents the options `createTerminalRoutes` takes — the shared route, authorization, keepalive, timer, and body-limit configuration both routes read. |
253
+ | `TerminalToken` | type | `string \| ((value: string \| undefined) => boolean)` | Represents the `token` gate `TerminalRoutesOptions` requires — a plain string compared for equality against the `x-orkestrel-token` header, or a validator function the consumer fully controls, enabling the expiry and rotation a fixed string cannot express (a JWT `exp` check, a revocation-list lookup, anything time-varying). The explicit open is the validator `() => true`. |
254
+ | `terminalAnswerShape` | const | `import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; values: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, false>` | Describes the body a terminal POST route admits — the pending form's `id` and its answers. |
255
+ | `TERMINAL_ROUTES_PATH` | const | `"/terminals/:name"` | Holds the default `:name`-templated path `createTerminalRoutes` mounts its GET (SSE) and POST (answer) routes under, `/terminals/:name`. |
256
+ | `TERMINAL_KEEPALIVE_MS` | const | `15000` | Holds the default SSE keepalive interval `createTerminalRoutes` arms per open connection, `15_000` ms — a `:` comment ping a conforming SSE parser ignores, keeping intermediary proxies from timing out an otherwise-idle stream. |
239
257
 
240
258
  > A reconnecting SSE client replays every pending form from the top on every (re)connect (the GET handler's replay loop), so a raw `EventSource` (or any hand-rolled consumer that isn't `PromptClient`) must dedupe `pending` frames by their SSE `id` — the same form id may arrive more than once across a reconnect. `PromptClient` (`@orkestrel/terminal`) already does this; a consumer bypassing it does not get the dedupe for free.
241
259
  >
@@ -247,11 +265,11 @@ Every `create*Tool` factory returns a plain `ToolInterface` (`@orkestrel/tool`'s
247
265
 
248
266
  #### `DefinitionStoreInterface`
249
267
 
250
- | Method | Returns | Summary |
251
- | -------- | ------------------------------------------ | ------------------------------------------------------------------------------------ |
252
- | `get` | `Promise<DatabaseDefinition \| undefined>` | Resolves the persisted definition for `id`, or `undefined` when none is stored. |
253
- | `set` | `Promise<void>` | Inserts or replaces a definition under its own `id`, taking no separate id argument. |
254
- | `delete` | `Promise<void>` | Drops the definition for `id`, treating an absent id as a no-op that never throws. |
268
+ | Method | Returns | Summary |
269
+ | -------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
270
+ | `get` | `Promise<DatabaseDefinition \| undefined>` | Resolves the persisted definition for `id`, or `undefined` when none is stored; a present row an implementation cannot read as a definition throws. |
271
+ | `set` | `Promise<void>` | Inserts or replaces a definition under its own `id`, taking no separate id argument. |
272
+ | `delete` | `Promise<void>` | Drops the definition for `id`, treating an absent id as a no-op that never throws. |
255
273
 
256
274
  #### `MemoryDefinitionStore`
257
275
 
@@ -306,51 +324,51 @@ These invariants hold across `src/core` ↔ `toolbox.md`:
306
324
 
307
325
  1. **doc ↔ source bijection.** Every `function` / `class` / `const` / `interface` / `type` row in the `## Surface` tables is a real export of `src/core`, and every export appears as a Surface row — exhaustive, both directions under AGENTS' documentation contract.
308
326
 
309
- 2. **One tool = one behavior; the runtime supplies the envelope, this package supplies the handler.** Each `create*Tool` factory returns a plain `ToolInterface` (`@orkestrel/tool`). Under AGENTS' narrow-untrusted-input-with-guards rule, its handler parses the model-supplied `args` against a compiled [contract](contract.md), dispatches, and either returns a plain value on success or throws a typed error on every failure path — it never builds a `ToolResult` itself. The runtime supplies registry execution and result isolation; see [`tool.md`](tool.md). Through that registry, a failure's flattened message text appears exactly once, identically, over both the agent loop and MCP.
327
+ 2. **One tool = one behavior; the runtime supplies the envelope, this package supplies the handler.** Each `create*Tool` factory returns a plain `ToolInterface` (`@orkestrel/tool`). Under AGENTS' narrow-untrusted-input-with-guards rule, malformed model-supplied `args` refuse before the handler acts, as a `ToolError` with code `ARGUMENTS` whose text says what to send and whose `context.faults` lists every fault (see [`tool.md`](tool.md)). The handler reads a typed value from the compiled [contract](contract.md), dispatches, and either returns a plain value on success or throws a typed error on every failure path — it never builds a `ToolResult` itself. Every refusal a model can read names the subject, what to send, and the candidates where there are some, encodes each untrusted identifier and candidate through `preview` (`renderCandidates`), and stays within 2048 characters: where a message joins parts this package cannot bound one by one, a head beside a report or an upstream error's text, `limitRefusal` caps the whole. A `WorkspaceError`, `WorkflowError`, or `AgentError` that passes through by identity carries its owner's text. The runtime supplies registry execution and result isolation; see [`tool.md`](tool.md). Through that registry, a failure's flattened message text appears exactly once, identically, over both the agent loop and MCP.
310
328
 
311
- 3. **Contract-compiled schemas throughout.** Every advertised `parameters` is `schemaToParameters(contract.schema)` off a `createContract`-compiled shape (`workflowStepsShape` / `workflowDraftShape` / `workspaceToolShape` / `agentToolShape`) — never a hand-written JSON Schema — so the guard / parser / schema the handler validates against can never drift from what the tool advertises.
329
+ 3. **Contract-compiled schemas throughout.** The workspace, answer, database, relation, agent, describe, prompt, and infer tools pass their shapes through `contract`, so the Tool door enforces the advertised schema. A union value selecting one operation reports that arm's faults and admits lossless leaf repairs: `find` with `limit: '5'` reaches the handler as `5`, while `'many'` names `limit` and `'0x10'` refuses. A value selecting no arm receives a bounded summary of alternatives. Handlers use `requireToolCall` to type the parsed arguments. The workflow tool advertises its flat schema through `parameters` and uses `strict: false` because its handler accepts several authoring forms; `resolveWorkflowTarget` applies the matching contract through `requireToolCall`.
312
330
 
313
331
  4. **Workflow/agent recursion is lineage-derived and contextually composed.** `WorkflowLineage` is a copied, frozen chain of nonempty unique tags, strictly alternating `workflow:` then `agent:`. Malformed configured lineage or a factory-incompatible final tag throws `ToolboxError('TOOL')`; runtime workflow mismatch, repeated workflow/agent id, or over-depth target throws `ToolboxError('DEPTH')` before agent, tool, or runner activity. Depth is zero-based and derived only from workflow-tag count minus one (empty/root is `0`): root plus eight nested workflows is allowed, the ninth nested workflow is rejected. `createWorkflowFunctions` is the sole composition engine: it snapshots opaque `functions`, rejects a marked `AgentFunction` supplied through that opaque channel, rejects function/agent key collisions, and contextually adapts raw `agents` for the exact target lineage. Its frozen registry has a null prototype, so the workflow runner's native bracket lookup cannot resolve unregistered inherited names such as `toString`, `constructor`, `valueOf`, `hasOwnProperty`, or `__proto__`; those remain genuine native `WorkflowError('TRANSITION')` failures. Opaque wrappers or spoofed metadata that hide their real agent behavior are not covered; hosts must not use them to share one live agent concurrently.
314
332
 
315
- 5. **`createWorkflowTool` widens the authoring surface additively; the strict contract stays the soundness gate.** It advertises the simple flat shape (`{ name?, steps: [{ name }] }`) as its `parameters` so a small model can author a whole tree in one call, but its handler accepts empty args (the wrapped `definition`), a `steps` array (the flat form, `expandSteps`'d), or a nested draft/full definition (`createWorkflowDraftContract`-parsed and `completeDraft`'d, or accepted as-is when already strict) — and every path converges on the byte-for-byte-unchanged `createWorkflowContract().is` gate before it runs. A blob that fails to parse, expand, or complete, or whose result fails that strict gate, throws a `TOOL` `ToolboxError`; the leniency never reaches the runner. An omitted task `behavior` is the native JSON-`null` no-op. A present unresolved name reaches the runner and is rejected by the native drivability gate as a genuine `WorkflowError('TRANSITION')`; Toolbox does not duplicate that preflight.
333
+ 5. **`createWorkflowTool` widens the authoring surface additively; the strict contract stays the soundness gate.** It advertises the simple flat shape (`{ name?, steps: [{ name }] }`) as its `parameters` so a small model can author a whole tree in one call, but its handler accepts empty args (the wrapped `definition`), a `steps` array (the flat form, `expandSteps`'d), or a nested draft/full definition (`createWorkflowDraftContract`-parsed and `completeDraft`'d, or accepted as-is when already strict) — and every path converges on the byte-for-byte-unchanged `createWorkflowContract().is` gate before it runs. `parameters` advertises the flat form alone, so the tool is built `strict: false` and `resolveWorkflowTarget` runs the door on the form the args take: a `phases` key with no `steps` key is the draft form, and everything else is the flat form, so a blob carrying both refuses `phases` as undeclared and a blob carrying neither is told to send `steps`. A refused form throws a `ToolError` with code `ARGUMENTS` naming each fault, including an undeclared key at any depth and a `timeout` or `concurrency` outside what the strict contract admits, whose draft bounds match it; a wrapped definition that fails the strict gate throws a `TOOL` `ToolboxError`; the leniency never reaches the runner. A target with no task reaches the runner, which rejects it as a genuine `WorkflowError('SCHEDULE')`, so a standalone tool wrapping `phases: []` needs authored args. An omitted task `behavior` is the native JSON-`null` no-op. A present unresolved name reaches the runner and is rejected by the native drivability gate as a genuine `WorkflowError('TRANSITION')`; Toolbox does not duplicate that preflight.
316
334
 
317
- Before shape branching or property reads, the handler snapshots untrusted `args` through Contract's `attempt` and `cloneJSONRecord`; hostile traversal or inexact JSON becomes `ToolboxError('TOOL', 'malformed workflow definition', ...)` before runner functions or persistence begin, never a raw Proxy/Contract error. A standalone `createWorkflowTool` called with empty args runs its wrapped definition. The tool bound onto an agent deliberately wraps the containing workflow id, so its empty-args call is a repeated-lineage cycle and throws `ToolboxError('DEPTH')`; a bound nested call must author a new target rather than receive an invented id.
335
+ Before shape branching or property reads, the handler snapshots untrusted `args` through Contract's `attempt` and `cloneJSONRecord`; hostile traversal or inexact JSON becomes a `ToolError` with code `ARGUMENTS` that shows the flat form before runner functions or persistence begin, never a raw Proxy/Contract error. A standalone `createWorkflowTool` called with empty args runs its wrapped definition. The tool bound onto an agent deliberately wraps the containing workflow id over no phases, so its empty-args call is a repeated-lineage cycle and throws `ToolboxError('DEPTH')` before the runner, and those phases never run; a bound nested call must author a new target rather than receive an invented id. An agent that runs a bound workflow tool needs an `authority` of its own, because an agent with none denies every tool call.
318
336
 
319
337
  6. **`createWorkflowTool` delegates composition and persistence without inventing identity.** Configured lineage/functions/agents registries are copied at construction. At invocation the strict target tag is appended, repeated ids and over-depth are rejected, and `createWorkflowFunctions` builds the contextual registry only when functions or agents were supplied. The resulting registry and optional store are forwarded to `runner.execute(target, { functions?, store? })`. The runner owns initial/attempt/settlement/final checkpoints, coalescing, restore-ready final snapshots, and persistence failures as data. `WorkflowToolResult` projects `{ status, count, durable?, fault? }`: `durable`/`fault` appear exactly when the native result supplies them. A flat authoring `name` is the deterministic workflow id; repeated runs with the same name address and replace the same store snapshot rather than minting a hidden id.
320
338
 
321
- 7. **`createWorkspaceTool` is manager-driven, with a no-active ergonomic seam.** `options.manager` (drive directly) takes priority over `options.store` (build a fresh manager over it through `@orkestrel/workspace`'s `createWorkspaceManager`); neither given constructs a manager over `@orkestrel/workspace`'s in-memory default. The `store` slot deliberately diverges from invariant 6: the workspace tool's `store` only backs the constructed manager's `open` / `save` — the tool's edits are not auto-persisted (durability requires an explicit caller `save`), whereas the workflow tool forwards its store to native run-wide checkpoint persistence. Every edit / read arm targets `manager.active` — never a specific workspace by id directly — so a host repoints which workspace the model edits through the registry arms (`workspaces` lists them, `switch` re-points `active`, lenient on an unknown id). A writing arm (write / splice / prepend / append / move / remove / replace) run with no active workspace auto-creates and activates one (`manager.add()`); a pure-read arm (read / list / has / search) against no active workspace returns the empty result, never creating one and never throwing. `search` / `replace` pass the workspace vocabulary through unchanged: `regex` chooses pattern-vs-literal matching, `sensitive` controls case sensitivity, and `limit` caps occurrences; `replace` returns the dependency's own `ReplaceResult` directly as `{ occurrences, files }`.
339
+ 7. **`createWorkspaceTool` is manager-driven, with a no-active ergonomic seam.** `options.manager` (drive directly) takes priority over `options.store` (build a fresh manager over it through `@orkestrel/workspace`'s `createWorkspaceManager`); neither given constructs a manager over `@orkestrel/workspace`'s in-memory default. The `store` slot deliberately diverges from invariant 6: the workspace tool's `store` only backs the constructed manager's `open` / `save` — the tool's edits are not auto-persisted (durability requires an explicit caller `save`), whereas the workflow tool forwards its store to native run-wide checkpoint persistence. Every edit / read arm targets `manager.active` — never a specific workspace by id directly — so a host repoints which workspace the model edits through the registry arms (`workspaces` lists them, `switch` re-points `active`, lenient on an unknown id). An arm that can create the file it names (write / prepend / append) run with no active workspace auto-creates and activates one (`manager.add()`); an arm that edits a file that must already exist (splice / move / remove / replace) refuses with a `TOOL` `ToolboxError` that says what to call and creates none; a pure-read arm (read / list / has / search) against no active workspace returns the empty result, never creating one and never throwing. `read` returns `null` for a path that holds no text, because JSON tells that from an empty file. `path`, `query`, `from`, and `to` are nonempty; an empty `replacement` is a deletion. `search` / `replace` pass the workspace vocabulary through unchanged: `regex` chooses pattern-vs-literal matching, `sensitive` controls case sensitivity, and `limit` caps occurrences; `replace` returns the dependency's own `ReplaceResult` directly as `{ occurrences, files }`.
322
340
 
323
341
  8. **`createAgentTool` carries its own `store` slot, composable with a registry-level store.** `AgentToolOptions.store` is an optional `ConversationStoreInterface` (`@orkestrel/agent`): when supplied, the handler `await`s `store.set(agent.context.conversations.active.snapshot())` after `agent.generate()` settles successfully, before returning — one snapshot per delegation (each `registry.build` mints a fresh conversation id through its seeded `add`, so a shared store never collides, it accumulates one snapshot per delegated call). A `store.set` failure propagates as the tool call's own failure (isolated by `ToolManagerInterface` into the canonical `error`, per invariant 2) — persistence is not best-effort. Omitted, the handler persists nothing from this tool. This composes with, and is independent of, `AgentRegistryOptions.store` (`@orkestrel/agent`): a registry built with its own `store` backs every agent it builds with a store-backed `ConversationManagerInterface`, including ones built through this tool — a caller may use either seam alone or both together.
324
342
 
325
343
  9. **A delegated sub-agent's lifecycle is a single `generate()` call.** `createAgentTool`'s handler resolves a live agent through `registry.build`, awaits one `agent.generate()`, and returns its settled `content` — `AgentInterface` (`@orkestrel/agent`) exposes no teardown method, so there is nothing to release afterwards; the agent's state lives entirely in the resolved `AgentContextInterface`, owned by the caller's registry.
326
344
 
327
- 10. **Provider-agnostic delegation.** `createAgentTool` never imports or references a concrete `ProviderInterface` implementation — `options.provider` / a per-call `call.provider` is a registry key resolved by `registry.build`, so swapping the provider behind that key changes nothing about the tool. A missing / unresolvable provider (neither the call nor the tool's own default supplies one) throws a `TOOL` `ToolboxError` before any agent is built.
345
+ 10. **Provider-agnostic delegation.** `createAgentTool` never imports or references a concrete `ProviderInterface` implementation — `options.provider` / a per-call `call.provider` is a registry key resolved by `registry.build`, so swapping the provider behind that key changes nothing about the tool. A missing / unresolvable provider (neither the call nor the tool's own default supplies one) throws a `TOOL` `ToolboxError` before any agent is built. `options.authority` is the registry key of the authority that decides the sub-agent's tool calls, a host's choice the model cannot send; tools named with no `authority`, per-call or defaulted from `options.tools`, throw a `TOOL` `ToolboxError` before any agent is built, because an agent with tools needs one, and its text says to send `tools: []` or have the host set `authority`. A `depth` that is not a nonnegative safe integer throws `TOOL` at construction.
328
346
 
329
- 11. **`ToolboxError` owns Toolbox boundary failures; upstream errors own genuine domain failures.** It carries a machine-readable `ToolboxErrorCode` and an optional `context` and is always thrown, never returned as `{ error }`: `TOOL` covers malformed authoring, missing tool bindings, invalid tool/agent JSON, and the other package-owned resolution/configuration guards; `DEPTH` covers Toolbox workflow/agent nesting refusal; the remaining codes retain their terminal/database/relation meanings. A genuine error thrown by an executed tool passes through unchanged. The native workflow runner's genuine `WorkflowError` also passes through unchanged, including `TRANSITION` for an unresolved named run; Toolbox never invents invalid workflow `TOOL`/`DEPTH` codes and never relabels runner errors. `WorkspaceError` similarly retains its upstream domain ownership. An in-process direct call can inspect typed codes/context; `ToolManagerInterface.execute` flattens the error to its message.
347
+ 11. **`ToolboxError` owns Toolbox boundary failures; upstream errors own genuine domain failures.** It carries a machine-readable `ToolboxErrorCode` and an optional `context` and is always thrown, never returned as `{ error }`: `TOOL` covers missing tool bindings, invalid tool/agent JSON, a wrapped workflow the strict contract refuses, and the other package-owned resolution/configuration guards, while malformed call arguments are `@orkestrel/tool`'s `ToolError` with code `ARGUMENTS`; `DEPTH` covers Toolbox workflow/agent nesting refusal; the remaining codes retain their terminal/database/relation meanings. A genuine error thrown by an executed tool passes through unchanged. The native workflow runner's genuine `WorkflowError` also passes through unchanged, including `TRANSITION` for an unresolved named run; Toolbox never invents invalid workflow `TOOL`/`DEPTH` codes and never relabels runner errors. `WorkspaceError` similarly retains its upstream domain ownership. An in-process direct call can inspect typed codes/context; `ToolManagerInterface.execute` flattens the error to its message.
330
348
 
331
- 12. **The workflow-function adapters are opt-in and exact at the JSON boundary.** `createToolFunction(tools, name)` resolves the live tool, awaits `tool.execute(controller.input, { signal: controller.signal })` — the execution context carries the running task's own cancellation, so a handler that reads `context.signal` observes the run's cancellation rather than an uncancellable stand-in — then deep-gates the unknown return through `parseJSONValue`; a missing binding or non-JSON result throws `ToolboxError('TOOL')`, while a genuine tool throw passes through by identity. It rejects `name === WORKFLOW_TOOL_NAME` at construction so the reserved live workflow tool cannot be adapted back into a workflow registry. `createAgentFunction(agent, options?)` returns a frozen `AgentFunction` with frozen category/lineage metadata. It starts `agent.generate({ signal: controller.signal })` synchronously after any runner-bound tool installation, using Agent's native per-run cancellation seam: an already-aborted signal starts no provider call, and cancellation settles as a partial result. The full `AgentResult` is projected through Agent-owned `agentResultToJSON`; malformed structural results become `ToolboxError('TOOL')`. With a runner, an already-running real agent is rejected before its workflow-tool binding can be replaced, so another Toolbox branch observes the running state. Genuine agent/provider errors retain identity.
349
+ 12. **The workflow-function adapters are opt-in and exact at the JSON boundary.** `createToolFunction(tools, name)` resolves the live tool, awaits `tool.execute(controller.input, { signal: controller.signal })` — the execution context carries the running task's own cancellation, so a handler that reads `context.signal` observes the run's cancellation rather than an uncancellable stand-in — then deep-gates the unknown return through `parseJSONValue`; a missing binding or non-JSON result throws `ToolboxError('TOOL')`, while a genuine tool throw passes through by identity, so a task input the tool does not declare surfaces as the tool door's `ToolError`. It rejects `name === WORKFLOW_TOOL_NAME` at construction so the reserved live workflow tool cannot be adapted back into a workflow registry. `createAgentFunction(agent, options?)` returns a frozen `AgentFunction` with frozen category/lineage metadata. It starts `agent.generate({ signal: controller.signal })` synchronously after any runner-bound tool installation, using Agent's native per-run cancellation seam: an already-aborted signal starts no provider call, and cancellation settles as a partial result. The full `AgentResult` is projected through Agent-owned `agentResultToJSON`; malformed structural results become `ToolboxError('TOOL')`. With a runner, an already-running real agent is rejected before its workflow-tool binding can be replaced, so another Toolbox branch observes the running state. Genuine agent/provider errors retain identity.
332
350
 
333
- 13. **The lean `summary` / full `description` split, and `createDescribeTool`'s expansion seam.** `createWorkflowTool`, `createWorkspaceTool`, and `createAgentTool` each set `ToolInterface.summary` (`@orkestrel/tool`) to a frozen one-sentence constant (`WORKFLOW_TOOL_SUMMARY` / `WORKSPACE_TOOL_SUMMARY` / `AGENT_TOOL_SUMMARY`) alongside their unchanged full teaching `description`; `ToolManagerInterface.definitions()` advertises `summary ?? description`, so a model sees the lean text by default. `createDescribeTool(tools)` is the on-demand expansion: given a registered `name`, it looks the tool up through `tools.tool(name)` and returns its full `tool.description` (falling back to `tool.summary`, then a placeholder, when a tool has neither) — never truncated, never re-derived. Each summary's text points the model at `describe('<name>')` for the full schema.
351
+ 13. **The lean `summary` / full `description` split, and `createDescribeTool`'s expansion seam.** `createWorkflowTool`, `createWorkspaceTool`, and `createAgentTool` each set `ToolInterface.summary` (`@orkestrel/tool`) to a frozen one-sentence constant (`WORKFLOW_TOOL_SUMMARY` / `WORKSPACE_TOOL_SUMMARY` / `AGENT_TOOL_SUMMARY`) alongside their unchanged full teaching `description`; `ToolManagerInterface.definitions()` advertises `summary ?? description`, so a model sees the lean text by default. `createDescribeTool(tools)` is the on-demand expansion: given a registered `name`, it looks the tool up through `tools.tool(name)` and returns its full `tool.description` (falling back to `tool.summary`, then an explicit `null` when a tool has neither) — never truncated, never re-derived. An unknown `name` lists the registered names. Each summary's text points the model at `describe('<name>')` for the full schema.
334
352
 
335
- 14. **`createDatabaseTool` and `createRelationTool` are single-tool-many-operations, matching `createWorkspaceTool`'s shape.** `createDatabaseTool` dispatches `create` / `tables` / `get` / `records` / `count` / `aggregate` / `add` / `set` / `update` / `remove` / `destroy` off `databaseToolShape`; `createRelationTool` dispatches `load` / `find` / `link` / `unlink` / `links` off `relationToolShape`. Both set `ToolInterface.summary` (`DATABASE_TOOL_SUMMARY` / `RELATION_TOOL_SUMMARY`) alongside their full teaching `description`, retrievable through `createDescribeTool`, per invariant 13. Every `'get'` / `'add'` / `'set'` / `'update'` / `'remove'` and `'load'` operation's `key` field takes either a single key or an array of keys (AGENTS' batch overload mold, with the array form resolving first); a single-key call returns a singular result field (`row` / `key` / `updated` / `removed`), an array-key call returns the plural (`rows` / `keys` / `updated` / `removed` as arrays).
353
+ 14. **`createDatabaseTool` and `createRelationTool` are single-tool-many-operations, matching `createWorkspaceTool`'s shape.** `createDatabaseTool` dispatches `create` / `tables` / `get` / `records` / `count` / `aggregate` / `add` / `set` / `update` / `remove` / `destroy` off `databaseToolShape`; `createRelationTool` dispatches `load` / `find` / `link` / `unlink` / `links` off `relationToolShape`. Both set `ToolInterface.summary` (`DATABASE_TOOL_SUMMARY` / `RELATION_TOOL_SUMMARY`) alongside their full teaching `description`, retrievable through `createDescribeTool`, per invariant 13. Every `'get'` / `'add'` / `'set'` / `'update'` / `'remove'` and `'load'` operation's `key` field takes either a single key or an array of keys (AGENTS' batch overload mold, with the array form resolving first); a single-key call returns a singular result field (`row` / `key` / `updated` / `removed`), an array-key call returns the plural (`rows` / `keys` / `updated` / `removed` as arrays). A row a `'get'` or `'load'` misses is an explicit `null` in either form, where JSON would otherwise drop the key.
336
354
 
337
355
  15. **The database tool's query form is serialized, never fluent.** `databaseToolShape`'s `query` is a flat object — `{ conditions?: [{ column, operator, values, connector? }], order?, limit?, offset? }` — where `values` is always an array, even for a single-value operator (`{ column: 'age', operator: 'from', values: [18] }`), so a small model never chains method calls or guesses arity. `normalizeQuery` normalizes the parsed form into a live `@orkestrel/database` `QueryInput`, defaulting an omitted condition `connector` to `'and'` (the wire form lets a caller drop `connector` on the last condition, because it joins nothing forward).
338
356
 
339
357
  16. **The `TableSpec` column DSL is bounded to the primitives `'string'` / `'integer'` / `'number'` / `'boolean'`.** A `ColumnSpec` is either a bare `ColumnPrimitive` shorthand or `{ primitive, optional? }`; `expandTables` compiles a `TableSpec` into the `@orkestrel/database` `TableMap` `createDatabase` accepts through `compileColumn` / `compileColumnPrimitive`, wrapping an `optional: true` column in `optionalShape`. There is no nested/composite column primitive — a table's shape is a flat map of column name to `ColumnSpec`, never an object/array column.
340
358
 
341
- 17. **`'records'` / `'find'` / `'links'` truncate against a configured cap, never silently.** `createDatabaseTool`'s `'records'` (cap: `DatabaseToolOptions.limit`, default `DATABASE_TOOL_LIMIT`) and `createRelationTool`'s `'find'` / `'links'` (cap: `RelationToolOptions.limit`, default `RELATION_TOOL_LIMIT`) each probe one row past the effective limit (`clampQuery` for the database tool; `resolveLimit` plus the same probe for `'find'`) to detect truncation without a separate count round trip, returning `{ rows, count, truncated, limit }` (`'links'`: `{ keys, count, truncated, limit }`) — `truncated` is `true` exactly when storage held more than `limit` matching rows/keys. A caller's own `query.limit` / `limit` can only lower the effective cap, never raise it past the configured ceiling.
359
+ 17. **`'records'` / `'find'` / `'links'` truncate against a configured cap, never silently.** `createDatabaseTool`'s `'records'` (cap: `DatabaseToolOptions.limit`, default `DATABASE_TOOL_LIMIT`) and `createRelationTool`'s `'find'` / `'links'` (cap: `RelationToolOptions.limit`, default `RELATION_TOOL_LIMIT`) each probe one row past the effective limit (`clampQuery` for the database tool; `resolveLimit` plus the same probe for `'find'`) to detect truncation without a separate count round trip, returning `{ rows, count, truncated, limit }` (`'links'`: `{ keys, count, truncated, limit }`) — `truncated` is `true` exactly when storage held more than `limit` matching rows/keys. A caller's own `query.limit` / `limit` can only lower the effective cap, never raise it past the configured ceiling. A configured `limit` that is not a positive safe integer throws `TOOL` at construction (`resolveBound`), because `NaN` as a bound passes every comparison.
342
360
 
343
- 18. **A typed upstream failure re-surfaces in-process as a typed `ToolboxError`, never passes through raw.** `createDatabaseTool` catches a `@orkestrel/database` `DatabaseError` and re-throws a typed `DATABASE` `ToolboxError` carrying the original `DatabaseErrorCode` in `context.code` (`inferDatabaseCode`); `createRelationTool` does the same for a `@orkestrel/relation` `RelationError` → `RELATION` (`inferRelationCode`, checked first) and, underneath it, a `DatabaseError` → `DATABASE` (mirroring the database tool's own mapping) — so an in-process catch or direct `tool.execute(args, context)` call sees exactly one of `TOOL` (this tool's own guards: malformed args, unknown manager/model/database/driver), `RELATION`, or `DATABASE`, never an unwrapped upstream error. A `ToolboxError` already thrown by this tool's own guards passes through unwrapped (never re-mapped a second time). A `ToolManagerInterface.execute` registry caller does not receive that code or context; it receives only the flattened message string.
361
+ 18. **A typed upstream failure re-surfaces in-process as a typed `ToolboxError`, never passes through raw.** `createDatabaseTool` catches a `@orkestrel/database` `DatabaseError` and re-throws a typed `DATABASE` `ToolboxError` carrying the original `DatabaseErrorCode` in `context.code` (`inferDatabaseCode`); `createRelationTool` does the same for a `@orkestrel/relation` `RelationError` → `RELATION` (`inferRelationCode`, checked first) and, underneath it, a `DatabaseError` → `DATABASE` (mirroring the database tool's own mapping) — so an in-process catch or direct `tool.execute(args, context)` call sees exactly one of `TOOL` (this tool's own guards: unknown manager/model/database/driver), `RELATION`, or `DATABASE`, never an unwrapped upstream error, beside the `ToolError` with code `ARGUMENTS` that malformed args throw before any of it. A `ToolboxError` already thrown by this tool's own guards passes through unwrapped (never re-mapped a second time). A `ToolManagerInterface.execute` registry caller does not receive that code or context; it receives only the flattened message string.
344
362
 
345
363
  19. **`DatabaseToolOptions.readonly` gates every mutating operation up front.** When `true`, `createDatabaseTool` throws a typed `TOOL` `ToolboxError` for `'create'` / `'add'` / `'set'` / `'update'` / `'remove'` / `'destroy'` before resolving a database or touching storage — the non-mutating operations (`'tables'` / `'get'` / `'records'` / `'count'` / `'aggregate'`) are unaffected. The exported `DATABASE_TOOL_MUTATIONS` membership list is a runtime-frozen readonly array, so a consumer cannot mutate it to bypass this gate. There is no equivalent gate on `createRelationTool` — its `'link'` / `'unlink'` writes are ungated (relation-tool callers rely on the underlying database's own access controls, if any).
346
364
 
347
- 20. **A `DatabaseDefinition` is config-only and round-trips through a `DefinitionStoreInterface` — never a live handle.** `createDatabaseTool`'s `'create'` persists `{ id, driver, tables, primary?, indexes?, version? }` (never the constructed `DatabaseInterface`) when `options.store` is supplied, and publishes the new live handle to its resolver only after persistence succeeds. Every other operation lazily `resolve`s an uncached id by reading the definition back and reconstructing a live database from it (`createDatabase` and `expandTables`) — the live handle itself is cached only in-process (`Map<string, DatabaseInterface>`), reconstructed fresh on the next process from the stored config. `primary` and `indexes` are paired schema metadata, while `version` is the target stamp a versioning driver writes after first use when it implements paired `metadata` / `stamp` capabilities. `isDatabaseDefinition` is the boundary guard a `DefinitionStoreInterface` applies to an untrusted persisted blob before trusting it. `MemoryDefinitionStore` structured-clones definitions on copy-in and copy-out; `DatabaseDefinitionStore` stores one opaque JSON column in a `@orkestrel/database` table and narrows it back with `isDatabaseDefinition` on read, reporting `undefined` for a malformed blob. They implement the same `get` / `set` / `delete` contract; only the memory store prevents caller mutation from aliasing stored state on its own, because the table-backed store's isolation follows from its driver.
365
+ 20. **A `DatabaseDefinition` is config-only and round-trips through a `DefinitionStoreInterface` — never a live handle.** `createDatabaseTool`'s `'create'` persists `{ id, driver, tables, primary?, indexes?, version? }` (never the constructed `DatabaseInterface`) when `options.store` is supplied, and publishes the new live handle to its resolver only after persistence succeeds. Every other operation lazily `resolve`s an uncached id by reading the definition back and reconstructing a live database from it (`createDatabase` and `expandTables`) — the live handle itself is cached only in-process (`Map<string, DatabaseInterface>`), reconstructed fresh on the next process from the stored config. `primary` and `indexes` are paired schema metadata, while `version` is the target stamp a versioning driver writes after first use when it implements paired `metadata` / `stamp` capabilities. `isDatabaseDefinition` is the boundary guard a `DefinitionStoreInterface` applies to an untrusted persisted blob before trusting it, exact on its owned keys and held to `definitionShape` by a lockstep test. `MemoryDefinitionStore` structured-clones definitions on copy-in and copy-out; `DatabaseDefinitionStore` stores one opaque JSON column in a `@orkestrel/database` table and narrows it back with `isDatabaseDefinition` on read. Only a missing row reads as `undefined`: a present row whose blob fails the guard throws a `DATABASE` `ToolboxError` that names the id, the first fault, and the remedy, with `definitionContract.audit`'s faults in `context.faults`, and a row that names another id throws the same code naming the id it holds and the id it must hold, so a later `create` stops instead of overwriting it, and `set` refuses what `get` would, so no row is written that `get` refuses. `store.delete` reads nothing, so it clears such a row. Read the row through your own table to migrate it. They implement the same `get` / `set` / `delete` contract; only the memory store prevents caller mutation from aliasing stored state on its own, because the table-backed store's isolation follows from its driver.
348
366
 
349
- 21. **The relation tool's `include` is a flat dot-path list, capped by `RelationToolOptions.depth`.** `'load'` / `'find'` accept `include?: string[]` — each path a dot-separated chain of relation names (`'contacts.account'`) — expanded by `expandInclude` into a live `@orkestrel/relation` `Include` tree; a longer path subsumes a shorter sibling's bare `true` (`['contacts', 'contacts.account']` → `{ contacts: { account: true } }`). A path exceeding `depth` segments (default `RELATION_TOOL_DEPTH`), or carrying an empty segment (a leading/trailing/doubled `.`), throws a typed `TOOL` `ToolboxError` before any query runs. `resolveRelationManager` resolves which registered `RelationManagerInterface` a call addresses (an explicit `manager` miss, or an omitted one with other-than-exactly-one registered, throws typed `TOOL`); `resolveRelationModel` resolves `model` against it the same way.
367
+ 21. **The relation tool's `include` is a flat dot-path list, capped by `RelationToolOptions.depth`.** `'load'` / `'find'` accept `include?: string[]` — each path a dot-separated chain of relation names (`'contacts.account'`) — expanded by `expandInclude` into a live `@orkestrel/relation` `Include` tree; a longer path subsumes a shorter sibling's bare `true` (`['contacts', 'contacts.account']` → `{ contacts: { account: true } }`). A path exceeding `depth` segments (default `RELATION_TOOL_DEPTH`), or carrying an empty segment (a leading/trailing/doubled `.`), throws a typed `TOOL` `ToolboxError` before any query runs, and a `depth` that is not a positive safe integer throws `TOOL` at construction. `resolveRelationManager` resolves which registered `RelationManagerInterface` a call addresses (an explicit `manager` miss, or an omitted one with other-than-exactly-one registered, throws typed `TOOL`); `resolveRelationModel` resolves `model` against it the same way.
350
368
 
351
369
  22. **`createDatabaseTool` durability and ownership are narrower than they look.** A lazily re-minted database over the default in-memory driver yields an empty database — only the `DatabaseDefinition` schema persists in `store`, never rows; durable rows need a persistent driver factory registered in `DatabaseToolOptions.drivers`. A cached live database is never evolved in place. To adopt a new target `version`, create a new database id backed by a versioned persistent driver, or close the old tool lifecycle and construct a new tool whose stored definition carries the new schema metadata and stamp. `'destroy'` closes whatever handle is cached for the id, including an embedder-supplied `DatabaseToolOptions.databases` handle — the embedder relinquishes that handle's lifecycle to this tool for any id it wires in. `timeout`, when present, must be a nonnegative safe integer and is validated when the tool is constructed. Its fresh abort signal is passed only to `records`, `count`, `aggregate`, `add`, `set`, `update`, and `remove`, whose current table APIs accept operation options; it does not bound store resolution, construction, schema inspection, `get`, or `close`, and is not an outer deadline. The tool assumes the single-writer, non-reentrant model `@orkestrel/database` itself assumes — concurrent tool calls against one id are not serialized by this tool. Unlike `'records'` / `'find'` / `'links'`, `'get'` is uncapped by `DatabaseToolOptions.limit` (bounded only by the caller's `key` array size).
352
370
 
353
- 23. **`createEndpointTool` enforces its advertised inferred schema through a normalizing parse by default (`@orkestrel/contract`'s `schemaToShape`), with an explicit `validate: false` opt-out.** `parameters` is inferred once at construction (`samplesToSchema` and `schemaToObject` over `definition.samples`, tuned by `EndpointToolOptions.format`/`enum`) — the same object-rooted schema is compiled once (`schemaToShape` → `createContract`) into the contract the tool's `execute` `parse`s every call's `args` through before `definition.execute` runs. The parse coerces a scalar to its inferred type where the house parsers coerce (a number to/from a numeric string, a boolean from `'1'`/`'0'`/`'true'`/`'false'`/`1`/`0`) — `definition.execute` receives the coerced values (for example `7` sent for a string slot arrives as `'7'`), not the raw call args. A call whose `args` fails to parse into a record — a required key missing, or a value not coercible to its slot's type — throws a typed `TOOL` `ToolboxError` carrying the compiled contract's structured `explain` faults (through `contract.explain(args)`), and `definition.execute` is never called. Beyond that coercion, enforcement is structural: required keys, `enum` membership, and numeric bounds — `format` annotations (`email`, `date-time`, `uuid`, `uri`, ...) are never asserted, mirroring `@orkestrel/contract`'s own widening-only law for `schemaToShape` (a `format: true`-tuned endpoint still accepts a non-conforming string in that slot); a key outside the closed inferred schema is silently dropped, not rejected — `@orkestrel/contract`'s own `parse` grants that same leniency to any closed object. `EndpointToolOptions.validate: false` disables that enforcement: the tool's `execute` calls `definition.execute` with the model-supplied `args` exactly as received, never re-parsed, coerced, or checked against the advertised schema. The execution context the tool's `execute` receives reaches `definition.execute` unchanged whether or not that enforcement runs, so a handler that reads `context.signal` observes the caller's cancellation. `createInferTool`'s own call args are, as before, always validated against `inferToolShape` (a hand-written shape) regardless — it is the schema inference's caller, not an inferred schema's consumer. `createEndpointTool`'s and `createInferTool`'s inferred schemas surface sample-derived strings verbatim (property names, and enum entries when opted in), so treat sample data intended for schema inference as untrusted content whenever the resulting schema will be advertised to other agents. `createInferTool`'s optional `candidates` call arg is the opposite seam: it checks values against the same call's freshly inferred schema (compiled per-call, because the schema itself is derived from that call's `samples`) and returns a uniform `{ index, valid, coercible, faults? }` entry per candidate. `valid` is a strict `.is` guard verdict, not a normalizing `.parse` — `7` against an inferred string slot is invalid (no coercion), where the same value would be silently coerced to `'7'` by `createEndpointTool`'s enforcement. `coercible` (`checker.parse(candidate) !== undefined`) answers that separate question directly — would `createEndpointTool`'s default enforcement admit this value — and, by the house parse/guard round-trip, is always `true` on a `valid: true` entry. Because `@orkestrel/contract`'s `.explain` mirrors `.parse`'s leniency, not `.is`'s strictness, a strictly-invalid but coercible candidate (`7` against a string slot) yields `{ valid: false, coercible: true, faults: [] }` — empty faults, because the mismatch normalization would silently fix is not one `.explain` reports; `faults` populates only for a non-coercible mismatch (`coercible: false`). `checker.is` / `.parse` / `.explain` are total over JSON-safe input — a JSON-safe hostile candidate (a `__proto__`-carrying object, deep nesting) reaches each of them and yields a bounded, non-throwing per-candidate verdict; a non-JSON-safe candidate (a throwing-getter `Proxy`) never reaches the checker — it fails the outer `args` parse and rejects the whole call as a `TOOL` error, with no per-candidate verdict. `candidates` is uncapped in count (any array length is accepted), but each individual check is bounded (`.explain`'s fault list and the checker's own schema are both bounded by the inference limits already governing `samples`), so the total per-call cost is linear in `candidates.length`.
371
+ 23. **`createEndpointTool` enforces its advertised inferred schema through the Tool door by default (`@orkestrel/contract`'s lenient `schemaToShape`), with an explicit `strict: false` opt-out.** `parameters` is inferred once at construction (`samplesToSchema` and `schemaToObject` over `definition.samples`, tuned by `EndpointToolOptions.format`/`enum`) — the door converts the same object-rooted schema on the first call and runs on every call's `args` before `definition.execute`. Admission permits only lossless repairs: a numeric string whose trimmed text equals the parsed number's own text, the exact strings `'true'` and `'false'` for a boolean, a literal's trimmed text, and a finite number for a string slot. For example, `' 30 '` can become `30` and `7` can become `'7'`, but `'30.0'`, `'007'`, and `'0x10'` cannot become numbers, and `'1'`, `'0'`, `1`, and `0` cannot become booleans. The `definition.execute` handler receives the admitted value without another parse. A call that carries a key the closed inferred schema does not declare, misses a required key, or needs a repair that loses information or cannot parse throws a `ToolError` with code `ARGUMENTS` carrying `context.faults`, and `definition.execute` is never called. Beyond those repairs, enforcement is structural: required keys, `enum` membership, and numeric bounds — `format` annotations (`email`, `date-time`, `uuid`, `uri`, ...) are never asserted, mirroring `@orkestrel/contract`'s own widening-only law for `schemaToShape` (a `format: true`-tuned endpoint still accepts a non-conforming string in that slot). `EndpointToolOptions.strict: false` disables that enforcement: the tool's `execute` calls `definition.execute` with the model-supplied `args` exactly as received, never parsed, coerced, or checked against the advertised schema. Under the door `args` is a null-prototype record, on which `String(args)` and `args.hasOwnProperty()` throw, so a handler reads it with `Object.hasOwn`. The execution context the tool's `execute` receives reaches `definition.execute` unchanged whether or not that enforcement runs, so a handler that reads `context.signal` observes the caller's cancellation. `createInferTool`'s own call args are, as before, always validated against `inferToolShape` (a hand-written shape) regardless — it is the schema inference's caller, not an inferred schema's consumer. `createEndpointTool`'s and `createInferTool`'s inferred schemas surface sample-derived strings verbatim (property names, and enum entries when opted in), so treat sample data intended for schema inference as untrusted content whenever the resulting schema will be advertised to other agents. `createInferTool`'s optional `candidates` call arg is the opposite seam: it checks values against the same call's freshly inferred schema (compiled per-call, because the schema itself is derived from that call's `samples`) and returns a uniform `{ index, valid, coercible, faults? }` entry per candidate. `valid` is a strict `.is` guard verdict, not a normalizing `.parse` — `7` against an inferred string slot is invalid (no coercion), where the same value would be silently coerced to `'7'` by `createEndpointTool`'s enforcement. `coercible` (`checker.parse(candidate) !== undefined`) reports parser success, not endpoint admission, and is always `true` on a `valid: true` entry. A candidate can parse while requiring a lossy repair that the endpoint refuses. `faults` is `checker.audit(candidate)`, which reports against `.is`'s strictness, so a strictly-invalid but coercible candidate (`7` against a string slot) yields `{ valid: false, coercible: true, faults: [{ reason: 'type', ... }] }` and an undeclared key is a named `extra` fault: every invalid candidate names why. `checker.is` / `.parse` / `.audit` are total over JSON-safe input — a JSON-safe malformed candidate (a `__proto__`-carrying object, deep nesting) reaches each of them and yields a bounded, non-throwing per-candidate verdict; a non-JSON-safe candidate (a throwing-getter `Proxy`) never reaches the checker — the Tool door refuses the whole call with a `ToolError`, with no per-candidate verdict. `candidates` is uncapped in count (any array length is accepted), but each individual check is bounded (`.audit`'s fault list and the checker's own schema are both bounded by the inference limits already governing `samples`), so the total per-call cost is linear in `candidates.length`.
354
372
 
355
373
  24. **The terminal seam speaks whole forms, and `@orkestrel/form` owns their shape.** `promptToolShape` bounds a call to `{ to, schema }` and `answerToolShape`'s `'answer'` arm to `{ id, values }`, each of `schema` and `values` admitted only as exact JSON — Toolbox does not restate the form schema as a second contract. `createPromptTool` then hands `schema` to `parseForm`; a refusal (an unknown control, a duplicate field name, a `'select'` / `'checkbox'` field without usable choices, any other schema fault) throws a typed `TOOL` `ToolboxError` and nothing parks, so a malformed schema can never become a form nobody can answer. A parsed schema becomes a live form through `createForm` and is passed to `manager.ask(from, to, form)`, whose settled `FormValues` is the tool's return value — one record keyed by field name, however many fields the form declared. `createAnswerTool` narrows `values` with `isFormValues` before `manager.answer`, so a non-form payload is refused as `TOOL` rather than reaching the parked form. Expiry reaches one code from either side: a `TerminalError('EXPIRE')` from the broker and a `FormError('ABANDONED')` from the form itself both re-surface as `EXPIRE`, so a caller branches on Toolbox's own code and never on which layer timed the form out. A failed apply carries the manager's `TerminalAnswerError` through: `context.reason` is `'unknown'` / `'rejected'` / `'target'`, and a `'rejected'` apply also carries the per-field `errors` in `context.errors` so the asking side can name which field failed.
356
374
 
@@ -873,6 +891,68 @@ const linked = await tools.execute({
873
891
  linked.value // { keys: ['rep1'], count: 1, truncated: false, limit: 1000 }
874
892
  ```
875
893
 
894
+ ### Refusing a call with what to send
895
+
896
+ Hold a persisted definition's parts to their guards, run a tool's door by hand when the tool cannot pass `contract`, read the option bounds, describe a stored definition this package refuses, and bound what a refusal offers:
897
+
898
+ ```ts
899
+ import {
900
+ createContract,
901
+ literalShape,
902
+ numberShape,
903
+ objectShape,
904
+ stringShape,
905
+ unionShape,
906
+ } from '@orkestrel/contract'
907
+ import { createWorkspaceManager } from '@orkestrel/workspace'
908
+ import {
909
+ buildArgumentRefusal,
910
+ describeDefinitionMismatch,
911
+ describeDefinitionRefusal,
912
+ isIndexMap,
913
+ isPrimaryMap,
914
+ isTableSpec,
915
+ limitRefusal,
916
+ renderCandidates,
917
+ requireActiveWorkspace,
918
+ requireToolCall,
919
+ resolveBound,
920
+ } from '@orkestrel/toolbox'
921
+
922
+ isTableSpec({ items: { columns: { id: 'string' } } }) // true
923
+ isPrimaryMap({ items: 'id' }) // true
924
+ isIndexMap({ items: [['id']] }) // true
925
+
926
+ const amount = createContract(objectShape({ amount: numberShape() }))
927
+ requireToolCall(amount, { amount: '3' }) // { amount: 3 }
928
+
929
+ const { schema } = createContract(
930
+ unionShape(
931
+ objectShape({ operation: literalShape(['read']), path: stringShape() }),
932
+ objectShape({ operation: literalShape(['list']) }),
933
+ ),
934
+ )
935
+ buildArgumentRefusal(schema, { operation: 'read' }, []).message
936
+ // 'path: missing; expected string\nsend {"operation": "read", "path": string} | {"operation": "list"}'
937
+ buildArgumentRefusal(schema, { operation: 'nope' }, []).context?.faults?.[0]?.reason
938
+ // 'variant'
939
+
940
+ resolveBound(undefined, 100, 'database limit') // 100
941
+ resolveBound(25, 100, 'database limit') // 25
942
+
943
+ const manager = createWorkspaceManager()
944
+ const workspace = manager.add()
945
+ requireActiveWorkspace(manager, 'remove') === workspace // true
946
+
947
+ describeDefinitionRefusal('shop', [{ reason: 'extra', path: ['keys'] }])
948
+ // 'database "shop" holds a definition this version refuses (extra key "keys" at the root; ...'
949
+ describeDefinitionMismatch('shop', 'other')
950
+ // 'database "shop" holds a definition that names id "other"; its id must be "shop"; ...'
951
+
952
+ renderCandidates(['read', 'list']) // '"read", "list"'
953
+ limitRefusal('x'.repeat(5000)).length // 2048
954
+ ```
955
+
876
956
  ### The database and relation helpers, standalone
877
957
 
878
958
  Call the column compilers, the error classifiers, the query normalizer, and the relation resolvers directly:
@@ -971,16 +1051,15 @@ const checked = await tools.execute({
971
1051
  // checks: [
972
1052
  // { index: 0, valid: true, coercible: true },
973
1053
  // { index: 1, valid: false, coercible: false, faults: [{ reason: 'type', path: ['id'], expected: 'integer', received: '"x"' }] },
974
- // { index: 2, valid: false, coercible: true, faults: [] },
1054
+ // { index: 2, valid: false, coercible: true, faults: [{ reason: 'type', path: ['name'], expected: 'string', received: '7' }] },
975
1055
  // ],
976
1056
  // }
977
1057
  // Note: `valid` is a strict guard verdict (`.is`), not a normalizing parse — the opposite of
978
1058
  // `createEndpointTool`'s enforcement (Contract invariant 23), which coerces (`7` becomes `'7'`
979
1059
  // for a string slot); here `7` against a string slot is `valid: false`. `coercible` answers that
980
1060
  // separate question directly (would the endpoint tool's normalizing parse accept it) — candidate 2
981
- // is a strict mismatch that is still coercible, so it carries empty `faults`: `.explain` mirrors
982
- // `.parse`'s leniency, not `.is`'s strictness, so faults populate only for a non-coercible mismatch
983
- // (candidate 1's wrong, non-coercible `id` type).
1061
+ // is a strict mismatch that is still coercible. `faults` is `.audit`, which reports against `.is`'s
1062
+ // strictness, so every invalid candidate names why.
984
1063
  ```
985
1064
 
986
1065
  ### Bridging an existing API endpoint into an LLM-callable tool
@@ -1012,15 +1091,15 @@ const result = await tools.execute({
1012
1091
  })
1013
1092
  // result.value -> { id: '1', name: 'Ada' }
1014
1093
  // Note: by default `args` is parsed and validated against the advertised schema before the
1015
- // definition's `execute` runs (see Contract invariant 23) — a nonconforming call throws a typed
1016
- // `TOOL` `ToolboxError` with structured faults instead of reaching the handler. Pass
1017
- // `{ validate: false }` as the second argument to `createEndpointTool` for raw passthrough.
1094
+ // definition's `execute` runs (see Contract invariant 23) — a nonconforming call throws a
1095
+ // `ToolError` with code `ARGUMENTS` and structured faults instead of reaching the handler. Pass
1096
+ // `{ strict: false }` as the second argument to `createEndpointTool` for raw passthrough.
1018
1097
  ```
1019
1098
 
1020
1099
  The handler takes the caller's execution context as its second parameter, the same one a
1021
1100
  `@orkestrel/tool` handler takes. `createEndpointTool` forwards that context unchanged whichever way
1022
1101
  it handled the args — parsed against the inferred schema, or passed through raw under
1023
- `{ validate: false }` — so a handler that reads `context.signal` observes the caller's cancellation.
1102
+ `{ strict: false }` — so a handler that reads `context.signal` observes the caller's cancellation.
1024
1103
  The preceding fence declares `args` alone, which still satisfies `EndpointHandler`: a handler reads
1025
1104
  the signal only where it has cancellable work to abandon.
1026
1105
 
@@ -1029,15 +1108,15 @@ the signal only where it has cancellable work to abandon.
1029
1108
  - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` and `src/server` bijection (value and type exports, spanning both barrels), this guide's `## Patterns` fences resolving to real exports (per-specifier) with resolving imports, the `DefinitionStoreInterface` and `DatabaseResolver` method bijections, and the equality gate: every `Summary` cell against its declaration's description paragraph, the titled `Authoring and running a workflow through the tool with a real ToolManager` 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.
1030
1109
  - [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — every factory returning a working instance or value; workflow coverage composes real runners, agents, tools, stores, and scripted providers across direct roots, top-level authoring tools, opaque-leaf propagation, frozen null-prototype registry isolation/collisions, inherited-name `TRANSITION` refusals, explicitly registered dangerous own keys, depth 8/9 boundaries, repeated workflow ids, bound no-arg cycle refusal, self-recursion, A→B→A, same-agent concurrency, native per-run cancellation (including already-aborted provider exclusion), hostile argument containment before runner/store entry, Agent-owned projection, malformed structural results, genuine error identity, and deterministic named-store replacement. Database coverage includes every operation, frozen readonly-mutation membership, persistence-before-cache publication through a real failing database store, timeout validation, query truncation, and typed failures. Creation and resolver coverage prove `primary` / `indexes` reach real memory-driver metadata and `version` is stamped after first use. Terminal coverage drives a real `TerminalManagerInterface` through the ask/answer pair: a multi-field schema parking once and settling into one values record, the pending listing carrying `{ id, from, schema }`, a schema `parseForm` refuses (an unknown control, duplicate field names, missing or non-array choices) throwing typed `TOOL` with nothing parked, the fixed `from` surviving a spoofing attempt, and the `DEADLOCK` / `EXPIRE` (injected timer) / unknown-terminal / unknown-id classifications.
1031
1110
  - [`tests/src/core/databases/DatabaseResolver.test.ts`](../tests/src/core/databases/DatabaseResolver.test.ts) — caller-map isolation, explicit cache operations, stored-definition construction and reuse, and the typed unknown-database failure.
1032
- - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the reusable workflow, terminal, database, and relation helpers; lineage coverage proves copy/freeze isolation, extension, and zero-based depth derivation. Database coverage includes `normalizeQuery` connector defaults, `resolveLimit` clamping a request to the cap and flooring a negative one at `0`, and `clampQuery` probe limits.
1033
- - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — every guard at its untrusted boundary: `isWorkflowLineage` alternating/nonempty/unique validation and hostile-boundary totality, `isAgentFunction` metadata narrowing, `isColumnPrimitive` and `isColumnSpec` over the column DSL, and strict `isDatabaseDefinition` validation for `primary` / `indexes` / finite `version` with obsolete-field rejection.
1111
+ - [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — the reusable workflow, terminal, database, and relation helpers; lineage coverage proves copy/freeze isolation, extension, and zero-based depth derivation. Database coverage includes `normalizeQuery` connector defaults, `resolveLimit` clamping a request to the cap and flooring a negative one at `0`, and `clampQuery` probe limits. Door coverage holds `requireToolCall` and `buildArgumentRefusal` to a named refusal for a form or an operation, and `resolveBound`, `requireActiveWorkspace`, and `describeDefinitionRefusal` to what each says.
1112
+ - [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — every guard at its untrusted boundary: `isWorkflowLineage` alternating/nonempty/unique validation and hostile-boundary totality, `isAgentFunction` metadata narrowing, `isColumnPrimitive` and `isColumnSpec` over the column DSL, and strict `isDatabaseDefinition` validation for `primary` / `indexes` / finite `version` with obsolete-field rejection, exact on owned keys and in lockstep with `definitionContract` over every fixture in both directions.
1034
1113
  - [`tests/src/core/compilers.test.ts`](../tests/src/core/compilers.test.ts) — the `TableSpec` column DSL compiled through a real `createContract` gate: every `ColumnPrimitive` accepting its own values and rejecting the others, `optional: true` admitting an absent column, `optional: false` staying required, integer separated from number, and multiple tables compiled independently.
1035
1114
  - [`tests/src/core/shapers.test.ts`](../tests/src/core/shapers.test.ts) — every advertised shape, including valid samples of every database operation arm, create-time `primary` / `indexes` / `version`, query inputs, single/array row-key forms, and malformed metadata rejection.
1036
1115
  - [`tests/src/core/errors.test.ts`](../tests/src/core/errors.test.ts) — `ToolboxError` carrying its `code` and its optional `context`, and `isToolboxError` narrowing a caught value (accepting a real instance, rejecting a plain `Error` / non-error value).
1037
1116
  - [`tests/src/core/stores/MemoryDefinitionStore.test.ts`](../tests/src/core/stores/MemoryDefinitionStore.test.ts) — the memory twin against the shared `DefinitionStoreInterface` contract: round-trip, replacement, deletion, absent-id no-op, optional-metadata, and nested copy-isolation scenarios.
1038
- - [`tests/src/core/stores/DatabaseDefinitionStore.test.ts`](../tests/src/core/stores/DatabaseDefinitionStore.test.ts) — the database twin against the same contract scenarios, plus database-backed-only cases covering the default in-memory driver and malformed stored blobs.
1117
+ - [`tests/src/core/stores/DatabaseDefinitionStore.test.ts`](../tests/src/core/stores/DatabaseDefinitionStore.test.ts) — the database twin against the same contract scenarios, plus database-backed-only cases covering the default in-memory driver, and a malformed stored blob or a row naming another id throwing a `DATABASE` `ToolboxError` on `get`, a malformed definition refused by `set` before any write, and `delete` clearing such a row.
1039
1118
  - [`tests/src/server/factories.test.ts`](../tests/src/server/factories.test.ts) — `createTerminalRoutes` returning exactly the GET and POST records, in that order, sharing one path.
1040
- - [`tests/src/server/terminals/TerminalBridge.test.ts`](../tests/src/server/terminals/TerminalBridge.test.ts) — the bridge's own handlers, driven through the routes the factory projects: the GET route replaying every pending form as a `pending` frame then live-forwarding `pending` / `expire` events scoped to `name`, arming a keepalive `: ` comment ping through an injected `timer` that re-validates the connection's presented token on every tick (a `TerminalToken` function that starts rejecting mid-stream tears the stream down through the shared teardown and does not re-arm; a static string token is a no-op across ticks), ending the stream (unsubscribing and cancelling the keepalive) on the request's `AbortSignal` firing, and `401`/`404` on a token mismatch / unknown `name`; the POST route reading the body capped at `options.limit` bytes and parsing the JSON body and routing it through `manager.answer` — `200` and the JSON `Result` on success, `413` an over-limit body (a lying small `Content-Length` on a big streamed body still capped, `manager.answer` never called), `400` invalid JSON, `422` a non-`{ id, values }` body or a `'unknown'`/`'rejected'` answer result, `404` an unknown `name` or a `'target'` answer result, `401` on a token mismatch; mount-churn pressure (50 sequential GET connect→abort cycles) proving zero leaked keepalive timers / manager listener subscriptions and no ghost duplicate `pending` frames; POST fuzz pressure over malformed/invalid-shape bodies, unknown endpoint, bad token, and an expired id; and consumer-side stream-close self-heal — a live `pending` event or a keepalive tick arriving on a stream closed without the request `AbortSignal` ever firing runs the same teardown the abort path runs (listeners detached, keepalive cancelled), never re-arming or leaking.
1119
+ - [`tests/src/server/terminals/TerminalBridge.test.ts`](../tests/src/server/terminals/TerminalBridge.test.ts) — the bridge's own handlers, driven through the routes the factory projects: construction refusing a missing or malformed `token`, `keepalive`, or `limit`; the GET route replaying every pending form as a `pending` frame then live-forwarding `pending` / `expire` events scoped to `name`, arming a keepalive `: ` comment ping through an injected `timer` that re-validates the connection's presented token on every tick (a `TerminalToken` function that starts rejecting mid-stream tears the stream down through the shared teardown and does not re-arm; a static string token is a no-op across ticks), ending the stream (unsubscribing and cancelling the keepalive) on the request's `AbortSignal` firing, and `401`/`404` on a token mismatch / unknown `name`; the POST route reading the body capped at `options.limit` bytes and parsing the JSON body and routing it through `manager.answer` — `200` and the JSON `Result` on success, `413` an over-limit body (a lying small `Content-Length` on a big streamed body still capped, `manager.answer` never called), `400` invalid JSON, `422` a non-`{ id, values }` body (an undeclared key included, carrying its faults) or a `'unknown'`/`'rejected'` answer result, `404` an unknown `name` or a `'target'` answer result, `401` on a token mismatch; mount-churn pressure (50 sequential GET connect→abort cycles) proving zero leaked keepalive timers / manager listener subscriptions and no ghost duplicate `pending` frames; POST fuzz pressure over malformed/invalid-shape bodies, unknown endpoint, bad token, and an expired id; and consumer-side stream-close self-heal — a live `pending` event or a keepalive tick arriving on a stream closed without the request `AbortSignal` ever firing runs the same teardown the abort path runs (listeners detached, keepalive cancelled), never re-arming or leaking.
1041
1120
  - [`tests/src/server/terminals/TerminalConnection.test.ts`](../tests/src/server/terminals/TerminalConnection.test.ts) — idempotent direct opening, already-aborted request teardown, and fail-closed handling when a direct token validator throws.
1042
1121
 
1043
1122
  ## See also