@orkestrel/scaffold 0.0.123 → 0.0.125
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.
- package/dist/agents/skills/orkestrel-publish/scripts/steps.js +523 -0
- package/dist/agents/skills/orkestrel-publish/scripts/wave.js +70 -11
- package/dist/bin/main.js +18 -18
- package/dist/bin/main.js.map +1 -1
- package/dist/host/agents/orchestration.md +5 -1
- package/dist/host/agents/platforms/windows.md +9 -1
- package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +1 -1
- package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +1 -0
- package/dist/host/agents/skills/orkestrel-harden/references/methods.md +30 -2
- package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -0
- package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +5 -1
- package/dist/host/agents/skills/orkestrel-publish/SKILL.md +1 -0
- package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
- package/dist/host/agents/skills/orkestrel-publish/references/wave.md +23 -6
- package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +654 -0
- package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +79 -14
- package/dist/host/claude/agents/orkestrel.md +45 -45
- package/dist/host/claude/rules/patterns.md +1 -1
- package/dist/host/claude/rules/portability.md +2 -0
- package/dist/host/claude/rules/quality.md +3 -1
- package/dist/host/claude/rules/tests.md +3 -1
- package/dist/host/guides/agent.md +349 -244
- package/dist/host/guides/brief.md +52 -48
- package/dist/host/guides/browser.md +2 -2
- package/dist/host/guides/contract.md +226 -104
- package/dist/host/guides/database.md +12 -12
- package/dist/host/guides/interpret.md +531 -155
- package/dist/host/guides/mcp.md +183 -61
- package/dist/host/guides/ndjson.md +47 -34
- package/dist/host/guides/ollama.md +123 -66
- package/dist/host/guides/program.md +117 -39
- package/dist/host/guides/qualifier.md +110 -59
- package/dist/host/guides/rater.md +85 -32
- package/dist/host/guides/reason.md +377 -114
- package/dist/host/guides/scaffold.md +20 -12
- package/dist/host/guides/study.md +580 -483
- package/dist/host/guides/tool.md +163 -58
- package/dist/host/guides/toolbox.md +159 -80
- package/dist/host/guides/workflow.md +44 -25
- package/dist/host/manifest.json +41 -35
- package/dist/src/core/index.cjs +17 -17
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.js +17 -17
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +23 -11
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +10 -6
- package/dist/src/server/index.d.ts +10 -6
- package/dist/src/server/index.js +23 -11
- package/dist/src/server/index.js.map +1 -1
- package/package.json +17 -17
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
> results, through the `quantitative`, `logical`, `symbolic`, and `inferential`
|
|
6
6
|
> strategies behind one dispatch surface.
|
|
7
7
|
|
|
8
|
-
Each strategy is a `ReasonerInterface` registered on the thin `Reason` orchestrator: `quantitative` scores factors into a number, `logical` deduces
|
|
8
|
+
Each strategy is a `ReasonerInterface` registered on the thin `Reason` orchestrator: `quantitative` scores factors into a number, `logical` deduces `met`, `unmet`, or `unread` from rules by forward or backward chaining, `symbolic` solves algebraic equations by variable isolation, and `inferential` derives facts through unification variables and proof trees. The injectable `Evaluator`, `Transformer`, and `Aggregator` operators do the arithmetic every strategy shares. Every result is a fresh object carrying `success`, a human-readable `trace`, accumulated `errors`, and the `faults` naming what it could not read; nothing mutates its inputs.
|
|
9
9
|
|
|
10
|
-
The design stance is data in, data out, no surprises. Definitions are pure data, built by hand or with the shipped value factories. The orchestrator holds no strategy logic — dispatch is a registry lookup by the `reasoning` discriminant. The operators are total: an unknown comparison surfaces as a `CheckResult.error`, an unknown math operation
|
|
10
|
+
The design stance is data in, data out, no surprises. What the engine cannot read it refuses: a missing field, a value of the wrong type, and a malformed definition entry never stand in for an answer, and the result names what stopped it. Definitions are pure data, built by hand or with the shipped value factories. The orchestrator holds no strategy logic — dispatch is a registry lookup by the `reasoning` discriminant. The operators are total: an unknown comparison surfaces as a `CheckResult.error`, and an unknown math operation and divide-by-zero are `NaN` rather than a throw. A reasoner never assumes `validate` ran, so a malformed definition yields a failure result and a throw is reserved for caller misuse, as a coded `ReasonError`.
|
|
11
11
|
|
|
12
12
|
On top of the evaluation engine sits the definitions & subjects capability layer: a pure copy-on-write helper family that changes, extends, merges, and round-trips definitions as data, plus the brand-guarded `DefinitionBuilder` (one self-owning manager per collection) and `SubjectBuilder` (one flat collection) workspaces, which accumulate state through named methods and `build()` a fresh plain payload on demand. Building happens outside the engine: `reason` and `validate` take only the plain data, so a builder's `build()` output is passed at the call site. Deliberately absent: async reasoners, definition persistence, and probabilistic strategies beyond the multiplicative `confidence` of inferential facts. Source: [`src/core`](../src/core). Surfaced through the `@src/core` barrel.
|
|
13
13
|
|
|
@@ -31,7 +31,7 @@ const reason = createReason({ reasoners: [createQuantitativeReasoner()] })
|
|
|
31
31
|
|
|
32
32
|
const definition = createQuantitativeDefinition('risk', 'Risk score', [
|
|
33
33
|
createFactorGroup('drivers', 'sum', [
|
|
34
|
-
createFieldFactor('age', 'age'), // reads subject.age,
|
|
34
|
+
createFieldFactor('age', 'age'), // reads subject.age, a finite number or the run refuses
|
|
35
35
|
createStaticFactor('floor', 10), // a fixed contribution
|
|
36
36
|
]),
|
|
37
37
|
])
|
|
@@ -48,25 +48,29 @@ reason.reasoner('quantitative')?.supports(definition) // the reasoner's own guar
|
|
|
48
48
|
|
|
49
49
|
### Entity factories
|
|
50
50
|
|
|
51
|
-
| Name
|
|
52
|
-
|
|
|
53
|
-
| `
|
|
54
|
-
| `
|
|
55
|
-
| `
|
|
56
|
-
| `
|
|
57
|
-
| `
|
|
58
|
-
| `
|
|
59
|
-
| `
|
|
60
|
-
| `
|
|
61
|
-
| `
|
|
62
|
-
| `
|
|
63
|
-
| `
|
|
64
|
-
| `
|
|
65
|
-
| `
|
|
66
|
-
| `
|
|
67
|
-
| `
|
|
68
|
-
| `
|
|
69
|
-
| `
|
|
51
|
+
| Name | Kind | Signature | Summary |
|
|
52
|
+
| ---------------------------------- | -------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
53
|
+
| `createSymbolicDefinitionContract` | function | `() => ContractInterface<unknown>` | Creates the contract of a `SymbolicDefinition`. Cross it on `is`, and hold the result. |
|
|
54
|
+
| `createLogicalDefinitionContract` | function | `() => ContractInterface<unknown>` | Creates the contract of a `LogicalDefinition`. Cross it on `is`, and hold the result. |
|
|
55
|
+
| `createDefinitionContract` | function | `() => ContractInterface<unknown>` | Creates the contract of any `Definition`, its `schema` for an LLM, a tool, or MCP. |
|
|
56
|
+
| `createSubjectDoor` | function | `() => SubjectDoorInterface` | Creates a door that admits subjects through a shape before a reasoner reads them. |
|
|
57
|
+
| `createReason` | function | `(options?: ReasonOptions) => ReasonInterface` | Creates the reasoning orchestrator. |
|
|
58
|
+
| `createQuantitativeReasoner` | function | `(options?: QuantitativeReasonerOptions) => ReasonerInterface` | Creates the quantitative reasoner — factor-based numeric scoring. |
|
|
59
|
+
| `createLogicalReasoner` | function | `(options?: LogicalReasonerOptions) => ReasonerInterface` | Creates the logical reasoner — rule-based deduction with forward / backward chaining. |
|
|
60
|
+
| `createSymbolicReasoner` | function | `(options?: SymbolicReasonerOptions) => ReasonerInterface` | Creates the symbolic reasoner — algebraic equation solving by variable isolation. |
|
|
61
|
+
| `createInferentialReasoner` | function | `(options?: InferentialReasonerOptions) => ReasonerInterface` | Creates the inferential reasoner — fact derivation with unification variables and proof trees. |
|
|
62
|
+
| `createEvaluator` | function | `(options?: EvaluatorOptions) => EvaluatorInterface` | Creates a check evaluator. |
|
|
63
|
+
| `createTransformer` | function | `(options?: TransformerOptions) => TransformerInterface` | Creates a math transformer. |
|
|
64
|
+
| `createAggregator` | function | `(options?: AggregatorOptions) => AggregatorInterface` | Creates a number aggregator. |
|
|
65
|
+
| `createDefinitionBuilder` | function | `(seed: Definition, options?: DefinitionBuilderOptions) => DefinitionBuilderInterface` | Creates a `DefinitionBuilder` — a stateful workspace builder accumulating a `Definition` through the `groups`, `factors`, `rules`, `equations`, `variables`, `facts`, and `inferences` self-owning manager properties. |
|
|
66
|
+
| `createSubjectBuilder` | function | `(seed: Subject, options?: SubjectBuilderOptions) => SubjectBuilderInterface` | Creates a `SubjectBuilder` — a stateful workspace builder accumulating a `Subject`. |
|
|
67
|
+
| `createGroupManager` | function | `(options?: GroupManagerOptions) => GroupManagerInterface` | Creates a `GroupManager` — a self-owning manager over a quantitative definition's `groups`. |
|
|
68
|
+
| `createFactorManager` | function | `(groups: GroupManagerInterface, options?: FactorManagerOptions) => FactorManagerInterface` | Creates a `FactorManager` — the divergent manager over a group's `factors`, threaded through a required `groupId` locator. |
|
|
69
|
+
| `createRuleManager` | function | `(options?: RuleManagerOptions) => RuleManagerInterface` | Creates a `RuleManager` — a self-owning manager over a logical definition's `rules`. |
|
|
70
|
+
| `createEquationManager` | function | `(options?: EquationManagerOptions) => EquationManagerInterface` | Creates an `EquationManager` — a self-owning manager over a symbolic definition's `equations`. |
|
|
71
|
+
| `createVariableManager` | function | `(options?: VariableManagerOptions) => VariableManagerInterface` | Creates a `VariableManager` — a self-owning manager over a symbolic definition's `variables` (a name-keyed record; `add` / `remove` only). |
|
|
72
|
+
| `createFactManager` | function | `(options?: FactManagerOptions) => FactManagerInterface` | Creates a `FactManager` — a self-owning manager over an inferential definition's `facts`. |
|
|
73
|
+
| `createInferenceManager` | function | `(options?: InferenceManagerOptions) => InferenceManagerInterface` | Creates an `InferenceManager` — a self-owning manager over an inferential definition's `inferences`. |
|
|
70
74
|
|
|
71
75
|
### Orchestrator & reasoners
|
|
72
76
|
|
|
@@ -74,7 +78,7 @@ reason.reasoner('quantitative')?.supports(definition) // the reasoner's own guar
|
|
|
74
78
|
| ---------------------- | ----- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- |
|
|
75
79
|
| `Reason` | class | `new (options?: ReasonOptions) => ReasonInterface` | Implements the reasoning orchestrator — a thin router over registered `ReasonerInterface`s. |
|
|
76
80
|
| `QuantitativeReasoner` | class | `new (options?: QuantitativeReasonerOptions) => ReasonerInterface` | Performs factor-based numeric scoring. |
|
|
77
|
-
| `LogicalReasoner` | class | `new (options?: LogicalReasonerOptions) => ReasonerInterface` | Deduces
|
|
81
|
+
| `LogicalReasoner` | class | `new (options?: LogicalReasonerOptions) => ReasonerInterface` | Deduces states from rules with forward or backward chaining, refusing what it cannot read. |
|
|
78
82
|
| `SymbolicReasoner` | class | `new (options?: SymbolicReasonerOptions) => ReasonerInterface` | Solves algebraic equations by variable isolation. |
|
|
79
83
|
| `InferentialReasoner` | class | `new (options?: InferentialReasonerOptions) => ReasonerInterface` | Derives facts with unification variables and proof trees. |
|
|
80
84
|
|
|
@@ -82,7 +86,7 @@ reason.reasoner('quantitative')?.supports(definition) // the reasoner's own guar
|
|
|
82
86
|
|
|
83
87
|
| Name | Kind | Signature | Summary |
|
|
84
88
|
| ------------- | ----- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
|
|
85
|
-
| `Evaluator` | class | `new (options?: EvaluatorOptions) => EvaluatorInterface` | Evaluates
|
|
89
|
+
| `Evaluator` | class | `new (options?: EvaluatorOptions) => EvaluatorInterface` | Evaluates field predicates against subjects. |
|
|
86
90
|
| `Transformer` | class | `new (options?: TransformerOptions) => TransformerInterface` | Applies math `Transform`s to numbers — the quantitative reasoner's per-factor pipeline stage. |
|
|
87
91
|
| `Aggregator` | class | `new (options?: AggregatorOptions) => AggregatorInterface` | Reduces number lists to one number per `Aggregation` — the quantitative reasoner's group and definition combiner. |
|
|
88
92
|
|
|
@@ -92,6 +96,7 @@ The definitions & subjects capability layer's stateful workspace builders: mutat
|
|
|
92
96
|
|
|
93
97
|
| Name | Kind | Signature | Summary |
|
|
94
98
|
| ------------------- | ----- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
99
|
+
| `SubjectDoor` | class | `new () => SubjectDoorInterface` | Admits a subject through a definition's shape before any reasoner reads it. |
|
|
95
100
|
| `DefinitionBuilder` | class | `new (seed: Definition, options?: DefinitionBuilderOptions) => DefinitionBuilderInterface` | Implements a stateful workspace builder accumulating a `Definition` through always-present self-owning manager properties: a private scalar envelope (reasoning / id / name plus the kind's scalars) composed with each collection read from its manager. |
|
|
96
101
|
| `GroupManager` | class | `new (options?: GroupManagerOptions) => GroupManagerInterface` | Implements the `GroupManagerInterface` — a self-owning, kind-free manager over a quantitative definition's `groups`. |
|
|
97
102
|
| `FactorManager` | class | `new (groups: GroupManagerInterface, options?: FactorManagerOptions) => FactorManagerInterface` | Implements the `FactorManagerInterface` — the one divergent manager: factors nest inside groups, so it holds no collection state of its own and threads a required `groupId` locator. |
|
|
@@ -138,35 +143,68 @@ Every value factory returns a fresh object and omits absent optional keys entire
|
|
|
138
143
|
|
|
139
144
|
### Helpers
|
|
140
145
|
|
|
141
|
-
| Name | Kind | Signature
|
|
142
|
-
| -------------------------- | -------- |
|
|
143
|
-
| `
|
|
144
|
-
| `
|
|
145
|
-
| `
|
|
146
|
-
| `
|
|
147
|
-
| `
|
|
148
|
-
| `
|
|
149
|
-
| `
|
|
150
|
-
| `
|
|
151
|
-
| `
|
|
152
|
-
| `
|
|
153
|
-
| `
|
|
154
|
-
| `
|
|
155
|
-
| `
|
|
156
|
-
| `
|
|
157
|
-
| `
|
|
158
|
-
| `
|
|
159
|
-
| `
|
|
160
|
-
| `
|
|
161
|
-
| `
|
|
162
|
-
| `
|
|
163
|
-
| `
|
|
164
|
-
| `
|
|
165
|
-
| `
|
|
166
|
-
| `
|
|
167
|
-
| `
|
|
168
|
-
| `
|
|
169
|
-
| `
|
|
146
|
+
| Name | Kind | Signature | Summary |
|
|
147
|
+
| -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
148
|
+
| `projectCheck` | function | `(check: CheckResult) => CheckResult` | Projects a check's `actual` on its own budget, omitting it when it has no JSON form. |
|
|
149
|
+
| `describeMismatch` | function | `(expected: string, definition: unknown) => string` | Describes a definition whose reasoning is not the one a reasoner expected. |
|
|
150
|
+
| `describeTerms` | function | `(terms: readonly unknown[]) => string` | Describes a fact's terms for the trace. |
|
|
151
|
+
| `scanConclusionValues` | function | `(expression: Expression) => readonly string[]` | Scans a conclusion for one key asserted with two values, of which a run would keep the last. |
|
|
152
|
+
| `collectVariables` | function | `(expression: SymbolicExpression) => readonly string[]` | Collects every variable a symbolic expression reads. |
|
|
153
|
+
| `scanSymbolicExpression` | function | `(expression: SymbolicExpression) => readonly string[]` | Scans a symbolic expression for a binary operation with no right side. |
|
|
154
|
+
| `scanFactor` | function | `(factor: Factor) => readonly string[]` | Scans a factor for a `fallback` its source cannot use and for malformed checks. |
|
|
155
|
+
| `scanConclusion` | function | `(expression: Expression) => readonly string[]` | Scans a rule's conclusion, which may only assert: `equals` atoms under `and`, none of them asserting `false`. |
|
|
156
|
+
| `scanExpression` | function | `(expression: Expression) => readonly string[]` | Scans a premise expression for a wrong connective arity and a malformed check. |
|
|
157
|
+
| `scanCheck` | function | `(check: Check) => readonly string[]` | Scans a check for an expected value its comparison cannot use. |
|
|
158
|
+
| `scanShapeConclusions` | function | `(shape: ContractShape, rules: readonly Rule[]) => readonly string[]` | Scans a shape for a key the rules conclude, which a subject may not supply. |
|
|
159
|
+
| `scanCheckExpected` | function | `(shape: ContractShape, check: Check, known: ReadonlySet<string>) => readonly string[]` | Scans a check's expected value against the shape of the field it reads. |
|
|
160
|
+
| `scanShapeReads` | function | `(shape: ContractShape, checks: readonly Check[], fields: readonly FieldPath[], known: ReadonlySet<string>) => ShapeScan` | Scans what a definition reads against its shape. |
|
|
161
|
+
| `scanShape` | function | `(shape: ContractShape, path?: readonly string[], required?: boolean) => readonly string[]` | Scans a shape for what cannot stand in a definition. |
|
|
162
|
+
| `admitsLiteral` | function | `(shape: ContractShape, value: string) => boolean` | Determines whether a shape admits a string as one of its closed values. |
|
|
163
|
+
| `isUntypedShape` | function | `(shape: ContractShape \| undefined) => boolean` | Determines whether a field's shape leaves its value untyped, which a `raw` or `json` node does. |
|
|
164
|
+
| `findFieldShape` | function | `(shape: ContractShape, path: FieldPath) => ShapeRead` | Finds what a shape says about a field path. |
|
|
165
|
+
| `findFilledPaths` | function | `(input: unknown, parsed: unknown, path?: readonly string[]) => readonly FieldPath[]` | Lists the paths `parse` filled: absent or `undefined` in the input and present in the output. |
|
|
166
|
+
| `projectResult` | function | `(result: ReasonResult) => JSONValue \| undefined` | Projects a result to the JSON its contract reads. |
|
|
167
|
+
| `projectValue` | function | `(value: unknown, ancestors?: ReadonlySet<object>, budget?: { left: number; }) => JSONValue \| undefined` | Projects any value to JSON: a non-finite number becomes `null`, and what JSON cannot hold is dropped. |
|
|
168
|
+
| `filterUniqueFaults` | function | `(faults: readonly AuditFault[]) => readonly AuditFault[]` | Returns the faults of a list once per field, compared by the flattened path. |
|
|
169
|
+
| `filterUniqueFields` | function | `(fields: readonly FieldPath[]) => readonly FieldPath[]` | Returns the fields of a list once each, compared by the flattened path. |
|
|
170
|
+
| `valueToKind` | function | `(value: unknown) => FaultKind` | Names the fault kind of a JSON value. |
|
|
171
|
+
| `readExpectedKind` | function | `(check: Check) => FaultKind` | Names what a check needed from its field, for the fault an unread read becomes. |
|
|
172
|
+
| `valueToFault` | function | `(path: FieldPath, expected: FaultKind, actual: unknown) => AuditFault` | Builds the fault for a field the engine could not read. |
|
|
173
|
+
| `collectPolarReads` | function | `(expression: Expression, negated: boolean) => readonly PolarRead[]` | Collects every key an expression reads with the polarity of that read. |
|
|
174
|
+
| `collectReachable` | function | `(start: string, edges: ReadonlyArray<readonly [string, string]>) => ReadonlySet<string>` | Collects every node a list of directed edges reaches from a start, the start included. |
|
|
175
|
+
| `findNegativeCycles` | function | `(rules: readonly Rule[]) => readonly string[]` | Finds the conclusion keys on a cycle through negation, which no order of evaluation can settle. |
|
|
176
|
+
| `findSuppliedConclusions` | function | `(rules: readonly Rule[], subject: Subject) => readonly string[]` | Finds the conclusion keys a subject supplies itself, which would let it assert what a rule has to derive. |
|
|
177
|
+
| `collectConcluders` | function | `(rules: readonly Rule[]) => ReadonlyMap<string, readonly Rule[]>` | Collects each conclusion key with the rules that conclude it. |
|
|
178
|
+
| `buildRefusedResult` | function | `(definition: Definition, admission: SubjectAdmission) => ReasonResult` | Builds the empty failure result for a subject the door refused. |
|
|
179
|
+
| `combineStates` | function | `(operator: LogicalOperator \| string, states: readonly CheckState[]) => CheckState` | Combines operand states under a logical connective, in strong Kleene logic. |
|
|
180
|
+
| `readClosedState` | function | `(operator: string) => CheckState` | Returns what a comparison reads on a conclusion no rule concluded, once every rule that could have has settled. |
|
|
181
|
+
| `settleComparison` | function | `(actual: unknown, operator: string, expected: unknown) => CheckState` | Compares a subject value with an expected value and returns what that settles. |
|
|
182
|
+
| `formatField` | function | `(field: FieldPath) => string` | Formats a `FieldPath` for display — the single string key itself, or the array segments joined with `.`. |
|
|
183
|
+
| `clamp` | function | `(value: number, limit?: Bounds) => number` | Clamps a number to inclusive `Bounds`. |
|
|
184
|
+
| `roundTo` | function | `(value: number, precision?: number) => number` | Rounds a number to a fixed count of decimal places. |
|
|
185
|
+
| `matchesBounds` | function | `(value: unknown, range: unknown) => boolean` | Checks whether a value falls inside an inclusive range expressed as an array. |
|
|
186
|
+
| `emptyAggregate` | function | `(aggregation: Aggregation) => number` | Returns the empty-input identity of one `Aggregation`. |
|
|
187
|
+
| `resolveSource` | function | `(source: FactorSource, subject: Subject, fallback?: number) => SourceResult` | Resolves one `FactorSource` against a subject, falling back when it cannot. |
|
|
188
|
+
| `equalValues` | function | `(left: unknown, right: unknown) => boolean` | Determines whether two values are SameValueZero-equal — strict `===` with `NaN` equal to itself (and, unlike `Object.is`, `+0` equal to `-0`). |
|
|
189
|
+
| `sortByPriority` | function | `<T extends { readonly priority?: number; }>(items: readonly T[]) => readonly T[]` | Sorts items ascending by `priority ?? DEFAULT_PRIORITY` — a stable copy sort. |
|
|
190
|
+
| `findDuplicates` | function | `(items: ReadonlyArray<{ readonly id: string; }>) => readonly string[]` | Collects the ids that appear more than once in an id-carrying list — each duplicated id reported once, in first-occurrence order. |
|
|
191
|
+
| `factToArityKey` | function | `(fact: Fact) => string` | Derives a fact's predicate+arity bucket key — length-prefixed so the delimiter cannot be forged. |
|
|
192
|
+
| `indexByArity` | function | `(facts: readonly Fact[]) => ReadonlyMap<string, readonly Fact[]>` | Buckets facts by predicate+arity, preserving append order within each bucket. |
|
|
193
|
+
| `termToKey` | function | `(term: unknown, identities: Map<object, number>) => string` | Derives one fact term's contribution to a dedup key — reference identity for non-null objects / functions, a SameValueZero value string for primitives. |
|
|
194
|
+
| `factToKey` | function | `(fact: Fact, identities: Map<object, number>) => string` | Derives a fact's canonical dedup key — predicate + arity + per-term SameValueZero identity, with confidence excluded from it. |
|
|
195
|
+
| `matchFacts` | function | `(pattern: Fact, candidate: Fact) => Record<string, unknown> \| undefined` | Unifies a pattern fact positionally against a candidate fact — returning the variable bindings on success, `undefined` on mismatch. |
|
|
196
|
+
| `instantiateFact` | function | `(fact: Fact, bindings: Record<string, unknown>) => Fact` | Substitutes a fact's bound `'?'`-variables with their values — a fresh fact with unbound terms passed through unchanged. |
|
|
197
|
+
| `subjectToFacts` | function | `(subject: Subject) => { readonly facts: readonly Fact[]; readonly trace: readonly string[]; }` | Projects a subject's scalar fields into `has(key, value)` base facts — the inferential reasoner's subject-injection step. |
|
|
198
|
+
| `computePremiseConfidence` | function | `(premises: readonly Fact[], index: ReadonlyMap<string, readonly Fact[]>, bindings: Record<string, unknown>) => number` | Computes the confidence a set of matched premises contributes to a derived fact — the product of each premise's first matching fact's confidence. |
|
|
199
|
+
| `containsVariable` | function | `(expression: SymbolicExpression, target: string, bindings: Record<string, number>) => boolean` | Determines whether a symbolic expression contains an unbound occurrence of a target variable. |
|
|
200
|
+
| `invertLeft` | function | `(operator: MathOperation, value: number, rightValue: number) => number` | Inverts a `x op right = value` step, solving for the left operand `x`. |
|
|
201
|
+
| `invertRight` | function | `(operator: MathOperation, value: number, leftValue: number) => number` | Inverts a `left op x = value` step, solving for the right operand `x`. |
|
|
202
|
+
| `applyOperation` | function | `(operator: string, left: number, right: number) => number` | Applies one binary/unary math operation to already-evaluated operands. |
|
|
203
|
+
| `resolveOperand` | function | `(operation: MathOperation, operand?: number) => number` | Resolves the effective right operand of a math operation — the supplied `operand`, or the operation's own identity-preserving default when absent. |
|
|
204
|
+
| `extractAtoms` | function | `(expression: Expression) => readonly Atom[]` | Returns every atom leaf of an expression tree, depth-first, left-to-right. |
|
|
205
|
+
| `extractConclusions` | function | `(expression: Expression) => Record<string, unknown>` | Flattens a logical conclusion expression into its asserted `field = value` pairs, ignoring the connectives. |
|
|
206
|
+
| `findUnboundVariables` | function | `(inference: Inference) => readonly string[]` | Collects the `'?'`-prefixed conclusion variables no premise binds. |
|
|
207
|
+
| `buildErrorResult` | function | `(definition: Definition, message: string) => ReasonResult` | Builds the empty, type-shaped failure `ReasonResult` matching a definition's reasoning. |
|
|
170
208
|
|
|
171
209
|
The definitions & subjects capability layer (§ Classes) adds a pure, copy-on-write change / extend / merge / store surface over every definition kind, plus a subject engine of pure helpers — none of it mutates an input, and every helper returns a fresh value.
|
|
172
210
|
|
|
@@ -224,6 +262,13 @@ Total guards return `false`, never throw, for adversarial input such as junk, cy
|
|
|
224
262
|
|
|
225
263
|
| Name | Kind | Signature | Summary |
|
|
226
264
|
| -------------------------- | -------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
265
|
+
| `isPaddedText` | function | `(value: unknown) => boolean` | Determines whether a value is a string that is blank or differs from its trim, which no comparison reads as the text it would be without the padding. |
|
|
266
|
+
| `isMembership` | const | `Guard<ReadonlyArray<LiteralValue \| null>>` | Determines whether a value is a well-formed membership list for `any` and `none` — a non-empty array of comparable values. |
|
|
267
|
+
| `isRange` | const | `Guard<readonly [number, number]>` | Determines whether a value is a well-formed range for `between` and `outside` — two finite numbers, the first no greater than the second. |
|
|
268
|
+
| `isContractShape` | function | `(value: unknown) => value is ContractShape` | Determines whether a value is a well-formed `ContractShape`, by asking `contract`. |
|
|
269
|
+
| `isComparable` | const | `Guard<LiteralValue \| null>` | Determines whether a value is one a comparison can settle — a lookup key or `null`, which is a value of its own. |
|
|
270
|
+
| `isLookupKey` | const | `Guard<LiteralValue>` | Determines whether a value can key a lookup table — a finite number, a string, or a boolean. |
|
|
271
|
+
| `isCheckState` | const | `Guard<CheckState>` | Determines whether a value is a `CheckState` literal. |
|
|
227
272
|
| `isReasoning` | const | `Guard<Reasoning>` | Determines whether a value is a `Reasoning` literal. |
|
|
228
273
|
| `isChainStrategy` | const | `Guard<ChainStrategy>` | Determines whether a value is a `ChainStrategy` literal. |
|
|
229
274
|
| `isMathOperation` | const | `Guard<MathOperation>` | Determines whether a value is a `MathOperation` literal. |
|
|
@@ -269,6 +314,55 @@ Total guards return `false`, never throw, for adversarial input such as junk, cy
|
|
|
269
314
|
| `isDefinitionBuilder` | function | `(value: unknown) => value is DefinitionBuilderInterface` | Determines whether a value is a `DefinitionBuilder` entity — the brand-guarded stateful workspace, not the plain `Definition` data union. |
|
|
270
315
|
| `isSubjectBuilder` | function | `(value: unknown) => value is SubjectBuilderInterface` | Determines whether a value is a `SubjectBuilder` entity — the brand-guarded stateful workspace, not the plain `Subject` data record. |
|
|
271
316
|
|
|
317
|
+
### Shapes
|
|
318
|
+
|
|
319
|
+
The package's definitions and results as `ContractShape` values, compiled below and read by § Publishing definitions and results.
|
|
320
|
+
|
|
321
|
+
| Name | Kind | Signature | Summary |
|
|
322
|
+
| ------------------------------- | -------- | ----------------------------------- | --------------------------------------------------------------------------------------------- |
|
|
323
|
+
| `createDefinitionShape` | function | `() => ContractShape` | Creates the shape of any `Definition`, discriminated by `reasoning`. |
|
|
324
|
+
| `createSymbolicDefinitionShape` | function | `() => ContractShape` | Creates the shape of a `SymbolicDefinition`. |
|
|
325
|
+
| `createEquationShape` | function | `() => ContractShape` | Creates the shape of an `Equation` — `left = right`, solved for `target`. |
|
|
326
|
+
| `createLogicalDefinitionShape` | function | `() => ContractShape` | Creates the shape of a `LogicalDefinition`. |
|
|
327
|
+
| `createRuleShape` | function | `() => ContractShape` | Creates the shape of a `Rule` — premises and a conclusion. |
|
|
328
|
+
| `resultShape` | const | `ContractShape` | Describes any `ReasonResult` in its JSON projection, discriminated by `reasoning`. |
|
|
329
|
+
| `inferentialResultShape` | const | `ContractShape` | Describes an `InferentialResult` in its JSON projection. |
|
|
330
|
+
| `symbolicResultShape` | const | `ContractShape` | Describes a `SymbolicResult` in its JSON projection. |
|
|
331
|
+
| `logicalResultShape` | const | `ContractShape` | Describes a `LogicalResult` in its JSON projection. |
|
|
332
|
+
| `quantitativeResultShape` | const | `ContractShape` | Describes a `QuantitativeResult` in its JSON projection, where a non-finite number is `null`. |
|
|
333
|
+
| `ruleResultShape` | const | `ContractShape` | Describes a `RuleResult` in its JSON projection. |
|
|
334
|
+
| `groupResultShape` | const | `ContractShape` | Describes a `GroupResult` in its JSON projection, where a non-finite number is `null`. |
|
|
335
|
+
| `factorResultShape` | const | `ContractShape` | Describes a `FactorResult` in its JSON projection, where a non-finite number is `null`. |
|
|
336
|
+
| `checkResultShape` | const | `ContractShape` | Describes a `CheckResult` in its JSON projection. |
|
|
337
|
+
| `inferentialDefinitionShape` | const | `ContractShape` | Describes an `InferentialDefinition`. |
|
|
338
|
+
| `inferenceShape` | const | `ContractShape` | Describes an `Inference` — premise patterns and a conclusion pattern. |
|
|
339
|
+
| `factShape` | const | `ContractShape` | Describes a `Fact` — a predicate over positional terms. |
|
|
340
|
+
| `createSymbolicExpressionShape` | function | `(depth?: number) => ContractShape` | Creates the shape of a `SymbolicExpression` nesting at most `depth` operations. |
|
|
341
|
+
| `createExpressionShape` | function | `(depth?: number) => ContractShape` | Creates the shape of an `Expression` nesting at most `depth` connectives. |
|
|
342
|
+
| `quantitativeDefinitionShape` | const | `ContractShape` | Describes a `QuantitativeDefinition`. |
|
|
343
|
+
| `factorGroupShape` | const | `ContractShape` | Describes a `FactorGroup` — a group of factors aggregated into one value. |
|
|
344
|
+
| `factorShape` | const | `ContractShape` | Describes a `Factor` — one scored input of a quantitative group. |
|
|
345
|
+
| `factorSourceShape` | const | `ContractShape` | Describes a `FactorSource` — a static, field, lookup, or range source. |
|
|
346
|
+
| `factorRangeShape` | const | `ContractShape` | Describes a `FactorRange` — one band of a range source. |
|
|
347
|
+
| `boundsShape` | const | `ContractShape` | Describes a `Bounds` — an inclusive numeric clamp. |
|
|
348
|
+
| `transformShape` | const | `ContractShape` | Describes a `Transform` — one math step. |
|
|
349
|
+
| `checkShape` | const | `ContractShape` | Describes a `Check` — one field predicate, its expected value any JSON value. |
|
|
350
|
+
| `fieldPathShape` | const | `ContractShape` | Describes a `FieldPath` — one key, or the keys descending into nested objects. |
|
|
351
|
+
|
|
352
|
+
### Contracts
|
|
353
|
+
|
|
354
|
+
The compiled contracts of what is flat enough to compile at import, each carrying its JSON Schema. The recursive definition contracts are in § Entity factories.
|
|
355
|
+
|
|
356
|
+
| Name | Kind | Signature | Summary |
|
|
357
|
+
| -------------------------------- | ----- | ---------------------------- | ------------------------------------------------------------------------------------------- |
|
|
358
|
+
| `inferentialResultContract` | const | `ContractInterface<unknown>` | Publishes an `InferentialResult`'s JSON projection as a contract. |
|
|
359
|
+
| `symbolicResultContract` | const | `ContractInterface<unknown>` | Publishes a `SymbolicResult`'s JSON projection as a contract. |
|
|
360
|
+
| `logicalResultContract` | const | `ContractInterface<unknown>` | Publishes a `LogicalResult`'s JSON projection as a contract. |
|
|
361
|
+
| `quantitativeResultContract` | const | `ContractInterface<unknown>` | Publishes a `QuantitativeResult`'s JSON projection as a contract. |
|
|
362
|
+
| `resultContract` | const | `ContractInterface<unknown>` | Publishes any `ReasonResult`'s JSON projection as a contract, read through `projectResult`. |
|
|
363
|
+
| `inferentialDefinitionContract` | const | `ContractInterface<unknown>` | Publishes an `InferentialDefinition` as a contract. Cross it on `is`. |
|
|
364
|
+
| `quantitativeDefinitionContract` | const | `ContractInterface<unknown>` | Publishes a `QuantitativeDefinition` as a contract. Cross it on `is`. |
|
|
365
|
+
|
|
272
366
|
### Errors
|
|
273
367
|
|
|
274
368
|
| Name | Kind | Signature | Summary |
|
|
@@ -280,32 +374,49 @@ Total guards return `false`, never throw, for adversarial input such as junk, cy
|
|
|
280
374
|
|
|
281
375
|
### Constants
|
|
282
376
|
|
|
283
|
-
| Name | Kind | Signature
|
|
284
|
-
| -------------------------- | ----- |
|
|
285
|
-
| `
|
|
286
|
-
| `
|
|
287
|
-
| `
|
|
288
|
-
| `
|
|
289
|
-
| `
|
|
290
|
-
| `
|
|
291
|
-
| `
|
|
292
|
-
| `
|
|
293
|
-
| `
|
|
294
|
-
| `
|
|
295
|
-
| `
|
|
296
|
-
| `
|
|
297
|
-
| `
|
|
298
|
-
| `
|
|
299
|
-
| `
|
|
300
|
-
| `
|
|
301
|
-
| `
|
|
302
|
-
| `
|
|
303
|
-
| `
|
|
377
|
+
| Name | Kind | Signature | Summary |
|
|
378
|
+
| -------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
379
|
+
| `PROJECTION_NODE_LIMIT` | const | `10000` | Holds how many objects and arrays one JSON projection walks before it drops the rest, so a value sharing its sub-objects cannot unfold without end. |
|
|
380
|
+
| `SYMBOLIC_SHAPE_DEPTH` | const | `4` | Holds how many operations the published `SymbolicExpression` shape may nest. |
|
|
381
|
+
| `EXPRESSION_SHAPE_DEPTH` | const | `8` | Holds how many connectives the published `Expression` shape may nest. |
|
|
382
|
+
| `LOGICAL_OPERATORS` | const | `readonly ['and', 'or', 'not', 'implies', 'xor']` | Lists the connectives of a compound expression. |
|
|
383
|
+
| `COMPARISONS` | const | `readonly ['equals', 'not', 'above', 'below', 'from', 'to', 'any', 'none', 'between', 'outside']` | Lists the comparisons a check applies. |
|
|
384
|
+
| `AGGREGATIONS` | const | `readonly ['sum', 'product', 'average', 'minimum', 'maximum']` | Lists how an aggregator reduces a list of numbers to one. |
|
|
385
|
+
| `MATH_OPERATIONS` | const | `readonly ['add', 'subtract', 'multiply', 'divide', 'percentage', 'minimum', 'maximum', 'average', 'power', 'round', 'ceil', 'floor', 'abs']` | Lists the math operations a transform or a symbolic operation applies. |
|
|
386
|
+
| `CHAIN_STRATEGIES` | const | `readonly ['forward', 'backward']` | Lists how a chaining reasoner walks its rules. |
|
|
387
|
+
| `REASONINGS` | const | `readonly ['quantitative', 'logical', 'symbolic', 'inferential']` | Lists the reasoning strategies. |
|
|
388
|
+
| `CHECK_STATES` | const | `readonly ['met', 'unmet', 'unread']` | Lists the states a check, a rule, and a conclusion settle on. |
|
|
389
|
+
| `DEFAULT_REASON_BAIL` | const | `true` | Holds the default `bail` for the `Reason` orchestrator — a reasoner throw is rethrown after the `error` emit. Default: `true`. |
|
|
390
|
+
| `DEFAULT_VALIDATE` | const | `true` | Holds the default `validate` for the `Reason` orchestrator — a definition is validated before it first runs, and remembered by identity. Default: `true`. |
|
|
391
|
+
| `DEFAULT_DEPTH` | const | `10` | Holds the default `depth` for chaining definitions — the forward-iteration / backward-recursion cap of the logical and inferential reasoners. Default: `10`. |
|
|
392
|
+
| `DEFAULT_BASE` | const | `0` | Holds the default `base` added before aggregation, at both group and definition level. Default: `0`. |
|
|
393
|
+
| `DEFAULT_PRECISION` | const | `4` | Holds the default `precision` (decimal places) for quantitative values and symbolic solutions. Default: `4`. |
|
|
394
|
+
| `DEFAULT_CONFIDENCE` | const | `1` | Holds the default `confidence` for facts, inferences, and injected subject facts. Default: `1`. |
|
|
395
|
+
| `DEFAULT_WEIGHT` | const | `1` | Holds the default factor `weight` at group aggregation. Default: `1`. |
|
|
396
|
+
| `DEFAULT_PRIORITY` | const | `0` | Holds the default factor / rule `priority` — evaluation order is ascending and stable. Default: `0`. |
|
|
397
|
+
| `CONFIDENCE_PRECISION` | const | `4` | Holds the decimal places a derived fact's confidence is rounded to during forward inferential chaining. |
|
|
398
|
+
| `INVERTIBLE_OPERATIONS` | const | `ReadonlySet<MathOperation>` | Lists the math operations the symbolic reasoner can invert while isolating a target variable — anything else (a `power`, an `abs`) fails the equation with a non-invertible error. |
|
|
399
|
+
| `EVALUATOR_ID` | const | `"evaluator"` | Names the default `id` for an `Evaluator`. |
|
|
400
|
+
| `TRANSFORMER_ID` | const | `"transformer"` | Names the default `id` for a `Transformer`. |
|
|
401
|
+
| `AGGREGATOR_ID` | const | `"aggregator"` | Names the default `id` for an `Aggregator`. |
|
|
402
|
+
| `QUANTITATIVE_ID` | const | `"quantitative"` | Names the default `id` for a `QuantitativeReasoner`. |
|
|
403
|
+
| `LOGICAL_ID` | const | `"logical"` | Names the default `id` for a `LogicalReasoner`. |
|
|
404
|
+
| `SYMBOLIC_ID` | const | `"symbolic"` | Names the default `id` for a `SymbolicReasoner`. |
|
|
405
|
+
| `INFERENTIAL_ID` | const | `"inferential"` | Names the default `id` for an `InferentialReasoner`. |
|
|
406
|
+
| `DEFINITION_BUILDER_BRAND` | const | `unique symbol` | Holds the `DefinitionBuilder` entity brand — a `unique symbol` key carrying `readonly true` on every `DefinitionBuilderInterface` instance. |
|
|
407
|
+
| `SUBJECT_BUILDER_BRAND` | const | `unique symbol` | Holds the `SubjectBuilder` entity brand — a `unique symbol` key carrying `readonly true` on every `SubjectBuilderInterface` instance. |
|
|
304
408
|
|
|
305
409
|
### Types
|
|
306
410
|
|
|
307
411
|
| Name | Kind | Signature | Summary |
|
|
308
412
|
| ----------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
413
|
+
| `ShapeScan` | interface | `{ errors, warnings }` | Represents what scanning a definition's shape against its reads found. |
|
|
414
|
+
| `ShapeRead` | interface | `{ declared, shape? }` | Represents what a shape says about one field path. |
|
|
415
|
+
| `SubjectDoorInterface` | interface | `{ admit() }` | Declares the door a subject passes before a reasoner reads it. |
|
|
416
|
+
| `SubjectAdmission` | interface | `{ subject?, faults, repairs, defaulted, errors }` | Represents what the `SubjectDoorInterface` made of one subject. |
|
|
417
|
+
| `SourceResult` | interface | `{ value?, fallback }` | Represents what resolving a `FactorSource` found. |
|
|
418
|
+
| `PolarRead` | interface | `{ key, negated }` | Represents one key an expression reads, with whether that read sits under an odd number of negations. |
|
|
419
|
+
| `CheckState` | type | `'met' \| 'unmet' \| 'unread'` | Names what a `Check`, a `RuleResult`, or a `LogicalResult` settled on. |
|
|
309
420
|
| `Reasoning` | type | `'quantitative' \| 'logical' \| 'symbolic' \| 'inferential'` | Names the reasoning strategies — the axis a `Definition` and a `ReasonResult` discriminate on. |
|
|
310
421
|
| `ChainStrategy` | type | `'forward' \| 'backward'` | Names how a chaining reasoner walks its rules: `forward` (data-driven fixpoint) or `backward` (goal-driven proving). |
|
|
311
422
|
| `MathOperation` | type | `'add' \| 'subtract' \| 'multiply' \| 'divide' \| 'percentage' \| 'minimum' \| 'maximum' \| 'average' \| 'power' \| 'round' \| 'ceil' \| 'floor' \| 'abs'` | Names a math operation applied by the `TransformerInterface` and inside `SymbolicExpression` trees. |
|
|
@@ -314,7 +425,7 @@ Total guards return `false`, never throw, for adversarial input such as junk, cy
|
|
|
314
425
|
| `LogicalOperator` | type | `'and' \| 'or' \| 'not' \| 'implies' \| 'xor'` | Names a logical connective inside a compound `Expression`. |
|
|
315
426
|
| `Subject` | type | `Readonly<Record<string, unknown>>` | Represents the data record being reasoned about — a plain readonly bag of fields, read by `FieldPath`. |
|
|
316
427
|
| `Check` | interface | `{ field, operator, value }` | Represents a single field predicate: resolves `field` from the subject and compares it to `value` with `operator`. |
|
|
317
|
-
| `CheckResult` | interface | `{ field,
|
|
428
|
+
| `CheckResult` | interface | `{ field, state, actual, error? }` | Represents the outcome of one `Check` evaluation. |
|
|
318
429
|
| `Transform` | interface | `{ operation, operand? }` | Represents one math step applied to a number by the `TransformerInterface`. |
|
|
319
430
|
| `Bounds` | interface | `{ minimum?, maximum? }` | Represents an inclusive numeric clamp — either side may be absent (unbounded). |
|
|
320
431
|
| `StaticSource` | interface | `{ origin, value }` | Represents a factor source yielding a fixed number. |
|
|
@@ -325,37 +436,36 @@ Total guards return `false`, never throw, for adversarial input such as junk, cy
|
|
|
325
436
|
| `FactorRange` | interface | `{ bounds?, value }` | Represents one band of a `RangeSource` — an optional inclusive bounds test and the value it yields. |
|
|
326
437
|
| `Factor` | interface | `{ id, name, description?, source, fallback?, checks?, transforms?, bounds?, weight?, priority?, enabled?, required? }` | Represents one scored input of a quantitative group. |
|
|
327
438
|
| `FactorGroup` | interface | `{ id, name, description?, factors, aggregation, base?, bounds?, enabled?, strict? }` | Represents a group of factors aggregated into one value. |
|
|
328
|
-
| `QuantitativeDefinition` | interface | `{ reasoning, id, name, description?, groups, aggregation, base?, bounds?, precision? }`
|
|
439
|
+
| `QuantitativeDefinition` | interface | `{ reasoning, id, name, description?, groups, aggregation, base?, bounds?, precision?, shape? }` | Defines factor-based numeric scoring. |
|
|
329
440
|
| `Atom` | interface | `{ form, check }` | Represents a leaf boolean expression — one `Check` against the subject. |
|
|
330
441
|
| `Compound` | interface | `{ form, operator, operands }` | Represents a compound boolean expression — a `LogicalOperator` over nested operands. |
|
|
331
442
|
| `Expression` | type | `Atom \| Compound` | Represents a boolean expression tree, discriminated by `form`. |
|
|
332
443
|
| `Rule` | interface | `{ id, name, description?, premises, conclusion, priority?, enabled? }` | Represents one deduction rule: when every premise holds, the `conclusion`'s atoms are asserted as derived facts. |
|
|
333
|
-
| `LogicalDefinition` | interface | `{ reasoning, id, name, description?, rules, strategy, depth? }`
|
|
444
|
+
| `LogicalDefinition` | interface | `{ reasoning, id, name, description?, rules, strategy, depth?, shape? }` | Defines rule-based deduction. |
|
|
334
445
|
| `Variable` | interface | `{ form, name }` | Represents a symbolic expression leaf naming a variable. |
|
|
335
446
|
| `Constant` | interface | `{ form, value }` | Represents a symbolic expression leaf holding a fixed number. |
|
|
336
447
|
| `Operation` | interface | `{ form, operator, left, right? }` | Represents a symbolic operation node. |
|
|
337
448
|
| `SymbolicExpression` | type | `Variable \| Constant \| Operation` | Represents an algebraic expression tree, discriminated by `form`. |
|
|
338
449
|
| `Equation` | interface | `{ id, name, description?, left, right, target }` | Represents one equation `left = right`, solved for the `target` variable. |
|
|
339
|
-
| `SymbolicDefinition` | interface | `{ reasoning, id, name, description?, equations, variables, precision? }`
|
|
450
|
+
| `SymbolicDefinition` | interface | `{ reasoning, id, name, description?, equations, variables, precision?, shape? }` | Defines equation-solving. |
|
|
340
451
|
| `Fact` | interface | `{ id, predicate, terms, confidence? }` | Represents one fact: a `predicate` over positional `terms`. |
|
|
341
452
|
| `Inference` | interface | `{ id, name, description?, premises, conclusion, confidence?, enabled? }` | Represents one inference rule: when every premise pattern unifies against known facts (with consistent variable bindings), the instantiated `conclusion` is derived. |
|
|
342
|
-
| `InferentialDefinition` | interface | `{ reasoning, id, name, description?, inferences, facts, strategy, depth? }`
|
|
453
|
+
| `InferentialDefinition` | interface | `{ reasoning, id, name, description?, inferences, facts, strategy, depth?, shape? }` | Defines fact-derivation. |
|
|
343
454
|
| `Definition` | type | `QuantitativeDefinition \| LogicalDefinition \| SymbolicDefinition \| InferentialDefinition` | Represents any reasoning definition, discriminated by `reasoning`. |
|
|
344
455
|
| `DefinitionEnvelope` | type | `Omit<QuantitativeDefinition, 'groups'> \| Omit<LogicalDefinition, 'rules'> \| Omit<SymbolicDefinition, 'equations' \| 'variables'> \| Omit<InferentialDefinition, 'facts' \| 'inferences'>` | Represents the scalar-only projection of each definition kind — the `DefinitionBuilderInterface` implementation's private envelope holds the non-collection fields; `build()` re-composes the kind's collections from the managers' plural accessors. |
|
|
345
|
-
| `QuantitativeClearKey` | type | `'description' \| 'base' \| 'bounds' \| 'precision'`
|
|
346
|
-
| `LogicalClearKey` | type | `'description' \| 'depth'`
|
|
347
|
-
| `SymbolicClearKey` | type | `'description' \| 'precision'`
|
|
348
|
-
| `InferentialClearKey` | type | `'description' \| 'depth'`
|
|
349
|
-
| `LogicalChainResult` | interface | `{ conclusion, rules }` | Represents one chaining pass of the `LogicalReasoner` — the overall `conclusion` plus the per-rule results the pass produced. |
|
|
456
|
+
| `QuantitativeClearKey` | type | `'description' \| 'base' \| 'bounds' \| 'precision' \| 'shape'` | Names the optional `QuantitativeDefinition` fields `clearQuantitativeDefinition` (and a quantitative `DefinitionBuilderInterface`'s `clear`) can delete. |
|
|
457
|
+
| `LogicalClearKey` | type | `'description' \| 'depth' \| 'shape'` | Names the optional `LogicalDefinition` fields `clearLogicalDefinition` (and a logical `DefinitionBuilderInterface`'s `clear`) can delete. |
|
|
458
|
+
| `SymbolicClearKey` | type | `'description' \| 'precision' \| 'shape'` | Names the optional `SymbolicDefinition` fields `clearSymbolicDefinition` (and a symbolic `DefinitionBuilderInterface`'s `clear`) can delete. |
|
|
459
|
+
| `InferentialClearKey` | type | `'description' \| 'depth' \| 'shape'` | Names the optional `InferentialDefinition` fields `clearInferentialDefinition` (and an inferential `DefinitionBuilderInterface`'s `clear`) can delete. |
|
|
350
460
|
| `InferentialChainResult` | interface | `{ derived, proof? }` | Represents one chaining pass of the `InferentialReasoner` — the facts the pass derived plus the proof tree, when the pass produced one. |
|
|
351
461
|
| `FactorResult` | interface | `{ id, applied, value, raw?, checks? }` | Represents one factor's evaluation outcome. |
|
|
352
462
|
| `GroupResult` | interface | `{ id, applied, value, factors }` | Represents one group's evaluation outcome — its clamped value and the per-factor results (disabled factors omitted entirely). |
|
|
353
|
-
| `QuantitativeResult` | interface | `{ reasoning, value, groups, count, success, trace, errors }`
|
|
354
|
-
| `RuleResult` | interface | `{ id,
|
|
355
|
-
| `LogicalResult` | interface | `{ reasoning, conclusion, rules, count, success, trace, errors }`
|
|
356
|
-
| `SymbolicResult` | interface | `{ reasoning, solutions, success, trace, errors }`
|
|
463
|
+
| `QuantitativeResult` | interface | `{ reasoning, value, groups, count, success, trace, errors, faults, repairs, defaulted }` | Represents the outcome of quantitative reasoning. |
|
|
464
|
+
| `RuleResult` | interface | `{ id, state, premises, checks }` | Represents one rule's evaluation outcome. |
|
|
465
|
+
| `LogicalResult` | interface | `{ reasoning, conclusion, rules, count, success, trace, errors, faults, repairs, defaulted }` | Represents the outcome of logical reasoning. |
|
|
466
|
+
| `SymbolicResult` | interface | `{ reasoning, solutions, success, trace, errors, faults, repairs, defaulted }` | Represents the outcome of symbolic reasoning — final bindings keyed by each equation's `target` (a failed equation's target still appears when bound elsewhere). |
|
|
357
467
|
| `ProofNode` | interface | `{ fact, inference?, children?, depth }` | Represents one node of a backward-chaining proof tree. |
|
|
358
|
-
| `InferentialResult` | interface | `{ reasoning, derived, proof?, success, trace, errors }`
|
|
468
|
+
| `InferentialResult` | interface | `{ reasoning, derived, proof?, success, trace, errors, faults, repairs, defaulted }` | Represents the outcome of inferential reasoning. |
|
|
359
469
|
| `ReasonResult` | type | `QuantitativeResult \| LogicalResult \| SymbolicResult \| InferentialResult` | Represents any reasoning result, discriminated by `reasoning`. |
|
|
360
470
|
| `ReasonValidationResult` | interface | `{ valid, errors, warnings }` | Represents the outcome of validating a definition — hard `errors` (definition unusable) and soft `warnings` (suspicious but runnable). `valid` is `true` exactly when `errors` is empty. |
|
|
361
471
|
| `EvaluatorOptions` | interface | `{ id? }` | Configures `createEvaluator` / the `Evaluator` constructor. |
|
|
@@ -449,6 +559,12 @@ The array overload of `reason` is declared first so a subject list resolves to t
|
|
|
449
559
|
| ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
450
560
|
| `aggregate` | `number` | Reduces the values per aggregation; `weights` are honored only on an exact length match, and `minimum` / `maximum` ignore them. |
|
|
451
561
|
|
|
562
|
+
#### `SubjectDoorInterface`
|
|
563
|
+
|
|
564
|
+
| Method | Returns | Summary |
|
|
565
|
+
| ------- | ------------------ | ------------------------------------------------------------------------------------------- |
|
|
566
|
+
| `admit` | `SubjectAdmission` | Admits a subject through a shape, or refuses it and says why; no shape admits it unchanged. |
|
|
567
|
+
|
|
452
568
|
#### `GroupManagerInterface`
|
|
453
569
|
|
|
454
570
|
The self-owning manager over a quantitative definition's `groups`. Managers are kind-free — an off-kind collection is ignored by `build()`, never a throw. A call after `destroy()` throws `DESTROYED`.
|
|
@@ -583,21 +699,21 @@ The `SUBJECT_BUILDER_BRAND`-carrying stateful builder accumulating a `Subject`.
|
|
|
583
699
|
These invariants hold across `src/core` ↔ `reason.md`:
|
|
584
700
|
|
|
585
701
|
1. **DOC ↔ SOURCE bijection.** Every `function` / `class` / `const` / `interface` / `type` row in the `## Surface` tables is a real export of the reason source tree, and every export appears as a Surface row — exhaustive in each direction.
|
|
586
|
-
2. **Deterministic, synchronous, immutable.** Same subject + same definition → the same result, every time — no clocks, no randomness, no I/O, nothing async. No input is ever mutated; every result (and every builder output) is a fresh object. A result always carries `success`, a `trace` narrating each step,
|
|
587
|
-
3. **Dispatch and `bail`.** The orchestrator is a thin router: registry lookup by `definition.reasoning`, one reasoner per reasoning, re-registration replaces. A registry miss throws `MISSING` and a pre-run validation failure (
|
|
588
|
-
4. **Failure results, not throws, inside a reasoner.** A reasoner's single throw is `MISMATCH` (handed a definition of a different reasoning); every structural malformation — missing / non-array `groups` / `rules` / `equations` / `facts` — yields a failure result, because the runtime never assumes `validate` ran. The operators are total the same way: an unknown `Comparison` surfaces as `CheckResult.error` (`
|
|
589
|
-
5. **Guard totality and exactness.** Every validator is a total `Guard` — adversarial input (cycles, depth, hostile prototypes) returns `false`, never throws. Caller-supplied input records are exact and their numeric fields require `isFiniteNumber` because definitions must survive JSON. result guards accept open objects, including class instances, and guard published numeric members with `isNumber`, including `NaN` and infinities. Nested result members follow the same posture; `isInferentialResult` checks `derived` with the open `isResultFact` guard. The recursive input shapes enter through `lazyOf`; `isProofNode` uses a bounded iterative traversal. Builders omit absent optional input keys so their outputs round-trip the input guards.
|
|
702
|
+
2. **Deterministic, synchronous, immutable.** Same subject + same definition → the same result, every time — no clocks, no randomness, no I/O, nothing async. No input is ever mutated; every result (and every builder output) is a fresh object. A result always carries `success`, a `trace` narrating each step, the accumulated `errors`, and the `faults`, `repairs`, and `defaulted` channel — `success` is exactly `errors.length === 0`, and an error does not abort the run (the value / solutions are still computed from whatever applied), it makes `success` false. Expression evaluation and symbolic isolation recurse with the input expression's own depth, so a pathologically deep hand-built expression (on the order of `10,000` levels of nesting) is outside the supported contract and may exhaust the call stack; `extractAtoms` and `containsVariable` are the exception — both walk iteratively and stay total at any depth. The workspace builders (and their managers) are the deliberate stateful exception to statelessness, not to immutability: they mutate nothing they are given (the seed is spread on construction, every mutation is copy-on-write through the pure helper family), and `build()` returns a fresh payload deterministically derived from the current state, every call — handed to `reason` by the caller, never built inside the engine.
|
|
703
|
+
3. **Dispatch and `bail`.** The orchestrator is a thin router: registry lookup by `definition.reasoning`, one reasoner per reasoning, re-registration replaces. A registry miss throws `MISSING` and a pre-run validation failure (the `validate` option is on by default) throws `INVALID` — both are caller misuse, bypass `bail`, and emit nothing. A reasoner throw always emits `error` with the raw thrown value; under `bail: true` (the default) it is rethrown, under `bail: false` it becomes an empty type-shaped failure result. Only successful results emit `reason`. The batch overload maps subjects in order. A valid definition is remembered by identity, so one definition validates once per orchestrator.
|
|
704
|
+
4. **Failure results, not throws, inside a reasoner.** A reasoner's single throw is `MISMATCH` (handed a definition of a different reasoning); every structural malformation — missing / non-array `groups` / `rules` / `equations` / `facts` — yields a failure result, because the runtime never assumes `validate` ran. The operators are total the same way: an unknown `Comparison` surfaces as `CheckResult.error` (`state: 'unread'`), an unknown `MathOperation` and divide-by-zero are `NaN`, weights of another length, a zero total weight, and an unknown `Aggregation` are `NaN`, and the `Aggregator` has fixed empty-input identities (`sum` / `average` → `0`, `product` → `1`, `minimum` / `maximum` → `NaN`). Definition arrays (`facts` / `inferences` / `rules` / `equations` / `groups` / `factors`) are iterated defensively — an array hole, `null`, or other ill-typed junk entry never crashes evaluation and never passes unnoticed: it is named in `errors`, and the run refuses.
|
|
705
|
+
5. **Guard totality and exactness.** Every validator is a total `Guard` — adversarial input (cycles, depth, hostile prototypes) returns `false`, never throws. Caller-supplied input records are exact and their numeric fields require `isFiniteNumber` because definitions must survive JSON. result guards accept open objects, including class instances, and guard published numeric members with `isNumber`, including `NaN` and infinities. Nested result members follow the same posture; `isInferentialResult` checks `derived` with the open `isResultFact` guard. The recursive input shapes enter through `lazyOf`; `isProofNode` uses a bounded iterative traversal. Builders omit absent optional input keys so their outputs round-trip the input guards. A numeric subject read takes a finite number and nothing else — a numeric string and `NaN` / `±Infinity` subject values read `unread`, never the non-finite error path (still reachable through static sources and transform / inversion results). § Reading what is there states each rule. The only coercion is the door's, which reports it (§ The subject door).
|
|
590
706
|
6. **Observation is a pure side-channel.** The `Reason` owns a typed `emitter` (`ReasonEventMap` — `register(reasoning)` / `reason(result)` / `error(error)` / `destroy()`); each manager owns its own (`{X}ManagerEventMap` — its mutation verbs, element-id payloads, plus `destroy`), and the builders keep reduced maps of the operations that are theirs alone (`DefinitionBuilderEventMap` — `merge` / `clear` / `destroy`; `SubjectBuilderEventMap` — `set` / `remove` / `merge` / `clear` / `destroy`); reasoners and operators are event-free by design (stateless evaluators have no observable lifecycle). Every event is emitted directly and synchronously, after the mutation it reports; listener isolation is the emitter's own — a throwing listener routes to the `error` option handler (`(error, event)`), never onto the domain map. `destroy()` clears the registry, emits `destroy`, then destroys the emitter last; it is idempotent, and afterwards every method except the `emitter` getter and `destroy` itself throws `DESTROYED`. The managers follow the identical lifecycle, and `DefinitionBuilder.destroy()` cascades to every manager first, its own emitter last.
|
|
591
707
|
7. **Coded errors.** Every throw out of this module is a `ReasonError` with a machine-readable `code` (`MISSING` / `INVALID` / `MISMATCH` / `DESTROYED` / `TARGET` / `OPERATOR`) and — except `DESTROYED` — a `context` carrying the definition id and the reasoning involved, or the offending `id` / `target` / `groupId` for `TARGET`, the `key` for a non-clearable `clear`, and the `operator` for `OPERATOR`; `catch` blocks narrow with `isReasonError`, never `as`. `MISMATCH` covers a cross-reasoning definition handed to a reasoner or to `DefinitionBuilder.merge`, a `clear` key that is not clearable for the builder's reasoning, and a write to a `SubjectBuilder`'s immutable `id`; `DESTROYED` covers any use of a destroyed orchestrator, builder, or manager; `OPERATOR` covers a math operator outside the accepted vocabulary — `invertLeft` / `invertRight` on a non-invertible operation, and `applyOperation` on an unknown one.
|
|
592
708
|
8. **DOC ↔ SOURCE method bijection.** Every behavioral interface's `## Methods` table lists exactly its public methods (call-signature members) — exhaustive in each direction — and each implementing class exposes the same public methods, no more. A renamed / added / removed method breaks the gate until the table is reconciled.
|
|
593
709
|
|
|
594
|
-
These runtime rules hold alongside the numbered invariants. Derivation bookkeeping compares with SameValueZero (`equalValues`), so a NaN-valued conclusion or fact term derives once and the fixpoint converges. The definition-level quantitative value is finite-checked after rounding (`Definition "<id>" produced non-finite value: <v>`). `roundTo` passes the value through unchanged at extreme precisions whose scale factor overflows. Inverting a left-operand divide by zero (`x / 0 = c`) yields the non-finite equation error. A lookup reads only own table keys
|
|
710
|
+
These runtime rules hold alongside the numbered invariants. Derivation bookkeeping compares with SameValueZero (`equalValues`), so a NaN-valued conclusion or fact term derives once and the fixpoint converges. The definition-level quantitative value is finite-checked after rounding (`Definition "<id>" produced non-finite value: <v>`). `roundTo` passes the value through unchanged at extreme precisions whose scale factor overflows. Inverting a left-operand divide by zero (`x / 0 = c`) yields the non-finite equation error. A lookup reads only own table keys; a missing / `null` field refuses before any `''` key or `fallback`, and the `fallback` answers only a readable value the table misses. The malformed-shape paths stay graceful and refuse — a missing / non-array `premises` on a logical rule and a missing factor `source` are named in `errors`, never thrown. `validate` refuses what a run could only guess at (§ Narrowing untrusted definitions), while runtime behavior around duplicates is unchanged when it is skipped. Still out of scope: asynchronous reasoners, definition persistence, and contract-DSL shapes for the definition family (the plain guards in § Validators suffice) — all additive, leaving the preceding surface unchanged.
|
|
595
711
|
|
|
596
712
|
## Patterns
|
|
597
713
|
|
|
598
714
|
### Quantitative scoring
|
|
599
715
|
|
|
600
|
-
Each factor runs a pipeline — `checks` gate (all must be met) → `source` resolve (`fallback`
|
|
716
|
+
Each factor runs a pipeline — `checks` gate (all must be met) → `source` resolve (an unread field refuses, and `fallback` answers only a readable value a lookup or range misses) → finite check → `transforms` chain → `bounds` clamp — in ascending `priority` order (stable). A group's value is its `base` plus the weighted aggregation of the factors that applied, clamped but never rounded; `strict: true` makes the group all-or-nothing. The definition's value aggregates the applied groups (no weights at this level), clamps, rounds to `precision`, then is finite-checked: the `Aggregator`'s empty-input `NaN` for `minimum` / `maximum` is its deliberate "no data" signal, so aggregating zero applied groups under those surfaces as a `Definition "<id>" produced non-finite value: NaN` error (`success: false`, the `NaN` left visible in `value`) rather than a silent success. An unapplied group's `GroupResult.value` may still be `NaN` the same way — it is excluded from the definition aggregate, so only its own record shows it.
|
|
601
717
|
|
|
602
718
|
```ts
|
|
603
719
|
import {
|
|
@@ -623,7 +739,7 @@ const definition = createQuantitativeDefinition('premium', 'Premium', [
|
|
|
623
739
|
checks: [createCheck('licensed', 'equals', true)], // gate: all checks must be met
|
|
624
740
|
transforms: [createTransform('percentage', 50)], // then 50% of the raw value
|
|
625
741
|
bounds: createBounds(0, 40), // then clamp
|
|
626
|
-
required: true, //
|
|
742
|
+
required: true, // an unmet gate becomes a result error
|
|
627
743
|
}),
|
|
628
744
|
createLookupFactor('region', 'region', { CA: 12, NY: 8 }, { fallback: 5, weight: 2 }),
|
|
629
745
|
],
|
|
@@ -638,7 +754,7 @@ if (result.reasoning === 'quantitative') {
|
|
|
638
754
|
}
|
|
639
755
|
```
|
|
640
756
|
|
|
641
|
-
An `enabled: false` factor or group is skipped and omitted from results; a `required` factor
|
|
757
|
+
An `enabled: false` factor or group is skipped and omitted from results; a `required` factor whose gate settles unmet adds an error, and a field a gate or source cannot read adds one whether the factor is required or not (`success: false`), while the rest of the run continues.
|
|
642
758
|
|
|
643
759
|
The `Evaluator`, `Transformer`, and `Aggregator` operators are usable directly, independent of any reasoner — the `QuantitativeReasoner` composes them internally, but each is a total, injectable seam:
|
|
644
760
|
|
|
@@ -652,7 +768,7 @@ import {
|
|
|
652
768
|
} from '@orkestrel/reason'
|
|
653
769
|
|
|
654
770
|
const evaluator = createEvaluator()
|
|
655
|
-
evaluator.evaluate(createCheck('age', 'above', 18), { age: 25 }) // { field: 'age',
|
|
771
|
+
evaluator.evaluate(createCheck('age', 'above', 18), { age: 25 }) // { field: 'age', state: 'met', actual: 25 }
|
|
656
772
|
evaluator.batch([createCheck('age', 'above', 18)], { age: 25 }) // one CheckResult per check, positionally
|
|
657
773
|
|
|
658
774
|
const transformer = createTransformer()
|
|
@@ -712,7 +828,7 @@ Number(rounded) / 10000 // 21.1313 — matches the exact value
|
|
|
712
828
|
|
|
713
829
|
### Logical chaining — forward and backward
|
|
714
830
|
|
|
715
|
-
Forward chaining runs the rules (ascending `priority`) to a fixpoint: each firing rule asserts its conclusion's atoms as derived facts overlaid on the subject (keyed by `formatField`),
|
|
831
|
+
Forward chaining runs in two phases. First the rules (ascending `priority`) run to a fixpoint: each firing rule asserts its conclusion's atoms as derived facts overlaid on the subject (keyed by `formatField`), and an atom on a conclusion key no rule has derived yet reads `unread`, so a rule reading it holds rather than guessing. Then every key whose concluding rules have all settled `unmet` closes, and the held rules run again; a key that only waits on itself closes too, so a positive cycle is `unmet` rather than stuck. The reported `rules` are re-evaluated in original order against the final overlay, and `conclusion` is the last enabled rule's state, `unmet` when none ran, or `unread` when anything refused. Backward chaining answers from that same loop, so both strategies reach one supported model: `rules`, `conclusion`, `faults`, and `success` agree on any definition, and only the trace differs. What backward adds is an explanation: it also proves every enabled rule goal-first in priority order, on its own state, recursing into the rules concluding a premise's field with a visited-rule cycle guard, and the trace says what held and what did not. Those proofs answer nothing, and one past `depth` stops and says so. It costs the forward run plus the proofs, so choose it for the trace and not for speed. `depth` counts the passes that derive something, in both. `priority` sets the order rules fire in, and it no longer picks backward's `conclusion`, which comes from the last authored rule as forward's does. Hitting `depth` refuses in both.
|
|
716
832
|
|
|
717
833
|
```ts
|
|
718
834
|
import {
|
|
@@ -744,19 +860,166 @@ const forward = reason.reason(
|
|
|
744
860
|
{ age: 25, accidents: 0 },
|
|
745
861
|
createLogicalDefinition('e', 'Eligibility', rules),
|
|
746
862
|
)
|
|
747
|
-
if (forward.reasoning === 'logical') forward.conclusion //
|
|
863
|
+
if (forward.reasoning === 'logical') forward.conclusion // 'met' — 'eligible' through the derived 'adult'
|
|
748
864
|
|
|
749
865
|
// Backward: prove the last rule's conclusion, recursing only where needed.
|
|
750
866
|
const goal = createLogicalDefinition('e', 'Eligibility', rules, { strategy: 'backward', depth: 5 })
|
|
751
867
|
```
|
|
752
868
|
|
|
753
|
-
Connectives
|
|
869
|
+
Connectives combine in strong Kleene logic (§ Reading what is there), and one of the wrong arity reads `unread`. A conclusion may only assert: `equals` atoms, joined by `and`, none asserting `false`.
|
|
870
|
+
|
|
871
|
+
Quirks to design around. **Derived-overlay keys are `formatField` strings**: a conclusion written with an array path derives the dot-joined flat key, and the overlay answers a premise reading that path in either form. **A `premises: []` rule refuses in both strategies** with `Rule "<id>" has no premises`. **The fixpoint snapshots per iteration**: a derivation made mid-pass is invisible until the next pass (unlike the inferential reasoner's live fact list), so a `depth` cap truncates chains one hop per iteration regardless of declaration order.
|
|
872
|
+
|
|
873
|
+
Both strategies pass over every rule once per pass, so a chain grows about quadratically. At the default `depth` a long chain refuses after 10 passes, so these costs only show with `depth` raised to fit it. A chain with `depth` raised, median of three on one desktop, with a chain this long not a path anything takes today:
|
|
874
|
+
|
|
875
|
+
| Rules | Forward | Backward |
|
|
876
|
+
| ----- | -------- | -------- |
|
|
877
|
+
| 100 | 24 ms | 18 ms |
|
|
878
|
+
| 300 | 133 ms | 134 ms |
|
|
879
|
+
| 600 | 541 ms | 565 ms |
|
|
880
|
+
| 1,200 | 2,307 ms | 2,150 ms |
|
|
881
|
+
|
|
882
|
+
### Reading what is there
|
|
883
|
+
|
|
884
|
+
The engine answers only from what it read. A check and a rule settle on `met`, `unmet`, or `unread`, a logical result's `conclusion` does too, and `unread` never becomes an answer by default: any rule left `unread` makes `success` false, `faults` names each input field that stopped it, and `errors` holds one string per fault.
|
|
885
|
+
|
|
886
|
+
```ts
|
|
887
|
+
import {
|
|
888
|
+
createAtom,
|
|
889
|
+
createLogicalDefinition,
|
|
890
|
+
createLogicalReasoner,
|
|
891
|
+
createReason,
|
|
892
|
+
createRule,
|
|
893
|
+
} from '@orkestrel/reason'
|
|
894
|
+
|
|
895
|
+
const reason = createReason({ reasoners: [createLogicalReasoner()] })
|
|
896
|
+
|
|
897
|
+
const definition = createLogicalDefinition('credit', 'Credit', [
|
|
898
|
+
createRule('low', [createAtom('credit', 'below', 600)], createAtom('low', 'equals', true)),
|
|
899
|
+
])
|
|
900
|
+
|
|
901
|
+
const result = reason.reason({}, definition)
|
|
902
|
+
if (result.reasoning === 'logical') {
|
|
903
|
+
result.conclusion // 'unread' — no credit is not low credit
|
|
904
|
+
result.success // false
|
|
905
|
+
result.errors // ['credit: missing; expected number']
|
|
906
|
+
result.faults // [{ reason: 'missing', path: 'credit', expected: 'number' }]
|
|
907
|
+
}
|
|
908
|
+
```
|
|
909
|
+
|
|
910
|
+
A comparison reads `unread` when it cannot read a side, and these reads hold with a shape or without one, because a `raw` field and an open object's extras are never normalized. Nothing is coerced. An absent field, an object, an array, `NaN`, `±Infinity`, and a bigint read `unread` for every comparison.
|
|
911
|
+
|
|
912
|
+
| Comparison | Settles when | Reads `unread` on |
|
|
913
|
+
| --------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
|
914
|
+
| `above` / `below` / `from` / `to` | Both sides are finite numbers. | Anything else, a numeric string, a boolean, and `null` included. |
|
|
915
|
+
| `between` / `outside` | The field is a finite number and the expected value is `[minimum, maximum]` of finite numbers in order. | Anything else, a reversed or short range included. |
|
|
916
|
+
| `equals` / `not` | Both sides have one primitive type, or the expected value is `null` and the field is present. | Any other difference of type, and a string that is blank or differs from its trim. |
|
|
917
|
+
| `any` / `none` | An element is exactly the field's value, or no element is and every element has the field's type. | No hit and an element of another type, a string that is blank or differs from its trim, an empty list, or a list that is not one. |
|
|
918
|
+
|
|
919
|
+
A difference of type never settles, because every answer would be a guess about what the writer meant. `'1' equals 1`, `'no' equals false`, and `true not 'true'` all refuse rather than read `unmet` or `met`, and `x not 'none'` over 90 refuses too, so the author writes `x not null`.
|
|
920
|
+
|
|
921
|
+
`null` is a value. `equals null` and `not null` settle on a present field unless it is a blank or padded string, an ordering on `null` reads `unread`, and `and(spouse not null, spouse above 0)` settles on `null`, which is the authored form of "does not apply".
|
|
922
|
+
|
|
923
|
+
Connectives combine in strong Kleene logic, so `unread` survives only where the answer could still change. `age above 18 and credit above 600` with age 15 and no credit is exactly `unmet`, and nothing is asked about credit.
|
|
924
|
+
|
|
925
|
+
| Left | Right | `and` | `or` | `implies` | `xor` |
|
|
926
|
+
| -------- | -------- | -------- | -------- | --------- | -------- |
|
|
927
|
+
| `met` | `met` | `met` | `met` | `met` | `unmet` |
|
|
928
|
+
| `met` | `unmet` | `unmet` | `met` | `unmet` | `met` |
|
|
929
|
+
| `met` | `unread` | `unread` | `met` | `unread` | `unread` |
|
|
930
|
+
| `unmet` | `met` | `unmet` | `met` | `met` | `met` |
|
|
931
|
+
| `unmet` | `unmet` | `unmet` | `unmet` | `met` | `unmet` |
|
|
932
|
+
| `unmet` | `unread` | `unmet` | `unread` | `met` | `unread` |
|
|
933
|
+
| `unread` | `met` | `unread` | `met` | `met` | `unread` |
|
|
934
|
+
| `unread` | `unmet` | `unmet` | `unread` | `unread` | `unread` |
|
|
935
|
+
| `unread` | `unread` | `unread` | `unread` | `unread` | `unread` |
|
|
936
|
+
|
|
937
|
+
`not` flips `met` and `unmet` and leaves `unread`. A hole in the operands and a wrong arity read `unread`.
|
|
938
|
+
|
|
939
|
+
Closed-world covers one thing: a key an enabled rule of the same definition concludes. Once every rule that could conclude it has settled `unmet`, `equals` and `any` read `unmet` on it, `not` and `none` read `met`, and an ordering or range comparison refuses (`Rule "<id>" reads conclusion "<key>" with "<operator>", and no rule concluded a value`), because the key holds no number. A subject may not supply such a key (`Subject supplies conclusion "<key>"`), since that would assert what a rule has to derive. A cycle through negation has no answer any order of evaluation could settle: `validate` names its keys, and on a run that skipped `validate`, backward refuses it before any proof and forward refuses it when it fires. A positive cycle only waits on itself, so it closes `unmet` before anything reading it settles.
|
|
940
|
+
|
|
941
|
+
A quantitative factor refuses the same way. A field or range source reads a finite number, and a lookup key is a string, a finite number, or a boolean. A readable value the table or bands have no answer for, with no `fallback`, is an error rather than a fault, because the input is not what is wrong. `fallback` is for a lookup or range source and answers one case, a readable value the table or bands miss, which the trace records as `Factor "<id>": took its fallback, <value>`; `validate` refuses it on a field or static source. A symbolic subject field binds only as a finite number, and an inferential `depth` cap that leaves a goal unproved refuses.
|
|
942
|
+
|
|
943
|
+
### The subject door
|
|
944
|
+
|
|
945
|
+
A definition may carry a `shape`, one `ContractShape` that says what its subject is: which fields, of what type, required or optional. The reasoner admits the subject through it first, so the shape is the one place that decides, and it reaches an LLM, a tool, or MCP unchanged as `compileSchema(shape)`.
|
|
946
|
+
|
|
947
|
+
```ts
|
|
948
|
+
import { booleanShape, numberShape, objectShape, optionalShape } from '@orkestrel/contract'
|
|
949
|
+
import {
|
|
950
|
+
createAtom,
|
|
951
|
+
createLogicalDefinition,
|
|
952
|
+
createLogicalReasoner,
|
|
953
|
+
createRule,
|
|
954
|
+
} from '@orkestrel/reason'
|
|
955
|
+
|
|
956
|
+
const definition = createLogicalDefinition(
|
|
957
|
+
'adult',
|
|
958
|
+
'Adult',
|
|
959
|
+
[createRule('adult', [createAtom('age', 'from', 18)], createAtom('adult', 'equals', true))],
|
|
960
|
+
{ shape: objectShape({ age: numberShape(), licensed: optionalShape(booleanShape()) }) },
|
|
961
|
+
)
|
|
962
|
+
const reasoner = createLogicalReasoner()
|
|
963
|
+
|
|
964
|
+
const repaired = reasoner.reason({ age: '30' }, definition)
|
|
965
|
+
repaired.success // true
|
|
966
|
+
repaired.repairs // [{ reason: 'type', path: ['age'], expected: 'number', received: '"30"' }]
|
|
967
|
+
|
|
968
|
+
reasoner.reason({ age: 30, agee: 1 }, definition).errors // ['agee: extra; this key is not declared, remove it']
|
|
969
|
+
reasoner.reason({ age: '30.0' }, definition).errors // ['age: type; expected number; received "30.0"']
|
|
970
|
+
```
|
|
971
|
+
|
|
972
|
+
A subject with accessors has to read the same every time, because `explain`, `audit`, and `parse` each read it: a getter answering `30` and then `'30.0'` is admitted as `{ age: 30 }` with no repair recorded. Hand the door plain data. The same goes for a definition: `validate` runs once per definition by identity, so one edited in place after its first run is not validated again. Build a new one instead.
|
|
973
|
+
|
|
974
|
+
The door uses the dependency's admission boundary to refuse undeclared keys, ambiguous unions, truncated audits, and lossy repairs. An object declared open admits extras.
|
|
975
|
+
|
|
976
|
+
A door fault's `path` is `contract`'s array of keys and an engine fault's is the path the rule wrote, so compare them with `formatField`. `parse` gives the subject the reasoner reads. What it coerced is reported in `repairs`, and only a lossless repair is accepted: a number from a string whose trim is the number's own text, so `'30'` and `' 30 '` pass and `'30.0'`, `'007'`, `'0x10'`, and `'1e3'` refuse; a boolean from `'true'` or `'false'` only; a literal from its trimmed text; a string from a finite number. A field declared with `optionalShape(inner, { default })` carries that default in its schema, and `parse` fills it when the key is absent or `undefined`. `defaulted` lists what `parse` filled, read from the difference between what arrived and what came out.
|
|
977
|
+
|
|
978
|
+
A required key that is absent refuses at the door even where the engine alone would settle `age 15 and credit above 600`. An author who wants that lever declares the field optional, with no default.
|
|
979
|
+
|
|
980
|
+
With a shape, `validate` reads the definition against it: every path read is in the shape or is a key the definition produces, every expected value satisfies the field's shape, per element for a list, and a string expected needs a field that admits it as a literal, because free text is never compared by equality. A shape carrying a `pattern` refuses at authoring, because a `pattern` does not survive JSON and a definition must, and so does a shape declaring a conclusion key. A `raw` or `json` field read is a warning, since the typed read is then the only guard.
|
|
981
|
+
|
|
982
|
+
`createSubjectDoor` gives a package that reads a shape at its own root the same door:
|
|
983
|
+
|
|
984
|
+
```ts
|
|
985
|
+
import { numberShape, objectShape } from '@orkestrel/contract'
|
|
986
|
+
import { createSubjectDoor } from '@orkestrel/reason'
|
|
987
|
+
|
|
988
|
+
const door = createSubjectDoor()
|
|
989
|
+
const shape = objectShape({ age: numberShape() })
|
|
990
|
+
door.admit({ age: '30' }, shape).subject // { age: 30 }
|
|
991
|
+
door.admit({}, shape).errors // ['age: missing; expected number']
|
|
992
|
+
```
|
|
993
|
+
|
|
994
|
+
### Publishing definitions and results
|
|
995
|
+
|
|
996
|
+
The definitions and results are published as shapes and contracts, so they reach an LLM, a tool, or MCP as JSON Schema with nothing translated.
|
|
997
|
+
|
|
998
|
+
```ts
|
|
999
|
+
import {
|
|
1000
|
+
createDefinitionContract,
|
|
1001
|
+
createLogicalDefinition,
|
|
1002
|
+
createLogicalReasoner,
|
|
1003
|
+
projectResult,
|
|
1004
|
+
resultContract,
|
|
1005
|
+
} from '@orkestrel/reason'
|
|
1006
|
+
|
|
1007
|
+
const definition = createLogicalDefinition('e', 'Eligibility', [])
|
|
1008
|
+
const contract = createDefinitionContract() // build once and hold it
|
|
1009
|
+
contract.is(definition) // true
|
|
1010
|
+
contract.schema // the JSON Schema of any definition
|
|
1011
|
+
|
|
1012
|
+
const result = createLogicalReasoner().reason({}, definition)
|
|
1013
|
+
resultContract.is(projectResult(result)) // true
|
|
1014
|
+
```
|
|
1015
|
+
|
|
1016
|
+
A definition crosses on `is`, never `parse`, because `parse` would turn `enabled: '0'` into `false` and accept a padded operator. A shape refuses cycles, so `Expression` and `SymbolicExpression` are depth-bounded expansions (`EXPRESSION_SHAPE_DEPTH`, `SYMBOLIC_SHAPE_DEPTH`) and the recursive guards stay the authority: what `is` admits the guard admits, including a definition's own nested `shape`. A malformed nested shape such as `shape: 42` fails both checks. A deeper authored expression still runs in memory, because the guard admits it, and cannot cross on `is`. Building those expansions is what costs, so the recursive definition contracts are functions (`createDefinitionContract`, `createLogicalDefinitionContract`, `createSymbolicDefinitionContract`) a caller holds the result of, and an import pays nothing for them. Arity and the rest of what `validate` reads are left to `validate`. A definition's own `shape` key must satisfy the dependency's shape contract.
|
|
754
1017
|
|
|
755
|
-
|
|
1018
|
+
A result crosses as `projectResult`, because the engine publishes `NaN` by design and a check's `actual` holds whatever the subject held: a non-finite number becomes `null`, and what JSON cannot hold is omitted, so is a reference back to an ancestor, anything past `PROJECTION_NODE_LIMIT` objects, and a value that throws on being read. The in-memory result and its guard stay as they are.
|
|
756
1019
|
|
|
757
1020
|
### Symbolic solving
|
|
758
1021
|
|
|
759
|
-
Bindings start from the definition's `variables`, then numeric subject fields override same-named variables (every own key except `id`,
|
|
1022
|
+
Bindings start from the definition's `variables`, then numeric subject fields override same-named variables (every own key except `id`, finite numbers only, so a numeric string never binds). Equations solve strictly in order: when the `target` is unbound and sits on exactly one side, it is isolated algebraically through the `INVERTIBLE_OPERATIONS`; each solution is rounded to `precision` before feeding forward into later equations. A failing equation (unbound variable, non-invertible isolation, non-finite value, a binary operation with no right side) records an error and a `FAILED` trace — the run continues, and an unbound variable also joins `faults`.
|
|
760
1023
|
|
|
761
1024
|
```ts
|
|
762
1025
|
import {
|
|
@@ -1055,7 +1318,7 @@ draft.emitter.on('merge', (reasoning) => console.log(`merged a ${reasoning} revi
|
|
|
1055
1318
|
|
|
1056
1319
|
### Narrowing untrusted definitions
|
|
1057
1320
|
|
|
1058
|
-
Definitions are JSON-serializable data, so they arrive from storage / the wire as `unknown`. Narrow first with the structural guard (`isDefinition` — exact records, total on adversarial input), then with the semantic pass (`validate` — ids present, sources declared, non-empty rule sets) whose `warnings` flag runnable-but-suspicious definitions.
|
|
1321
|
+
Definitions are JSON-serializable data, so they arrive from storage / the wire as `unknown`. Narrow first with the structural guard (`isDefinition` — exact records, total on adversarial input), then with the semantic pass (`validate` — ids present, sources declared, expressions readable, non-empty rule sets) whose `errors` refuse and whose `warnings` flag runnable-but-suspicious definitions.
|
|
1059
1322
|
|
|
1060
1323
|
```ts
|
|
1061
1324
|
import { createLogicalReasoner, createReason, isDefinition } from '@orkestrel/reason'
|
|
@@ -1071,17 +1334,17 @@ if (isDefinition(parsed)) {
|
|
|
1071
1334
|
}
|
|
1072
1335
|
```
|
|
1073
1336
|
|
|
1074
|
-
`
|
|
1337
|
+
`errors` name what a run could only guess at: empty collections, duplicate rule / group / factor / equation / inference ids (`Duplicate <noun> id "<id>"`, once per duplicated id), inferential confidences outside `[0, 1]`, an expected value its comparison cannot use (`scanCheck`), a connective of the wrong arity (`scanExpression`), a conclusion that does not assert (`scanConclusion`), a `fallback` its source cannot use (`scanFactor`), a binary operation with no right side (`scanSymbolicExpression`), a cycle through negation (`Conclusions depend on their own negation: <keys>`, `findNegativeCycles`), and what a `shape` says the definition cannot read (§ The subject door). `warnings` are left for what derives nothing false: an empty inference set, a premise-less inference, and an inferential conclusion `?variable` unbound by all of its inference's premises (`Inference "<id>" conclusion variable "<variable>" is unbound by all premises`, `findUnboundVariables`). Duplicates are refused because they are first/last-wins artifacts at run time, where a group's weight lookup takes the first same-id factor.
|
|
1075
1338
|
|
|
1076
|
-
|
|
1339
|
+
The orchestrator runs this pass itself by default and throws `INVALID`, remembering a valid definition by identity, so a definition edited in place after its first run is not validated again. Build a new one, as the copy-on-write helpers do. Call `validate` at a boundary that reports rather than throws. `validate: false` skips the pass, and a reasoner still refuses what it cannot read.
|
|
1077
1340
|
|
|
1078
1341
|
### Practices
|
|
1079
1342
|
|
|
1080
1343
|
- **Register every reasoner before the first `reason` call** — dispatch is a registry lookup; a miss throws `MISSING` regardless of `bail`.
|
|
1081
1344
|
- **Build definitions with the value factories** — they default `name` to the id, omit absent optional keys (so outputs round-trip the exact-record validators), and keep call sites terse.
|
|
1082
|
-
- **Gate untrusted definitions twice** — `isDefinition` for shape at the boundary, `validate` for semantics;
|
|
1083
|
-
- **Keep ids unique** — `validate`
|
|
1084
|
-
- **Check `success` before trusting the payload** — errors accumulate without aborting, so a `value`
|
|
1345
|
+
- **Gate untrusted definitions twice** — `isDefinition` for shape at the boundary, `validate` for semantics; the orchestrator's own `validate` option is on by default and throws `INVALID`.
|
|
1346
|
+
- **Keep ids unique** — `validate` refuses duplicates; with `validate: false` the runtime resolves them first/last-wins, silently.
|
|
1347
|
+
- **Check `success` before trusting the payload** — errors accumulate without aborting, so a `value` computed alongside errors is a partial answer, and `faults` names each field that stopped it.
|
|
1085
1348
|
- **Read the `trace` when a result surprises you** — every skip, gate, derivation, and convergence is narrated step by step.
|
|
1086
1349
|
- **Use `FieldPath` arrays for nested access** — `['address', 'city']` descends; a dotted string like `'address.city'` is one literal key, never split.
|
|
1087
1350
|
- **Choose `bail` deliberately** — the default (`true`) rethrows a reasoner throw after the `error` emit; `bail: false` degrades it to an empty failure result for batch pipelines that must keep going.
|
|
@@ -1098,21 +1361,21 @@ Prefer this at boundaries over the orchestrator's `validate: true` option (which
|
|
|
1098
1361
|
- [`tests/src/core/Reason.test.ts`](../tests/src/core/Reason.test.ts) — the orchestrator: dispatch, batch order, `bail` on and off, the `MISSING` / `INVALID` / `DESTROYED` codes, event sequences, idempotent `destroy`, build-outside equivalence (a builder's `build()` output reasons identically to inline plain data).
|
|
1099
1362
|
- [`tests/src/core/builders/DefinitionBuilder.test.ts`](../tests/src/core/builders/DefinitionBuilder.test.ts) — the definition builder: mutation → `build` round-trips per manager, inert off-kind managers, per-manager event pins, manager + builder destroy semantics, brand-forge negatives, seed immutability.
|
|
1100
1363
|
- [`tests/src/core/builders/SubjectBuilder.test.ts`](../tests/src/core/builders/SubjectBuilder.test.ts) — the subject builder: id defaulting + immutability + anonymous builds, batch `remove`, incoming-wins `merge`, deterministic `repeat`, `build` determinism, destroy semantics.
|
|
1101
|
-
- [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — `formatField`, `clamp` / `roundTo` / `matchesBounds` / `equalValues` / `sortByPriority` / `findDuplicates`, the fact and algebra machinery, and the capability-layer engine (`appendById` placement + `TARGET`, per-kind append / prepend / replace / remove, `merge*` / `clear*`, `parseDefinition`, the subject helpers).
|
|
1364
|
+
- [`tests/src/core/helpers.test.ts`](../tests/src/core/helpers.test.ts) — `formatField`, `clamp` / `roundTo` / `matchesBounds` / `equalValues` / `sortByPriority` / `findDuplicates`, the `combineStates` truth tables and `settleComparison`, the `scan*` family, `findNegativeCycles`, the fact and algebra machinery, and the capability-layer engine (`appendById` placement + `TARGET`, per-kind append / prepend / replace / remove, `merge*` / `clear*`, `parseDefinition`, the subject helpers).
|
|
1102
1365
|
- [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — each guard accepts valid / rejects invalid + adversarial junk, exact-record semantics, `lazyOf` recursion containment.
|
|
1103
1366
|
- [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — every value factory's output shape (override merging, key omission, `name` defaulting); every entity factory wires a working instance with custom `id`s through the options objects.
|
|
1104
1367
|
- [`tests/src/core/operators/Evaluator.test.ts`](../tests/src/core/operators/Evaluator.test.ts) — every comparison (strictness, numeric requirements, the `any` / `none` asymmetry vs the pure-negation `outside`), `FieldPath` resolution, unknown-operator totality.
|
|
1105
1368
|
- [`tests/src/core/operators/Transformer.test.ts`](../tests/src/core/operators/Transformer.test.ts) — per-operation operand defaults, divide-by-zero `NaN`, unary operations, `chain` folding.
|
|
1106
|
-
- [`tests/src/core/operators/Aggregator.test.ts`](../tests/src/core/operators/Aggregator.test.ts) — empty-input identities, weight-as-exponent `product`, zero
|
|
1107
|
-
- [`tests/src/core/reasoners/QuantitativeReasoner.test.ts`](../tests/src/core/reasoners/QuantitativeReasoner.test.ts) — the factor pipeline, priorities, `strict` / `required`, source resolution +
|
|
1108
|
-
- [`tests/src/core/reasoners/LogicalReasoner.test.ts`](../tests/src/core/reasoners/LogicalReasoner.test.ts) — forward fixpoint + derived overlays, backward proving + cycle safety,
|
|
1369
|
+
- [`tests/src/core/operators/Aggregator.test.ts`](../tests/src/core/operators/Aggregator.test.ts) — empty-input identities, weight-as-exponent `product`, the `NaN` answers for a zero total weight and for weights of another length.
|
|
1370
|
+
- [`tests/src/core/reasoners/QuantitativeReasoner.test.ts`](../tests/src/core/reasoners/QuantitativeReasoner.test.ts) — the factor pipeline, priorities, `strict` / `required`, source resolution + refusal, base / bounds / precision stacking.
|
|
1371
|
+
- [`tests/src/core/reasoners/LogicalReasoner.test.ts`](../tests/src/core/reasoners/LogicalReasoner.test.ts) — forward fixpoint + derived overlays, backward proving + cycle safety, closing conclusion keys, refusal in both strategies, cycles through negation.
|
|
1109
1372
|
- [`tests/src/core/reasoners/SymbolicReasoner.test.ts`](../tests/src/core/reasoners/SymbolicReasoner.test.ts) — subject binding + overrides, isolation through invertible operations, rounded feed-forward, per-equation failure isolation.
|
|
1110
1373
|
- [`tests/src/core/reasoners/InferentialReasoner.test.ts`](../tests/src/core/reasoners/InferentialReasoner.test.ts) — unification + relational joins, confidence products, dedupe, subject-fact injection, backward proof trees.
|
|
1111
1374
|
- [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) — cross-strategy scenarios through one orchestrator.
|
|
1112
1375
|
|
|
1113
1376
|
## See also
|
|
1114
1377
|
|
|
1115
|
-
- [`contract.md`](contract.md) — the guards, combinators, and `parseNumber`
|
|
1378
|
+
- [`contract.md`](contract.md) — the guards, combinators, and `parseNumber` the validators and reasoners compose.
|
|
1116
1379
|
- [`emitter.md`](emitter.md) — the typed emitter behind the orchestrator's observation surface.
|
|
1117
1380
|
- [`AGENTS.md`](../AGENTS.md) — the rules.
|
|
1118
1381
|
- [`README.md`](README.md) — the guides index.
|