trilean 1.0.13 → 1.2.0

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/README.md CHANGED
@@ -188,8 +188,9 @@ These hold across every part of the design below, and any implementation change
188
188
 
189
189
  - **No assumptions about consumer data.** The only places this package touches real data are three named resolver contracts (see [Resolvers](#resolvers)). The schema stores *what to pass* to a resolver, never any resolver logic itself, and never interprets the meaning of an opaque key, table identifier, or collection reference.
190
190
  - **Three outcomes, never two.** Every evaluation produces a definite result or an indeterminate result carrying a reason — never a bare `boolean`/`number`, and never a thrown exception for a data-quality problem. See [The evaluation model](#the-evaluation-model).
191
- - **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives) and [Derived aggregates](#derived-aggregates).
191
+ - **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives), [Derived aggregates](#derived-aggregates), [Derived values](#derived-values), and [Defining your own named presets](#defining-your-own-named-presets).
192
192
  - **One schema, mechanically derived artefacts.** A single canonical type definition produces the runtime validator and the portable wire-format schema; they cannot drift apart because there is only one source. See [Schema strategy](#schema-strategy).
193
+ - **A numeric extension that stays closed-form is in scope; a different kind of computation is not.** When something the current numeric model does not cover comes up, the test is whether evaluating it is still closed-form numeric evaluation — no solving, no simplification, no code execution. If it is, it belongs here, however unlike the existing kinds it looks: [Complex values](#complex-values) were once listed under [Out of scope](#out-of-scope) on a sizing judgement that turned out to be wrong, since complex arithmetic is exactly the closed-form evaluation this evaluator already does for every other kind. What stays behind [`delegate`](#delegate) is a genuinely different *kind* of computation — symbolic algebra, arbitrary external computation — not merely a kind of number the model has not reached yet.
193
194
  - **Generic examples only.** Every example in this document uses invented, placeholder field names (`temperature`, `orderTotal`, `isActive`, `x`, `y`, `amount`, `items`) with no resemblance to any particular company, product, or industry's real data model.
194
195
 
195
196
  ## The evaluation model
@@ -353,7 +354,8 @@ type PredicateNode =
353
354
  | { kind: "memberOf"; op: MembershipOperator; operand: ExpressionNode; candidates: ExpressionNode[] }
354
355
  | { kind: "exists"; operand: ExpressionNode }
355
356
  | { kind: "some"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode }
356
- | { kind: "every"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode };
357
+ | { kind: "every"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode }
358
+ | { kind: "treeReference"; key: JsonValue };
357
359
  ```
358
360
 
359
361
  ### `not`, `and`, `or`
@@ -366,7 +368,7 @@ The N-ary forms of `and`/`or`: given an ordered list of operands (rather than ex
366
368
 
367
369
  ### `compare`
368
370
 
369
- A relational-comparison leaf: compares two computed values using `gt`/`gte`/`lt`/`lte`/`eq`/`neq`. **Both `left` and `right` are `ExpressionNode`** — either side may be a plain literal/reference or an arbitrary formula from the expression tree; the comparison is symmetric, and an implementation that only allows a formula on one side is incomplete. Valid operand kinds are `number` (matching units required — see [Units](#units)), `instant`, or `duration`; comparing across different computed-value kinds, or comparing two numbers with incompatible units, is `wrong-type`.
371
+ A relational-comparison leaf: compares two computed values using `gt`/`gte`/`lt`/`lte`/`eq`/`neq`. **Both `left` and `right` are `ExpressionNode`** — either side may be a plain literal/reference or an arbitrary formula from the expression tree; the comparison is symmetric, and an implementation that only allows a formula on one side is incomplete. Valid operand kinds are `number` (matching units required — see [Units](#units)), `instant`, `duration`, or `boolean`, plus `complex` for `eq`/`neq` only (see [Complex values](#complex-values)); comparing across different computed-value kinds, or comparing two numbers with incompatible units, is `wrong-type`. `boolean` only supports `eq`/`neq` — there is no natural ordering for a truth value, so `gt`/`gte`/`lt`/`lte` are `wrong-type` for a `boolean` operand.
370
372
 
371
373
  ### `textCompare`
372
374
 
@@ -399,8 +401,10 @@ type DurationUnit = "ms" | "s" | "min" | "h" | "d";
399
401
  type ComputedValue =
400
402
  | { kind: "number"; value: number; unit?: Unit }
401
403
  | { kind: "text"; value: string }
404
+ | { kind: "boolean"; value: boolean }
402
405
  | { kind: "instant"; value: string } // ISO-8601 timestamp
403
- | { kind: "duration"; value: number; unit: DurationUnit };
406
+ | { kind: "duration"; value: number; unit: DurationUnit }
407
+ | { kind: "complex"; re: number; im: number; unit?: Unit };
404
408
 
405
409
  type ArithmeticOperator = "add" | "subtract" | "multiply" | "divide" | "power" | "modulo";
406
410
 
@@ -409,27 +413,33 @@ type FoldCombiner =
409
413
  | { mode: "min"; item: ExpressionNode }
410
414
  | { mode: "reduce"; initial: ExpressionNode; combine: ExpressionNode };
411
415
 
416
+ type HitPolicy = "first" | "unique";
417
+
412
418
  type ExpressionNode =
413
419
  | { kind: "numberLiteral"; value: number; unit?: Unit }
414
420
  | { kind: "textLiteral"; value: string }
421
+ | { kind: "booleanLiteral"; value: boolean }
415
422
  | { kind: "instantLiteral"; value: string }
416
423
  | { kind: "durationLiteral"; value: number; unit: DurationUnit }
424
+ | { kind: "complexLiteral"; re: number; im: number; unit?: Unit } // rectangular
425
+ | { kind: "complexLiteral"; magnitude: number; phase: number; unit?: Unit } // polar -- see Complex values
417
426
  | { kind: "reference"; key: JsonValue; unit?: Unit }
418
427
  | { kind: "arithmetic"; op: ArithmeticOperator; left: ExpressionNode; right: ExpressionNode }
419
428
  | { kind: "negate"; operand: ExpressionNode }
420
429
  | { kind: "call"; fn: string; args: ExpressionNode[] }
421
430
  | { kind: "lookup"; table: JsonValue; keys: ExpressionNode[] }
422
- | { kind: "conditional"; cases: { when: PredicateNode; then: ExpressionNode }[]; fallback: ExpressionNode }
431
+ | { kind: "conditional"; hitPolicy?: HitPolicy; cases: { when: PredicateNode; then: ExpressionNode }[]; fallback: ExpressionNode }
423
432
  | { kind: "fold"; collection: JsonValue; filter?: PredicateNode; combiner: FoldCombiner }
424
433
  | { kind: "accumulator" }
425
- | { kind: "delegate"; system: string; payload: JsonValue };
434
+ | { kind: "delegate"; system: string; payload: JsonValue }
435
+ | { kind: "treeReference"; key: JsonValue };
426
436
  ```
427
437
 
428
438
  A `textLiteral` kind is included even though it is not separately enumerated as its own top-level construct, because `textCompare`'s symmetry requirement (either side may be an arbitrary computed value, per the section above) is meaningless without a way to write a constant string or pattern — matching a field against the fixed text `"active"`, or against a fixed regular expression, needs a text constant on one side. This is a structural consequence of the symmetry already required for text matching, not an added feature.
429
439
 
430
440
  ### Literals
431
441
 
432
- `numberLiteral`, `textLiteral`, `instantLiteral` (an ISO-8601 timestamp string), and `durationLiteral` (a magnitude plus a `DurationUnit`) are always definite by construction — a literal node never itself produces an indeterminate outcome.
442
+ `numberLiteral`, `textLiteral`, `booleanLiteral`, `instantLiteral` (an ISO-8601 timestamp string), `durationLiteral` (a magnitude plus a `DurationUnit`), and `complexLiteral` (either a real and an imaginary component, or a magnitude and a phase, plus an optional `Unit` — see [Complex values](#complex-values)) are always definite by construction — a literal node never itself produces an indeterminate outcome.
433
443
 
434
444
  ### `reference`
435
445
 
@@ -437,7 +447,7 @@ A reference to a single external value, identified by an opaque `key` whose mean
437
447
 
438
448
  ### `arithmetic`, `negate`
439
449
 
440
- Binary arithmetic (`add`/`subtract`/`multiply`/`divide`/`power`/`modulo`) and unary negation, each over `number` computed values by default, with the temporal exceptions listed under [Temporal values](#temporal-values) below. `negate` is an explicit node — never sugar for "zero minus the value" — because it also applies to `duration` values (negating a duration reverses its direction) where "zero minus" has no natural literal-zero counterpart. Division by zero, or any operator given an operand outside its mathematical domain, is `domain-error`; a non-numeric, non-temporal operand where a number was required is `wrong-type`; any operand that is itself indeterminate makes the whole node indeterminate, with no rescuing value on the other side (see [Three-valued propagation rules](#three-valued-propagation-rules)).
450
+ Binary arithmetic (`add`/`subtract`/`multiply`/`divide`/`power`/`modulo`) and unary negation, each over `number` computed values by default, with the temporal exceptions listed under [Temporal values](#temporal-values) and the complex ones under [Complex values](#complex-values) below. `negate` is an explicit node — never sugar for "zero minus the value" — because it also applies to `duration` values (negating a duration reverses its direction) where "zero minus" has no natural literal-zero counterpart; over a `complex` value it flips both components. Division by zero, or any operator given an operand outside its mathematical domain, is `domain-error`; a non-numeric, non-temporal operand where a number was required is `wrong-type`; any operand that is itself indeterminate makes the whole node indeterminate, with no rescuing value on the other side (see [Three-valued propagation rules](#three-valued-propagation-rules)).
441
451
 
442
452
  ### `call`
443
453
 
@@ -445,7 +455,7 @@ A named function applied to an ordered list of `ExpressionNode` arguments. The s
445
455
 
446
456
  ### Units
447
457
 
448
- `numberLiteral` and `reference` may carry a `unit`, represented as a dimensional-exponent map (e.g. `{ m: 1, s: -1 }` for metres per second) rather than an opaque string, so that unit combination follows real dimensional analysis instead of string matching. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`.
458
+ `numberLiteral`, `complexLiteral`, and `reference` may carry a `unit`, represented as a dimensional-exponent map (e.g. `{ m: 1, s: -1 }` for metres per second) rather than an opaque string, so that unit combination follows real dimensional analysis instead of string matching. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`.
449
459
 
450
460
  - `add`/`subtract` between two unit-tagged numbers require **identical** dimensional-exponent maps. A mismatch is `wrong-type` ("incompatible units") — units are never silently coerced or dropped.
451
461
  - `multiply`/`divide` combine the two operands' unit maps by dimensional analysis: multiplying adds exponents per dimension, dividing subtracts them. An operand with no `unit` is treated as dimensionless (an empty map) for this purpose.
@@ -459,13 +469,69 @@ A named function applied to an ordered list of `ExpressionNode` arguments. The s
459
469
 
460
470
  Any other arithmetic combination touching an `instant` or `duration` (adding two instants, multiplying a duration by an instant, comparing an instant against a plain number, and so on) is `wrong-type`. A reference implementation normalises `duration` values to a single base unit (milliseconds) internally before combining two durations of different `DurationUnit`s, then reports the result in whichever unit the node's own context calls for.
461
471
 
472
+ ### Complex values
473
+
474
+ `complex` is a computed-value kind alongside `number`, for the domains — signal processing, control theory, anything phasor-shaped — where a formula naturally mixes real and complex terms in one expression. It stays inside this evaluator rather than behind [`delegate`](#delegate) because it is closed-form numeric evaluation, exactly what every other kind here already does; see [Design principles](#design-principles) for that scope test in general.
475
+
476
+ **One canonical representation, rectangular.** A `complex` value is stored as `{ re, im }` and never as a magnitude and a phase, and there is deliberately no `form` discriminant offering both. Three reasons, in order of weight:
477
+
478
+ 1. **A second form would make equality ambiguous.** Polar coordinates do not encode a value uniquely — phase is only defined modulo a full turn, and a zero-magnitude value has no meaningful phase at all — so the same complex number would have unboundedly many polar encodings. `eq` and `memberOf` are exact equality throughout this design (see [`compare`](#compare)); making them work across two forms would mean either normalising on every comparison or introducing an approximate equality for this one kind, and neither belongs in a design where every other kind compares exactly.
479
+ 2. **A discriminant would double the branching in every operator** — quadruple it for a binary one — for a choice that changes no value. Every operator would still convert to rectangular internally, because that is where the closed forms live, so the discriminant would buy nothing at evaluation time and cost at every boundary.
480
+ 3. **Rectangular is what the operators actually need.** `add`/`subtract` are component-wise in it; `multiply`, `divide`, `negate`, and integer `power` all have standard closed forms in it. Polar's advantage — multiplication and division as one product of magnitudes and one sum of angles — does not extend to addition at all, which would have to convert back and forth.
481
+
482
+ The magnitude-and-phase view stays reachable through four exported conversion helpers rather than a second encoding: `complexFromPolar(magnitude, phase, unit?)` and `complexLiteralFromPolar(magnitude, phase, unit?)` build a value or a literal node from polar terms, and `complexMagnitude(value)` and `complexPhase(value)` read them back out — the magnitude as a real number in the value's own unit, the phase as a dimensionless real number of radians. Conversions at the edges, one representation in the middle.
483
+
484
+ **The wire-format literal accepts either authoring form, structurally discriminated.** `ComputedValue`'s own `complex` kind stays exactly the single rectangular shape described above — nothing about it changes. But the `complexLiteral` *node* is a plain union of two shapes, `{ kind: "complexLiteral", re, im, unit? }` and `{ kind: "complexLiteral", magnitude, phase, unit? }`, told apart by which fields are present rather than by a `form` tag, since both still share the one literal `kind`. This is not a second encoding of `ComputedValue` reappearing through the back door — it exists only at the authoring boundary, for whichever of the two forms is natural for a given domain to write directly into JSON rather than hand-computing a conversion before ever constructing the tree, and the evaluator normalises whichever form was used to the single rectangular `ComputedValue` immediately, before any arithmetic, comparison, or negation ever runs. A rectangular literal and a polar literal representing the same underlying number are therefore indistinguishable from that point on: they evaluate to the identical `ComputedValue` and compare `eq` to one another exactly as two rectangular literals with the same components would.
485
+
486
+ **Arithmetic.**
487
+
488
+ - `add`/`subtract` are component-wise, requiring **identical** dimensional-exponent maps exactly as real numbers do (see [Units](#units)).
489
+ - `multiply`/`divide` are real complex multiplication and division — `(a + bi)(c + di) = (ac − bd) + (ad + bc)i`, and the corresponding quotient — never component-wise. Units combine by the same dimensional analysis real numbers use. A zero divisor means both components zero; a divisor with only a zero real part divides perfectly well.
490
+ - `power` is defined for a **real integer exponent** and evaluated as the repeated multiplication that integer exponentiation is, with a negative exponent the reciprocal of the positive one. Like a real `power`, it requires dimensionless operands. An arbitrary complex exponent is a genuinely bigger question — it needs the complex logarithm, which is multivalued, so it needs a branch-cut convention this design has not chosen — and is deliberately out of scope for now: it is `wrong-type`, as is a non-integer real exponent, on the same reading of that code used throughout ("an answer exists, but this operator does not accept this operand" — compare `power`'s existing dimensionless-operands requirement, also `wrong-type`).
491
+ - `modulo` is `domain-error`, not `wrong-type`: a remainder needs a canonical notion of how many whole divisors fit, and the complex plane has no ordering to supply one. There is no answer to accept, which is the same category as division by zero.
492
+
493
+ **A real operand is promoted, never rejected.** Mixing a `number` with a `complex` in one `arithmetic` node works: every real number *is* a complex number with a zero imaginary part, so the promotion is exact, total, and canonical — unlike the temporal cross-kind combinations above, which had to be enumerated one by one precisely because no such embedding exists between an `instant` and a `duration`. Scaling a complex value by a real one, or offsetting it by a real constant, is the common case, and forcing every real literal in such a formula to be rewritten as a complex one would defeat the point. The result is `complex` whenever either operand is, even when the imaginary part comes out zero: a node's result kind follows its operand kinds, never the values that happen to flow through it.
494
+
495
+ **Comparison is kind-strict, deliberately unlike arithmetic.** `gt`/`gte`/`lt`/`lte` are `wrong-type` for a `complex` operand — the complex plane carries no total order — exactly as they already are for `text`. `eq`/`neq` work normally, as exact equality across both components under the same unit-compatibility rule numbers already have, and `memberOf` matches the same way. But a `complex` compared against a `number` is `wrong-type`, with no promotion: arithmetic *produces* a value, so promoting a real operand loses nothing, whereas a comparison *consumes* two, and this design already treats a kind difference between them as a modelling error worth surfacing — the same reason an `instant` is never compared against a plain `number` despite being a count of milliseconds underneath.
496
+
497
+ Ordering a complex quantity therefore goes through whichever real projection the formula actually means — most often its magnitude. This package ships no built-in function set (see [`call`](#call)), so that bridge is an ordinary registry entry, one line over the exported helper:
498
+
499
+ ```ts
500
+ const functions: FunctionRegistry = {
501
+ magnitude: (args) =>
502
+ args[0]?.kind === "complex"
503
+ ? complexMagnitude(args[0])
504
+ : { domainError: "expected a complex argument" },
505
+ };
506
+ ```
507
+
508
+ which a tree then calls like any other function, putting a real number back on the left of an ordinary `compare`:
509
+
510
+ ```json
511
+ {
512
+ "kind": "compare",
513
+ "op": "gt",
514
+ "left": { "kind": "call", "fn": "magnitude", "args": [{ "kind": "reference", "key": "x" }] },
515
+ "right": { "kind": "numberLiteral", "value": 13 }
516
+ }
517
+ ```
518
+
462
519
  ### `lookup`
463
520
 
464
521
  Resolves a single value from a named external table-like source, keyed by one or more `ExpressionNode` keys, via resolver 2 (see [Resolvers](#resolvers)). The schema never interprets what "table" or "key" mean to a given consumer; `table` and the resolved key values are passed through verbatim. If any key expression is itself indeterminate, the lookup is indeterminate with that reason (no key evaluation, no lookup attempt). If the resolver reports no match, the result is `not-found`.
465
522
 
466
523
  ### `conditional`
467
524
 
468
- A piecewise/conditional-value node: an ordered, possibly-empty list of `{ when, then }` cases plus a required `fallback`. Evaluates to the `then` of the first case whose `when` predicate is definitely `true`; if no case matches, evaluates to `fallback`. If evaluating a `when` predicate produces an indeterminate outcome **before any earlier case has matched**, the whole `conditional` node's own result is that same indeterminate outcome (reason preserved) — evaluation does not skip past an unknown guard to try the next one, because doing so could silently pick a later branch that only looks correct because an earlier one couldn't actually be checked.
525
+ A piecewise/conditional-value node: an ordered, possibly-empty list of `{ when, then }` cases plus a required `fallback`. An optional `hitPolicy` field (`"first"` or `"unique"`) decides how cases are read; absent is treated as `"first"` — the exact, unchanged behaviour of every tree serialised before this field existed, not a masked-bug fallback.
526
+
527
+ **`hitPolicy: "first"`** (the default). Evaluates to the `then` of the first case whose `when` predicate is definitely `true`; if no case matches, evaluates to `fallback`. If evaluating a `when` predicate produces an indeterminate outcome **before any earlier case has matched**, the whole `conditional` node's own result is that same indeterminate outcome (reason preserved) — evaluation does not skip past an unknown guard to try the next one, because doing so could silently pick a later branch that only looks correct because an earlier one couldn't actually be checked.
528
+
529
+ **`hitPolicy: "unique"`** asserts that at most one case is expected to match, and treats two or more matches as a data error rather than silently taking the first. Every case's `when` is evaluated concurrently (there is no "earlier case" to short-circuit on), then resolved in this order:
530
+
531
+ 1. **Two or more cases are definitely `true`** — `domain-error` ("more than one case matched under the 'unique' hit policy"), regardless of any other case's own indeterminacy. This mirrors `memberOf`/`some`/`every`'s existing absorption: a confirmed outcome (here, "there is a genuine ambiguity") cannot be undone by an unrelated case's data problem.
532
+ 2. Otherwise, **any case's `when` is indeterminate** — the whole node is indeterminate with that reason (first such candidate, in declared case order, per [The evaluation model](#the-evaluation-model)'s tie-break rule). This is deliberately **not** absorbed by a single already-confirmed match, unlike step 1 above and unlike `memberOf`/`some`/`every`'s own absorption: an unresolved case might still turn out to be a second match, so "exactly one match so far" cannot be trusted as final until every other case is known to not also match.
533
+ 3. Otherwise, **exactly one case is definitely `true`** — evaluate and return that case's `then`. No other case's `then` is ever evaluated.
534
+ 4. Otherwise (zero matches, and nothing indeterminate) — evaluate and return `fallback`, exactly as `"first"` already does.
469
535
 
470
536
  ### `fold`
471
537
 
@@ -534,14 +600,85 @@ const average = (collection: JsonValue, item: ExpressionNode, filter?: Predicate
534
600
 
535
601
  `sum` needs no per-item probe beyond `item` itself: it is a literal `reduce` seeded at `0`, adding each participating item's projected value to the running total, and it already goes indeterminate if `item` fails to resolve for any participating item — no separate mechanism needed, since `item`'s value is exactly what gets added.
536
602
 
537
- `count` takes an optional third argument, `probe`, and this is where it matters that `filter` and a probe are not the same thing. `filter` *excludes* an item from participating — a filtered-out item's absence is invisible in the final result, exactly as if it had never been in the collection at all. A `probe` does the opposite: it doesn't decide whether an item participates, it makes the *whole count* indeterminate if it fails to resolve for *any* participating item, surfacing "I cannot give you a trustworthy count" rather than silently reporting a smaller, technically-successful count for the same underlying data-quality problem — precisely the distinction the rest of this document's indeterminate-outcome model exists to preserve (see [The evaluation model](#the-evaluation-model)). `count(collection, filter)` with no `probe` is a plain `reduce` seeded at `0` that adds `1` per participating item, with no indeterminacy of its own beyond `filter`'s. `count(collection, filter, probe)` instead adds `presenceOf(probe)` per participating item — a small helper built entirely from already-established primitives, with no restriction on `probe`'s kind: it tests `probe` for membership in the single-element list `[probe]`, so a `memberOf` "in" test against itself is trivially true whenever `probe` resolves to a definite value of *any* kind (`memberOf`'s equality is already kind-agnostic across `number`/`text`/`instant`/`duration` — see [`memberOf`](#memberof)), and exactly `probe`'s own indeterminate outcome otherwise, per `memberOf`'s own "evaluate `operand` first" rule. A `conditional` then turns that boolean into the number `1`; its `fallback` is never reached, since a definite `probe` always equals itself. (A real implementation may memoise `probe`'s single evaluation rather than running the resolver twice for `operand` and its one `candidates` entry — resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.)
603
+ `count` takes an optional third argument, `probe`, and this is where it matters that `filter` and a probe are not the same thing. `filter` *excludes* an item from participating — a filtered-out item's absence is invisible in the final result, exactly as if it had never been in the collection at all. A `probe` does the opposite: it doesn't decide whether an item participates, it makes the *whole count* indeterminate if it fails to resolve for *any* participating item, surfacing "I cannot give you a trustworthy count" rather than silently reporting a smaller, technically-successful count for the same underlying data-quality problem — precisely the distinction the rest of this document's indeterminate-outcome model exists to preserve (see [The evaluation model](#the-evaluation-model)). `count(collection, filter)` with no `probe` is a plain `reduce` seeded at `0` that adds `1` per participating item, with no indeterminacy of its own beyond `filter`'s. `count(collection, filter, probe)` instead adds `presenceOf(probe)` per participating item — a small helper built entirely from already-established primitives, with no restriction on `probe`'s kind: it tests `probe` for membership in the single-element list `[probe]`, so a `memberOf` "in" test against itself is trivially true whenever `probe` resolves to a definite value of *any* kind (`memberOf`'s equality is already kind-agnostic across `number`/`text`/`boolean`/`instant`/`duration` — see [`memberOf`](#memberof)), and exactly `probe`'s own indeterminate outcome otherwise, per `memberOf`'s own "evaluate `operand` first" rule. A `conditional` then turns that boolean into the number `1`; its `fallback` is never reached, since a definite `probe` always equals itself. (A real implementation may memoise `probe`'s single evaluation rather than running the resolver twice for `operand` and its one `candidates` entry — resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.)
538
604
 
539
605
  `average` is `sum` divided by `count` over the same `collection`/`filter`, with no `probe` — `sum`'s own `item` already forces every participating item's projected value to resolve, so `average`'s numerator is already indeterminate under exactly the condition a `count` probe exists to detect, with nothing left to duplicate. Nothing new to verify for the empty-collection case either: division's own already-established rule (zero divisor is `domain-error`) is *why* `average` over an empty collection is `domain-error`, since `count` over an empty collection is `0` and `sum(...)/0` already means exactly that.
540
606
 
607
+ ### Derived values
608
+
609
+ `coalesce` is never its own evaluated node kind — it is a builder function that assembles an ordinary `conditional`, the same treatment [Derived connectives](#derived-connectives) and [Derived aggregates](#derived-aggregates) already give `xor`/`nand`/`nor`/`implies`/`iff`/`none`/`sum`/`count`/`average`: correctness is inherited from the mechanism it's built from, rather than needing its own independent implementation that could silently drift from it.
610
+
611
+ ```ts
612
+ const coalesce = (
613
+ first: ExpressionNode,
614
+ second: ExpressionNode,
615
+ ...rest: ExpressionNode[]
616
+ ): ExpressionNode =>
617
+ [first, second, ...rest].reduceRight(
618
+ (fallback, candidate): ExpressionNode => ({
619
+ kind: "conditional",
620
+ cases: [{ when: { kind: "exists", operand: candidate }, then: candidate }],
621
+ fallback,
622
+ }),
623
+ );
624
+ ```
625
+
626
+ Built right-to-left over the full candidate list via `reduceRight`, needing no seed value: `first`/`second` are required arguments (rather than accepting a single `ExpressionNode[]`), which guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
627
+
628
+ **Worked correctness check.** `coalesce`'s only interesting behaviour — whether a given candidate is skipped past or propagated — reduces entirely to what its single `exists` probe reports, per [`exists`](#exists)'s and [`conditional`](#conditional)'s own already-established rules:
629
+
630
+ | A candidate's own evaluation | `exists(candidate)` | The `conditional` case | `coalesce` evaluates to |
631
+ |---|---|---|---|
632
+ | A definite value | definite `true` | matches | The candidate's value (re-evaluated as `then`, same result) |
633
+ | Indeterminate, `not-found` | definite `false` | does not match | The next candidate (the enclosing `fallback`), evaluated fresh |
634
+ | Indeterminate, `wrong-type` | definite `true` | matches | The candidate's own `wrong-type` result (re-evaluated as `then`) |
635
+ | Indeterminate, `domain-error` | definite `true` | matches | The candidate's own `domain-error` result (re-evaluated as `then`) |
636
+
637
+ Falling through to the next candidate therefore happens only on `exists`'s own `false` — a genuinely absent value (`not-found`) — never on a candidate that resolved to something merely unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line, and `coalesce` inherits it unmodified rather than re-deciding it. This is the one behaviour a naive reimplementation is likely to get backwards (treating *any* indeterminate candidate as "try the next one"), so it is worth stating explicitly rather than leaving it to be inferred from the composition alone.
638
+
639
+ A real implementation may memoise a candidate's single evaluation rather than running its resolver twice — once for the `exists` probe, once again for `then` — exactly the same performance caveat [Derived aggregates](#derived-aggregates)'s `presenceOf` already documents for its own `memberOf` probe; resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.
640
+
641
+ ### Defining your own named presets
642
+
643
+ This is exactly the same composition-not-new-logic treatment already given to `xor`/`sum`/`coalesce` above — nothing stops application code from defining its own named builder functions the same way, for whatever domain-specific composed queries come up repeatedly in a given consumer's own rules.
644
+
645
+ ```ts
646
+ /** isRecentlyActive(30) reads as "the item's lastActiveAt instant is within the last 30 days" — a small, named composition over compare/arithmetic, exactly the same "assembles ordinary nodes" treatment sum/coalesce already get above. Built as `now + (-days)` rather than `now - days`: per "Temporal values" above, `instant - duration` is not a defined cross-kind combination, only `instant + duration` is, so negating the duration first is how this reaches the same "days ago" instant using only defined operators. */
647
+ const isRecentlyActive = (days: number): PredicateNode => ({
648
+ kind: "compare",
649
+ op: "gt",
650
+ left: { kind: "reference", key: "lastActiveAt" },
651
+ right: {
652
+ kind: "arithmetic",
653
+ op: "add",
654
+ left: { kind: "reference", key: "now" },
655
+ right: { kind: "negate", operand: { kind: "durationLiteral", value: days, unit: "d" } },
656
+ },
657
+ });
658
+ ```
659
+
660
+ A UI surfacing these to an end user treats each one as a named preset in a node-picker — a label ("Recently active") plus whatever parameters the builder function takes (`days`) — and splices the expanded tree in at the point the user picked it, exactly as if they'd hand-built that subtree themselves; nothing about the resulting PredicateNode/ExpressionNode distinguishes a preset-sourced subtree from a manually-authored one.
661
+
662
+ This is the "bake in at authoring time" half of the picture: a preset's own definition lives in application code, expanded once, at the moment a user picks it, into an ordinary static subtree. [`treeReference`](#treereference) is the complementary half — a *live*, centrally-editable reference, resolved fresh on every evaluation rather than expanded once at authoring time. Choosing between them is exactly the choice between "this composition is fixed application logic" (a named preset, this section) and "this composition is itself data someone should be able to edit without a deploy" (a treeReference).
663
+
541
664
  ### `delegate`
542
665
 
543
666
  An explicitly-named external system plus an arbitrary, unevaluated JSON payload, standing in for the whole node without this package attempting to evaluate it itself — see [Out of scope](#out-of-scope). Evaluating a `delegate` node is not part of this package's own evaluation semantics. The reference evaluator accepts an optional delegate handler per external system name; if none is registered for the named `system`, evaluating the node is indeterminate (`wrong-type`, "no delegate handler registered for external system '<name>'"). Consumers who want a `delegate` node to actually resolve are expected either to register a handler, or to pre-process the tree — walk it, find delegation nodes, invoke the named external system out of band, and substitute the result as a literal — before the tree ever reaches this package's evaluator.
544
667
 
668
+ ### `treeReference`
669
+
670
+ A reference to a whole other tree, identified by an opaque `key` (see [Resolvers](#resolvers)) — the only node kind valid from *both* a `PredicateNode` and an `ExpressionNode` position: the exact same schema is appended as the last member of each of the two discriminated unions above, not two separately-declared copies that happen to look alike. Unlike [`delegate`](#delegate), which hands the whole node off to an *external* system this package never evaluates, `treeReference` resolves to *another tree of this same schema* and evaluates it with this same evaluator — a sub-rule reference, not an escape hatch.
671
+
672
+ `resolveTree` is optional on `Resolvers`, for the same reason `resolveDelegate` is: a well-defined indeterminate result on absence, not a masked bug, and an additive, non-breaking interface change for every consumer implemented before this node kind existed. If no `resolveTree` is registered, evaluating a `treeReference` node is `wrong-type` ("no tree resolver registered for treeReference nodes"). If the resolver reports no match, the result is `not-found`.
673
+
674
+ A resolved tree is never merely trusted — it is re-validated with a fresh `PredicateNodeSchema`/`ExpressionNodeSchema` parse (`PredicateNodeSchema` from a predicate-position reference, `ExpressionNodeSchema` from an expression-position one) before evaluation proceeds, exactly the same discipline the top-level tree itself is subject to when it first arrives at this package. A resolver fetching "a named rule from storage" is very often surfacing the same non-developer-authored JSON the top-level tree already is, with no static guarantee it still matches the schema; a failed parse is `wrong-type`.
675
+
676
+ `context` and the enclosing fold's `accumulator` both pass through a `treeReference` unchanged — the referenced tree shares the caller's evaluation scope, like a subroutine call, not a nested evaluation with its own fresh context. There is deliberately no mechanism to override the context at a `treeReference` boundary; a consumer wanting that already has [`delegate`](#delegate).
677
+
678
+ **Cycle and depth protection.** A tree that references itself, directly or through a longer chain, is guarded by two independent, layered checks rather than one: a cycle detector tracks every `key` (by its `JSON.stringify`'d form) already on the current reference chain, and reports `domain-error` ("circular treeReference detected") the moment a repeat is seen; a fixed depth cap separately reports `domain-error` ("...exceeds the maximum depth") on a long *acyclic* chain the cycle detector alone would never catch. Neither check is a substitute for the other.
679
+
680
+ **A known, accepted design consequence.** `resolveTree` has no built-in way to know whether a given `key` is being resolved from a predicate-position or an expression-position reference — the same is already true of `reference.key` and `lookup.table`, neither of which carries a type discriminator either. A consumer needing to disambiguate structures their own key accordingly (e.g. `{ kind: "predicate", id: "..." }` as the `JsonValue` itself) rather than this schema growing a bespoke field for it.
681
+
545
682
  ## Collections
546
683
 
547
684
  Both `fold` and the two quantifier leaves (`some`/`every`, and transitively `none`) need "a collection of items" resolved from something the schema itself treats as opaque data. The schema's job is only to carry an opaque reference to what collection is meant, plus a sub-node (an `ExpressionNode` for `fold`, a `PredicateNode` for the quantifiers) to be evaluated once per resolved item, using that single item as its evaluation context, plus an optional per-item pre-filter — see [Pre-filtering which items participate](#pre-filtering-which-items-participate).
@@ -564,13 +701,17 @@ An item whose `filter` is itself indeterminate is never silently included or exc
564
701
 
565
702
  ## Resolvers
566
703
 
567
- Three independent points of extension, each supplied separately by the embedding consumer, each treated by the schema as pure data to hand over — never as resolver logic living inside the schema itself:
704
+ Three core, required points of extension, plus two further independent optional ones, each supplied separately by the embedding consumer, each treated by the schema as pure data to hand over — never as resolver logic living inside the schema itself:
568
705
 
569
706
  ```ts
570
707
  type Resolution =
571
708
  | { found: true; value: ComputedValue }
572
709
  | { found: false };
573
710
 
711
+ type TreeResolution =
712
+ | { found: true; node: JsonValue }
713
+ | { found: false };
714
+
574
715
  interface Resolvers {
575
716
  /** Resolver 1 — a single opaque key to a single value (IV.reference). */
576
717
  resolveValue(key: JsonValue, context: EvaluationContext): Promise<Resolution>;
@@ -583,10 +724,15 @@ interface Resolvers {
583
724
 
584
725
  /** Optional, separate from the three core contracts — see the `delegate` node kind. */
585
726
  resolveDelegate?(system: string, payload: JsonValue, context: EvaluationContext): Promise<Resolution>;
727
+
728
+ /** Optional, separate from the three core contracts — see the `treeReference` node kind. */
729
+ resolveTree?(key: JsonValue, context: EvaluationContext): Promise<TreeResolution>;
586
730
  }
587
731
  ```
588
732
 
589
- `resolveCollection` takes no narrowing parameter of its own: it always returns the full candidate list for the given reference, and narrowing which of those candidates actually take part is handled uniformly, after resolution, by the `filter` mechanism described under [Pre-filtering which items participate](#pre-filtering-which-items-participate) — no resolver needs a bespoke narrowing argument for this. It also returns a plain array rather than a `Resolution` envelope: a collection's "nothing here" state is unambiguously an empty array, unlike a single value's absence, which needs an explicit flag to distinguish "there is genuinely nothing here" from any value the resolver might otherwise legitimately return. Each resolver may itself be asynchronous, independently of the others. None of the three needs to know anything about the other two; a consumer implementing all three (and, optionally, the delegate handler) is free to have them share underlying data-access logic, but the schema and evaluator never require or assume that they do.
733
+ `resolveCollection` takes no narrowing parameter of its own: it always returns the full candidate list for the given reference, and narrowing which of those candidates actually take part is handled uniformly, after resolution, by the `filter` mechanism described under [Pre-filtering which items participate](#pre-filtering-which-items-participate) — no resolver needs a bespoke narrowing argument for this. It also returns a plain array rather than a `Resolution` envelope: a collection's "nothing here" state is unambiguously an empty array, unlike a single value's absence, which needs an explicit flag to distinguish "there is genuinely nothing here" from any value the resolver might otherwise legitimately return. Each resolver may itself be asynchronous, independently of the others. None of the three core resolvers needs to know anything about the other two, or about either optional one; a consumer implementing all five is free to have them share underlying data-access logic, but the schema and evaluator never require or assume that they do.
734
+
735
+ `resolveTree` returns a `TreeResolution`, deliberately shaped like `Resolution` but distinct from it: `node` carries opaque JSON — the referenced tree, re-validated by the evaluator rather than trusted (see [`treeReference`](#treereference)) — where `Resolution`'s `value` carries an already-typed `ComputedValue`. It is otherwise the same "found" envelope for the same reason: a `treeReference`'s absence needs to be distinguishable from any tree the resolver might otherwise legitimately return, exactly as a `reference`'s absence needs to be distinguishable from any value. `resolveDelegate` and `resolveTree` solve different problems and are never a substitute for one another: `resolveDelegate` hands a payload to an *external* system this package never evaluates; `resolveTree` hands back *more of this same schema*, for this same evaluator to keep evaluating.
590
736
 
591
737
  ## Evaluator entry points
592
738
 
@@ -643,27 +789,28 @@ How each reason category can arise, per node kind. "Propagates" means: an indete
643
789
  | `and` | propagates, **unless** the other operand is definitely `false` (absorbs) | as `not-found` | as `not-found` |
644
790
  | `or` | propagates, **unless** the other operand is definitely `true` (absorbs) | as `not-found` | as `not-found` |
645
791
  | `allOf` / `anyOf` | as `and`/`or`, extended pairwise across the list | as `and`/`or` | as `and`/`or` |
646
- | `compare` | either operand not found | operand kinds differ, or units incompatible, or kind is not `number`/`instant`/`duration` | never directly (comparison itself has no domain restriction) |
792
+ | `compare` | either operand not found | operand kinds differ, or units incompatible, or kind is not `number`/`instant`/`duration`/`complex`, or an ordering operator was given a `complex` operand (see [Complex values](#complex-values)) | never directly (comparison itself has no domain restriction) |
647
793
  | `textCompare` | either operand not found | either operand is not `text` | never directly |
648
794
  | `memberOf` | `operand` not found, or (with no definite match found) a scanned candidate not found | `operand`/a candidate resolves to an incompatible kind or unit, with no definite match found among the rest | never directly |
649
795
  | `exists` | never — converts operand `not-found` to definite `false` | never — converts operand `wrong-type`/`domain-error` to definite `true` | never — see `wrong-type` column |
650
796
  | `some` / `every` | an item's `filter` or `item` sub-node reports not-found, and it is not absorbed by an already-decided item | as `not-found` | as `not-found` |
651
- | literals (`numberLiteral`, `textLiteral`, `instantLiteral`, `durationLiteral`) | never | never | never |
797
+ | literals (`numberLiteral`, `textLiteral`, `instantLiteral`, `durationLiteral`, `complexLiteral`) | never | never | never |
652
798
  | `reference` | resolver reports absence | resolver's value doesn't match an expected `unit`, or is used where an incompatible kind is required upstream | never directly |
653
- | `arithmetic` | either operand not found | operand not numeric (or temporal-kind mismatch — see [Temporal values](#temporal-values)), or unit mismatch on add/subtract | zero divisor, or any other documented domain violation for the operator |
654
- | `negate` | operand not found | operand not `number`/`duration` | never directly |
799
+ | `arithmetic` | either operand not found | operand not numeric (or temporal-kind mismatch — see [Temporal values](#temporal-values)), or unit mismatch on add/subtract, or a `power` exponent that is not a real integer over a `complex` operand (see [Complex values](#complex-values)) | zero divisor, `modulo` over a `complex` operand, or any other documented domain violation for the operator |
800
+ | `negate` | operand not found | operand not `number`/`duration`/`complex` | never directly |
655
801
  | `call` | any argument not found | unregistered function name, or an argument of the wrong kind for that function | argument outside the function's valid domain (e.g. negative input to `squareRoot`) |
656
802
  | `lookup` | any key not found, or resolver reports no match | a key expression resolves to the wrong kind for that table | never directly |
657
- | `conditional` | an unmatched guard's own evaluation is `not-found`, before any earlier guard matched | as `not-found`; also the chosen branch's own result if it is `wrong-type` | as `not-found`; also the chosen branch's own result if it is `domain-error` |
803
+ | `conditional` | `"first"`: an unmatched guard's own evaluation is `not-found`, before any earlier guard matched.<br>`"unique"`: any case's `when` is `not-found`, unless 2+ cases already definitely matched (see `domain-error`, which then takes priority).<br>Both: also the chosen branch's (`then`/`fallback`) own result if it is `not-found`. | Same pattern as `not-found`, substituting `wrong-type` throughout (guard evaluation and chosen branch alike). | `"unique"` only: 2+ cases are definitely `true` — see [`conditional`](#conditional)'s absorption order.<br>Both: same pattern as `not-found`, substituting `domain-error` (guard evaluation and chosen branch alike). |
658
804
  | `fold` | any participating item's `filter`, `item`, or `combine` evaluation is `not-found`; or a `reduce`'s `initial` is `not-found` | any participating item's `filter`, `item`, or `combine` evaluation is `wrong-type`; or a `reduce`'s `initial` is `wrong-type` | empty (post-filter) collection with `max`/`min` (no first item to seed from); or any participating item's `item`/`combine` evaluation is `domain-error`; or a `reduce`'s `initial` is `domain-error` |
659
805
  | `accumulator` | never | used outside a reduce fold's `combine` expression | never |
660
806
  | `delegate` | never (no resolution attempted without a handler) | no handler registered for the named `system` | never |
807
+ | `treeReference` | resolver reports no match | no `resolveTree` registered; or the resolved node fails schema validation | a circular reference is detected; or the reference chain exceeds the maximum depth |
661
808
 
662
809
  ## Worked example
663
810
 
664
811
  A single condition combining a boolean tree, a comparison leaf whose value side is itself a formula, a fold/aggregation node, and all three resolver contracts in use — every name below is a generic placeholder.
665
812
 
666
- **Rule:** "`isActive` is true, and the sum of `amount` across the `items` collection is greater than `x + y`." `isActive` is modelled as the number `1` for true — the computed-value model has no native boolean kind, so a boolean data point is represented however best suits the consumer, here as a numeric flag compared for equality. The `fold` below is exactly what the [`sum`](#derived-aggregates) builder produces — shown here as the literal tree it assembles, to keep the resolver trace below concrete.
813
+ **Rule:** "`isActive` is true, and the sum of `amount` across the `items` collection is greater than `x + y`." `isActive` is a `boolean` computed value, compared for equality against the literal `true`. The `fold` below is exactly what the [`sum`](#derived-aggregates) builder produces — shown here as the literal tree it assembles, to keep the resolver trace below concrete.
667
814
 
668
815
  ```json
669
816
  {
@@ -672,7 +819,7 @@ A single condition combining a boolean tree, a comparison leaf whose value side
672
819
  "kind": "compare",
673
820
  "op": "eq",
674
821
  "left": { "kind": "reference", "key": "isActive" },
675
- "right": { "kind": "numberLiteral", "value": 1 }
822
+ "right": { "kind": "booleanLiteral", "value": true }
676
823
  },
677
824
  "right": {
678
825
  "kind": "compare",
@@ -705,7 +852,7 @@ A minimal set of resolvers backing this against a plain in-memory record:
705
852
 
706
853
  ```ts
707
854
  const data = {
708
- isActive: 1,
855
+ isActive: true,
709
856
  x: 10,
710
857
  y: 5,
711
858
  items: [{ amount: 8 }, { amount: 12 }, { amount: 1 }],
@@ -715,7 +862,9 @@ const resolvers: Resolvers = {
715
862
  async resolveValue(key, context) {
716
863
  const record = context as Record<string, unknown>;
717
864
  if (typeof key !== "string" || !(key in record)) return { found: false };
718
- return { found: true, value: { kind: "number", value: record[key] as number } };
865
+ const value = record[key];
866
+ if (typeof value === "boolean") return { found: true, value: { kind: "boolean", value } };
867
+ return { found: true, value: { kind: "number", value: value as number } };
719
868
  },
720
869
  async resolveLookup() {
721
870
  return { found: false }; // unused by this example
@@ -729,7 +878,7 @@ const resolvers: Resolvers = {
729
878
 
730
879
  Tracing the evaluation against `data` as the root `EvaluationContext`:
731
880
 
732
- 1. `compare eq` (left branch): `resolveValue("isActive", data)` → `{ found: true, value: { kind: "number", value: 1 } }`; compared against `numberLiteral 1` → definite `true`.
881
+ 1. `compare eq` (left branch): `resolveValue("isActive", data)` → `{ found: true, value: { kind: "boolean", value: true } }`; compared against `booleanLiteral true` → definite `true`.
733
882
  2. `fold` (`reduce`, seeded at `0`): `resolveCollection("items", data)` → three items. The accumulator starts at `0`; for each item in turn, `combine` evaluates `accumulator + reference("amount")` with that single item as context — `resolveValue("amount", item)` → `8`, `12`, `1`, all definite — stepping the accumulator `0 → 8 → 20 → 21`. Final accumulator → `21`.
734
883
  3. `arithmetic add`: `resolveValue("x", data)` → `10`; `resolveValue("y", data)` → `5`. Sum → `15`.
735
884
  4. `compare gt` (right branch): `21 > 15` → definite `true`.
@@ -744,10 +893,11 @@ Two variations show the propagation rules in action without changing the tree at
744
893
  This package is a representation-plus-evaluator for conditions and formulas over already-available (or resolver-obtained) data. It deliberately does not include:
745
894
 
746
895
  - **Symbolic algebra.** It cannot solve an expression for an unknown quantity, symbolically simplify an expression, or perform symbolic differentiation or integration. A consumer needing any of that is expected to translate the pure-arithmetic portion of an expression tree into the input format of existing, general-purpose symbolic-mathematics software — several mature, freely available options already exist — and let that external system do the symbolic work. This package's job stops at representing and numerically evaluating a tree, not manipulating it symbolically.
747
- - **Complex-number or phasor arithmetic.** Every numeric value in this design is real-valued. Some domains occasionally need calculations naturally expressed with complex numbers; rather than extending the core numeric model to support that — a far larger and more invasive change than adding one more named function — the recommended approach is the same delegation escape hatch described under [`delegate`](#delegate): hand the relevant subtree, unevaluated, to an external system built for that kind of mathematics, several of which already exist as mature, freely available tooling.
748
- - **Batch unresolvable-reference reporting.** This design deliberately has no node kind for asking "which of these references, across a whole batch, are unresolvable" as a single evaluation — only the [`exists`](#exists) leaf's one-at-a-time true/false/false-on-absence check. A tool that wants to report a *list* of every missing reference (for an authoring UI validating a tree before it's saved, say) is expected to build that on top of `exists` — walk the references of interest and evaluate an `exists` leaf over each — at the authoring/tooling layer, rather than this package growing a bespoke aggregate-diagnostic node kind for it. This is a deliberate boundary, not an oversight: it keeps the evaluation tree itself limited to producing one `Evaluation` per node, and leaves "collect many such results and report on them together" to whatever sits above the evaluator, exactly like symbolic algebra and complex-number arithmetic above are left to whatever sits beside it.
896
+ - **Batch unresolvable-reference reporting.** This design deliberately has no node kind for asking "which of these references, across a whole batch, are unresolvable" as a single evaluation — only the [`exists`](#exists) leaf's one-at-a-time true/false/false-on-absence check. A tool that wants to report a *list* of every missing reference (for an authoring UI validating a tree before it's saved, say) is expected to build that on top of `exists` — walk the references of interest and evaluate an `exists` leaf over each — at the authoring/tooling layer, rather than this package growing a bespoke aggregate-diagnostic node kind for it. This is a deliberate boundary, not an oversight: it keeps the evaluation tree itself limited to producing one `Evaluation` per node, and leaves "collect many such results and report on them together" to whatever sits above the evaluator, exactly like symbolic algebra above is left to whatever sits beside it.
897
+
898
+ This package does not name or depend on any specific external tool for the delegation case above — it only defines the shape of the hand-off (an opaque payload plus a named destination system).
749
899
 
750
- This package does not name or depend on any specific external tool for either of the two delegation cases above — it only defines the shape of the hand-off (an opaque payload plus a named destination system).
900
+ Complex-number and phasor arithmetic used to be listed here too, delegated out on the reasoning that supporting them would be a far larger and more invasive change than adding one more named function. That sizing was wrong: unlike symbolic algebra, which is a genuinely different kind of system, complex arithmetic is closed-form numeric evaluation, exactly what this evaluator already does for every other computed-value kind. It is now part of the core numeric model — see [Complex values](#complex-values), and [Design principles](#design-principles) for the scope test that judgement is now written down as.
751
901
 
752
902
  ## Prior art
753
903
 
@@ -0,0 +1,34 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/complex.ts
3
+ const complexFromPolar = (magnitude, phase, unit) => ({
4
+ kind: "complex",
5
+ re: magnitude * Math.cos(phase),
6
+ im: magnitude * Math.sin(phase),
7
+ unit
8
+ });
9
+ /** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
10
+ const complexLiteralFromPolar = (magnitude, phase, unit) => {
11
+ const { re, im } = complexFromPolar(magnitude, phase, unit);
12
+ return {
13
+ kind: "complexLiteral",
14
+ re,
15
+ im,
16
+ unit
17
+ };
18
+ };
19
+ /** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
20
+ const complexMagnitude = (value) => ({
21
+ kind: "number",
22
+ value: Math.hypot(value.re, value.im),
23
+ unit: value.unit
24
+ });
25
+ /** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
26
+ const complexPhase = (value) => ({
27
+ kind: "number",
28
+ value: Math.atan2(value.im, value.re)
29
+ });
30
+ //#endregion
31
+ exports.complexFromPolar = complexFromPolar;
32
+ exports.complexLiteralFromPolar = complexLiteralFromPolar;
33
+ exports.complexMagnitude = complexMagnitude;
34
+ exports.complexPhase = complexPhase;
@@ -0,0 +1,23 @@
1
+ import { ComputedValue, Unit } from "./computed-value.cjs";
2
+ import { ComplexLiteralNode } from "./tree.cjs";
3
+ //#region src/complex.d.ts
4
+ /**
5
+ * The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
6
+ *
7
+ * Phase is in radians throughout, measured from the positive real axis, matching `Math.atan2`'s own range of (-pi, pi].
8
+ */
9
+ type ComplexValue = Extract<ComputedValue, {
10
+ kind: "complex";
11
+ }>;
12
+ type NumberValue = Extract<ComputedValue, {
13
+ kind: "number";
14
+ }>;
15
+ declare const complexFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexValue;
16
+ /** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
17
+ declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
18
+ /** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
19
+ declare const complexMagnitude: (value: ComplexValue) => NumberValue;
20
+ /** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
21
+ declare const complexPhase: (value: ComplexValue) => NumberValue;
22
+ //#endregion
23
+ export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
@@ -0,0 +1,23 @@
1
+ import { ComputedValue, Unit } from "./computed-value.js";
2
+ import { ComplexLiteralNode } from "./tree.js";
3
+ //#region src/complex.d.ts
4
+ /**
5
+ * The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
6
+ *
7
+ * Phase is in radians throughout, measured from the positive real axis, matching `Math.atan2`'s own range of (-pi, pi].
8
+ */
9
+ type ComplexValue = Extract<ComputedValue, {
10
+ kind: "complex";
11
+ }>;
12
+ type NumberValue = Extract<ComputedValue, {
13
+ kind: "number";
14
+ }>;
15
+ declare const complexFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexValue;
16
+ /** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
17
+ declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
18
+ /** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
19
+ declare const complexMagnitude: (value: ComplexValue) => NumberValue;
20
+ /** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
21
+ declare const complexPhase: (value: ComplexValue) => NumberValue;
22
+ //#endregion
23
+ export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
@@ -0,0 +1,30 @@
1
+ //#region src/complex.ts
2
+ const complexFromPolar = (magnitude, phase, unit) => ({
3
+ kind: "complex",
4
+ re: magnitude * Math.cos(phase),
5
+ im: magnitude * Math.sin(phase),
6
+ unit
7
+ });
8
+ /** The `complexLiteral` node counterpart of `complexFromPolar`, for authoring a tree in polar terms; the conversion itself is done once, there, rather than repeated here. */
9
+ const complexLiteralFromPolar = (magnitude, phase, unit) => {
10
+ const { re, im } = complexFromPolar(magnitude, phase, unit);
11
+ return {
12
+ kind: "complexLiteral",
13
+ re,
14
+ im,
15
+ unit
16
+ };
17
+ };
18
+ /** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
19
+ const complexMagnitude = (value) => ({
20
+ kind: "number",
21
+ value: Math.hypot(value.re, value.im),
22
+ unit: value.unit
23
+ });
24
+ /** arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. */
25
+ const complexPhase = (value) => ({
26
+ kind: "number",
27
+ value: Math.atan2(value.im, value.re)
28
+ });
29
+ //#endregion
30
+ export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
@@ -20,6 +20,10 @@ const ComputedValueSchema = zod.z.discriminatedUnion("kind", [
20
20
  kind: zod.z.literal("text"),
21
21
  value: zod.z.string()
22
22
  }),
23
+ zod.z.object({
24
+ kind: zod.z.literal("boolean"),
25
+ value: zod.z.boolean()
26
+ }),
23
27
  zod.z.object({
24
28
  kind: zod.z.literal("instant"),
25
29
  value: zod.z.string()
@@ -28,6 +32,12 @@ const ComputedValueSchema = zod.z.discriminatedUnion("kind", [
28
32
  kind: zod.z.literal("duration"),
29
33
  value: zod.z.number(),
30
34
  unit: DurationUnitSchema
35
+ }),
36
+ zod.z.object({
37
+ kind: zod.z.literal("complex"),
38
+ re: zod.z.number(),
39
+ im: zod.z.number(),
40
+ unit: UnitSchema.optional()
31
41
  })
32
42
  ]);
33
43
  /** Drops zero-exponent dimensions so that, e.g., dividing a unit by itself normalises to the same dimensionless `{}` as an absent unit -- without this, `{ m: 0 }` and `{}` would compare unequal despite representing the same dimension. */
@@ -18,6 +18,9 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
18
18
  }, z.core.$strip>, z.ZodObject<{
19
19
  kind: z.ZodLiteral<"text">;
20
20
  value: z.ZodString;
21
+ }, z.core.$strip>, z.ZodObject<{
22
+ kind: z.ZodLiteral<"boolean">;
23
+ value: z.ZodBoolean;
21
24
  }, z.core.$strip>, z.ZodObject<{
22
25
  kind: z.ZodLiteral<"instant">;
23
26
  value: z.ZodString;
@@ -31,6 +34,11 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
31
34
  h: "h";
32
35
  d: "d";
33
36
  }>;
37
+ }, z.core.$strip>, z.ZodObject<{
38
+ kind: z.ZodLiteral<"complex">;
39
+ re: z.ZodNumber;
40
+ im: z.ZodNumber;
41
+ unit: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
34
42
  }, z.core.$strip>], "kind">;
35
43
  type ComputedValue = z.infer<typeof ComputedValueSchema>;
36
44
  /** An operand with no `unit` is dimensionless (an empty map) for comparison purposes. */
@@ -18,6 +18,9 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
18
18
  }, z.core.$strip>, z.ZodObject<{
19
19
  kind: z.ZodLiteral<"text">;
20
20
  value: z.ZodString;
21
+ }, z.core.$strip>, z.ZodObject<{
22
+ kind: z.ZodLiteral<"boolean">;
23
+ value: z.ZodBoolean;
21
24
  }, z.core.$strip>, z.ZodObject<{
22
25
  kind: z.ZodLiteral<"instant">;
23
26
  value: z.ZodString;
@@ -31,6 +34,11 @@ declare const ComputedValueSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
31
34
  h: "h";
32
35
  d: "d";
33
36
  }>;
37
+ }, z.core.$strip>, z.ZodObject<{
38
+ kind: z.ZodLiteral<"complex">;
39
+ re: z.ZodNumber;
40
+ im: z.ZodNumber;
41
+ unit: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
34
42
  }, z.core.$strip>], "kind">;
35
43
  type ComputedValue = z.infer<typeof ComputedValueSchema>;
36
44
  /** An operand with no `unit` is dimensionless (an empty map) for comparison purposes. */