@bjornpagen/bumbledb 0.5.0 → 0.6.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.
Files changed (45) hide show
  1. package/COOKBOOK.md +96 -131
  2. package/README.md +9 -9
  3. package/dist/db.js +2 -2
  4. package/dist/db.js.map +1 -1
  5. package/dist/index.d.ts +8 -5
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +5 -2
  8. package/dist/index.js.map +1 -1
  9. package/dist/query/atom.d.ts +132 -201
  10. package/dist/query/atom.d.ts.map +1 -1
  11. package/dist/query/atom.js +30 -42
  12. package/dist/query/atom.js.map +1 -1
  13. package/dist/query/find.d.ts +116 -0
  14. package/dist/query/find.d.ts.map +1 -0
  15. package/dist/query/{select.js → find.js} +22 -22
  16. package/dist/query/find.js.map +1 -0
  17. package/dist/query/lower.d.ts +123 -158
  18. package/dist/query/lower.d.ts.map +1 -1
  19. package/dist/query/lower.js +437 -493
  20. package/dist/query/lower.js.map +1 -1
  21. package/dist/query/predicate.d.ts +22 -14
  22. package/dist/query/predicate.d.ts.map +1 -1
  23. package/dist/query/predicate.js +35 -42
  24. package/dist/query/predicate.js.map +1 -1
  25. package/dist/query/run.d.ts +3 -3
  26. package/dist/query/run.d.ts.map +1 -1
  27. package/dist/query/run.js +9 -9
  28. package/dist/query/run.js.map +1 -1
  29. package/dist/query/scope.d.ts +127 -72
  30. package/dist/query/scope.d.ts.map +1 -1
  31. package/dist/query/scope.js +80 -33
  32. package/dist/query/scope.js.map +1 -1
  33. package/package.json +2 -2
  34. package/src/db.ts +4 -4
  35. package/src/index.ts +11 -7
  36. package/src/query/atom.ts +181 -263
  37. package/src/query/find.ts +212 -0
  38. package/src/query/lower.ts +588 -722
  39. package/src/query/predicate.ts +37 -45
  40. package/src/query/run.ts +10 -10
  41. package/src/query/scope.ts +172 -87
  42. package/dist/query/select.d.ts +0 -128
  43. package/dist/query/select.d.ts.map +0 -1
  44. package/dist/query/select.js.map +0 -1
  45. package/src/query/select.ts +0 -215
@@ -5,31 +5,39 @@
5
5
  *
6
6
  * program(S, (p) => {
7
7
  * const reach = p.rec("reach")
8
- * reach.rule((r) => r.match(Node, { id: r.var("c") })
9
- * .where(r.eq(r.var("c"), r.param("root"))).select("c"))
10
- * reach.rule((r) => r.match(Parent, { child: r.var("c"), parent: r.var("m") })
11
- * .idb(reach, r.var("m")).select("c"))
12
- * return p.output((r) => r.match(Posting, { account: r.var("a"), minor: r.var("m") })
13
- * .idb(reach, r.var("a")).select(r.sum("m")))
8
+ * reach.rule((r) => {
9
+ * const n = v(Node)
10
+ * return r.match(Node, { id: n.id }).where(r.eq(n.id, r.param("root"))).find({ c: n.id })
11
+ * })
12
+ * reach.rule((r) => {
13
+ * const e = v(Parent)
14
+ * return r.match(Parent, { child: e.child, parent: e.parent }).idb(reach, { c: e.parent }).find({ c: e.child })
15
+ * })
16
+ * return p.output((r) => {
17
+ * const post = v(Posting)
18
+ * return r.match(Posting, { account: post.account, minor: post.minor })
19
+ * .idb(reach, { c: post.account }).find({ total: r.sum(post.minor) })
20
+ * })
14
21
  * })
15
22
  *
16
23
  * `p.rec(name)` declares one recursive predicate (declaration order = its
17
24
  * dense `PredId`); `rec.rule(...)` attaches one clause — its builder's
18
25
  * `idb` accepts ONLY the rec itself (the self-recursion cut as a
19
- * type-level boundary: mutual recursion is unwritable) and its head
20
- * projects bound variable NAMES only (aggregation/measure through a cycle
21
- * is unrepresentable — the strata judge's roster, made unwritable);
26
+ * type-level boundary: mutual recursion is unwritable) and its `find` head
27
+ * projects bound variables only (aggregation/measure through a cycle is
28
+ * unrepresentable — the strata judge's roster, made unwritable);
22
29
  * `p.output(...)` seals the recs and builds the output rules, whose `idb`
23
- * folds any FINISHED stratum (recipe 25's form). The rec value `.rule`
24
- * returns carries the params its rules used — thread it into the output's
25
- * `idb` and the program's inferred `Params` stays exactly the params the
26
- * rules use. Everything deeper — strata legality, signature sealing, the
27
- * three oracles — is the ENGINE's judge, surfacing typed at prepare.
30
+ * folds any FINISHED stratum by NAMED record over its head keys (recipe
31
+ * 25's form). The rec value `.rule` returns carries the params its rules
32
+ * used — thread it into the output's `idb` and the program's inferred
33
+ * `Params` stays exactly the params the rules use. Everything deeper —
34
+ * strata legality, signature sealing, the three oracles — is the ENGINE's
35
+ * judge, surfacing typed at prepare.
28
36
  */
29
37
 
30
38
  import * as errors from "@superbuilders/errors"
31
39
  import type { SchemaClasses } from "#law.ts"
32
- import type { RecData, RuleData, SelectColumn } from "#query/atom.ts"
40
+ import type { RecData } from "#query/atom.ts"
33
41
  import type {
34
42
  AnyRuleValue,
35
43
  HeadOf,
@@ -45,7 +53,7 @@ import type {
45
53
  RuleValue
46
54
  } from "#query/lower.ts"
47
55
  import { makeOutputRuleScope, makeQuery, makeRawScope } from "#query/lower.ts"
48
- import type { ClassedField, Flatten, ParamsRecord, ShapeOf } from "#query/scope.ts"
56
+ import type { Flatten, ParamsRecord, ShapeOf } from "#query/scope.ts"
49
57
  import { fieldJoins, inferred, renderFieldKind } from "#query/scope.ts"
50
58
  import type { Schema, SchemaRelations } from "#schema.ts"
51
59
 
@@ -112,20 +120,6 @@ interface RawRec<Name extends string> {
112
120
  rule(build: (r: RawScope) => RuleValue<never, never>): RawRec<Name>
113
121
  }
114
122
 
115
- /**
116
- * The classed slot one rec head column binds, through the rule's own
117
- * environment: a rec head projects bound variable NAMES only (the strata
118
- * roster's unwritability), so every column is a projected var and its
119
- * slot is the var's first positive binding.
120
- */
121
- function recHeadSlotOf(rule: RuleData, column: SelectColumn): ClassedField | undefined {
122
- const entry = column.entry
123
- if (entry.kind === "var") {
124
- return rule.varFields[entry.over]
125
- }
126
- return undefined
127
- }
128
-
129
123
  /** Builds the runtime rec handle over shared rec data. */
130
124
  function makeRawRec<Name extends string>(state: ProgramState, name: Name, data: RecData): RawRec<Name> {
131
125
  const rec: RawRec<Name> = {
@@ -137,13 +131,13 @@ function makeRawRec<Name extends string>(state: ProgramState, name: Name, data:
137
131
  `rec ${name}: the program's output is already declared — recursive rules attach before p.output`
138
132
  )
139
133
  }
140
- const built = build(makeRawScope({ kind: "rec", self: data, classes: state.classes }))
134
+ const built = build(makeRawScope({ kind: "rec", self: data, classes: state.classes, theory: state.theory }))
141
135
  const head = data.rules[0]
142
136
  if (head !== undefined) {
143
- const declared = head.select.map(function columnName(column) {
137
+ const declared = head.finds.map(function columnName(column) {
144
138
  return column.name
145
139
  })
146
- const candidate = built.rule.select.map(function columnName(column) {
140
+ const candidate = built.rule.finds.map(function columnName(column) {
147
141
  return column.name
148
142
  })
149
143
  if (declared.join(", ") !== candidate.join(", ")) {
@@ -153,21 +147,19 @@ function makeRawRec<Name extends string>(state: ProgramState, name: Name, data:
153
147
  }
154
148
  // The law-class wall on the sealed head: names alone do not
155
149
  // align value spaces. Every rule must bind each head column
156
- // at a slot that JOINS rule 0's (the sealing rule — the one
157
- // slot every downstream idb pairing class-checks against),
158
- // under the same fieldJoins judgment every reuse site
159
- // enforces; otherwise a later rule feeds (say) bare weights
160
- // into a column the idb joins as Node ids.
161
- built.rule.select.forEach(function verifyHeadSlot(column, position) {
162
- const lead = head.select[position]
150
+ // at a classed mint slot that JOINS rule 0's (the sealing rule
151
+ // — the one slot every downstream idb pairing class-checks
152
+ // against), under the same fieldJoins judgment every reuse
153
+ // site enforces; otherwise a later rule feeds (say) bare
154
+ // weights into a column the idb joins as Node ids.
155
+ built.rule.finds.forEach(function verifyHeadSlot(column, position) {
156
+ const lead = head.finds[position]
163
157
  if (lead === undefined) {
164
158
  return
165
159
  }
166
- const leadSlot = recHeadSlotOf(head, lead)
167
- const slot = recHeadSlotOf(built.rule, column)
168
- if (leadSlot !== undefined && slot !== undefined && !fieldJoins(leadSlot, slot)) {
160
+ if (lead.slot !== undefined && column.slot !== undefined && !fieldJoins(lead.slot, column.slot)) {
169
161
  throw errors.new(
170
- `rec ${name}: every rule derives the same head — the head column ${lead.name} is bound at ${renderFieldKind(leadSlot)} in rule 0 but at ${renderFieldKind(slot)} in this rule (a head column joins only class-equal slots; bare pairs only with bare)`
162
+ `rec ${name}: every rule derives the same head — the head column ${lead.name} is bound at ${renderFieldKind(lead.slot)} in rule 0 but at ${renderFieldKind(column.slot)} in this rule (a head column joins only class-equal slots; bare pairs only with bare)`
171
163
  )
172
164
  }
173
165
  })
@@ -221,7 +213,7 @@ function program<
221
213
  Classes extends SchemaClasses,
222
214
  Q extends Query<Rels, unknown, ParamsRecord, Classes>
223
215
  >(theory: Schema<Rels, Classes>, build: (p: ProgramScope<Rels, Classes>) => Q): Q {
224
- const state: ProgramState = { recs: [], classes: theory.classes, sealed: false }
216
+ const state: ProgramState = { recs: [], classes: theory.classes, theory, sealed: false }
225
217
  const names = new Set<string>()
226
218
  const made: { query: unknown } = { query: undefined }
227
219
  const scope: ProgramScope<Rels, Classes> = {
package/src/query/run.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * select column IS a row (the trusted read seam), and nothing is asserted
11
11
  * on any value. A CLOSED answer column decodes id → handle NAME through
12
12
  * the marshal's one bijection (`handleOf` — the same read half every fact
13
- * decode rides; the column's roster rides `SelectColumn.closed`), so query
13
+ * decode rides; the column's roster rides `FindColumn.closed`), so query
14
14
  * rows speak the vocabulary exactly as scans and gets do. Answers are
15
15
  * SETS — no order or limit exists anywhere; hosts sort. The `Prepared`
16
16
  * VALUE itself (no lifecycle, GC-reclaimed plan) lives in `#db.ts`.
@@ -19,7 +19,7 @@
19
19
  import * as errors from "@superbuilders/errors"
20
20
  import { handleOf } from "#marshal.ts"
21
21
  import type { FactValue, QueryParam, TaggedValue } from "#native.ts"
22
- import type { SelectColumn } from "#query/atom.ts"
22
+ import type { FindColumn } from "#query/atom.ts"
23
23
  import { ALLEN_ALL_BITS } from "#query/atom.ts"
24
24
  import { taggedCmpLiteral } from "#query/lower.ts"
25
25
  import type { ParamEntry } from "#query/scope.ts"
@@ -94,10 +94,10 @@ function wireParams(entries: readonly ParamEntry[], supplied: Readonly<Record<st
94
94
  * re-derive).
95
95
  */
96
96
  function isAnswerRow<Row>(
97
- select: readonly SelectColumn[],
97
+ finds: readonly FindColumn[],
98
98
  decoded: Readonly<Record<string, FactValue>>
99
99
  ): decoded is Readonly<Record<string, FactValue>> & Row {
100
- return select.every(function present(column) {
100
+ return finds.every(function present(column) {
101
101
  return decoded[column.name] !== undefined
102
102
  })
103
103
  }
@@ -109,13 +109,13 @@ function isAnswerRow<Row>(
109
109
  * NAME through the marshal's bijection — an out-of-roster id is the same
110
110
  * pointed throw a fact decode gives, never a silent fallback.
111
111
  */
112
- function decodeAnswers<Row>(select: readonly SelectColumn[], rows: FactValue[][]): Row[] {
112
+ function decodeAnswers<Row>(finds: readonly FindColumn[], rows: FactValue[][]): Row[] {
113
113
  return rows.map(function decodeRow(row) {
114
- if (row.length !== select.length) {
115
- throw errors.new(`query answer arity ${row.length} does not match the ${select.length} select columns`)
114
+ if (row.length !== finds.length) {
115
+ throw errors.new(`query answer arity ${row.length} does not match the ${finds.length} find columns`)
116
116
  }
117
117
  const decoded: Record<string, FactValue> = {}
118
- select.forEach(function decodeCell(column, ordinal) {
118
+ finds.forEach(function decodeCell(column, ordinal) {
119
119
  const cell = row[ordinal]
120
120
  if (cell === undefined) {
121
121
  throw errors.new(`query answer cell ${ordinal} (${column.name}) is absent`)
@@ -124,8 +124,8 @@ function decodeAnswers<Row>(select: readonly SelectColumn[], rows: FactValue[][]
124
124
  column.closed === undefined ? cell : handleOf(`query answer column ${column.name}`, column.closed, cell)
125
125
  })
126
126
  Object.freeze(decoded)
127
- if (!isAnswerRow<Row>(select, decoded)) {
128
- throw errors.new("query answer row is not a complete select record")
127
+ if (!isAnswerRow<Row>(finds, decoded)) {
128
+ throw errors.new("query answer row is not a complete find record")
129
129
  }
130
130
  return decoded
131
131
  })
@@ -1,26 +1,42 @@
1
1
  /**
2
- * Query scope terms, LAW-TYPED edition: string-named variables and
3
- * parameters as plain frozen values. A `Var` is a NAME — it is typed by the
4
- * field slot it first binds (the descriptor AND the slot's law-computed
5
- * CLASS, read off the schema's class map through the rule builder's
6
- * environment), reuse of the name within one rule IS the join, and a
7
- * class-mismatched reuse is a compile error: a var joins only class-equal
8
- * slots, and BARE PAIRS ONLY WITH BARE (ruling 3 — a slot in no law has no
9
- * class and never joins a classed slot; the deliberate sum-domain pointer
10
- * stays legal against other bare slots). Params are query-global by name
11
- * and typed BY USE: the field position or comparison sibling that anchors
12
- * a param types it, the query's inferred `Params` object is exactly the
13
- * params the rules use, and a param value that no rule uses simply never
14
- * registers — the query executes under its own inferred type (the
15
- * bug-hunt law). This module also owns the environment/typing utilities
16
- * the whole surface shares: the env shape (var name → classed slot), the
17
- * class-equality judgment {@link JoinOk} with its runtime twin
18
- * {@link fieldJoins}, and the record-folding helpers `Params` and `Row`
19
- * inference ride.
2
+ * Query scope terms, REFERENCE-IDENTITY edition: a query variable is an
3
+ * OBJECT, minted fresh by {@link v} over a relation's statically-known
4
+ * columns. `v(relation)` returns a record of fresh variables — one per
5
+ * column, each typed at mint by its column's descriptor AND the mint
6
+ * coordinate (the owner relation name and the column name), so
7
+ * destructuring preserves every literal and every class
8
+ * (`const { id, holder } = v(Account)`). Variable IDENTITY is the object
9
+ * reference: reusing the same var value across binding positions IS the
10
+ * join, and a name-collision join is unrepresentable (two `v()` calls mint
11
+ * two distinct batches, so two same-named vars are two variables). Params
12
+ * stay STRING-named — their names are the execute() params object's runtime
13
+ * keys, an honest load-bearing channel, not a lie.
14
+ *
15
+ * THE DESIGN THEOREM. {@link JoinOk} is an EQUALITY (kind, class, width,
16
+ * element, roster), so judging every binding position against the
17
+ * variable's MINT slot ({@link MintSlotOf}) makes all cross-binding joins
18
+ * mutually class-equal by transitivity — the env/sibling checks the
19
+ * name-keyed edition needed are subsumed, deleted rather than ported. The
20
+ * one check representation cannot carry is BOUNDNESS (is this var positively
21
+ * bound in this rule): TypeScript types cannot see object identity, so
22
+ * boundness moves from the type tier to construction-time walls only — an
23
+ * explicit essential-vs-accidental concession; every runtime twin is
24
+ * preserved.
25
+ *
26
+ * This module also owns the environment/typing utilities the whole surface
27
+ * shares: the join descriptor {@link ClassedField}, the mint-slot machinery
28
+ * ({@link MintSlotOf}/{@link MintClassOf}), the class-equality judgment
29
+ * {@link JoinOk} with its runtime twin {@link fieldJoins}, and the
30
+ * record-folding helpers `Params` and `Row` inference ride.
20
31
  */
21
32
 
33
+ import * as errors from "@superbuilders/errors"
34
+ import type { AnyClosed } from "#closed.ts"
35
+ import { sealedFieldsOf } from "#closed.ts"
22
36
  import type { AnyField, Infer } from "#fields.ts"
23
37
  import { rosterOf } from "#fields.ts"
38
+ import type { ClassLookup, ClassRecordOf, SchemaClasses } from "#law.ts"
39
+ import type { AnyRelation, RelationFields } from "#relation.ts"
24
40
 
25
41
  /**
26
42
  * The runtime discriminant of query term values. Host literals (bigints,
@@ -38,17 +54,47 @@ const term: unique symbol = Symbol("bumbledb.query.term")
38
54
  const inferred: unique symbol = Symbol("bumbledb.query.inferred")
39
55
 
40
56
  /**
41
- * A query variable — a NAME. Its type comes from the field it first binds
42
- * in the rule (the builder's environment); reusing the name joins, and a
43
- * cross-domain reuse is a compile error. Identity is the name, strictly
44
- * rule-scoped: the same name in two rules names two unrelated variables
45
- * (exactly as the IR scopes `VarId`).
57
+ * What a query atom matches over: an ordinary relation or a CLOSED
58
+ * vocabulary (ψ query atoms — the engine folds a resolvable closed atom
59
+ * into a plan-constant member set at prepare, or joins the L1-resident
60
+ * virtual image when the shape does not fold; the SDK never pre-folds and
61
+ * never knows which — transparency is the contract).
46
62
  */
47
- interface Var<Name extends string = string> {
63
+ type MatchOwner = AnyRelation | AnyClosed
64
+
65
+ /**
66
+ * The matchable field block of an atom owner: a relation's declared
67
+ * fields; a closed relation's SEALED shape — the synthetic `id` (the
68
+ * value's OWN roster-carrying descriptor, at its precise type) first, then
69
+ * the declared payload columns read through the typed `columns` carrier.
70
+ * The runtime twin is `sealedFieldsOf` in `#closed.ts`.
71
+ */
72
+ type MatchFields<R extends MatchOwner> = R extends AnyClosed
73
+ ? { readonly id: R["id"] } & R["columns"]
74
+ : R extends AnyRelation
75
+ ? RelationFields<R>
76
+ : never
77
+
78
+ /**
79
+ * A query variable — an OBJECT minted by {@link v}. Identity is the object
80
+ * reference: reuse of the same value across binding positions is the join,
81
+ * strictly rule-scoped (each rule numbers its own dense `VarId`s). The type
82
+ * carries the mint COORDINATE — `RN` the owner relation name literal, `K`
83
+ * the column name literal — and `F` the mint descriptor, so the mint slot
84
+ * (descriptor + law-computed class) is recoverable at every binding
85
+ * position for the join judgment.
86
+ */
87
+ interface Var<F extends AnyField = AnyField, RN extends string = string, K extends string = string> {
48
88
  readonly [term]: "var"
49
- readonly name: Name
89
+ readonly owner: MatchOwner & { readonly name: RN }
90
+ readonly column: K
91
+ readonly field: F
92
+ readonly label: string
50
93
  }
51
94
 
95
+ /** Any query variable, whatever its descriptor and mint coordinate. */
96
+ type AnyVar = Var
97
+
52
98
  /**
53
99
  * A scalar query parameter — `r.param("root")`. The name is the key of the
54
100
  * typed params object `execute` takes; the type is the element type of the
@@ -86,14 +132,13 @@ interface MaskParam<Name extends string = string> {
86
132
  /**
87
133
  * The measure of an interval-typed variable (`ir::Term::Measure`):
88
134
  * `|[s, e)| = e − s`, u64 — legal as one side of an order comparison, as a
89
- * select entry, and as the input of `sum`/`min`/`max`; every other position
90
- * is unwritable, exactly as the IR rejects it typed. A ray has no finite
91
- * measure — the engine's `MeasureOfRay` execution error; exclude rays first
92
- * (`allen` against a bounded window).
135
+ * find entry, and as the input of `sum`/`min`/`max`; every other position
136
+ * is unwritable, exactly as the IR rejects it typed. Carries the interval
137
+ * variable it measures BY REFERENCE.
93
138
  */
94
- interface Duration<Name extends string = string> {
139
+ interface Duration<V extends AnyVar = AnyVar> {
95
140
  readonly [term]: "duration"
96
- readonly name: Name
141
+ readonly over: V
97
142
  }
98
143
 
99
144
  /** Any scope term value. */
@@ -104,10 +149,55 @@ function isTerm(value: unknown): value is AnyTerm {
104
149
  return typeof value === "object" && value !== null && term in value
105
150
  }
106
151
 
107
- /** Builds one variable term. */
108
- function makeVar<const Name extends string>(name: Name): Var<Name> {
109
- const value: Var<Name> = { [term]: "var", name }
110
- return Object.freeze(value)
152
+ /**
153
+ * The record of fresh variables `v(owner)` mints — one per statically-known
154
+ * column, each typed by its column's descriptor and mint coordinate.
155
+ */
156
+ type VarsOf<R extends MatchOwner> = {
157
+ readonly [K in keyof MatchFields<R> & string]: Var<MatchFields<R>[K], R["name"], K>
158
+ }
159
+
160
+ /**
161
+ * The trusted admission seam of the variable-record mint (the pattern's
162
+ * home is `isTypedScope` in `#query/lower.ts`): the checkable fact — one own
163
+ * enumerable variable per sealed column — is verified before the record is
164
+ * admitted at its computed {@link VarsOf} type.
165
+ */
166
+ function varsMinted<R extends MatchOwner>(owner: R, record: Readonly<Record<string, AnyVar>>): record is VarsOf<R> {
167
+ return sealedFieldsOf(owner).every(function columnMinted(declared) {
168
+ return Object.hasOwn(record, declared.name)
169
+ })
170
+ }
171
+
172
+ /**
173
+ * Mints a FRESH batch of query variables over an atom owner's
174
+ * statically-known columns — one variable per sealed column
175
+ * (`sealedFieldsOf`: a closed owner mints `id` first, then payload columns),
176
+ * each frozen and each defined by OWN-property definition (object-protocol
177
+ * column names must work, the `closed()` precedent). Every `v()` call mints
178
+ * new objects, so two batches are two variables; property access within one
179
+ * batch is stable by construction (the record is an eager frozen record,
180
+ * never a Proxy). Variable identity is the object reference: destructure
181
+ * what you need (`const { id, holder } = v(Account)`) and reuse a value
182
+ * across binding positions to join.
183
+ */
184
+ function v<R extends MatchOwner>(owner: R): VarsOf<R> {
185
+ const record: Record<string, AnyVar> = {}
186
+ for (const declared of sealedFieldsOf(owner)) {
187
+ const variable: AnyVar = Object.freeze({
188
+ [term]: "var" as const,
189
+ owner,
190
+ column: declared.name,
191
+ field: declared.field,
192
+ label: `${owner.name}.${declared.name}`
193
+ })
194
+ Object.defineProperty(record, declared.name, { value: variable, enumerable: true })
195
+ }
196
+ Object.freeze(record)
197
+ if (!varsMinted(owner, record)) {
198
+ throw errors.new(`v(${owner.name}): variable-record minting incomplete`)
199
+ }
200
+ return record
111
201
  }
112
202
 
113
203
  /** Builds one scalar-parameter term. */
@@ -128,19 +218,17 @@ function makeMaskParam<const Name extends string>(name: Name): MaskParam<Name> {
128
218
  return Object.freeze(value)
129
219
  }
130
220
 
131
- /** Builds one measure term over an interval-typed variable's name. */
132
- function makeDuration<const Name extends string>(name: Name): Duration<Name> {
133
- const value: Duration<Name> = { [term]: "duration", name }
221
+ /** Builds one measure term over an interval-typed variable reference. */
222
+ function makeDuration<const V extends AnyVar>(over: V): Duration<V> {
223
+ const value: Duration<V> = { [term]: "duration", over }
134
224
  return Object.freeze(value)
135
225
  }
136
226
 
137
227
  /**
138
228
  * One bound field slot: the field's descriptor plus the slot's
139
229
  * law-computed CLASS (`undefined` = bare — the slot is in no law). The one
140
- * shape the rule environment carries per variable, at the TYPE level (env
141
- * entries hold the schema type's class-map lookups) and at RUNTIME alike
142
- * (the rule's `varFields` record holds exactly this shape, read off the
143
- * schema value's frozen class map) — one shape, two tiers, one walk.
230
+ * shape every join judgment compares, at the TYPE level (a variable's mint
231
+ * slot, a binding position's slot) and at RUNTIME alike.
144
232
  */
145
233
  interface ClassedField {
146
234
  readonly field: AnyField
@@ -148,11 +236,25 @@ interface ClassedField {
148
236
  }
149
237
 
150
238
  /**
151
- * A rule's typing environment: variable name → the classed slot it first
152
- * bound. Purely a TYPE — the runtime twin is the rule's `varFields`
153
- * record, and the two are built by the same walk.
239
+ * A variable's law-computed CLASS at the TYPE level: its column's class,
240
+ * read off the schema type's class map through the mint coordinate the
241
+ * variable carries (`RN.K`). `undefined` = bare.
154
242
  */
155
- type EnvShape = Record<string, ClassedField>
243
+ type MintClassOf<Classes extends SchemaClasses, V> =
244
+ V extends Var<AnyField, infer RN extends string, infer K extends string>
245
+ ? ClassLookup<ClassRecordOf<Classes, RN>, K>
246
+ : never
247
+
248
+ /**
249
+ * A variable's MINT slot: the descriptor it was minted at plus its
250
+ * law-computed class. The one slot every binding position judges against —
251
+ * because {@link JoinOk} is an equality, judging each position against the
252
+ * mint slot makes every cross-binding join transitively class-equal.
253
+ */
254
+ type MintSlotOf<Classes extends SchemaClasses, V extends AnyVar> = {
255
+ readonly field: V["field"]
256
+ readonly class: MintClassOf<Classes, V>
257
+ }
156
258
 
157
259
  /** A params object type — what `execute` takes and inference carries. */
158
260
  type ParamsRecord = Readonly<Record<string, unknown>>
@@ -177,7 +279,9 @@ type WidthOf<F extends AnyField> = F extends { readonly width: infer W } ? W : u
177
279
  /** Reads an interval descriptor's element kind; `undefined` on scalar kinds. */
178
280
  type ElementOf<F extends AnyField> = F extends { readonly element: infer E } ? E : undefined
179
281
 
180
- /** Reads a closed reference's handle union; `undefined` on every non-closed kind (the roster IS descriptor structure). */
282
+ /**
283
+ * Reads a closed reference's handle union; `undefined` on every non-closed kind (the roster IS descriptor structure).
284
+ */
181
285
  type RosterOf<F extends AnyField> = F extends {
182
286
  readonly closed: { readonly handles: readonly (infer H extends string)[] }
183
287
  }
@@ -188,13 +292,10 @@ type RosterOf<F extends AnyField> = F extends {
188
292
  * The join judgment: two bound slots join iff their descriptors' structure
189
293
  * agrees (kind, width label, interval element, and the closed ROSTER — a
190
294
  * closed reference pairs only with the same vocabulary, never with a bare
191
- * u64: the roster keys every closed judgment downstream, so a join across
192
- * it would decode/order/translate incoherently by binding order) AND their
193
- * law-computed classes agree — same class name joins, and bare
194
- * (`undefined`) pairs only with bare (ruling 3: a field in no law has no
195
- * class; a bare↔classed pairing refuses). The class names come off the
196
- * SCHEMA type's class map — the statements are the typing; no descriptor
197
- * label beyond the roster exists to compare.
295
+ * u64) AND their law-computed classes agree — same class name joins, and
296
+ * bare (`undefined`) pairs only with bare (ruling 3). The class names come
297
+ * off the SCHEMA type's class map; no descriptor label beyond the roster
298
+ * exists to compare.
198
299
  */
199
300
  type JoinOk<A extends ClassedField, B extends ClassedField> = [
200
301
  A["field"]["kind"],
@@ -218,10 +319,9 @@ type JoinOk<A extends ClassedField, B extends ClassedField> = [
218
319
  * The runtime twin of {@link JoinOk}: two bound slots join iff descriptor
219
320
  * structure and class agree — the same comparison the type tier makes,
220
321
  * judged on the honest runtime values (the descriptor, the roster by VALUE
221
- * IDENTITY — vocabulary identity is value identity — and the schema
222
- * value's frozen class map). The rule builders throw through this on a
223
- * class-unequal variable reuse, so the wall holds for untyped callers too,
224
- * not only where the compiler can see.
322
+ * IDENTITY, and the schema value's frozen class map). The rule builders
323
+ * throw through this on a class-unequal reuse, so the wall holds for untyped
324
+ * callers too.
225
325
  */
226
326
  function fieldJoins(a: ClassedField, b: ClassedField): boolean {
227
327
  const widthA = "width" in a.field ? a.field.width : undefined
@@ -242,9 +342,8 @@ function fieldJoins(a: ClassedField, b: ClassedField): boolean {
242
342
  /**
243
343
  * Renders one bound slot for join-mismatch diagnostics — the structural
244
344
  * kind in the schema grammar's spelling (a closed reference names its
245
- * vocabulary: the roster is part of the structure being compared) plus the
246
- * slot's law-computed class (`u64 in class Holder.id`; a lawless slot
247
- * renders `bare`).
345
+ * vocabulary) plus the slot's law-computed class (`u64 in class Holder.id`;
346
+ * a lawless slot renders `bare`).
248
347
  */
249
348
  function renderFieldKind(slot: ClassedField): string {
250
349
  const field = slot.field
@@ -266,11 +365,7 @@ function renderFieldKind(slot: ClassedField): string {
266
365
  * What a PARAM anchored at field `F` accepts at execution: the field's
267
366
  * bare value type, exactly — at a CLOSED-reference field that is the
268
367
  * handle-name union (`"DirectPass" | "Failed"`), translated name → row id
269
- * at execute through the one roster-verification point
270
- * (`taggedHandleId`). At an interval field the engine resolves the
271
- * bivalent anchor to the INTERVAL reading (value equality) — the point
272
- * reading of a param is spelled `pointIn(r.param(...), w)`, whose sibling
273
- * anchors it element-typed.
368
+ * at execute through the one roster-verification point (`taggedHandleId`).
274
369
  */
275
370
  type ParamValueAt<F extends AnyField> = Infer<F>
276
371
 
@@ -281,13 +376,9 @@ type InferredOf<T> = T extends { readonly [inferred]?: infer S } ? Exclude<S, un
281
376
  * One registered parameter of a query, as the wire marshal reads it: the
282
377
  * name, the wire shape, the field descriptor (or the measure) that anchored
283
378
  * it, and the comparison op the anchor came from (`"binding"` for atom
284
- * positions) — the op keeps literal tagging op-aware at `pointIn`
285
- * (the bug-hunt fix, preserved). `anchor` is `undefined` only on a query
286
- * built but not yet anchored by any rule; lowering and the wire both refuse
287
- * that state typed. `members` is present exactly on a MEMBERSHIP-ARRAY
288
- * entry (a literal set at a closed field, folded into the program): the
289
- * SDK itself translates and supplies the set at every execute — the entry
290
- * is never read from, and never demanded of, the host's params object.
379
+ * positions). `anchor` is `undefined` only on a query built but not yet
380
+ * anchored by any rule. `members` is present exactly on a MEMBERSHIP-ARRAY
381
+ * entry.
291
382
  */
292
383
  interface ParamEntry {
293
384
  readonly name: string
@@ -299,13 +390,17 @@ interface ParamEntry {
299
390
 
300
391
  export type {
301
392
  AnyTerm,
393
+ AnyVar,
302
394
  ClassedField,
303
395
  Duration,
304
- EnvShape,
305
396
  Flatten,
306
397
  InferredOf,
307
398
  JoinOk,
308
399
  MaskParam,
400
+ MatchFields,
401
+ MatchOwner,
402
+ MintClassOf,
403
+ MintSlotOf,
309
404
  Param,
310
405
  ParamEntry,
311
406
  ParamsRecord,
@@ -313,17 +408,7 @@ export type {
313
408
  SetParam,
314
409
  ShapeOf,
315
410
  UnionToIntersection,
316
- Var
317
- }
318
- export {
319
- fieldJoins,
320
- inferred,
321
- isTerm,
322
- makeDuration,
323
- makeMaskParam,
324
- makeParam,
325
- makeSetParam,
326
- makeVar,
327
- renderFieldKind,
328
- term
411
+ Var,
412
+ VarsOf
329
413
  }
414
+ export { fieldJoins, inferred, isTerm, makeDuration, makeMaskParam, makeParam, makeSetParam, renderFieldKind, term, v }