@aeye/query 0.6.4 → 0.6.6

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 (5) hide show
  1. package/README.md +96 -5
  2. package/aeye-query.md +540 -299
  3. package/dist/index.d.ts +3634 -190
  4. package/dist/index.js +14916 -10558
  5. package/package.json +9 -3
package/aeye-query.md CHANGED
@@ -1,299 +1,540 @@
1
- # @aeye/query — LLM relational query language
2
-
3
- **Purpose:** A JSON, LLM-authorable relational query language with an in-memory runtime and a SQL converter. You register *Types* (table-like entities) made of *Fields*; from those an LLM (or a developer) builds a **typed, validated, runnable** query — a `select` / `insert` / `update` / `delete` / set-operation / CTE / single-expression statement. A built query resolves to an output type, has typed bind params, can be cost-bounded, run in-memory, emitted to SQL (base + Postgres), auto-paginated, and drilled down.
4
-
5
- It is standalone (only depends on `zod`) and exhaustively type-safe: every polymorphic node is a discriminated union, so handling is compiler-checkable with no `any`/casts.
6
-
7
- ## When to use it
8
-
9
- - You want an LLM to author a **structured, validated** query over a schema you control — and get compiler-style diagnostics instead of free-form SQL you have to trust.
10
- - You need the SAME query to run in-memory AND emit dialect SQL (base ANSI + Postgres) identically.
11
- - You want the conceptual schema the model sees to stay minimal while the physical reality (real tables, RLS/FLS, computed fields, hidden vector/tsvector columns, extra joins) lives in dev-side backing code.
12
- - You need cost bounding, aggregate drill-down, pagination, semantic/full-text ranking, or execution-time filters over model-authored queries.
13
-
14
- ## The query/expr JSON contract (state once)
15
-
16
- A query is a `QueryDef` and an expression is an `ExprDef` — plain JSON discriminated unions (keyed by `kind`) that round-trip through `JSON.stringify`. **The LLM does not hand-write these shapes from memory:** `buildSchemas` / `querySchema` generate a Zod schema the model emits against, and that schema is both **depth-graduated** (how tightly Type names / field refs / function args / filters are locked — see *Schema depth*) and **capability-gated** (expr kinds an available Type/function can't use are omitted). The doc below therefore describes *what is supported*; the schema tells the model *how to shape it*. `schema.ts` is the single source of truth for every `*Def`.
17
-
18
- Developers compose the same trees ergonomically with the **`e.*` builder** (one builder per expr kind); each `e.*` returns a real `Expr` instance and `.toJSON()` is its wire `ExprDef`. `registry.parseExpr` is a pass-through for an already-built `Expr`, so built and parsed exprs compose freely.
19
-
20
- ```ts
21
- import { e } from '@aeye/query';
22
- const cond = e.and(e.eq(e.ref('task', 'done'), e.value(true)), e.gt(e.ref('task', 'hours'), e.value(0)));
23
- ```
24
-
25
- Builders, by group: leaves (`value`/`lit`, `param`, `ref`, `path`, `output`, `excluded`, `filters`), arithmetic (`add`/`sub`/`mul`/`div`/`mod`, `neg`/`pos`), comparison (`eq`/`neq`/`lt`/`lte`/`gt`/`gte`/`like`/`notLike`/`ilike`), logical (`and`/`or`/`not`), predicates (`isNull`/`notNull`, `between`/`notBetween`, `inList`/`notInList`, `inSubquery`/`notInSubquery`, `exists`/`notExists`), array (`contains`/`containsAny`/`containsAll`/`isEmpty`/`notEmpty`), `case`/`when`, calls (`fn`, `agg`/`count`/`countStar`/`sum`/`avg`/`min`/`max`, `window`, `tableFn`), `subquery`, search (`textSearch`, `textScore`, `semantic`). Every builder is also a named export.
26
-
27
- ## The type / field model
28
-
29
- A `Type` is a named collection of `Field`s plus index + cardinality estimates (`count` rows, `bytes`/row for cost). Each field has a `FieldType` — one of `number`, `text`, `money`, `bool`, `relation`, `date`, `timestamp`, `json`, `array` (nine kinds). Nullability lives on the field, not the type.
30
-
31
- - **Text** is case-insensitive by default; set `sensitive: true` for case-sensitive matching. Fields may be flagged `semantic` (embedding-eligible) and/or `search` (full-text-eligible); a whole Type may carry the same `semantic` / `search` flags.
32
- - **Closed value sets** — `text` and `number` fields take `values?: { value, label? }[]`, an enum expressed as a CONSTRAINT ON the scalar rather than a separate field-type kind. Membership is a QUERY fact: it makes `= x` a `1/n` predicate instead of the fixed `EQ_SELECTIVITY` guess, narrows `toValueSchema()` to the members, and is rendered to the model as `status: text one of applied|screening (In screening)|hired`. The per-member `label` rides along so one closed set has ONE home. Composes with `min`/`max` / `pattern` (a regex is a SHAPE, a value set is MEMBERSHIP — different facts, both allowed).
33
- - **Relations** carry a target `to` Type and cardinality `count`: the relation field's **name IS the join key** (there are no explicit FK fields). A belongs-to may set `inverseRelation` so its target auto-gains the matching has-many. **Which side the FK is on is `RelationFieldType.isBelongsTo()`, not `count` alone**: a MATERIALIZED INVERSE is never belongs-to however its estimated `count` came out, because the registry derives that count from a row RATIO — so a 1:1 pair (or two types sharing one declared row estimate) legitimately yields `1`.
34
- - **Identity** — a Type may declare `identity?: string | string[]`, the field (or ordered fields) that IDENTIFY a row. When present it is THE answer for `identityField()` / `primaryKey()` and index ORDER stops mattering. Without it, identity is INFERRED as "the first single-part unique index, else the field named `id`" — so a Type declaring both `id` and a unique `email`, with the email index listed first, silently identifies by `email`, and every relation into it joins a stored id against an email address. Declaring a name the Type does not have is an ERROR, not a silent fall-back to the inferred rule.
35
- - **Indexes** are composite (ordered parts, each with a non-increasing prefix distinct-row `count`); unique iff the last part's `count === 1`. They drive cost estimation. An index part is a TYPE-level fact, so it is written against the Type NAME; a query binding that Type under an ALIAS (`{kind:'aliased'}`, either side of a self-join) has its probes NORMALIZED back to the type name before matching (`renameSource` / `aliasedDigest` / `Index.prefixReduction(used, alias?)`), and matching is SOURCE-SCOPED so a join alias equal to another Type's name cannot match the scanned Type's parts.
36
- - **Arrays** are ordered collections with optional `minItems`/`maxItems` and an optional `item` element field type (omit `item` for heterogeneous); they nest (`array<array<number>>`).
37
-
38
- `createRegistry()` bootstraps the Type/expr/function catalog; `registry.parseType(def)` + `registerType` add Types. `inferType(name, rows)` derives a `TypeDef` (field types + nullability, array detection) straight from sampled JSON rows.
39
-
40
- ## Expression kinds
41
-
42
- Every kind is one branch of the `ExprDef` union. Availability in the LLM schema is depth-graduated and capability-gated; the always-usable core is never gated. Each Expr class also exposes a concise `static INSTRUCTIONS` one-liner (enumerable via `registry.exprClassList()`) — the canonical terse doc mirrored by the table below — plus, on the high-confusion kinds, a `static EXAMPLES` set of RAW JSON strings that `describeEngine` renders (capped by `maxExamples`).
43
-
44
- | kind | one-line meaning |
45
- | ---- | ---------------- |
46
- | `literal` | A constant value: a scalar, or a whole JSON DOCUMENT (object / array) for a `json` / `array` field — bound as ONE parameter, never interpolated. |
47
- | `param` | A named bind parameter; type inferred from use, bound at run/emit time. |
48
- | `field-ref` | `<source>.<field>` — a field's value from a bound source. A BELONGS-TO relation field projects that relation's IDENTITY off this row (no join); a HAS-MANY is refused (`ref.relation-has-many`). Read the target's OTHER fields through a `relation` join. |
49
- | `binary` | Arithmetic `left <op> right` (`+ - * / %`). |
50
- | `unary` | `<op> operand` (`-` / `+`). |
51
- | `comparison` | `left <op> right` → boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION operand compares by identity in `=`/`<>` only: RHS a same-target relation (FK key) or a `{ pk }` value param; a has-many compares by membership (correlated `EXISTS`). |
52
- | `logical` | Boolean connective `and` / `or` / `not` over operands. |
53
- | `is-null` | `value IS [NOT] NULL`. On a belongs-to relation it tests the KEY COLUMNS — i.e. whether the relation is UNSET — so it stays index-usable. |
54
- | `between` | `value BETWEEN lower AND upper` (negatable). |
55
- | `in` | `value IN (list \| subquery)` (negatable). A RELATION `value` matches list `{ pk }` values by FK key (belongs-to) or membership (has-many); a COMPOSITE-key relation may not use the subquery form (`in.relation-composite`). |
56
- | `case` | `CASE WHEN … THEN … [ELSE …] END`. |
57
- | `function-call` | A scalar function call by name with named args. |
58
- | `aggregate` | An aggregate function over a group (`count(*)` = empty args); optional `distinct`. A relation field-ref is not aggregable (`ref.relation-aggregate`) — group by it instead. |
59
- | `window` | A window (or windowed-aggregate) function over `partitionBy` / `orderBy`. |
60
- | `subquery` | A scalar / single-field subquery in value position. |
61
- | `exists` | `[NOT] EXISTS (subquery)` → boolean. |
62
- | `array-op` | Predicate over an array field: `contains` / `containsAny` / `containsAll` / `isEmpty` / `notEmpty`. |
63
- | `text-search` | Full-text predicate over a source (optionally one field) → boolean. Narrow it to a field unless the Type declares a search DOCUMENT — an unbacked whole-source search is refused (`text-search.unbacked`). |
64
- | `text-score` | Numeric full-text relevance score of a source (optionally one field) → number (`ts_rank`). Same backing rule as `text-search` (`text-score.unbacked`). |
65
- | `semantic` | Embedding-similarity score of a source's row vs a query (string / param / pairing ref) → number. |
66
- | `filters` | An execution-time filter placeholder bound to a source (optional `fields` allowlist); predicate supplied at run time. |
67
- | `excluded` | `EXCLUDED."field"` — the proposed row inside `INSERT … ON CONFLICT DO UPDATE`. |
68
- | `output` | References a projected SELECT output field by name (valid ONLY in `groupBy`/`orderBy`/`having`); expands to that item's expr. |
69
- | `tabular-function-call` | A row-producing (table-valued) function call, usable as a source. |
70
-
71
- **A relation's VALUE is its IDENTITY.** A `field-ref` to a **belongs-to** relation is a legal VALUE, reading the key off the caller's OWN row — no join, no scope. It yields a JSON object keyed by the TARGET's identity field names (`{ id: 'userB' }`, `{ tenantId: 3, userId: 1 }`), or SQL `NULL` when ANY key column is null (a partial composite key cannot join, so the relation is unset). A keyed object, not a positional tuple: a tuple's meaning would depend on element order, and that order derives from index order.
72
-
73
- - **Projectable without a join** — legal in `fields` / `RETURNING`, emitting `CASE WHEN <keys IS NULL> THEN NULL ELSE <json object> END` over the local columns. This is what lets an audit column (`createdBy`) report a value: reading the target through an RLS-scoped join nulls its id along with the rest of the hidden row, making UNSET indistinguishable from HIDDEN. Reading the local column discloses nothing — it is data the reader's own row already holds. The projected field reports `fieldType: 'json'` and is nullable.
74
- - **Comparable, orderable, groupable** — `=` / `<>` / `in` compare per key column (a bare scalar is accepted iff the key is single-column); `is null` / `is not null` test the KEY COLUMNS (`json_build_object(…) IS NULL` would be a constant false), so they stay index-usable; `order by` expands to one clause per key column (lexicographic over the declared key order) and `group by` to the key columns (structural).
75
- - **Refusals are STATEABLE** — a **has-many** has no key on this row and its value is a SET, so it is `ref.relation-has-many` (join it, or test membership); an AGGREGATE over an identity is undefined, so it is `ref.relation-aggregate` (group by it instead); anywhere a relation is not a value at all — an arithmetic operand, a `case` arm, a function argument — it stays `ref.relation-not-value` / `compare.relation-vs-value` with the join-it hint.
76
-
77
- ## Sources & aliasing
78
-
79
- Everything is referenced by its **Type name** — there is no alias to invent or keep in sync.
80
-
81
- - **FROM** — `{ kind: 'type', type: 'user' }` binds under `source: 'user'` (not aliasable). Also available: `aliased` (escape hatch), `subquery`, and `function` (a tabular-function source).
82
- - **Joins** — a `JoinDef` crosses a **single relation hop**: `on` is a `{ source, field }` ref (the bound source + its relation field). Joined rows bind under the target Type name; the join key is synthesized from the relation (you never write ON). Multi-hop = chained single-hop joins. `joinType` (`inner`/`left`/`right`/`full`, default `left`) is renamed from `type` to free that key. `and` adds an optional extra predicate.
83
- - **DML** targets (`insert.into` / `update.type` / `delete.from`) bind under the Type name; DML targets take no alias.
84
- - **`type` vs `source` rule.** `type` = a registered Type name (FROM `type`, DML targets, relation `to`, a `{ type, field }` semantic ref). `source` = a bound name in scope (Type name / join alias / CTE / aliased source) — used by `field-ref`, `semantic`/`text-search`/`text-score`/`filters`, and a join's `on.source`.
85
- - **Disambiguation.** For a self-join or two instances of one Type, use `{ kind: 'aliased', type, as }` on FROM, or `as` on a join to override its hop's bound name. Two sources bound under one name → a `source.duplicate` validation error.
86
-
87
- ## What queries can do
88
-
89
- - **SELECT** — `fields` (each `{ expr, as? }`), `from`, `joins`, `where` (ANDed), `groupBy`, `having` (ANDed), `order` (`{ expr, dir, nulls? }`), `limit`/`offset` (a literal or a `param`), and `distinct`.
90
- - **Condition clauses must be boolean** — every top-level condition predicate (a `where`/`having` entry, a join's `and`, and a DML `update`/`delete` `where`) must resolve to a boolean, exactly as `logical` operands and `case` `when` clauses already require; a non-boolean predicate (a bare `field-ref` to a number/money/text field, a `literal`, an arithmetic `binary`, a non-bool function) is rejected with `condition.non-bool` at the predicate's own path. A bare `param` predicate is EXEMPT (its type is inferred from use).
91
- - **Output references** — `groupBy` / `order` / `having` may use `{ kind: 'output', name }` to reference a projected field by name (its `as`, or a natural derived name) instead of repeating the expression. It EXPANDS to the target item's expr in both SQL and runtime (a group key re-computes over the source row; an ORDER BY / HAVING ref re-computes over the group, incl. an aggregate target). Valid **only** in those three positions (`output.not-available` elsewhere; `output.unknown` / `output.aggregate` on misuse). `drillDown` expands `output` refs before un-ravelling.
92
- - **Aggregates & grouping** — any registered aggregate over a `groupBy`; `count(*)` is `count` with empty args; `distinct` on the aggregate. `having` filters groups.
93
- - **Set operations** — `union` / `intersect` / `except` over two queries, `all?` to keep duplicates, plus **set-level** `order` / `limit` / `offset` applied to the combined rows (ORDER BY terms reference output columns by name).
94
- - **CTEs** — `{ kind: 'cte', ctes, final }`. Each entry is either non-recursive (`{ name, query }`) or **recursive** (`{ name, base, recursive }` — a seed UNION-ed with an arm reading the CTE's own accumulating rows to a fixpoint, iteration-capped). Recursion is its own structural shape (no `recursive?` flag).
95
- - **DML** — `insert` (row tuples or a `select`, optional `returning`, optional `onConflict`), `update` (`set` assignments, optional `joins`/`where`/`returning`), `delete` (optional `joins`/`where`/`returning`). `onConflict` = conflict-target `fields` plus `doNothing` or an `update` assignment list (which may reference the `excluded` proposed row).
96
- - **Single-expression query** — `{ kind: 'expr', expr }` for a scalar computation.
97
- - **Params** — `{ kind: 'param', name }` infers its type from use; bound at run/emit via `options.params`. Introspect with `query.params(engine)` → `ParamDef[]`. It reports **every param the statement binds, at any DEPTH** — including a `limit`/`offset` bound, which lives outside the expr tree, wherever it sits: on a `cte`'s `final` (where `autoPaginate` puts it), on a set-operation arm or its set-level bound, or inside a FROM / `in` / `exists` subquery or an `insert … select` source. So what `params()` declares is always enough to BIND the emitted SQL — an under-reported bound emits `LIMIT ?` with nothing to fill it, and `LIMIT NULL` is *no limit* (the whole table), not an error.
98
- - **Filters** — a `filters` placeholder (`{ source, fields? }`) is authored by the LLM but the **predicate is supplied at execution time** by the developer: `options.filters` is a `Record<source, boolean Expr | ExprDef | null>`. The placeholder evaluates/emits it (vacuously `TRUE` when none). Introspect exposed sources + fields with `query.filters(engine)` → `Record<source, { fields: QueryField[] }>` (name + resolved type + nullability + kind, restricted to any `fields` allowlist); `query.filterSources()` lists targetable sources.
99
- - **Cost & estimation** — bottom-up estimates driven by Type `count`/`bytes`, indexes + selectivity, and per-Type/field `changes` rates. `engine.cost(query)` → `{ rows, bytes }` (the WORK to produce the result); `engine.outputCost(query)` → `{ rows, bytes }` (the SIZE of the result — delivered rows × projection width); `engine.affected(query)` → `{ rows, types[] }` (rows an INSERT/UPDATE/DELETE or CTE mutates, OR-aware via indexes); `engine.references(query)` → `{ types, fields, functions }` (exactly what the query reads, incl. execution-time `filters`/`sort` and called functions); `engine.changeInterval(query)` → ms until the data behind it could change (freshness/cache-TTL: `0` = always, `-1` = never, else the fastest read rate). `validateQuery(query, _, { maxRows, maxBytes })` rejects over-budget queries (`cost.rows-exceeded` / `cost.bytes-exceeded`).
100
-
101
- ## Write model & permissions
102
-
103
- Types and fields declare **what write operations are possible**, and the model flows into BOTH validation AND the LLM-facing schema — so the generated schema is accurate to what can actually be done.
104
-
105
- - **Type flags** — `insertable` / `updatable` / `deletable` on a `TypeDef` (each default **true**). A restricted Type drops the matching DML: validation rejects it (`insert.type-readonly` / `update.type-readonly` / `delete.type-readonly`) AND the schema omits the query kind entirely when NO Type permits it, and filters each DML's target-name enum (`into` → insertable Types, `update.type` → updatable, `delete.from` → deletable).
106
- - **Field flags** — `insertable` / `updatable` on a `FieldDef` (default **true**). A field whose `FieldBacking.compute` is set defaults to `insertable:false, updatable:false` (override with an explicit flag). Validation rejects a listed non-insertable field (`insert.field-readonly`) / an assigned non-updatable field (`update.field-readonly`); the paired schema offers only insertable `fields` / updatable `set` fields.
107
- - **Insert-requiredness (THE rule)** — a field is REQUIRED on insert iff it is **insertable AND non-nullable AND has no default AND is not computed**; otherwise optional (nullable / has-default) or excluded (non-insertable). One shared helper (`requiredOnInsert`) drives both the schema (required-vs-optional in paired mode) and validation (`insert.missing-required`, which lists the missing names).
108
- - **Defaults** — `FieldBacking.default` is a `Value` or a factory `() => Value | Promise<Value>`. Its **presence alone** makes the field optional-on-insert (there is no `hasDefault` flag). At **runtime** an omitted defaulted field is materialized (the value is evaluated / the factory awaited, per row) into the inserted record. In **SQL** the column is simply left out of the INSERT and the database's own column `DEFAULT` fills it — so a JS-factory default is a runtime-only concern.
109
- - **A write CELL carries a JSON value or an expression** — `WriteValueDef = JsonValue | ExprDef`. A raw SCALAR or a whole DOCUMENT (object / array, for a `json` / `array` column) becomes a literal; a `{ kind }` object is read as an EXPRESSION only when the kind names a REGISTERED expr kind, so a settings blob carrying a `kind` key stays data. An absent key OR a JSON `null` OMITS the field (its default fills in / it stays unset); `{ kind:"literal", value:null }` is the only way to set SQL NULL. A value written to a `json` / `array` column is JSON-ENCODED and bound as ONE parameter cast to the COLUMN's type (`Dialect.jsonValue`) — Postgres `CAST($1 AS jsonb)`, or `ARRAY[$1,$2]::text[]` for a native array column, which cannot take JSON text. The COLUMN decides, not the value's shape, so a JSON *scalar* into a `json` column (`"a bare string"`, `42`) is encoded and cast like any document rather than bound raw. SQL NULL is the exception: a null literal and an unbound param bind NULL, never the JSON value `null`. A param bound to a document is bound, never silently NULL.
110
- - **A write value is checked against its COLUMN** — the cell's expr is walked in the target's scope, a `param` cell is OBSERVED against the column's field type (which is the only place a write param's type can come from), and a value of an incompatible category is refused (`write.type`). A RELATION column is exempt: what you write to it is the target's identity, not a value of the relation's own category.
111
- - **Expr restrictions** — `FieldDef.exprs` is `{ not: ExprKind[] }` (exclude these kinds) or `{ only: ExprKind[] }` (allow exactly these). It can only NARROW what the field TYPE already permits. `field.allowsExpr(kind)` respects both the type floor and the restriction. Validation rejects a denied kind at the field's use site (`field.expr-denied`) — checked on a standalone `field-ref` (gated as `field-ref`), on each gating operator's DIRECT field-ref operand (gated as `comparison` / `between` / `in` / `is-null` / `array-op`), and on the field-naming exprs (`text-search` / `text-score` / `semantic` / `filters`). The paired schema omits an excluded field from the relevant enum and gates a kind away entirely when every candidate field excludes it.
112
-
113
- ## Semantic & text search + scoring / ranking
114
-
115
- All three search exprs bind to a **source** with an OPTIONAL `field` (omit ⇒ whole source); eligibility requires a `semantic`/`search`-flagged Type or field (`Type.isSearchable()` / `isSemantic()` answer "anywhere on this Type"; `isFieldSearchable(f)` / `isFieldSemantic(f)` answer per field).
116
-
117
- **An unnarrowed `text-search` / `text-score` needs a `SearchBacking` and does NOT guess.** A whole-source search wants the Type's searchable DOCUMENT, which only a backing supplies (a precomputed `vectorField`, or a `sql` override). Without one it is refused — `text-search.unbacked` / `text-score.unbacked` in validation, and a `QueryTypeError` on emission — rather than resolving to the first `search`-flagged field, then the first text field of any kind, then a column literally named `search`. Those three fallbacks meant a query asking for a multi-field document silently searched ONE column, and which column depended on field ORDER. Narrowing to a field needs no backing and is unaffected. Relation fields are no longer counted as semantic-eligible (a foreign key is a join, not an embedding).
118
-
119
- - **`text-search`** — full-text **predicate** (boolean). `query` is a literal string or a `param`.
120
- - **`text-score`** — the **numeric** relevance counterpart (same eligibility): usable in SELECT + ORDER BY, so "top N by text relevance" works. Postgres emits `ts_rank(to_tsvector(col), plainto_tsquery(query))`; base (ANSI) degrades to `CASE WHEN <LIKE> THEN 1 ELSE 0 END`; in-memory is a deterministic token-overlap fraction. Build with `e.textScore(source, query, field?)`.
121
- - **`semantic`** — embedding-similarity **score** (≈1 = most similar; requires an embedder). `query` is a literal string, a `param`, a `{ source, field }` ref to ANOTHER bound source + semantic field (the **cross-source pairing** form), or a `{ type, field }` ref resolving to the single bound source of that Type (`semantic.query-unbound` / `semantic.query-ambiguous` steer you to the `{ source }` form).
122
-
123
- **Cross-Type pairing + ranking.** Join (or cross-join) two Types so both are bound, score one against the other's embedding, then `ORDER BY score DESC LIMIT N`. Postgres emits the dialect's `similarity` over both bound aliases' vectors (each side's hidden `vectorField` if backed, else `<alias>."embedding"`); the base dialect degrades similarity to `0` and never throws.
124
-
125
- ## Array fields & operations
126
-
127
- Query an `array` field with the `array-op` predicate: `contains` (a single element present), `containsAny` / `containsAll` (overlap / superset vs an element list), `isEmpty` / `notEmpty`. Element count is a `comparison` over the builtin `arrayLength(arr)`. Non-`sensitive` text elements match case-insensitively.
128
-
129
- **Dialects.** Array ops are Postgres-native: `contains` → `value = ANY(col)`, `containsAll` → `col @> ARRAY[…]`, `containsAny` → `col && ARRAY[…]`, length → `cardinality(col)`. The base (ANSI) dialect has no array operators, so containment throws a clear `array-op.unsupported-dialect` `QueryTypeError` rather than emit wrong SQL; emptiness / length still work via `COALESCE(json_array_length(col), 0)`.
130
-
131
- ## Type backing (physical reality behind the conceptual schema)
132
-
133
- The flat `TypeDef` the LLM sees can be arbitrarily richer behind the scenes. A `TypeBacking` is dev-side TypeScript registered alongside the Type (`registerType(type, backing)` or `new QueryEngine(registry, { backings })`); the JSON `TypeDef`/`FieldDef` are never touched. All of it resolves IDENTICALLY in `engine.run` and `engine.toSQL`. Every factory receives the **bound `alias`** for the occurrence and must reference it (never hardcode the Type name), so aliased/self-joined sources resolve correctly.
134
-
135
- - **Real table remap** — `TypeBacking.name` maps to the physical table (`FROM "projects" AS "project"`); `FieldBacking.name` remaps a stored column.
136
- - **Computed fields** — `FieldBacking.compute` supplies a field's value: a dual `{ expr }` (one `Expr` emitted to SQL AND evaluated in memory), with `sql` / `run` per-mode overrides. Compute/access exprs reaching into other sources flow through the join planner (fields sharing a join collapse to one join). A computed field is non-insertable / non-updatable by default (see **Write model & permissions**).
137
- - **Insert defaults** — `FieldBacking.default` (a `Value` or a `() => Value | Promise<Value>` factory) makes a field optional-on-insert and is materialized into the row at runtime when omitted; emitted SQL omits the column and relies on the DB's own `DEFAULT` (see **Write model & permissions**).
138
- - **RLS** (`TypeBacking.access`) — a row predicate ANDed into WHERE and filtering executor rows; `false` ⇒ no rows, `true`/`undefined` ⇒ no filter; combines with any `RlsProvider` passed to run/toSQL.
139
- - **Default conditions (soft scope)** (`TypeBacking.defaultConditions`) — a SOFT, suppressible default scope (think archived / soft-delete filtering): unlike RLS, the query can REVEAL past it. Each `DefaultCondition` is `{ where, without?, ops?, description? }`. While ACTIVE its `where` (an `Access` — dual `{ expr }` / `sql` / `run`, resolved exactly like RLS: `false` ⇒ no rows, `true`/`undefined` ⇒ no filter, else ANDed) is ANDed into the WHERE of every occurrence of the Type. It **lifts** for a bound source the moment a **condition-position** clause (the query's `where` / `having`, or a JOIN's `and`) references one of the condition's `without` fields **on that source** — a reference in a SELECT item / ORDER BY / GROUP BY does NOT lift it, and each bound alias (incl. a self-join) is decided independently. `without` defaults to the fields the `where.expr` reads (a `sql`/`run`-only `where` with no `without` is therefore ALWAYS-ON — set `without` explicitly to make it liftable). `ops` picks the row-filtering ops it scopes (default `['select','update','delete']`; INSERT is never scoped). RLS is separate and never lifts; a default condition ANDs in alongside it. Example — archived files: `defaultConditions: [{ where: { expr: (a) => isNull(ref(a, 'archivedAt')) } }]` scopes every query to `archivedAt IS NULL`, until a query filters on `archivedAt` (e.g. `WHERE archivedAt IS NOT NULL`), which reveals the archived rows for that source.
140
- - **Default ordering** (`TypeBacking.defaultOrder`) — a Type's NATURAL sort, applied to a SELECT's `ORDER BY` when the query specifies none (and ordering is meaningful). `DefaultOrder` is `{ by: DefaultOrderTerm[]; applyTo? }`; each `DefaultOrderTerm` is `{ by: Computed; dir?; nulls? }` whose `by` is the sort KEY — the same dual `{ expr }` / `sql` / `run` `Computed` as computed fields, so one key emits to SQL AND sorts in memory identically (`dir` default `'asc'`; `nulls` else the direction-based default — asc ⇒ nulls first, desc ⇒ last — matching an explicit ORDER BY). It applies ONLY when the FROM binds the backed Type (joins never contribute their default order), the query has NO explicit `order`, and it is NOT aggregated (no `groupBy`, no bare aggregate) and NOT `DISTINCT` (both skipped — a base-field order is meaningless post-aggregation, and a non-selected DISTINCT key is illegal SQL). `applyTo` scopes WHICH selects receive it: `'result'` (default) ⇒ the ROOT query being run/emitted OR any `LIMIT`/`OFFSET` select; `'paginated'` ⇒ only a `LIMIT`/`OFFSET` select; `'all'` ⇒ every eligible select (incl. subqueries / CTEs). The ROOT is tracked by an `isRoot` marker threaded from `engine.run` / `engine.toSQL` onto the runtime / SQL context; nested queries (a subquery / EXISTS / IN subquery, a FROM subquery, a CTE body, a set-op branch) run/emit non-root. Example — newest-first: `defaultOrder: { by: [{ by: { expr: (a) => ref(a, 'createdAt') }, dir: 'desc' }] }` ⇒ an unsorted select over the Type gets `ORDER BY "t"."createdAt" DESC`. SELECT-only; DML is never reordered.
141
- - **FLS** (`FieldBacking.access`) — a per-field gate emitting `CASE WHEN <pred> THEN <value> ELSE NULL END`; `false` ⇒ constant `NULL`.
142
- - **Named joins & LATERAL** (`TypeBacking.joins`, opted into by `FieldBacking.joins: [name]`) — hidden joins added once per query only when a referencing field is emitted, deduped by name. A `JoinSpec` is a `relation` (reuses relation-join machinery) or a `lateral` (a correlated sub-select; Postgres `LEFT JOIN LATERAL (…) ON true`, base degrades to `ON 1 = 1` and evaluates per outer row; a `lateral.pick` names the default column).
143
- - **Relation-join backing** (`FieldBacking.relation`, on a relation-typed field only) — drives a relation join's `ON` from explicit, LLM-HIDDEN physical foreign-key columns instead of the name convention (the JSON `FieldDef`/`TypeDef` are unchanged). `keys: [{ local, foreign? }]` are physical key-column pairs, ALL ANDed (composite FKs supported); `local` is the column on the side that DECLARES the relation, `foreign` the column on the TARGET (defaults to the target's identity). The backing lives on the OWNING **belongs-to** relation; a materialized inverse has-many REUSES the same FK (its forward relation's backing, orientation swapped). `on` is a fully custom, alias-correct predicate — `{ expr }` dual (SQL + runtime), with `sql` / `run` per-mode overrides; precedence like compute/access (`run`/`sql` override → `expr` → the `keys` mapping, else the convention). Every ON site (authored joins, fan-out aggregate grouping, the `TypeBacking.joins` relation spec, joined UPDATE/DELETE) honors it and references the BOUND ALIASES, so aliased / self-joins work; `JoinDef.and` still ANDs onto whatever ON is produced. Example (the belongs-to owner): `fields: { user: { relation: { keys: [{ local: 'user_id', foreign: 'id' }] } } }` ⇒ `ON src.user_id = tgt.id` (and its inverse has-many `ON one.id = many.user_id`).
144
- - **Search / semantic backing** — a `search`/`semantic`-flagged Type/field usually has a physical field hidden from the type system holding a precomputed `tsvector` / `pgvector`. `TypeBacking` and `FieldBacking` each take optional `search?: SearchBacking` / `semantic?: SemanticBacking` (field-level overrides type-level). Knobs (each factory takes the bound `alias` first): `vectorField` (the hidden physical field — a `SearchBacking.vectorField` emits `<alias>."f" @@ plainto_tsquery('<language>', $n)` without re-wrapping in `to_tsvector`; a `SemanticBacking.vectorField` is the left operand of the dialect's `similarity`, query vector bound as `$n::vector`), `language` (default `'english'`), `sql` (full override → boolean/numeric), `run` (runtime override), plus `SemanticBacking.vector` (row embedding source) and `embedder` (per-Type/field query embedder). Precedence (both modes): full `sql`/`run` override wins; else the hidden `vectorField`/`vector`; else the engine default. `toSQL` stays synchronous — the async embedder is never called there; a `vectorField`/`vector` query vector is a bound `$n::vector` param, and a `semantic(...)` TEXT-literal / text-param term is resolved to a pgvector-text literal from the caller's precomputed `embeddings` cache (see [SQL conversion](#sql-conversion): extract terms with `engine.semanticTexts`, embed, then `toSQL(query, dialect, { embeddings })`; a plain-text term with no/missing cache throws). The base dialect degrades (tsvector → `LIKE`, similarity → `0`) and never throws.
145
-
146
- ## Function library
147
-
148
- `createRegistry()` ships a default library (60+ functions across all four shapes), registered as `FunctionDef` (name + shape + **named** params + output) paired with a shape-tagged runtime. Calls use named args (`args: { paramName: <expr> }`). Register your own with `registerFunction` + `registerFunctionRun`. Introspect with `registry.functionList()`; get a promptable by-shape listing with `describeFunctions(engine)`. Every builtin `FunctionDef` carries a terse `instructions` one-liner (what it does / arg meaning / gotcha), surfaced on `QueryFunction.instructions`; the high-confusion ones also carry `examples` (RAW JSON strings, round-tripped by `QueryFunction.from` / `toJSON`) that `describeEngine` renders under the signature.
149
-
150
- Shapes: `scalar` `(args, ctx)→value`, `tabular` `(args, ctx)→rows`, `aggregate` `(rows, ctx)→value`, `window` `(partition, index, ctx)→value/row`. All builtin names are **camelCase**; where the emitted SQL name differs it is noted. The base (ANSI) dialect degrades where noted and never throws.
151
-
152
- **Scalar — string:** `concat`, `lower`, `upper`, `trim`, `length`, `substring`, `replace`, `trimLeft`(→`ltrim`), `trimRight`(→`rtrim`), `left`, `right`, `padLeft`(→`lpad`), `padRight`(→`rpad`), `repeat`, `reverse`, `indexOf`(→`strpos`, 1-based, 0=absent), `startsWith`(→`starts_with`), `splitPart`(→`split_part`, 1-based), `concatWs`(→`concat_ws`).
153
-
154
- **Scalar — math:** `abs`, `ceil`, `floor`, `round`, `sqrt`, `power`, `mod`, `sign`, `exp`, `ln`, `log`(base, value), `log10`(→`log`), `trunc`, `pi()`, `degrees`, `radians`, `random()`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`(y, x).
155
-
156
- **Scalar — conditional / other:** `coalesce`, `nullif`, `greatest`, `least`, `arrayLength`, `iif`(cond, then, else → `CASE WHEN`), `now()`, `currentDate()`(→`CURRENT_DATE`, bare).
157
-
158
- **Scalar — date / time:** `currentTime()`, `currentTimestamp()`, `datePart(field, d)`, `year`/`month`/`day`/`hour`/`minute`/`second(d)`, `dayOfWeek(d)`(0=Sun…6=Sat), `dayOfYear(d)`, `week(d)`(ISO week), `dateAdd(field, n, d)`, `dateDiff(field, a, b)`(component difference), `dateTrunc(field, d)`, `makeDate(year, month, day)`, `dateFormat(d, format)`(→`to_char`; tokens `YYYY/MM/DD/HH24/HH/MI/SS`), `epoch(ts)`, `fromEpoch(value)`(→`to_timestamp`), `age(a, b)`(runtime = whole-day span). The selectors' `field` arg is an inline literal token (`year`/`month`/`day`/`dow`/`doy`/`week`/`hour`/`minute`/`second`/`quarter`/`isodow`/`epoch`), spliced not bound.
159
-
160
- **Scalar — array** (Postgres-native; base degrades): `arrayContains`, `arrayAppend`, `arrayPrepend`, `arrayConcat`, `arrayIndexOf`(1-based), `arraySlice`(1-based inclusive), `arrayRemove`, `arrayDistinct`, `arrayToString`, `stringToArray`.
161
-
162
- **Aggregate:** `count`, `sum`, `avg`, `min`, `max`, `stddev`, `variance` (both sample/n-1), `stringAgg`(→`string_agg`), `arrayAgg`(→`array_agg`; base degrades to `NULL`), `boolAnd`(→`bool_and`), `boolOr`(→`bool_or`), `countIf`(→ portable `sum(CASE WHEN … THEN 1 ELSE 0 END)`).
163
-
164
- **Window:** `rowNumber`(→`row_number`), `rank`, `denseRank`(→`dense_rank`), `lag(value, offset?, default?)`, `lead(value, offset?, default?)`, `percentRank`(→`percent_rank`), `cumeDist`(→`cume_dist`), `ntile(n)`, `firstValue`(→`first_value`), `lastValue`(→`last_value`; full-partition frame), `nthValue`(→`nth_value`; 1-based).
165
-
166
- ## Schema depth & capability gating
167
-
168
- `buildSchemas` / `querySchema` / `buildQueryTool` constrain the LLM-facing schema along **four independent axes**, each dialed by `depth`:
169
-
170
- | axis | levels (loose → tight) | constrains |
171
- | ---- | ---------------------- | ---------- |
172
- | `refs` | `open` · `types` · `fields` · `both` · `paired` | every `{ source/type, field }` reference position — `field-ref`, a join's `on`, `semantic` / `text-search` / `text-score` / `filters` |
173
- | `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
174
- | `functions` | `open` · `names` · `typed` | function name + named-arg objects |
175
- | `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
176
-
177
- Pass a full/partial `SchemaDepth` object, or a preset string: `'open'` (every axis loose) / `'paired'` (every axis tight); the deprecated `strict: true`/`false` are sugar for those. A `FunctionSelector` (`{ scalar: [...], … }`) picks which functions appear; `maxEnumSize` auto-degrades any axis whose enumeration overflows the budget one level looser so a large catalog never yields an unusable schema.
178
-
179
- **Capability gating** (independent of depth) omits any expr kind the available Types/functions can't use: `semantic` (some Type `isSemantic()`), `text-search`/`text-score` (`isSearchable()`), `array-op` (a Type has an array field), `joins` (a Type has a relation), `tabular-function-call` (≥1 tabular fn), `aggregate`/`window`/`function-call` (≥1 fn of that shape), `filters` (a Type has filterable fields). The always-usable core (`literal`/`param`/`binary`/`unary`/`comparison`/`logical`/`in`/`between`/`is-null`/`exists`/`case`/`field-ref`/`subquery`) is never gated.
180
-
181
- ## Execution model
182
-
183
- One contract: **run a query, optionally with params + filters, and get back `{ rows, fields, total }`.**
184
-
185
- ```ts
186
- const result = await engine.run(query, { params, filters, includeTotal });
187
- // result.rows — output rows (objects; pass { rows: 'array' } for arrays)
188
- // result.fields — resolved output fields (name + type + summary metadata)
189
- // result.total — pre-limit count, when run with includeTotal: true
190
- ```
191
-
192
- - **An output field's `type`** is the full `ResolvedType`. A COMPUTED one carries `aggregate` (does a group collapse happen anywhere in this expression?) and `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'` under any alias; `max(a) - min(b)` reports `aggregate: true` with NO `aggregateFn` (it contains aggregates but is none); a window over an aggregate-shaped function reports neither. Read it rather than inferring the function from the output column NAME, which cannot see through an alias and mistakes `hours * 2 as count` for an aggregate.
193
- - **`includeTotal`** is an execution-time option (not a `SelectDef` field): `run` captures the pre-limit count; `toSQL(query, dialect, { includeTotal: true })` emits `COUNT(*) OVER () AS "$total"`. It applies to the **ENTRY query ONLY** — never a CTE body, a set-operation arm, or a FROM subquery — because `$total` is a PROJECTED column: inside a set-operation arm it participates in the set comparison and would change the **rows** (UNION would stop de-duplicating; INTERSECT / EXCEPT would compare per-arm counts they were never meant to see). So a query whose entry is a **set operation reports NO total** — `result.total` is `undefined` and the SQL carries no `$total` — rather than a wrong one. To page a set operation *and* count it, wrap it in a SELECT over a `subquery` source and ask for the total there.
194
- - **`autoPaginate(query)`** adds `limit`/`offset` as bind params idempotently, so paging is just supplying values: `run(paged, { params: { limit, offset } })`. It pages exactly the kinds that HAVE a row bound: a `select`, a set operation (`union`/`intersect`/`except` — the SET-LEVEL bound over the combined rows, never an arm's), and a `cte` (paged through its `final`; a CTE body is an intermediate result). Every other kind (`insert`/`update`/`delete`/`expr`) **throws** `QueryTypeError` `paginate.unsupported-kind` — it used to silently return a query that looked paged and wasn't. `canAutoPaginate(query)` asks first.
195
- - **Drill-down.** `drillDown(query, engine)` rebuilds the underlying-rows query behind an aggregate, parameterized (each GROUP BY key pinned to a bind param) — returns `{ query, params, warnings }`. `drillDownInto(query, groupRow, engine)` extracts one aggregated row's key values; then it is the same `run` call. Each aggregate becomes its row-level expression; `count(*)` expands to the FROM type's fields MINUS the ones the SELECT already projects (matched on the EXPRESSION, not the output name), so a group key is projected once. Failures return LLM-friendly `Problems` (`drill.no-aggregation` / `non-invertible` / `having-aggregate` / `window-unsupported`).
196
- - **Standalone exprs.** `engine.evaluateExpr(expr, row?)` evaluates an `Expr`/`ExprDef` against a row; `engine.exprToSQL(expr, dialect)` emits `{ sql, params }` (params never interpolated).
197
-
198
- ### SQL conversion
199
-
200
- `engine.toSQL(query, dialect, options?)` emits `{ sql, params }` for any registered dialect. Base uses `?` placeholders; Postgres uses `$1, $2, …`. Relation joins synthesize their ON clause from the relation key. `toSQL` accepts the same `params` / `filters` / `includeTotal` options as `run`, so emitted SQL matches what would run.
201
-
202
- - **Semantic text terms → vectors (extract → embed → sync build).** A `semantic(...)` term whose query is a TEXT literal (or a text `param` value) is TEXT, not an embedding, and cannot be bound as `'<text>'::vector`. Because SQL emission is SYNCHRONOUS, the caller embeds up front and passes the vectors in — `toSQL` (and `run`) stay sync for every caller:
203
- 1. **Extract** — `engine.semanticTexts(query, opts?) → string[]` returns the DISTINCT plain-text semantic terms needing embedding, in a stable (first-seen) order. It reuses `toSQL`'s exact emit walk, so it finds terms at ANY depth (nested boolean AND/OR/NOT, a subquery WHERE, a computed-field expr, a function-call arg, a CASE/WHEN — anywhere an `Expr` sits) and never returns an already-`'[…]'` vector-text term. `opts` are the same `params` / `filters` a bind would see.
204
- 2. **Embed** each returned term (the caller's model/network call) and fill a `text → vector` cache — a `ReadonlyMap<string, readonly number[]>` (a resolver function `(text) => readonly number[] | undefined` is accepted too; both are the `SemanticEmbeddings` type).
205
- 3. **Build** — `engine.toSQL(query, dialect, { embeddings })` looks each term up, formats it with `toVectorText`, and binds `$n::vector` (all sync). A needed term MISSING from the cache **throws** (fail loud) rather than mis-binding; with NO cache a plain-text term likewise throws. A **pre-embedded `'[…]'` vector-text term / param is bound as-is** (never looked up), and a `vectorField` backing (query vector already a `$n::vector` param) is unchanged. The SAME `embeddings` cache is accepted by `engine.run(query, { embeddings })` for in-memory scoring (no embedder required). Helpers: `toVectorText(number[]) → '[…]'`, `parseVectorText('[…]') → number[]`, `isVectorText(string)`. (Replaces the former `convertSemanticText` seam + `toSQLAsync` — with vectors precomputed, nothing in `toSQL` is async.)
206
-
207
- ## The LLM tool
208
-
209
- The parse+validate pipeline is exposed **standalone**, so you can validate a query without building a `Tool` just to call `.parse` on it. All three entries share ONE implementation:
210
-
211
- - **`parseQueryTool(engine, raw, options?) → Query | QueryToolError`** — the DIRECT parse entry. Given the conceptual `{ query }` envelope, it validates the envelope, parses the structured `query` into a runnable `Query`, and runs full engine validation (structure + params + per-Type validators). Clean ⇒ the built `Query`; any problem ⇒ a rich `QueryToolError` whose `.report` (also its `.message`) is a concise compiler-style report (`formatProblems`), so the model sees real diagnostics instead of Zod's.
212
- - **`parseQueryRequest(engine, raw, options?) → { query, problems, report }`** — the same pipeline exposing the detailed result: the built `Query` (or `null`), the accumulated `Problems`, and the rendered `report`. (A SEMANTIC failure keeps the built `query` alongside its problems; a STRUCTURAL failure yields `query: null`.)
213
- - **`buildQueryTool(engine, options?) → Tool`** — the tool WRAPPER, built only when you need a runnable `@aeye/core` `Tool` to drop into an agent's tool set. Its wire `schema` is the engine's query schema (depth-graduated + capability-gated), its custom `parse` DELEGATES to `parseQueryTool` (Zod is demoted to the model-facing wire schema only), and its `call` handler RUNS the validated query and returns a `QueryResult`. Its `instructions` reflect the active depth + selected functions, and (past `max` Types via `shouldUseStringSchema`) it falls back to a prose-description schema.
214
-
215
- Because core wire-decodes the model's response **before** any custom `parse` hook runs (and a directly-parsed CLI/file def is already conceptual), the standalone functions operate on the **conceptual** value — they never need the wire schema for parsing.
216
-
217
- ```ts
218
- import { selectTypes, querySchema, parseQueryTool, parseQueryRequest, QueryToolError } from '@aeye/query';
219
-
220
- const types = await selectTypes(engine, 'revenue by customer last month'); // narrow the schema
221
-
222
- // DIRECT parse — no Tool built. Feed a def straight through (CLI / file / your own loop):
223
- const parsed = parseQueryTool(engine, { query: someQueryDef }, { depth: 'paired', types });
224
- if (parsed instanceof QueryToolError) console.log(parsed.report); // underlined diagnostics
225
- else console.log(await engine.run(parsed)); // runnable Query → QueryResult
226
-
227
- // Detailed result when you want the problems + report explicitly:
228
- const { query, problems, report } = parseQueryRequest(engine, { query: someQueryDef }, { types });
229
-
230
- // The model-facing schema for your own LLM loop (the model emits against it; core decodes with it):
231
- const schema = querySchema(engine, { depth: 'paired', types });
232
- ```
233
-
234
- Build a `Tool` only when an agent must CALL and RUN it:
235
-
236
- ```ts
237
- import { buildQueryTool } from '@aeye/query';
238
-
239
- const tool = buildQueryTool(engine, { depth: 'paired', types });
240
- const query = await tool.parse(ctx, JSON.stringify({ query: someQueryDef })); // delegates to parseQueryTool (throws QueryToolError on failure)
241
- const result = await tool.run(query, ctx); // runs it → QueryResult
242
- ```
243
-
244
- `buildSchemas` / `querySchema` expose the schema directly when you drive your own LLM loop.
245
-
246
- ### Underlined, compiler-style problem reports
247
-
248
- `QueryToolError.report` renders every problem — STRUCTURAL (the owned, zod-free parser `registry.parseCheckedQuery`, now the ACTIVE gate) *and* SEMANTIC (`validateWalk`: unknown fields, param conflicts, per-Type validators) — as underlined diagnostics over the model's **own** query JSON, so it sees exactly which value to fix:
249
-
250
- ```
251
- ── line 21 ──────────────────────────────────────────────
252
- 21 │ "left": "oops",
253
- │ ^^^^^^
254
- │ error: expected an expression
255
- ```
256
-
257
- **Messages are aid-directed (domain-specific), not Zod-generic.** The owned parser's `Shape` combinators reuse the same `aids.ts` vocabulary (`aidInfo` for the label, `didYouMean` for suggestions) as the wire schema, so the structural diagnostics read in the query's own terms: `"left": "oops"` → "expected **an expression**, got a string"; `"args": "total"` → "expected **named arguments**, an object of { argName: <expr> }, got a string"; `"kind": "comparise"` → "unknown **expression kind** `comparise` — did you mean `comparison`?"; `"op": "equals"` → "expected a comparison operator: =, <>, <, <=, >, >=, like, notLike, ilike"; `"limit": "three"` → "expected a number or a param, got a string". **Structure vs semantics:** the owned parser accepts any REGISTERED kind with any string field (capability/depth is a wire-schema concern), so an unknown Type / field / function name is a SEMANTIC rejection instead — e.g. an unknown field surfaces from `validateWalk` as "Type 'user' (source 'user') has no field 'ghost'." (with its own `didYouMean`), still underlined at the offending field-ref.
258
-
259
- How it works: `jsonSource(value)` (in `src/json-source.ts`) re-emits the canonical `JSON.stringify(value, null, 2)` text while recording, for every node (root, each property value, each array element), the `[start, end)` char offsets keyed by the node's structural path (the same `(string | number)[]` shape as `Problem.path`). `Code.fromJson(value)` builds a `Code` over that text with those spans pre-registered, and `formatProblems` resolves each `Problem.path → span → (line, col)` to draw the `^^^` underline with surrounding context. The owned parser records each structural problem DIRECTLY at the offending value's path (`problems.at(key, …)`, accumulating, never throwing), so — unlike zod's `.or`-folded union failures — there is no nesting/noise to collapse: one problem per offending value, already at the right path.
260
-
261
- Both the owned parser AND the wire schema draw their DIRECTED text from the SAME `aid → { label, noun? }` `AID_REGISTRY` in `src/aids.ts` (so the two never diverge): the owned parser's `Shape`s call `aidInfo` / `didYouMean` directly, while the wire schema uses **`withAid`** — every generated schema node is tagged with a stable `aid` (`.meta({ aid })`, unchanged — it also names the JSON-schema `$defs` entry) plus a per-schema, captured **error map** that renders domain text off `AID_REGISTRY`. On an `invalid_type` it reads `expected <label>[, got <received>]`; on an enum failure `expected <label>: <allowed values>`; on a union `.or` no-match either the union's `<label>` or, when the value carries a typo'd string `kind`, "unknown `<noun>` kind `x` — did you mean `y`? (available: …)". The wire schema the model consumes is unchanged except the added `aid` metadata and the friendlier error text (never serialized into JSON-schema). A problem whose path matches no node degrades gracefully (nearest ancestor, or a plain `<severity>: <message> @ <path>` line) rather than crashing. Valid queries produce no problems ⇒ an empty report.
262
-
263
- **"Did you mean?" on EVERY unknown-name diagnostic.** A single reusable suggester — `didYouMean(input, candidates, { max? })` in `src/aids.ts` — appends "` — did you mean \`X\`?`" (or "`\`X\` or \`Y\`?`" up to `max`, default 1) whenever a bad NAME is a genuine typo of a valid one, and appends nothing otherwise. It is **typo-only**: a case-insensitive edit distance under a length-scaled budget (`suggestionBudget(len) = min(3, max(1, floor(len/3)))`, exposed alongside the lower-level `nearest(input, candidates, budget?)` primitive), so a short word tolerates one edit and a long one up to three — never a false match on an unrelated word. It powers, uniformly:
264
- - **schema-enum** failures — a near-miss `op` / `dir` / `nulls` / function-name / Type-name / field-name value gets the canonical spelling appended to `expected <label>: <allowed>` (e.g. `"op": "notlike"` → "… like, notLike, ilike — did you mean `notLike`?"), and the union-no-match `kind` suggestion (`nearestKind` now just calls `nearest`);
265
- - **validation** (`validateWalk`) unknown-name diagnostics — **field** (`ref` / `filters` / `semantic` / `text-search` / `text-score` / `excluded` / `insert` / `update`, suggested from the resolved Type's field names), **source** (suggested from the bound source names in scope, via the new `QueryScope.sources()` accessor — every source bound anywhere up the chain), **Type** (`insert` / `update` / `delete` / `source` / relation-target, from the registry's Type names), **function** (`function-call` / `aggregate` / `window` / `tabular`, from the registry's function names of that shape), **named-arg** (from the function's declared param names), and **output** (`output` ref, from the SELECT's output field names). Candidates are gathered only when the error is emitted, so there is no hot-path cost.
266
-
267
- **Tuning the report.** `buildQueryTool(engine, { report })` forwards a `FormatProblemsOptions` (`{ contextLines?, sectionHeaders?, lineNumbers?, maxProblems? }`) straight into `formatProblems`, so a caller can shape the diagnostics the model sees. Absent ⇒ the defaults (`contextLines: 2`, section headers + the `N │` line-number gutter on). E.g. `{ contextLines: 0 }` drops the surrounding context (just the underlined line), `{ contextLines: 4 }` widens it, `{ lineNumbers: false }` drops the gutter, and `{ maxProblems: 3 }` caps how many problems render.
268
-
269
- ### Owned structural parser (zod-free, accumulating) — the ACTIVE gate
270
-
271
- A model-authored query is now gated by ONE structural authority, the owned parser: `parseQueryInput` (in `src/llm/tool.ts`) validates the `{ query }` envelope without zod, then calls `registry.parseCheckedQuery(queryDef, problems)` — the zod-free STRUCTURAL parse — and, only if it is structurally sound, runs the owned `validateWalk` SEMANTIC check. Both halves have the properties we want: they NEVER throw and ACCUMULATE every problem in one pass. **Zod is demoted to the model-facing WIRE schema only** — `buildQueryTool` still exposes `querySchema` / `buildSchemas` as the tool's `schema` (what the model emits against, and what `compile` / strict mode consume), but it is NO LONGER a validator: the `schema.safeParse` gate and its zod-issue flattening (`problemsFromZod` / `flattenZodIssues`) are gone. The **`src/shape/` combinator module** is the machinery that let each expr/query OWN its shape validation the same way it owns its semantics.
272
-
273
- A `Shape<T>` is a tiny structural schema: `check(json: unknown, ctx): T | INVALID`. It validates the untrusted `json` at the caller's current `Problems` path, RECORDS any problems (reusing `aids.ts` — `aidInfo` for the domain label, `didYouMean` for suggestions — never Zod, never `flattenZodIssues`), and returns the built value or the `INVALID` sentinel. It MUST NOT throw. Combinators: `lit` (a `kind` discriminant), `str` / `num` / `int` / `bool` / `scalar` (typeof / `Number.isInteger` guards → aid-directed `expected <label>, got <received>`), `enumOf` (membership → `expected <label>: a, b, c` + a `didYouMean` tail), `obj` / `optional` / `list` / `record` (composites — `record` is the named-argument map `{ [name]: value }`, returning an insertion-ordered `Map` to mirror `parseNamedArgs`), and the reference combinators `exprRef` / `queryRef` / `queryDefRef` / `sourceRef` (child-expr / child-query / raw-query-def / child-source slots, each defensively dispatched via the registry). **Accumulation, no throwing:** `obj` / `list` / `record` check ALL of their fields/elements before deciding — they never early-return on the first bad one — so a single `check` surfaces multiple problems in one pass (e.g. a `comparison` with a bad `op` AND a non-object `left` yields BOTH the `op` enum problem and the `left` not-object problem, each localized under its own path). Cross-field rules that a plain `obj` can't express (e.g. `logical`'s `not`-arity, or `in`'s list-vs-subquery dispatch) live in a thin hand-written `Shape` wrapper around the base `obj`.
274
-
275
- **Perfect type-safety, no casts.** The only `unknown` is the untrusted `json`, always narrowed by a type guard. `obj` is fully typed with NO `as`: rather than the usual `fields: Record<string, Shape<unknown>>` (whose indexed access erases each field's value type, forcing a cast in the assembler), the generic is INVERTED — `F` is the BUILT-VALUE record and the field map is the mapped type `{ [K in keyof F]: Shape<F[K]> }`, so `fields[key].check(...)` returns exactly `F[K] | INVALID`; the partial accumulator is promoted to the complete `F` for `build` by a user-defined completeness type GUARD (`acc is F`), not a cast.
276
-
277
- Three DEFENSIVE dispatches — the zod-free parallels to `parseExpr` / `parseQuery` / `QuerySource.from` — walk the whole tree: `Registry.parseCheckedExpr(json, problems)`, `Registry.parseCheckedQuery(json, problems)`, and `Registry.parseCheckedSource(json, problems)`. Each mirrors its throwing twin but records problems (`shape.not-object` / `shape.missing-kind` / `shape.unknown-kind` with a `didYouMean` over the real kinds) and returns the built `Expr` / `Query` / `QuerySource` or `undefined`, dispatching to each class's owned `static SHAPE` (query dispatch auto-includes every registered class that declares one; source dispatch reads `QuerySource.SHAPES`, keyed by the four source kinds). Each `SHAPE` builds a value `.toJSON()`-equal to the existing `from(def)` output on a valid def; the SEMANTIC checks (comparability, arg types, aggregate placement, source duplicates, write-model, unknown names) stay in `validateWalk`.
278
-
279
- The recursion is completed by four child-slot combinators alongside `exprRef`: **`queryRef`** (a parsed `Query` child — the set-operation arms, CTE bindings, subquery sources, `INSERT … SELECT`), **`queryDefRef`** (a subquery kept as a raw `QueryDef` — the value-position `subquery` / `exists` / `in`-subquery exprs re-parse it lazily, so it validates through `parseCheckedQuery` but returns the normalized `toJSON()` def), and **`sourceRef`** (a `QuerySource` child — a SELECT's `from`). The small building blocks are shared shapes in `queries/_shape.ts`: `selectFieldShape` (`{ expr, as? }`), `fieldValueShape` (`{ field, value }`), and `boundShape` (a limit/offset — a literal integer or a `{ kind:'param' }` def); `QueryOrder.SHAPE` and `QueryJoin.SHAPE` cover an ORDER BY term and a JOIN clause.
280
-
281
- **The whole query tree now parses through the owned parser.** Expr kinds with a `static SHAPE`: the C1 exemplars (`comparison`, `field-ref`, `literal`, `param`, `logical`) + the C2 operators/predicates/functions/refs (`binary`, `unary`, `is-null`, `between`, `case`, `aggregate`, `window`, `function-call`, `array-op`, `output`, `excluded`, `text-search`, `text-score`) + the C3 finishers: `subquery`, `exists`, `in` (BOTH forms — its `SHAPE` dispatches on `in`: an array → the list form, an object → the subquery form via `queryDefRef`), `semantic` (whose `query` shape dispatches over the string / `param` / `{source,field}` / `{type,field}` forms), `tabular-function-call`, and `filters`. Query kinds with a `static SHAPE`: `select`, `insert` (incl. `onConflict`), `update`, `delete`, `union` / `intersect` / `except` (three `lit(kind)`-anchored shapes over the shared `SetOperationQuery`), `cte` (its entry shape structurally discriminates the plain vs recursive binding), and `expr`. Source kinds: `type`, `aliased`, `subquery`, `function`. Cross-field rules a plain `obj` can't express (e.g. `logical`'s `not`-arity, `in`'s list-vs-subquery dispatch, `cte`'s entry discrimination) live in a thin hand-written `Shape` wrapper around the base `obj`. An end-to-end test parses a complex SELECT (joins + where + groupBy + having + subquery + aggregate) to a `Query` `.toJSON()`-equal to the throwing `parseQuery`, and a SELECT malformed across several clauses surfaces every problem in ONE pass.
282
-
283
- **This is the ACTIVE structural gate (C4 flipped).** `parseQueryInput` gates on `parseCheckedQuery` and feeds the sound result to `validateWalk`; the zod `safeParse` structural authority (and `problemsFromZod` / `flattenZodIssues`) has been retired. Zod remains ONLY the model-facing wire schema (`querySchema` / `buildSchemas`), unchanged. This is the intended structure-vs-semantics split: the owned parser accepts any registered kind + any string field, and unknown types / fields / functions are caught downstream by `validateWalk` with the existing aid-directed + `didYouMean` semantic messages.
284
-
285
- ### Compact tool-call schema (shared `$defs`)
286
-
287
- The model-facing JSON-Schema (what `z.toJSONSchema` — and core's `compile()` — emit from `querySchema`) is **structurally factored**: the largest repeated fragments are built ONCE per schema-generation (a `SchemaCache` threaded on `SchemaOptions.cache`) and REUSED by identity everywhere they occur, so the converter emits each as a single `$def` + `$ref`s instead of inlining every copy. Factored fragments: each Type's **field-name enum** (`$def` `Fields_<Type>`, shared by field-ref / order / group-by / having / filters / text-search / semantic), the shared **`param`** expr, the reused **`Limit`** (number-or-param), and — the biggest win — the per-function **typed-args** blocks, keyed by argument SIGNATURE so the 100+ builtin functions (which collapse to a few dozen distinct signatures — dozens share a lone `value` arg) reuse one `$def` each. Names come from each shared fragment's `aid`, stamped as `meta.id` (`Fields_user`, `param`, `Limit`, `Args…`) so `z.toJSONSchema` factors AND names them; the ids are salted per schema-generation to stay unique in zod's process-global registry. This is a pure size/structure win — the schema accepts and rejects exactly the same queries with the same aid-directed diagnostics (a golden invariance test guards that), only smaller: on the bundled example fixture the minified `z.toJSONSchema` drops from **21.3 KB → 20.2 KB** (`open`) and **105.6 KB → 95.5 KB** (`paired`), the paired reduction concentrated in the field enums + typed-args (the ~100 genuinely-distinct per-function branches of `typed` mode are irreducible). A size-threshold test catches any regression that re-inlines the shared fragments.
288
-
289
- ## Self-describing the engine to a model
290
-
291
- The `describe*` helpers render a compact, promptable capability summary (plain text, deliberately terse to protect the context budget):
292
-
293
- - **`describeEngine(engine, { types?, functions?, maxExamples?, instructions?, examples? })`** composes ONE block a model can read to know everything it may use: every (supplied) Type, then `describeExprs`, then `describeFunctions`, then `describeQueryExamples`, then `describeDialects`. `functions` narrows both the expr gating and the function listing to the schema's selection; `types` narrows the Type list + gating; `maxExamples` caps how many WORKED examples render PER function / node (default `DEFAULT_MAX_EXAMPLES` = 2; `0` omits examples). It no longer needs a separate example-text call — worked examples now live ON the nodes/functions (see below) and are folded in here.
294
- - **Bring your own instructions / examples (use your OWN Types).** `instructions?: Record<string, string>` and `examples?: Record<string, readonly string[]>` (also `DescribeOverrides`, threaded through `describeExprs` / `describeFunctions` / `describeQueryExamples`) let a caller REPLACE the shipped `INSTRUCTIONS` / `EXAMPLES` for a given item — keyed by function NAME (`sum`, `count`, …) or node KIND (`window`, `in`, `select`, `union`, `cte`, …); names and kinds share ONE flat namespace (they are distinct strings). A key that is PRESENT swaps in the caller's string(s) — e.g. worked examples written against the caller's real domain Types instead of the generic shipped ones — while every key NOT present keeps the shipped default; overridden example lists are still capped by `maxExamples`, and an absent / empty override map renders byte-identically to today. Override strings are the CALLER's responsibility (rendered VERBATIM, not validated at render time): a caller can structurally pre-check their own example strings the same way the shipped-example test does — `JSON.parse` then a bare `createRegistry().parseCheckedQuery(...)` (full queries) / `parseCheckedExpr(...)` (expr fragments) and assert zero problems — before passing them in.
295
- - **`describeExprs(engine, types?, functions?, maxExamples?)`** lists the CAPABILITY-GATED expression kinds — one `kind — INSTRUCTIONS` line per kind actually usable for the current Types/functions, filtered by the SAME gate the schema uses (`exprKindApplicable`), each followed by up to `maxExamples` `e.g. <json>` lines from the kind's `static EXAMPLES`. The always-usable core is never gated; `semantic` / `text-search` / `text-score` / `array-op` / `tabular-function-call` appear only when an eligible Type/function exists (`excluded` / `output` are position-only and never listed).
296
- - **`describeFunctions(engine, functions?, maxExamples?)`** renders each function as `name(a, b?): output — instructions` (named params, a trailing `?` marks optional), grouped by shape, each followed by up to `maxExamples` `e.g. <json>` lines from the function's `examples`.
297
- - **`describeQueryExamples(engine, maxExamples?)`** renders a query-examples section: each registered query KIND that ships `static EXAMPLES` (SELECT, UNION/INTERSECT/EXCEPT, WITH/CTE) as `kind — INSTRUCTIONS` plus up to `maxExamples` worked example queries. Query-level constructs have no expr-catalog entry, so they get their own section.
298
- - **Worked examples are a shipped, first-class surface.** Every `FunctionDef` may carry `examples?: readonly string[]` (RAW JSON strings — expr fragments or full queries that CALL it), and every Expr/Query node class may carry a `static readonly EXAMPLES?: readonly string[]` (plus, for query kinds, an optional `static INSTRUCTIONS`). Examples are TYPE-AGNOSTIC (illustrative generic source/field names like `event.score` / `user.name`) — they teach SHAPE while the catalog supplies the caller's real Type names. The shipped high-confusion set: the window family (`rank` / `denseRank` / `lag` / `lead` / `firstValue` / `lastValue` / `nthValue` / `cumeDist`), `dateTrunc` / `age` / `replace`, `count`; and the `window` / `exists` / `in` / `subquery` / `function-call` exprs and `select` / `union` / `cte` queries. This is the ONE source of truth — `describeEngine` only renders them. A structural test parses EVERY shipped example through a bare `createRegistry()`'s `parseCheckedQuery` / `parseCheckedExpr` and asserts zero problems.
299
- - **Generated Type / Field docs.** `describeType` / `describeField` always emit a short `label` + long `description`: the developer's `TypeDef.label` / `FieldDef.description` when set, otherwise a sensible default GENERATED on demand from the meta-model — a Field from its FieldType (kind, bounds, `sensitive` / `semantic` / `search` flags, array item/bounds, a relation's `to` + `count` + its DIRECTION → belongs-to / has-many, read from `isBelongsTo()` rather than `count` so a materialized inverse is never described as a belongs-to, nullability), a Type from its name + field/relation/index summary. Read the (possibly-generated) pair directly with `fieldMeta(field)` / `typeMeta(type)` (`{ label, description }`); nothing mutates the stored def — the strings are computed fresh per call.
1
+ # @aeye/query — LLM relational query language
2
+
3
+ **Purpose:** A JSON, LLM-authorable relational query language with an in-memory runtime and a SQL converter. You register *Types* (table-like entities) made of *Fields*; from those an LLM (or a developer) builds a **typed, validated, runnable** query — a `select` / `insert` / `update` / `delete` / set-operation / CTE / single-expression statement. A built query resolves to an output type, has typed bind params, can be cost-bounded, run in-memory, emitted to SQL (base + Postgres), auto-paginated, and drilled down.
4
+
5
+ It is standalone (only depends on `zod`) and exhaustively type-safe: every polymorphic node is a discriminated union, so handling is compiler-checkable with no `any`/casts.
6
+
7
+ ## When to use it
8
+
9
+ - You want an LLM to author a **structured, validated** query over a schema you control — and get compiler-style diagnostics instead of free-form SQL you have to trust.
10
+ - You need the SAME query to run in-memory AND emit dialect SQL (base ANSI + Postgres) identically.
11
+ - You want the conceptual schema the model sees to stay minimal while the physical reality (real tables, RLS/FLS, computed fields, hidden vector/tsvector columns, extra joins) lives in dev-side backing code.
12
+ - You need cost bounding, aggregate drill-down, pagination, semantic/full-text ranking, or execution-time filters over model-authored queries.
13
+
14
+ ## The query/expr JSON contract (state once)
15
+
16
+ A query is a `QueryDef` and an expression is an `ExprDef` — plain JSON discriminated unions (keyed by `kind`) that round-trip through `JSON.stringify`. **The LLM does not hand-write these shapes from memory:** `buildSchemas` / `querySchema` generate a Zod schema the model emits against, and that schema is both **depth-graduated** (how tightly Type names / field refs / function args / filters are locked — see *Schema depth*) and **capability-gated** (expr kinds an available Type/function can't use are omitted). The doc below therefore describes *what is supported*; the schema tells the model *how to shape it*. `schema.ts` is the single source of truth for every `*Def`.
17
+
18
+ Developers compose the same trees ergonomically with the **`e.*` builder** (one builder per expr kind); each `e.*` returns a real `Expr` instance and `.toJSON()` is its wire `ExprDef`. `registry.parseExpr` is a pass-through for an already-built `Expr`, so built and parsed exprs compose freely.
19
+
20
+ ```ts
21
+ import { e } from '@aeye/query';
22
+ const cond = e.and(e.eq(e.ref('task', 'done'), e.value(true)), e.gt(e.ref('task', 'hours'), e.value(0)));
23
+ ```
24
+
25
+ Builders, by group: leaves (`value`/`lit`, `param`, `ref`, `path`, `output`, `excluded`, `filters`), arithmetic (`add`/`sub`/`mul`/`div`/`mod`, `neg`/`pos`), comparison (`eq`/`neq`/`lt`/`lte`/`gt`/`gte`/`like`/`notLike`/`ilike`), logical (`and`/`or`/`not`), predicates (`isNull`/`notNull`, `between`/`notBetween`, `inList`/`notInList`, `inSubquery`/`notInSubquery`, `exists`/`notExists`), array (`contains`/`containsAny`/`containsAll`/`isEmpty`/`notEmpty`), `case`/`when`, calls (`fn`, `agg`/`count`/`countStar`/`sum`/`avg`/`min`/`max`, `window`, `tableFn`), `subquery`, search (`textSearch`, `textScore`, `semantic`). Every builder is also a named export.
26
+
27
+ ## The type / field model
28
+
29
+ A `Type` is a named collection of `Field`s plus index + cardinality estimates (`count` rows, `bytes`/row for cost). Each field has a `FieldType` — one of `number`, `text`, `money`, `bool`, `relation`, `date`, `timestamp`, `json`, `array` (nine kinds). Nullability lives on the field, not the type.
30
+
31
+ - **Text** matching is governed by the field's `casing` — `'fold'` (case-insensitive, the query wraps both operands in `LOWER(...)`), `'collated'` (case-insensitive because the COLUMN's collation folds, so no `LOWER` is emitted and the index still works), or `'exact'` (case-sensitive) — falling back to the engine's `textCasing` default (`'fold'`). A field's own `casing` always beats the engine default. Prefer `'exact'` / `'collated'` for identifiers, codes and uuids: `LOWER(col)` is not sargable, and over a physical `uuid` column Postgres has no such function. Fields may be flagged `semantic` (embedding-eligible) and/or `search` (full-text-eligible); a whole Type may carry the same `semantic` / `search` flags.
32
+ - **Closed value sets** — `text` and `number` fields take `values?: { value, label? }[]`, an enum expressed as a CONSTRAINT ON the scalar rather than a separate field-type kind; `money` declares one through its inner `number` bag. Membership is a QUERY fact, asked through the total **`FieldType.values()`** — so no consumer tests for the classes that happen to carry the option. Five things read it: `= x` becomes a `1/n` predicate instead of the fixed `EQ_SELECTIVITY` guess; `toValueSchema()` narrows to the members; the model is shown `status: text one of applied|screening (In screening)|hired` and `fee: money(USD) one of 0|10`; a WRITE of a non-member literal is refused (`write.value` — see the write model); and a bind param typed from several uses is NARROWED by it (`enum ⊓ text = enum`). Those last two are a PAIR: enforcing membership without rendering it would refuse a model against a set it was never shown. A **CONTAINER declares no set of its own** — an `array<text one of a|b>` admits ARRAYS, not members, so `values()` answers `undefined` for it and its `eqSelectivity` stays the fixed guess (a `=` there compares whole arrays). The ELEMENT's set still reaches every behaviour that applies to a container: the value schema and the write check validate ELEMENT-WISE at any depth (`Cannot write "bogus" to element 1 of field 'tags' — …`), the meet meets element types, and the description renders `array<text one of a|b>`. A set is a SET: duplicates are normalized away by `compactFieldValues` — a REWRITE, not just a read-side view, so a `toJSON()` round-trip hands back the deduped def — since `1/n` is only a selectivity if `n` counts distinct values. The per-member `label` rides along so one closed set has ONE home. A MEMBER IS A VALUE OF THE OWNING KIND's SCALAR — the `text` def schema offers a string member, the `number` / `money` one a number, so a mixed-scalar set is not something a generated schema can offer. Composes with `min`/`max` / `pattern` (a regex is a SHAPE, a value set is MEMBERSHIP — different facts, both allowed), and THE DECLARATION MUST BE SELF-CONSISTENT: a `pattern` must be a compilable regex, and EVERY declared member must satisfy the type's own constraints (`field-type.bad-values` — `text{values:['zz'], pattern:'^a'}`, `number{values:[1.5], whole:true}`, or a text member of a numeric set). Both are checked when the field type is PARSED. A member no constraint admits could never be stored, and until `0.6.6` such a set registered happily while `validValue` accepted the member (a closed set IS the value schema) and the param meet dropped it — the disagreement that made `x ⊓ ⊤ = x` fail. Refused on the DEF road only: the public constructors validate neither, exactly as before. **READS stay unconstrained on purpose**: `where status = 'bogus'` is legal, because querying for a value that should not exist is how you find the rows a bad migration wrote.
33
+ - **Relations** carry a target `to` Type and cardinality `count`: the relation field's **name IS the join key** (there are no explicit FK fields). A belongs-to may set `inverseRelation` so its target auto-gains the matching has-many. **Which side the FK is on is `RelationFieldType.isBelongsTo()`, not `count` alone**: a MATERIALIZED INVERSE is never belongs-to however its estimated `count` came out, because the registry derives that count from a row RATIO — so a 1:1 pair (or two types sharing one declared row estimate) legitimately yields `1`.
34
+ - **Identity** — a Type may declare `identity?: string | string[]`, the field (or ordered fields) that IDENTIFY a row. When present it is THE answer for `identityField()` / `primaryKey()` and index ORDER stops mattering. Without it, identity is INFERRED as "the first single-part unique index, else the field named `id`" — so a Type declaring both `id` and a unique `email`, with the email index listed first, silently identifies by `email`, and every relation into it joins a stored id against an email address. Declaring a name the Type does not have is an ERROR, not a silent fall-back to the inferred rule.
35
+ - **Indexes** are composite (ordered parts, each with a non-increasing prefix distinct-row `count`); unique iff the last part's `count === 1`. They drive cost estimation. An index part is a TYPE-level fact, so it is written against the Type NAME; a query binding that Type under an ALIAS (`{kind:'aliased'}`, either side of a self-join) has its probes NORMALIZED back to the type name before matching (`renameSource` / `aliasedDigest` / `Index.prefixReduction(used, alias?)`), and matching is SOURCE-SCOPED so a join alias equal to another Type's name cannot match the scanned Type's parts.
36
+ - **Arrays** are ordered collections with optional `minItems`/`maxItems` and an optional `item` element field type (omit `item` for heterogeneous); they nest (`array<array<number>>`).
37
+ - **Refinements** — any branch may carry `as: <registered name>`, naming a refinement of that builtin (`{ kind: 'text', as: 'uuid' }`), plus a `with` bag of values for the options that refinement declares for itself (`{ kind: 'json', as: 'Geometry', with: { srid: 4326 } }`). It is the ONE extension point on a field type: the nine kinds never grow. See "A registered REFINEMENT names a builtin" under the function library.
38
+
39
+ `createRegistry()` bootstraps the Type/expr/function catalog; `registry.parseType(def)` + `registerType` add Types. `inferType(name, rows)` derives a `TypeDef` (field types + nullability, array detection) straight from sampled JSON rows.
40
+
41
+ ## Expression kinds
42
+
43
+ Every kind is one branch of the `ExprDef` union. Availability in the LLM schema is depth-graduated and capability-gated; the always-usable core is never gated. Each Expr class also exposes a concise `static INSTRUCTIONS` one-liner (enumerable via `registry.exprClassList()`) — the canonical terse doc mirrored by the table below — plus, on the high-confusion kinds, a `static EXAMPLES` set of RAW JSON strings that `describeEngine` renders (capped by `maxExamples`).
44
+
45
+ | kind | one-line meaning |
46
+ | ---- | ---------------- |
47
+ | `literal` | A constant value: a scalar, or a whole JSON DOCUMENT (object / array) for a `json` / `array` field — bound as ONE parameter, never interpolated. |
48
+ | `param` | A named bind parameter; type inferred from use, bound at run/emit time. |
49
+ | `field-ref` | `<source>.<field>` — a field's value from a bound source. A BELONGS-TO relation field projects that relation's IDENTITY off this row (no join); a HAS-MANY is refused (`ref.relation-has-many`). Read the target's OTHER fields through a `relation` join. |
50
+ | `binary` | Arithmetic `left <op> right` (`+ - * / %`). |
51
+ | `unary` | `<op> operand` (`-` / `+`). |
52
+ | `comparison` | `left <op> right` → boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION operand compares by identity in `=`/`<>` only: RHS a same-target relation (FK key) or a `{ pk }` value param; a has-many compares by membership (correlated `EXISTS`). |
53
+ | `logical` | Boolean connective `and` / `or` / `not` over operands. |
54
+ | `is-null` | `value IS [NOT] NULL`. On a belongs-to relation it tests the KEY COLUMNS — i.e. whether the relation is UNSET — so it stays index-usable. |
55
+ | `between` | `value BETWEEN lower AND upper` (negatable). |
56
+ | `in` | `value IN (list \| subquery)` (negatable). A RELATION `value` matches list `{ pk }` values by FK key (belongs-to) or membership (has-many); a COMPOSITE-key relation may not use the subquery form (`in.relation-composite`). |
57
+ | `case` | `CASE WHEN … THEN … [ELSE …] END`. |
58
+ | `function-call` | A scalar function call by name with named args. |
59
+ | `aggregate` | An aggregate function over a group (`count(*)` = empty args); optional `distinct`. A relation field-ref is not aggregable (`ref.relation-aggregate`) — group by it instead. |
60
+ | `window` | A window (or windowed-aggregate) function over `partitionBy` / `orderBy`. |
61
+ | `subquery` | A scalar / single-field subquery in value position. |
62
+ | `exists` | `[NOT] EXISTS (subquery)` → boolean. |
63
+ | `array-op` | Predicate over an array field: `contains` / `containsAny` / `containsAll` / `isEmpty` / `notEmpty`. |
64
+ | `text-search` | Full-text predicate over a source (optionally one field) → boolean. Narrow it to a field unless the Type declares a search DOCUMENT — an unbacked whole-source search is refused (`text-search.unbacked`). |
65
+ | `text-score` | Numeric full-text relevance score of a source (optionally one field) → number (`ts_rank`). Same backing rule as `text-search` (`text-score.unbacked`). |
66
+ | `semantic` | Embedding-similarity score of a source's row vs a query (string / param / pairing ref) → number. |
67
+ | `filters` | An execution-time filter placeholder bound to a source (optional `fields` allowlist); predicate supplied at run time. |
68
+ | `excluded` | `EXCLUDED."field"` — the proposed row inside `INSERT … ON CONFLICT DO UPDATE`. |
69
+ | `output` | References a projected SELECT output field by name (valid ONLY in `groupBy`/`orderBy`/`having`); expands to that item's expr. |
70
+ | `tabular-function-call` | A row-producing (table-valued) function call, usable as a source. |
71
+ | `operator` | A REGISTERED operator (`&&`, `<->`, `@>`) applied to NAMED operands — `{op:'&&', args:{left:…, right:…}}`, keyed by the declared operand name, NOT positional. Function-shaped on the wire; infix exists only in the emitted SQL. The catalog's `operators:` block lists every one that exists here, with its operand types, result type and meaning — there are no others, and an operator is not a function (a call is `kind:'function-call'`). |
72
+
73
+ **A relation's VALUE is its IDENTITY.** A `field-ref` to a **belongs-to** relation is a legal VALUE, reading the key off the caller's OWN row — no join, no scope. It yields a JSON object keyed by the TARGET's identity field names (`{ id: 'userB' }`, `{ tenantId: 3, userId: 1 }`), or SQL `NULL` when ANY key column is null (a partial composite key cannot join, so the relation is unset). A keyed object, not a positional tuple: a tuple's meaning would depend on element order, and that order derives from index order.
74
+
75
+ - **Projectable without a join** — legal in `fields` / `RETURNING`, emitting `CASE WHEN <keys IS NULL> THEN NULL ELSE <json object> END` over the local columns. This is what lets an audit column (`createdBy`) report a value: reading the target through an RLS-scoped join nulls its id along with the rest of the hidden row, making UNSET indistinguishable from HIDDEN. Reading the local column discloses nothing — it is data the reader's own row already holds. The projected field reports `fieldType: 'json'` and is nullable.
76
+ - **Comparable, orderable, groupable** — `=` / `<>` / `in` compare per key column (a bare scalar is accepted iff the key is single-column); `is null` / `is not null` test the KEY COLUMNS (`json_build_object(…) IS NULL` would be a constant false), so they stay index-usable; `order by` expands to one clause per key column (lexicographic over the declared key order) and `group by` to the key columns (structural).
77
+ - **Refusals are STATEABLE** — a **has-many** has no key on this row and its value is a SET, so it is `ref.relation-has-many` (join it, or test membership); an AGGREGATE over an identity is undefined, so it is `ref.relation-aggregate` (group by it instead); anywhere a relation is not a value at all — an arithmetic operand, a `case` arm, a function argument — it stays `ref.relation-not-value` / `compare.relation-vs-value` with the join-it hint.
78
+
79
+ ## Sources & aliasing
80
+
81
+ Everything is referenced by its **Type name** — there is no alias to invent or keep in sync.
82
+
83
+ - **FROM** — `{ kind: 'type', type: 'user' }` binds under `source: 'user'` (not aliasable). Also available: `aliased` (escape hatch), `subquery`, and `function` (a tabular-function source).
84
+ - **Joins** — a `JoinDef` crosses a **single relation hop**: `on` is a `{ source, field }` ref (the bound source + its relation field). Joined rows bind under the target Type name; the join key is synthesized from the relation (you never write ON). Multi-hop = chained single-hop joins. `joinType` (`inner`/`left`/`right`/`full`, default `left`) is renamed from `type` to free that key. `and` adds an optional extra predicate.
85
+ - **DML** targets (`insert.into` / `update.type` / `delete.from`) bind under the Type name; DML targets take no alias.
86
+ - **`type` vs `source` rule.** `type` = a registered Type name (FROM `type`, DML targets, relation `to`, a `{ type, field }` semantic ref). `source` = a bound name in scope (Type name / join alias / CTE / aliased source) — used by `field-ref`, `semantic`/`text-search`/`text-score`/`filters`, and a join's `on.source`.
87
+ - **Disambiguation.** For a self-join or two instances of one Type, use `{ kind: 'aliased', type, as }` on FROM, or `as` on a join to override its hop's bound name. Two sources bound under one name → a `source.duplicate` validation error.
88
+
89
+ ## What queries can do
90
+
91
+ - **SELECT** — `fields` (each `{ expr, as? }`), `from`, `joins`, `where` (ANDed), `groupBy`, `having` (ANDed), `order` (`{ expr, dir, nulls? }`), `limit`/`offset` (a literal or a `param`), and `distinct`.
92
+ - **Condition clauses must be boolean** — every top-level condition predicate (a `where`/`having` entry, a join's `and`, and a DML `update`/`delete` `where`) must resolve to a boolean, exactly as `logical` operands and `case` `when` clauses already require; a non-boolean predicate (a bare `field-ref` to a number/money/text field, a `literal`, an arithmetic `binary`, a non-bool function) is rejected with `condition.non-bool` at the predicate's own path. A bare `param` predicate is EXEMPT (its type is inferred from use).
93
+ - **Output references** — `groupBy` / `order` / `having` may use `{ kind: 'output', name }` to reference a projected field by name (its `as`, or a natural derived name) instead of repeating the expression. It EXPANDS to the target item's expr in both SQL and runtime (a group key re-computes over the source row; an ORDER BY / HAVING ref re-computes over the group, incl. an aggregate target). Valid **only** in those three positions (`output.not-available` elsewhere; `output.unknown` / `output.aggregate` on misuse). `drillDown` expands `output` refs before un-ravelling.
94
+ - **Aggregates & grouping** — any registered aggregate over a `groupBy`; `count(*)` is `count` with empty args; `distinct` on the aggregate. `having` filters groups. `distinct` de-duplicates the ARGUMENT VALUES, so it is refused on the arg-less form (`aggregate.distinct-no-args`) — `count(DISTINCT *)` is a syntax error on every dialect and the runtime never de-duplicated it either; emission drops it, so an unvalidated statement still produces valid SQL.
95
+ - **Set operations** — `union` / `intersect` / `except` over two queries, `all?` to keep duplicates, plus **set-level** `order` / `limit` / `offset` applied to the combined rows (ORDER BY terms reference output columns by name).
96
+ - **CTEs** — `{ kind: 'cte', ctes, final }`. Each entry is either non-recursive (`{ name, query }`) or **recursive** (`{ name, base, recursive }` — a seed UNION-ed with an arm reading the CTE's own accumulating rows to a fixpoint, iteration-capped). Recursion is its own structural shape (no `recursive?` flag).
97
+ - **DML** — `insert` (row tuples or a `select`, optional `returning`, optional `onConflict`), `update` (`set` assignments, optional `joins`/`where`/`returning`), `delete` (optional `joins`/`where`/`returning`). `onConflict` = conflict-target `fields` plus `doNothing` or an `update` assignment list (which may reference the `excluded` proposed row).
98
+ - **Single-expression query** — `{ kind: 'expr', expr }` for a scalar computation.
99
+ - **Params** — `{ kind: 'param', name }` infers its type from use; bound at run/emit via `options.params`. Introspect with `query.params(engine)` → `ParamDef[]`. It reports **every param the statement binds, at any DEPTH** — including a `limit`/`offset` bound, which lives outside the expr tree, wherever it sits: on a `cte`'s `final` (where `autoPaginate` puts it), on a set-operation arm or its set-level bound, or inside a FROM / `in` / `exists` subquery or an `insert … select` source. So what `params()` declares is always enough to BIND the emitted SQL — an under-reported bound emits `LIMIT ?` with nothing to fill it, and `LIMIT NULL` is *no limit* (the whole table), not an error.
100
+ - **A param's type is the MEET of every use, and it is order-independent.** Uses are folded with `FieldType.meet` — the most SPECIFIC type compatible with all of them, the constructive form of `comparableWith`. So a param compared against an `enum` in one place and plain `text` in another is the **enum**; `text{minLength:5}` beside `text{maxLength:10}` carries **both** bounds; `enum{a,b}` beside `enum{b,c}` is `enum{b}`; `number` beside `money` is `money`; `date` beside `timestamp` is `timestamp`. The operation is commutative, associative, idempotent and SOUND (it accepts nothing that both operands do not), which is what makes the answer independent of where in the JSON each use happens to sit (before `0.6.6` the FIRST use won and nothing ever narrowed). Where no meet exists the param is in CONFLICT and is omitted from `params()`; an EMPTY meet (two closed sets sharing no member, two disjoint bounds, two different patterns) is a conflict rather than a type nothing satisfies — a "closed set of nothing" is not even representable, since an empty `values` array is an ABSENT declaration. **It is the GREATEST lower bound for every type built from a DEF, and only a lower bound for one built by hand.** Because a closed set IS the value schema, a meet narrows a merged set by the merged scalar constraints — so for a SELF-INCONSISTENT type (`text{values:['ab'], minLength:5}`, whose own member its own bound rejects) even `x ⊓ text` narrows or conflicts. Since `0.6.6` that declaration is REFUSED where declarations are read (`field-type.bad-values`, plus a per-kind member schema), so `x ⊓ ⊤ = x` holds unconditionally over everything `parseType` / `parseFieldType` can produce, and a param compared against such a column can no longer report `param.conflict` for a defect in the TYPE. The public CONSTRUCTORS still do not validate — `new TextFieldType({values:[{value:'ab'}], minLength:5})` is buildable, and the meet is a lower bound only for it — which is the same caveat a hand-built uncompilable `pattern` carries. Soundness is the law a validator depends on and is kept unconditionally on both roads.
101
+ - **A function ARGUMENT is one of the typing roads.** `abs(:p)`, `sum(:p)`, `ntile(n: :p)` and a tabular call's argument each observe the param against the function's DECLARED parameter type, so a param used NOWHERE else still reports its type from `params()` / `parameters()`. Through `0.6.6` only the scalar `function-call` observed at all, and it did so AFTER checking the argument's type — so `abs(:p) > 1` was refused with `function.arg-type: expects number, got text` (an un-observed param resolves to a `text` placeholder) unless an earlier clause happened to type `:p` first: `t.n = :p AND abs(:p) > 1` passed and the same two clauses SWAPPED did not. A bare param argument is now exempt from the arg-type check for the reason a param COMPARISON operand already was — the call site is where the param GETS a type, so there is nothing there to be wrong — and an inconsistency across uses is reported once, as `param.conflict`. A parameter declared `'any'` states no type to observe, so a param used only there is still `param.untyped`.
102
+ - **`engine.parameters(query)` → `ParamInfo[]`** is the full introspection behind that answer, at the same grade of detail as a query's RESULT fields: per param, its `references`, every `use` (`{ at, type, category, field? }` — the JSON path, the full FieldType that use requires, its `ScalarKind` summary, and the COLUMN the requirement came from), the merged `type` / `category`, and the `conflict` when there is none. Read it to EXPLAIN a param (label an input, say WHY it got its type); read `params()` to bind one. `ParamDef` is unchanged and still `{ name, type }` — a def without a type would be a lie about a param nothing can bind.
103
+ - **`engine.checkParams(query, params)` → `Problems`** checks SUPPLIED values against the merged type, BEFORE execution: `param.value` (error) is a value the merged type refuses — including one that each use in isolation would have admitted, which is the case nothing could previously catch; `param.missing` (warning) is a typed param with no value, which binds SQL NULL (what `autoPaginate` relies on); `param.unknown` (warning) is a value supplied under a name the query has no param for. `null` always passes — a param is potentially-null by construction — and so does a RELATION-typed param, whose value is the target's IDENTITY (a `{ pk }` object for a composite key), which the relation's own value schema does not describe; that is the same exemption `write.type` already makes for a relation column. Reported as Problems, never thrown, and it also rides on `validateQuery(query, _, _, { params })`. `run` / `toSQL` do NOT validate: a hot path that could only throw is the wrong place to learn this.
104
+ - **Filters** — a `filters` placeholder (`{ source, fields? }`) is authored by the LLM but the **predicate is supplied at execution time** by the developer: `options.filters` is a `Record<source, boolean Expr | ExprDef | null>`. The placeholder evaluates/emits it (vacuously `TRUE` when none). Introspect exposed sources + fields with `query.filters(engine)` → `Record<source, { fields: QueryField[] }>` (name + resolved type + nullability + kind, restricted to any `fields` allowlist); `query.filterSources()` lists targetable sources.
105
+ - **Cost & estimation** — bottom-up estimates driven by Type `count`/`bytes`, indexes + selectivity, and per-Type/field `changes` rates. `engine.cost(query)` → `{ rows, bytes }` (the WORK to produce the result); `engine.outputCost(query)` → `{ rows, bytes }` (the SIZE of the result — delivered rows × projection width); `engine.affected(query)` → `{ rows, types[] }` (rows an INSERT/UPDATE/DELETE or CTE mutates, OR-aware via indexes); `engine.references(query)` → `{ types, fields, functions }` (exactly what the query reads, incl. execution-time `filters`/`sort` and called functions); `engine.changeInterval(query)` → ms until the data behind it could change (freshness/cache-TTL: `0` = always, `-1` = never, else the fastest read rate). `validateQuery(query, _, { maxRows, maxBytes })` rejects over-budget queries (`cost.rows-exceeded` / `cost.bytes-exceeded`).
106
+ - **A DERIVED SOURCE is estimated from its BODY.** A CTE name, a FROM subquery and a joined subquery source all bind a synthetic Type, and that Type carries the rows its body produces — so `SELECT … FROM (SELECT … FROM million) x` costs a million, a join over such a source fans out by its real cardinality, and a `WITH` costs its `final` PLUS every entry's own work (an entry runs whether or not `final` reads it, and this runtime materializes each one in memory). A RECURSIVE entry is estimated as its seed plus `RECURSIVE_CTE_LEVELS` expansions of its arm — the fixpoint depth is data-dependent, so the model assumes a shallow hierarchy rather than pretending to know. Two consequences worth stating: a `cte` / derived table is no longer structurally free, so a `maxRows` budget can finally refuse one (before `0.6.5` these bound a zero-row Type and every such statement passed every budget at `{rows: 0}`); and a `LIMIT` bound to a PARAM *inside* a body is estimated UNCAPPED — those estimates are taken with `engine.neutralCost`, the neutral context, because execution-time `filters` / `sort` / `params` belong to the enclosing query.
107
+ - **`affected` descends into EVERY nesting position** — its own target, plus whatever its nested statements mutate: a FROM / joined subquery source, a `subquery` / `exists` / `in` subquery in any clause, a set-operation arm, an `insert … select` source, and a `cte`'s entries + `final`. Each kind declares its nested statements once, so this is total by construction rather than a list of remembered cases. Rows are summed per Type, in document (= execution) order.
108
+
109
+ ## Write model & permissions
110
+
111
+ Types and fields declare **what write operations are possible**, and the model flows into BOTH validation AND the LLM-facing schema — so the generated schema is accurate to what can actually be done.
112
+
113
+ - **Type flags** — `insertable` / `updatable` / `deletable` on a `TypeDef` (each default **true**). A restricted Type drops the matching DML: validation rejects it (`insert.type-readonly` / `update.type-readonly` / `delete.type-readonly`) AND the schema omits the query kind entirely when NO Type permits it, and filters each DML's target-name enum (`into` → insertable Types, `update.type` → updatable, `delete.from` → deletable).
114
+ - **Field flags** — `insertable` / `updatable` on a `FieldDef` (default **true**). A field whose `FieldBacking.compute` is set defaults to `insertable:false, updatable:false` (override with an explicit flag). Validation rejects a listed non-insertable field (`insert.field-readonly`) / an assigned non-updatable field (`update.field-readonly`); the paired schema offers only insertable `fields` / updatable `set` fields.
115
+ - **Insert-requiredness (THE rule)** — a field is REQUIRED on insert iff it is **insertable AND non-nullable AND has no default AND is not computed**; otherwise optional (nullable / has-default) or excluded (non-insertable). One shared helper (`requiredOnInsert`) drives both the schema (required-vs-optional in paired mode) and validation (`insert.missing-required`, which lists the missing names).
116
+ - **Defaults** — `FieldBacking.default` is a `Value` or a factory `() => Value | Promise<Value>`. Its **presence alone** makes the field optional-on-insert (there is no `hasDefault` flag). At **runtime** an omitted defaulted field is materialized (the value is evaluated / the factory awaited, per row) into the inserted record. In **SQL** the column is simply left out of the INSERT and the database's own column `DEFAULT` fills it — so a JS-factory default is a runtime-only concern.
117
+ - **A write CELL carries a JSON value or an expression** — `WriteValueDef = JsonValue | ExprDef`. A raw SCALAR or a whole DOCUMENT (object / array, for a `json` / `array` column) becomes a literal; a `{ kind }` object is read as an EXPRESSION only when the kind names a REGISTERED expr kind, so a settings blob carrying a `kind` key stays data. An absent key OR a JSON `null` OMITS the field (its default fills in / it stays unset); `{ kind:"literal", value:null }` is the only way to set SQL NULL. A value written to a `json` / `array` column is JSON-ENCODED and bound as ONE parameter cast to the COLUMN's type (`Dialect.jsonValue`) — Postgres `CAST($1 AS jsonb)`, or `ARRAY[$1,$2]::text[]` for a native array column, which cannot take JSON text. The COLUMN decides, not the value's shape, so a JSON *scalar* into a `json` column (`"a bare string"`, `42`) is encoded and cast like any document rather than bound raw. SQL NULL is the exception: a null literal and an unbound param bind NULL, never the JSON value `null`. A param bound to a document is bound, never silently NULL.
118
+ - **A write value is checked against its COLUMN** — the cell's expr is walked in the target's scope, a `param` cell is OBSERVED against the column's field type (which is the only place a write param's type can come from), a value of an incompatible category is refused (`write.type`), and a LITERAL written to a column declaring a closed value set must be one of the members (`write.value`, whose message NAMES them, because the members are the fix). The two are separate codes because the remedies differ — a category says "change the type of this value", membership says "use one of these". A RELATION column is exempt from both: what you write to it is the target's identity, not a value of the relation's own category. Membership additionally exempts everything with no statically knowable value — a `param` (checked later, against the type its uses require: see `engine.checkParams`), a null literal (matching Postgres, where a NULL passes a CHECK by three-valued logic), and any non-literal expr (a function call, a field ref, a `case`).
119
+ - **Expr restrictions** — `FieldDef.exprs` is `{ not: ExprKind[] }` (exclude these kinds) or `{ only: ExprKind[] }` (allow exactly these). It can only NARROW what the field TYPE already permits. `field.allowsExpr(kind)` respects both the type floor and the restriction. Validation rejects a denied kind at the field's use site (`field.expr-denied`) — checked on a standalone `field-ref` (gated as `field-ref`), on each gating operator's DIRECT field-ref operand (gated as `comparison` / `between` / `in` / `is-null` / `array-op`), and on the field-naming exprs (`text-search` / `text-score` / `semantic` / `filters`). The paired schema omits an excluded field from the relevant enum and gates a kind away entirely when every candidate field excludes it.
120
+
121
+ ## Semantic & text search + scoring / ranking
122
+
123
+ All three search exprs bind to a **source** with an OPTIONAL `field` (omit ⇒ whole source); eligibility requires a `semantic`/`search`-flagged Type or field (`Type.isSearchable()` / `isSemantic()` answer "anywhere on this Type"; `isFieldSearchable(f)` / `isFieldSemantic(f)` answer per field).
124
+
125
+ **The per-field fact is DECLARED ON THE FIELD TYPE**: `FieldType.isSearchable()` / `isSemantic()` (`false` by default; only `text` overrides them, from its `search` / `semantic` options, with `search` implying semantic-eligibility), plus `FieldType.itemType()` for a container's element. Everything that gates on a capability asks the TYPE — `Type.isFieldSearchable` / `isFieldSemantic`, `Field.allowsExpr`, the `semantic` expr's own check — so there is one definition rather than four `instanceof TextFieldType` reads of an option bag from outside the class. **A registered refinement INHERITS them and does not re-declare them**: `search` / `semantic` are `text`'s own options, so `registerFieldType({ base:'text', options:{ search:true, semantic:true } })` makes every column naming that type searchable and embeddable, and the flags OR through the meet — a use site may ADD one the declaration left off and cannot take one it set away. A `searchable` key on the declaration would be a second source for one fact, meeting through a different lattice than the option it duplicates. The KIND questions ("is this text / an array / a relation") stay `resolve()`, which is the same answer `categoryOf` gives every comparison.
126
+
127
+ **An unnarrowed `text-search` / `text-score` needs a `SearchBacking` and does NOT guess.** A whole-source search wants the Type's searchable DOCUMENT, which only a backing supplies (a precomputed `vectorField`, or a `sql` override). Without one it is refused — `text-search.unbacked` / `text-score.unbacked` in validation, and a `QueryTypeError` on emission — rather than resolving to the first `search`-flagged field, then the first text field of any kind, then a column literally named `search`. Those three fallbacks meant a query asking for a multi-field document silently searched ONE column, and which column depended on field ORDER. Narrowing to a field needs no backing and is unaffected. Relation fields are no longer counted as semantic-eligible (a foreign key is a join, not an embedding).
128
+
129
+ - **`text-search`** — full-text **predicate** (boolean). `query` is a literal string or a `param`.
130
+ - **`text-score`** — the **numeric** relevance counterpart (same eligibility): usable in SELECT + ORDER BY, so "top N by text relevance" works. Postgres emits `ts_rank(to_tsvector(col), plainto_tsquery(query))`; base (ANSI) degrades to `CASE WHEN <LIKE> THEN 1 ELSE 0 END`; in-memory is a deterministic token-overlap fraction. Build with `e.textScore(source, query, field?)`.
131
+ - **`semantic`** — embedding-similarity **score** (≈1 = most similar; requires an embedder). `query` is a literal string, a `param`, a `{ source, field }` ref to ANOTHER bound source + semantic field (the **cross-source pairing** form), or a `{ type, field }` ref resolving to the single bound source of that Type (`semantic.query-unbound` / `semantic.query-ambiguous` steer you to the `{ source }` form).
132
+
133
+ **Cross-Type pairing + ranking.** Join (or cross-join) two Types so both are bound, score one against the other's embedding, then `ORDER BY score DESC LIMIT N`. Postgres emits the dialect's `similarity` over both bound aliases' vectors (each side's hidden `vectorField` if backed, else `<alias>."embedding"`); the base dialect degrades similarity to `0` and never throws.
134
+
135
+ ## Array fields & operations
136
+
137
+ Query an `array` field with the `array-op` predicate: `contains` (a single element present), `containsAny` / `containsAll` (overlap / superset vs an element list), `isEmpty` / `notEmpty`. Element count is a `comparison` over the builtin `arrayLength(arr)`. Text elements match per the ELEMENT type's `casing`, else the engine's `textCasing` default.
138
+
139
+ **Dialects.** Array ops are Postgres-native: `contains` → `value = ANY(col)`, `containsAll` → `col @> ARRAY[…]`, `containsAny` → `col && ARRAY[…]`, length → `cardinality(col)`. The base (ANSI) dialect has no array operators, so containment throws a clear `array-op.unsupported-dialect` `QueryTypeError` rather than emit wrong SQL; emptiness / length still work via `COALESCE(json_array_length(col), 0)`.
140
+
141
+ ## Type backing (physical reality behind the conceptual schema)
142
+
143
+ The flat `TypeDef` the LLM sees can be arbitrarily richer behind the scenes. A `TypeBacking` is dev-side TypeScript registered alongside the Type (`registerType(type, backing)` or `new QueryEngine(registry, { backings })`); the JSON `TypeDef`/`FieldDef` are never touched. All of it resolves IDENTICALLY in `engine.run` and `engine.toSQL`. Every factory receives the **bound `alias`** for the occurrence and must reference it (never hardcode the Type name), so aliased/self-joined sources resolve correctly.
144
+
145
+ - **Real table remap** — `TypeBacking.name` maps to the physical table (`FROM "projects" AS "project"`); `FieldBacking.name` remaps a stored column.
146
+ - **Computed fields** — `FieldBacking.compute` supplies a field's value: a dual `{ expr }` (one `Expr` emitted to SQL AND evaluated in memory), with `sql` / `run` per-mode overrides. Compute/access exprs reaching into other sources flow through the join planner (fields sharing a join collapse to one join). A computed field is non-insertable / non-updatable by default (see **Write model & permissions**).
147
+ - **Insert defaults** — `FieldBacking.default` (a `Value` or a `() => Value | Promise<Value>` factory) makes a field optional-on-insert and is materialized into the row at runtime when omitted; emitted SQL omits the column and relies on the DB's own `DEFAULT` (see **Write model & permissions**).
148
+ - **RLS** (`TypeBacking.access`) — a row predicate ANDed into WHERE and filtering executor rows; `false` ⇒ no rows, `true`/`undefined` ⇒ no filter; combines with any `RlsProvider` passed to run/toSQL.
149
+ - **Default conditions (soft scope)** (`TypeBacking.defaultConditions`) — a SOFT, suppressible default scope (think archived / soft-delete filtering): unlike RLS, the query can REVEAL past it. Each `DefaultCondition` is `{ where, without?, ops?, description? }`. While ACTIVE its `where` (an `Access` — dual `{ expr }` / `sql` / `run`, resolved exactly like RLS: `false` ⇒ no rows, `true`/`undefined` ⇒ no filter, else ANDed) is ANDed into the WHERE of every occurrence of the Type. It **lifts** for a bound source the moment a **condition-position** clause (the query's `where` / `having`, or a JOIN's `and`) references one of the condition's `without` fields **on that source** — a reference in a SELECT item / ORDER BY / GROUP BY does NOT lift it, and each bound alias (incl. a self-join) is decided independently. `without` defaults to the fields the `where.expr` reads (a `sql`/`run`-only `where` with no `without` is therefore ALWAYS-ON — set `without` explicitly to make it liftable). `ops` picks the row-filtering ops it scopes (default `['select','update','delete']`; INSERT is never scoped). RLS is separate and never lifts; a default condition ANDs in alongside it. Example — archived files: `defaultConditions: [{ where: { expr: (a) => isNull(ref(a, 'archivedAt')) } }]` scopes every query to `archivedAt IS NULL`, until a query filters on `archivedAt` (e.g. `WHERE archivedAt IS NOT NULL`), which reveals the archived rows for that source.
150
+ - **Default ordering** (`TypeBacking.defaultOrder`) — a Type's NATURAL sort, applied to a SELECT's `ORDER BY` when the query specifies none (and ordering is meaningful). `DefaultOrder` is `{ by: DefaultOrderTerm[]; applyTo? }`; each `DefaultOrderTerm` is `{ by: Computed; dir?; nulls? }` whose `by` is the sort KEY — the same dual `{ expr }` / `sql` / `run` `Computed` as computed fields, so one key emits to SQL AND sorts in memory identically (`dir` default `'asc'`; `nulls` else the direction-based default — asc ⇒ nulls first, desc ⇒ last — matching an explicit ORDER BY). It applies ONLY when the FROM binds the backed Type (joins never contribute their default order), the query has NO explicit `order`, and it is NOT aggregated (no `groupBy`, no bare aggregate) and NOT `DISTINCT` (both skipped — a base-field order is meaningless post-aggregation, and a non-selected DISTINCT key is illegal SQL). `applyTo` scopes WHICH selects receive it: `'result'` (default) ⇒ the ROOT query being run/emitted OR any `LIMIT`/`OFFSET` select; `'paginated'` ⇒ only a `LIMIT`/`OFFSET` select; `'all'` ⇒ every eligible select (incl. subqueries / CTEs). The ROOT is tracked by an `isRoot` marker threaded from `engine.run` / `engine.toSQL` onto the runtime / SQL context; nested queries (a subquery / EXISTS / IN subquery, a FROM subquery, a CTE body, a set-op branch) run/emit non-root. Example — newest-first: `defaultOrder: { by: [{ by: { expr: (a) => ref(a, 'createdAt') }, dir: 'desc' }] }` ⇒ an unsorted select over the Type gets `ORDER BY "t"."createdAt" DESC`. SELECT-only; DML is never reordered.
151
+ - **FLS** (`FieldBacking.access`) — a per-field gate emitting `CASE WHEN <pred> THEN <value> ELSE NULL END`; `false` ⇒ constant `NULL`.
152
+ - **Named joins & LATERAL** (`TypeBacking.joins`, opted into by `FieldBacking.joins: [name]`) — hidden joins added once per query only when a referencing field is emitted, deduped by name. A `JoinSpec` is a `relation` (reuses relation-join machinery) or a `lateral` (a correlated sub-select; Postgres `LEFT JOIN LATERAL (…) ON true`, base degrades to `ON 1 = 1` and evaluates per outer row; a `lateral.pick` names the default column).
153
+ - **Relation-join backing** (`FieldBacking.relation`, on a relation-typed field only) — drives a relation join's `ON` from explicit, LLM-HIDDEN physical foreign-key columns instead of the name convention (the JSON `FieldDef`/`TypeDef` are unchanged). `keys: [{ local, foreign? }]` are physical key-column pairs, ALL ANDed (composite FKs supported); `local` is the column on the side that DECLARES the relation, `foreign` the column on the TARGET (defaults to the target's identity). The backing lives on the OWNING **belongs-to** relation; a materialized inverse has-many REUSES the same FK (its forward relation's backing, orientation swapped). `on` is a fully custom, alias-correct predicate — `{ expr }` dual (SQL + runtime), with `sql` / `run` per-mode overrides; precedence like compute/access (`run`/`sql` override → `expr` → the `keys` mapping, else the convention). Every ON site (authored joins, fan-out aggregate grouping, the `TypeBacking.joins` relation spec, joined UPDATE/DELETE) honors it and references the BOUND ALIASES, so aliased / self-joins work; `JoinDef.and` still ANDs onto whatever ON is produced. Example (the belongs-to owner): `fields: { user: { relation: { keys: [{ local: 'user_id', foreign: 'id' }] } } }` ⇒ `ON src.user_id = tgt.id` (and its inverse has-many `ON one.id = many.user_id`).
154
+ - **Search / semantic backing** — a `search`/`semantic`-flagged Type/field usually has a physical field hidden from the type system holding a precomputed `tsvector` / `pgvector`. `TypeBacking` and `FieldBacking` each take optional `search?: SearchBacking` / `semantic?: SemanticBacking` (field-level overrides type-level). Knobs (each factory takes the bound `alias` first): `vectorField` (the hidden physical field — a `SearchBacking.vectorField` emits `<alias>."f" @@ plainto_tsquery('<language>', $n)` without re-wrapping in `to_tsvector`; a `SemanticBacking.vectorField` is the left operand of the dialect's `similarity`, query vector bound as `$n::vector`), `language` (default `'english'`), `sql` (full override → boolean/numeric), `run` (runtime override), plus `SemanticBacking.vector` (row embedding source) and `embedder` (per-Type/field query embedder). Precedence (both modes): full `sql`/`run` override wins; else the hidden `vectorField`/`vector`; else the engine default. `toSQL` stays synchronous — the async embedder is never called there; a `vectorField`/`vector` query vector is a bound `$n::vector` param, and a `semantic(...)` TEXT-literal / text-param term is resolved to a pgvector-text literal from the caller's precomputed `embeddings` cache (see [SQL conversion](#sql-conversion): extract terms with `engine.semanticTexts`, embed, then `toSQL(query, dialect, { embeddings })`; a plain-text term with no/missing cache throws). The base dialect degrades (tsvector → `LIKE`, similarity → `0`) and never throws.
155
+
156
+ ## Function library
157
+
158
+ `createRegistry()` ships a default library (60+ functions across all four shapes), registered as `FunctionDef` (name + shape + **named** params + output) paired with a shape-tagged runtime. Calls use named args (`args: { paramName: <expr> }`). Register your own with `registerFunction` + `registerFunctionRun`. Introspect with `registry.functionList()`; get a promptable by-shape listing with `describeFunctions(engine)`. Every builtin `FunctionDef` carries a terse `instructions` one-liner (what it does / arg meaning / gotcha), surfaced on `QueryFunction.instructions`; the high-confusion ones also carry `examples` (RAW JSON strings, round-tripped by `QueryFunction.from` / `toJSON`) that `describeEngine` renders under the signature.
159
+
160
+ Shapes: `scalar` `(args, ctx)→value`, `tabular` `(args, ctx)→rows`, `aggregate` `(rows, ctx)→value`, `window` `(partition, index, ctx)→value/row`. All builtin names are **camelCase**; where the emitted SQL name differs it is noted. The base (ANSI) dialect degrades where noted and never throws.
161
+
162
+ **Scalar — string:** `concat`, `lower`, `upper`, `trim`, `length`, `substring`, `replace`, `trimLeft`(→`ltrim`), `trimRight`(→`rtrim`), `left`, `right`, `padLeft`(→`lpad`), `padRight`(→`rpad`), `repeat`, `reverse`, `indexOf`(→`strpos`, 1-based, 0=absent), `startsWith`(→`starts_with`), `splitPart`(→`split_part`, 1-based), `concatWs`(→`concat_ws`).
163
+
164
+ **Scalar — math:** `abs`, `ceil`, `floor`, `round`, `sqrt`, `power`, `mod`, `sign`, `exp`, `ln`, `log`(base, value), `log10`(→`log`), `trunc`, `pi()`, `degrees`, `radians`, `random()`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`(y, x).
165
+
166
+ **Scalar — conditional / other:** `coalesce`, `nullif`, `greatest`, `least`, `arrayLength`, `iif`(cond, then, else → `CASE WHEN`), `now()`, `currentDate()`(→`CURRENT_DATE`, bare).
167
+
168
+ **Scalar — date / time:** `currentTime()`, `currentTimestamp()`, `datePart(field, d)`, `year`/`month`/`day`/`hour`/`minute`/`second(d)`, `dayOfWeek(d)`(0=Sun…6=Sat), `dayOfYear(d)`, `week(d)`(ISO week), `dateAdd(field, n, d)`, `dateDiff(field, a, b)`(component difference), `dateTrunc(field, d)`, `makeDate(year, month, day)`, `dateFormat(d, format)`(→`to_char`; tokens `YYYY/MM/DD/HH24/HH/MI/SS`), `epoch(ts)`, `fromEpoch(value)`(→`to_timestamp`), `age(a, b)`(runtime = whole-day span). The selectors' `field` arg is an inline literal token (`year`/`month`/`day`/`dow`/`doy`/`week`/`hour`/`minute`/`second`/`quarter`/`isodow`/`epoch`), spliced not bound.
169
+
170
+ **Scalar — array** (Postgres-native; base degrades): `arrayContains`, `arrayAppend`, `arrayPrepend`, `arrayConcat`, `arrayIndexOf`(1-based), `arraySlice`(1-based inclusive), `arrayRemove`, `arrayDistinct`, `arrayToString`, `stringToArray`.
171
+
172
+ **Aggregate:** `count`, `sum`, `avg`, `min`, `max`, `stddev`, `variance` (both sample/n-1), `stringAgg`(→`string_agg`), `arrayAgg`(→`array_agg`; base degrades to `NULL`), `boolAnd`(→`bool_and`), `boolOr`(→`bool_or`), `countIf`(→ portable `sum(CASE WHEN … THEN 1 ELSE 0 END)`).
173
+
174
+ **An aggregate declares HOW ITS VALUES MERGE.** `FunctionDef.merge` (an `AggregateMerge`: `'sum' | 'min' | 'max' | 'and' | 'or' | 'none'`, default `'none'`, declarable only on an `aggregate` shape) says how two per-group values combine into the value over the UNION of those groups — `f(A ∪ B) = f(A) ⊕ f(B)` for every partition. Builtins: `count`/`sum`/`countIf` → `'sum'`, `min`/`max` → `'min'`/`'max'`, `boolAnd`/`boolOr` → `'and'`/`'or'`; `avg`, `stddev`, `variance`, `stringAgg`, `arrayAgg` declare NONE, deliberately — `avg` over the union needs each group's WEIGHT, which the value does not carry (adding the means or averaging them are both wrong), and the collectors need a separator/ordering. Declare it on your own aggregate and every consumer that folds groups is correct for it with no edit; declare nothing and the answer is `'none'`, which fails safe. Read the ALREADY-RESOLVED per-call answer off `ComputedResolved.aggregateMerge` rather than the raw declaration — or `mergeOfAggregateCall(declared, distinct)` to apply the rule yourself.
175
+
176
+ **Window:** `rowNumber`(→`row_number`), `rank`, `denseRank`(→`dense_rank`), `lag(value, offset?, default?)`, `lead(value, offset?, default?)`, `percentRank`(→`percent_rank`), `cumeDist`(→`cume_dist`), `ntile(n)`, `firstValue`(→`first_value`), `lastValue`(→`last_value`; full-partition frame), `nthValue`(→`nth_value`; 1-based).
177
+
178
+ **`FunctionDef.sql` is a NAME, not a template.** It replaces the emitted identifier (`log10` → `log`, `rowNumber` → `row_number`) and nothing else, so `name(arg, arg)` is the only call form a DECLARATION can produce — and it is held to the same identifier pattern as `name`, because it lands in the same raw-interpolated slot. Anything shaped otherwise, or differing BY DIALECT, is code: a `Dialect` subclass overriding `emitBuiltinCall`, which is consulted first (that is how `arrayContains` becomes `@>` on Postgres and `(1 = 0)` on base).
179
+
180
+ ### A domain vocabulary needs no new field type
181
+
182
+ A domain with its own predicates — PostGIS is the worked example — is reachable **today**, with no library change and no new `FieldTypeDef` kind: declare the domain's functions over a `{kind:'json'}` (or `text`, or `number`) column. The registry accepts any identifier-named function, `describeFunctions` puts its `instructions` in front of the model, and the SQL is dialect-native:
183
+
184
+ ```ts
185
+ registry.registerFunction({
186
+ name: 'ST_Contains', shape: 'scalar', output: { kind: 'bool' },
187
+ instructions: 'True when geometry a fully contains geometry b.',
188
+ params: [{ name: 'a', type: { kind: 'json' } }, { name: 'b', type: { kind: 'json' } }],
189
+ });
190
+ // …ST_Within, ST_Distance the same way; `shape` is a plain `{kind:'json'}` field on the Type.
191
+ ```
192
+
193
+ A SELECT filtering with `ST_Contains` and ordering by `ST_Distance` against a `:here` param emits, on the Postgres dialect:
194
+
195
+ ```sql
196
+ SELECT "parcel"."name" AS "name" FROM "parcel" AS "parcel"
197
+ WHERE ST_Contains("parcel"."shape", CAST($1 AS jsonb))
198
+ ORDER BY ST_Distance("parcel"."shape", CAST($2 AS jsonb)) ASC LIMIT 10
199
+ ```
200
+
201
+ That is valid PostGIS, and `:here` is typed `json` by the declared parameter — a param used ONLY as a function argument still reports its type through `engine.parameters` / `checkParams`. Four things a registered function CANNOT do, so you know what you are trading away — the first and third are what a REFINEMENT (below) adds:
202
+
203
+ 1. **The cast target is the BASE type's** — `CAST($1 AS jsonb)`, not `::geometry(Point,4326)`. A refinement's `sql` / `cast` fixes this, and its `ownOptions` make the target PER COLUMN (`geometry(Polygon,4326)` on one, `geometry(Point,3857)` on the next). **A VALUE reaches that cast only where its target type is known**, which is a write cell (the column's type) and a registered operator's operand (the declared operand type). Everywhere else — a document `literal` or a bound `param` as a FUNCTION argument, or in a bare `where` — it still binds through the dialect's default json cast, because `Literal/ParamExpr.toSQL` sees only the value's own shape and `engine.toSQL` runs no inference walk. There is no workaround for a function argument: casting in the function's own SQL is not expressible (`FunctionDef.sql` is a name), so use an `operator` when the cast matters.
204
+ 2. **No infix operators.** `&&` / `<->` have no call form, and `FunctionDef.sql` is a NAME, so a FUNCTION declaration can emit only `name(a, b)`. Declare an OPERATOR instead (below) — it is the mechanism for exactly this.
205
+ 3. **The domain's NAME and meaning do not reach the model beyond `instructions`** — the field still describes itself as `shape: json — A JSON document`. A refinement makes it `shape: json(as Geometry,subtype=Polygon,srid=4326) — <your instructions>`.
206
+ 4. **Meaningless comparisons are not refused.** `parcel.shape < parcel.other` is `json < json`, which is comparable. A refinement declaring `compare: { ordering: false }` refuses it — in `comparison`, `between` and `in`, and `equality: false` also refuses `array-op` containment — with the type's own instructions naming the alternative. It does NOT yet gate `ORDER BY`, grouping or set operations; `compare` below has the exact list.
207
+
208
+ ### A registered REFINEMENT names a builtin: `{ kind: <base>, as: <name> }`
209
+
210
+ `registry.registerFieldType(decl)` registers a NAME over a builtin, carrying the narrowing every use of it stands on. The wire form stays a builtin — `{ kind: 'text', as: 'uuid' }` — so `ScalarKind` never opens, `instanceof TextFieldType` and `def.kind === 'text'` stay correct for a refined column, and every exhaustiveness guard over those unions stays unreachable.
211
+
212
+ **A declaration is PURE JSON and is safe to persist and replay**; the code half (today a stricter value gate) is a separate `registerFieldTypeImpl` call. The split is the same one `FunctionDef` / `FunctionRun` has, and it is not cosmetic: a zod schema does not FAIL `JSON.stringify`, it survives as a plausible husk that passes every registration check and then throws a raw `TypeError` out of zod's internals at the first `validValue()`. Keeping a schema on the declaration would make that the default outcome of storing one.
213
+
214
+ ```ts
215
+ registry.registerFieldType({
216
+ name: 'uuid', // ^[A-Za-z][A-Za-z0-9_]*$ — capitals allowed
217
+ base: 'text', // any ScalarKind except `relation`
218
+ instructions: 'A UUID (RFC 4122) — lower-case, hyphenated, 36 characters.', // REQUIRED
219
+ options: { minLength: 36, maxLength: 36, casing: 'exact' }, // the BASE's own vocabulary
220
+ sql: { postgres: 'uuid' }, // per-dialect CAST TARGET; `{slot}` = a declared option
221
+ avgBytes: 16, // the base's estimate is wrong for this
222
+ });
223
+ registry.registerFieldTypeImpl('uuid', { value: z.uuid() }); // the CODE half — never persisted
224
+ // then, on any Type: { name: 'id', type: { kind: 'text', as: 'uuid' } }
225
+ ```
226
+
227
+ - **NARROWING, NEVER WIDENING.** The declared `options` are the FLOOR: a use site's own options are MET with them, so a site may narrow further, a site that tries to loosen is ABSORBED (the meet is a lower bound of both), and a site that contradicts is REFUSED (`field-type.refinement-conflict`). An unregistered `as` is refused too (`field-type.unknown-refinement`, with a `didYouMean`) — never silently degraded to the bare base, which would take the narrowing with it. `as` merges through the SAME flat `meetExact` every single-valued option uses: a registered name meets only itself, an unrefined base is TOP (`uuid ⊓ text = uuid`), and two refinements of one base conflict. **There is no new lattice law** — commutativity, associativity, idempotence, soundness and `x ⊓ ⊤ = x` are property-tested over refined shapes (one per refinable base, both sides of both cross-kind families, a closed-set one, a narrowed one, a refined array element) alongside the builtins, with no carve-out.
228
+ - **A meet that leaves the refinement's BASE KIND drops to no meet.** `number`↔`money` and `date`↔`timestamp` meet across kinds, answering with whichever side is more specific — so `money{as:'Usd'} ⊓ number` is still a money and keeps its name, while `number{as:'Score'} ⊓ money` is a MONEY and cannot carry one. It is checked on the RESULT, not on the operands: refusing whenever the operands' kinds differ is not associative (`money ⊓ number` is a money, so the two groupings of `Usd ⊓ money ⊓ number` would disagree). Dropping the tag instead of refusing would be unsound — it drops the refinement's stricter value gate.
229
+ - **Two DIFFERENT compilations of one name do not meet.** Names are per-registry, so a type from registry A and one from registry B can both say `as: 'uuid'` and mean different things. The meet operates on the compiled instances, not the names, so that is a conflict rather than "whichever operand was on the left".
230
+ - **The measured win.** A catalog declaring `id: { kind: 'text' }` at ~40 sites emits `LOWER("t"."id") = LOWER($1)` on every id predicate — not sargable, and a hard `function lower(uuid) does not exist` over a physical uuid column. One `uuid` refinement declaring `casing: 'exact'` turns all forty into a bare `=`, from one declaration site, through the ordinary meet rather than a new rule.
231
+ - **What the model sees.** The type tag becomes `id: text(as uuid)` — the refinement FIRST, then the base's own flags (`text(as uuid,search)`) — the generated description is the declaration's `instructions`, and the generated def schema renders `as` as a **`z.enum` of the names registered over that base**, so a model cannot invent `as: 'uuid4'`. The `as ` prefix disambiguates: `money(Usd,USD)` gives a model no way to tell which token is the refinement and which the currency, and the prefix also names the key it has to write. The NAME renders VERBATIM: never lower-cased, never pluralised, never decorated, because a model reads this surface and a sibling type system's in one session and a spelling difference between them reads as two types. `fieldTypeDefSchema(opts)` / `Type.toSchema(opts)` need `opts.registry` for that; a base with NO registrations REFUSES an `as` rather than stripping it, because the normal pipeline is `Tool.parse` → `engine.parseType(result)` and `parseType` never sees the raw def.
232
+ - **SQL.** `Dialect.sqlTypeFor` answers the refinement's `sql` for that dialect; a dialect with no entry falls back to the base kind's own mapping — a FALLBACK, not a degrade, because the base's answer is a real answer for a value of the base type. `cast` (which must place `{value}`) replaces the wrapper a bound DOCUMENT is cast with (`ST_GeomFromGeoJSON($1)::geometry`), and is likewise optional per dialect — but it is **declarable only on a `json` or `array` base**, because `Dialect.jsonValue` is the only road that reaches a cast template and a scalar predicate binds its value directly. A `cast` on a `text` base is REFUSED rather than accepted-and-inert. Both templates are validated at REGISTRATION: a `{slot}` must name a declared option whose value is a bare identifier/number token — they are raw-interpolated, so the values spliced into them are the injection surface — and a resolved `sql` must look like a SQL type name.
233
+ - **Registration is all-or-nothing**, because a refinement that registered half-broken would be wrong on every column that ever named it. `base` is a `ScalarKind` other than `relation` (a relation carries an IDENTITY and a cardinality ESTIMATE, neither of which is a constraint a name can narrow — refine what it points at instead); the name matches the pattern, is not a builtin `kind`, and is not already registered (the second declarer is REFUSED, naming the incumbent's `declaredBy`); `options` parse as a def of the base kind, with that road's own message; `avgBytes > 0`; and `instructions` is non-empty and REQUIRED — deliberately stricter than `FunctionDef.instructions`, because an undocumented registered type renders as a bare tag beside documented siblings and a model choosing among them guesses, which costs a validate-fail retry carrying the whole schema. `registerFieldTypeImpl` refuses an unknown name, a second impl, and a `value` that is not a zod schema. Every failure is a `QueryTypeError` (`field-type.bad-refinement`).
234
+ - **Ordering is ENFORCED, not advised.** `registerFieldType` / `registerFieldTypeImpl` are REFUSED (`field-type.late-refinement`) once that registry has built a FIELD TYPE — through `parseType`, `registerType`, `parseFieldType`, `Type.from`, or a declared function parameter, all of which route through the same parse. A stored `as` resolves against the registry as it stood at parse time, so a late registration would leave every already-built column carrying the un-narrowed base — with the `LOWER()` back and the tag still reading `text` — and a late IMPL is worse still, because it attaches to the compiled refinement every such column SHARES and retroactively changes what they validate against. It is the one failure in this design that would otherwise be silent.
235
+ - **An unknown declaration key is REFUSED, not ignored.** TypeScript's excess-property check only fires on an inline literal, so `registerFieldType(JSON.parse(stored) as FieldTypeRefinementDef)` would otherwise type-check and silently drop whatever it did not recognise — the same dead-gate end state the impl split exists to prevent, reached from the other side. A key that MOVED (`value`) is refused by name, with its new home.
236
+ - **THE IN-MEMORY HALF: `compareValues`.** A refinement's SQL half is its `sql` / `cast` declaration, and the DATABASE performs the ordering that follows from it; its in-memory half is `registerFieldTypeImpl`'s `compareValues`, which `Value.compareTo` consults before its own rules (numbers numerically, booleans false-first, EVERYTHING ELSE by `String(raw)`). Without it a type whose stored SQL type orders differently from its stringified form answers **two different things for one query**, decided by whether you ran it or emitted it — `{ base:'text', sql:{postgres:'inet'} }` holding `10.0.0.2` and `10.0.0.10` orders them by address at the database and lexicographically here. It **governs equality too** (`Value.equals` / `identical` are `compareTo(...) === 0`, so one comparator keeps the two from contradicting each other; there is no separate `equalValues` because a btree operator class requires its `=` and `<` to be consistent, and the corollary is that a type whose equality is FINER than its ordering must tie-break inside the comparator or its `ORDER BY` is undefined on both roads), it **out-ranks case folding on BOTH roads** — `compareToCase` skips its fold and `comparisonCasing` suppresses the emitted `LOWER()`, for `= <> < <= > >=` and **not** for the LIKE family (`compareValues` is an ORDER; `like` is a text pattern match, so it keeps folding per `casing` in run and in SQL alike) — and **NULL is decided before it** (placement belongs to the SORT, so a comparator is never handed one). It is asked about values that are NOT of your type — a sort key, a `min()`, every predicate — so it must ANSWER for them: a `NaN` or non-numeric answer reads as "equal" rather than corrupting a sort, a THROW is not caught, and `checkFieldType` property-tests reflexivity, antisymmetry, transitivity and totality over your `samples`. `differentialCheck` settles the one question neither it nor registration can — whether it agrees with the database.
237
+ - **WHAT A COMPARATOR DOES NOT REACH.** `DISTINCT`, `GROUP BY`, an aggregate's `DISTINCT` and the set operations key on the RAW value's JSON (`runtime/record.ts` `recordSignature`, which takes a `SourceRecord` and has no `FieldType` in scope — a whole ROW's identity is not a question one column's type answers). So a comparator whose equality is COARSER than raw identity calls two values the same under `WHERE a = b` while `SELECT DISTINCT` keeps them apart — and a database whose column type agrees with the comparator collapses them, so the two roads disagree. A comparator that only RE-ORDERS (an `inet`, a semver) has identical equality and is unaffected. `checkFieldType` warns when a declaration's comparator merges two values it admits (`conformance.comparator-coarser-than-identity`); `differentialCheck`'s `distinct` / `group by` probes settle it against a real column type.
238
+ - **A `text` refinement with a comparator must declare `casing: 'exact'`, and `'collated'` is the one casing that cannot agree with one.** The comparator governs the comparison arms; `like` / `notLike` / `ilike`, `text-search`, `text-score` and array-element containment fold per `casing`, which is the ENGINE default unless narrowed — so one column answers two case policies depending on the operator. `checkFieldType` warns for any casing other than `'exact'` (`conformance.comparator-without-casing`), declared or not. **`'collated'` is a run-vs-SQL DIVERGENCE, not a second answer**: it claims the STORE folds, so this package emits a bare `=` (it never emits `LOWER()` for it) that the folding store matches — while `Value.compareToCase` stops folding the moment a comparator is in effect. Measured on a `text as Tag` holding `V1.2.3`, predicate `tag = 'v1.2.3'`: same SQL either way, `run=[{"id":1}]` without the comparator and `run=[]` with it, against a row the database returns. If the split is deliberate, drop the COMPARATOR rather than the casing.
239
+ - **A COMPUTED value carries its callable's declared output type**, so the same comparator applies to `ORDER BY (a <-> b)` as to `ORDER BY parcel.distance`. The four scalar-valued dispatch helpers tag their result with the registered function's / operator's declared `output`; a function declaring `'inferred'` or a Type reference carries none (there is no declared type to carry), and a TABULAR function's value is its ROWS rather than a value of its output type, so it is not tagged. That channel carries a declared `casing` as well as a comparator, and the SQL road reads a computed operand's type for the same reason — so a `casing` declared on an output governs both roads.
240
+ - **Enumerating what a registry knows.** `registry.fieldTypeKinds()` lists the registered builtin kinds; `fieldTypeRefinement(name)` / `fieldTypeRefinementList()` / `fieldTypeRefinementNames()` list the refinements; `fieldTypeComparabilityNotes()` returns the `warn`-grade notes symmetrization filed. `REFINABLE_BASES` is the set a `base` may name.
241
+
242
+ ### A refinement's OWN options: `ownOptions` + a column's `with` bag
243
+
244
+ The base's vocabulary cannot say `srid`. `ownOptions` declares options the base has never heard of, each typed by an ordinary `FieldTypeDef` — so validation, the model-facing description and the JSON round-trip all come from machinery that already exists — and a column supplies them in a `with` bag.
245
+
246
+ ```ts
247
+ registry.registerFieldType({
248
+ name: 'Geometry', base: 'json',
249
+ instructions: 'A PostGIS geometry, carried as GeoJSON. Compare with ST_Contains / ST_Within, or order by ST_Distance; `<` and LIKE are not defined on one.',
250
+ ownOptions: {
251
+ subtype: { type: { kind: 'text', values: [{ value: 'Point' }, { value: 'Polygon' }] }, default: 'Point', docs: 'The subtype this column holds.' },
252
+ srid: { type: { kind: 'number', whole: true }, default: 4326 },
253
+ },
254
+ sql: { postgres: 'geometry({subtype},{srid})' },
255
+ cast: { postgres: 'ST_GeomFromGeoJSON({value})' }, // position-INDEPENDENT: no option slots
256
+ compare: { equality: true, ordering: false, textMatch: false },
257
+ comparableWith: ['Geography'],
258
+ avgBytes: 96,
259
+ });
260
+ // on a Type: { name: 'shape', type: { kind: 'json', as: 'Geometry', with: { subtype: 'Polygon', srid: 4326 } } }
261
+ // → postgres CAST target `geometry(Polygon,4326)`; a sibling column declaring
262
+ // `{ subtype: 'Point', srid: 3857 }` gets `geometry(Point,3857)`, from ONE declaration.
263
+ ```
264
+
265
+ - **TWO BAGS, DELIBERATELY.** `options` narrows the BASE's vocabulary; `ownOptions` declares new ones and a column writes them under `with`. Merging them would make a `{maxLength}` slot ambiguous between the base's option and a refinement's, and would force the strictly-parsed branch schemas open — after which a typo'd base option would be read as somebody's custom one. An `ownOptions` name colliding with a declared base option is REFUSED, and so is `value` (a `cast` puts the bound value there).
266
+ - **A `{slot}` now resolves at TWO different times.** A base-option slot still resolves at REGISTRATION (those are constants). An `ownOptions` slot resolves PER COLUMN, from that column's `with` bag or the option's declared `default`. `Dialect.sqlTypeFor` / `jsonValue` therefore ask the FIELD TYPE (`refinedSqlType` / `refinedCast`), not the refinement, because the column is the only thing holding both halves. A dialect with no entry still falls back to the base's answer.
267
+ - **A DEFAULT is resolved on READ, never materialized into the bag.** That is what leaves room to narrow: a column that said nothing carries no value at all, so it MEETS a column that said `Polygon` instead of conflicting with the default. It also keeps an existing def byte-identical — a column naming no options serializes with no `with` key.
268
+ - **They meet through the flat `meetExact` lattice, per key.** Unset is TOP, equal keeps, and two DIFFERENT values conflict — there is no third SRID that is both 4326 and 3857, exactly as there is no third `pattern` that is both `^a` and `^b`. So "narrow, never widen" reads here as *a use may SET an option the declaration left open, and may not contradict another use*. The merged bag's keys are SORTED, because `meet` compares two types by their serialized form. **No new law**: the same laws the builtins are held to pass over a set carrying every arm of this (unset, one set, both set, a sibling differing in one), with no carve-out.
269
+ - **THE INJECTION SURFACE MOVED, so the check did.** Through step 1 a template slot's value was a declared CONSTANT, checkable once. An `ownOptions` value is the COLUMN AUTHOR's, so three things replace that one check: (1) an option any template interpolates must have a **CLOSED declared type** — a `values` set whose members are all bare tokens, a `bool`, or a `number` with `whole: true` — and must declare a `default`, so the template resolves for every column; (2) the template is validated against **PROBE tokens** (`a`, `_`, `0`) rather than one resolved string, so `{srid}_geom` is refused at the DECLARATION rather than on the one column that writes a number there; (3) each column's actual value is re-checked as a bare token at PARSE. Together they make emission total — no reachable value can produce a token the templates were not checked for.
270
+ - **A column's bag is checked where the def is read.** An option the type does not declare is REFUSED (`field-type.unknown-option`, with a `didYouMean`), a value its declared type refuses is REFUSED (`field-type.bad-option`, naming the members), and a `with` with no `as` is refused too. The generated def schema offers `with` as a **strict** object keyed by every option registered over that base, each rendered as its own declared type's value schema, so a model cannot invent a member — and a base where no refinement declares options refuses a `with` rather than stripping it.
271
+ - **What the model sees.** `shape: json(as Geometry,subtype=Polygon,srid=4326)` — EFFECTIVE values, so a defaulted column reads with the defaults rather than blank. The SRID a column is stored under is a fact about it either way, and a model shown nothing has no way to know which one it is writing against.
272
+
273
+ ### `compare` — which arms of the builtin PREDICATE grammar apply
274
+
275
+ ```ts
276
+ compare: { equality: true, ordering: false, textMatch: false } // every arm defaults to `true`
277
+ ```
278
+
279
+ **WHERE IT IS ENFORCED, EXACTLY.** "Which arms of the grammar apply" does not say where, so here is the list rather than a slogan. **Enforced** on `comparison` (which also covers a join `on` and a `CASE WHEN`), `between`, `in` (list and subquery), and `array-op` containment (`contains` / `containsAny` / `containsAll`). **Not enforced**, all measured as emitting over a column whose type refuses the relevant arm:
280
+
281
+ | construct | emits | why not gated (yet) |
282
+ |---|---|---|
283
+ | `ORDER BY <column>` | `ORDER BY "t"."shape" ASC` | a sort over an unordered type is *deterministic nonsense* — a stable answer nobody asked for — where an unordered PREDICATE is worse, since its truth is a storage-format detail. And the gate must keep `ORDER BY ST_Distance(shape, :here)` working, so it belongs on a bare COLUMN REFERENCE in a sort position, not on the sort position. Not designed. |
284
+ | `min` / `max`, window `ORDER BY` | ordering, by another name | same answer as the row above, and it has to be one answer |
285
+ | `SELECT DISTINCT`, `GROUP BY`, window `PARTITION BY` | equality over rows | neither predicate nor sort — grouping is equality used to BUCKET rather than to filter, and whether a type that refuses `=` may still be grouped is a real question, not an oversight |
286
+ | `UNION` / `INTERSECT` / `EXCEPT` | row equality (the latter two compare rows) | same question as grouping, one level up |
287
+ | `text-search` | `to_tsvector(tok) @@ plainto_tsquery($1)` | `textMatch: false` refuses `LIKE` and not this; full-text matching is arguably a different capability from pattern matching, and `search: true` is already its own opt-in |
288
+
289
+ `array-op` containment is gated because **`contains` is `IN` with a different keyword** — it emits a literal `$1 = ANY("t"."list")`. `isEmpty` / `notEmpty` are deliberately NOT gated: they emit `cardinality(…) = 0`, which compares a COUNT and never an element, so a type that cannot be compared can still be asked whether there is one. Both refinement positions are checked — a refined ARRAY (`{kind:'array', as:'BlobList'}`) and an array of a refined ITEM (`array<json as Geometry>`) are two different places for the tag to sit.
290
+
291
+ `ComparisonOp` is a CLOSED nine-member union (`= <> < <= > >= like notLike ilike`) and it stays closed: a type does not ADD an operator, it says which of the nine mean anything for it. `ordering: false` refuses `< <= > >=` **and `BETWEEN`**, which is `>=` and `<=`; `textMatch: false` refuses the LIKE family (already gated by the operand's category being text, so it narrows a `text` refinement and is moot for the other eight bases); `equality: false` refuses `=` / `<>` **and `IN`**, which is a disjunction of `=`. All three predicates share ONE gate, keyed by ARM rather than by operator — keyed by operator it was reachable only from `comparison`, and a model refused at `shape < :p` got the SQL it was refused by writing `shape BETWEEN :p AND :q` instead.
292
+
293
+ ```
294
+ where[0] comparison.type
295
+ Cannot order `Geometry` values with '<': the type declares no ordering (`compare.ordering: false`).
296
+ Geometry — A PostGIS geometry, carried as GeoJSON. Compare with ST_Contains / ST_Within, or order
297
+ by ST_Distance; `<` and LIKE are not defined on one.
298
+ ```
299
+
300
+ The refusal quotes the type's own `instructions`, because a bare refusal costs the retry it was meant to prevent — the model then has to GUESS what to reach for, and the declaration is the one place that knows. **Neither operand is exempt**, unlike the comparability check which excuses a bare param: the fact belongs to the COLUMN's declared type and holds whatever it is compared to, so `shape < :p` is refused exactly as `shape < other.shape` is.
301
+
302
+ **`compare` gates the GRAMMAR, never the LATTICE.** A type declaring every arm `false` still meets exactly like any other (`Opaque ⊓ text = Opaque`). Tying the two together is the tempting simplification and it would owe `x ⊓ ⊤ = x` a carve-out on the first such type.
303
+
304
+ ### `comparableWith` — compatibility as a declared relation
305
+
306
+ ```ts
307
+ comparableWith: ['Geography'] // OTHER registered names this type may be compared with
308
+ ```
309
+
310
+ The declared form of the hardcoded `number`/`money` and `date`/`timestamp` families. **THE REGISTRY SYMMETRIZES IT**: naming a type that does not name you back records the edge in BOTH directions and files a `warn`-grade note (`registry.fieldTypeComparabilityNotes()`, code `field-type.one-sided-comparability`), so commutativity is structural rather than the declarer's discipline — and a name may be declared BEFORE the type it names is registered, which a mutual pair otherwise makes impossible. An edge naming something that never registers is simply inert.
311
+
312
+ **It only ever GROWS the relation, and that is load-bearing rather than a simplification.** `meet` implies `comparableWith` (a property test asserts it over every pair), so a declaration that could REMOVE an edge would have to remove the corresponding meet with it — and the meet a restriction would have to remove is `refinement ⊓ its own unrefined base`, i.e. the `x ⊓ ⊤ = x` identity. One declaration would then owe the lattice a carve-out. Growing it owes nothing. Correspondingly, **a declared edge does NOT create a meet**: `Geometry ⊓ Geography` is still no meet, because a registered name meets only itself. Comparable-and-un-meetable is an existing, real state (two disjoint closed sets are the builtin example), and keeping it is what lets the relation be NON-TRANSITIVE — `Meters` and `Feet` may each be comparable with `Number` without being comparable with each other.
313
+
314
+ ### A registered OPERATOR: `&&`, `<->`, `@>` — SQL a DECLARATION supplies, per dialect
315
+
316
+ `registerFunction` covers everything shaped `name(a, b)`. It cannot express the other half of a real SQL domain: the INFIX operators, which have no call form in any dialect, and whose SQL differs BY dialect — `FunctionDef.sql` is a NAME, never a template. `registry.registerOperator(decl)` is that half.
317
+
318
+ ```ts
319
+ registry.registerOperator({
320
+ name: '&&', // SQL operator punctuation ONLY (see below)
321
+ operands: [{ name: 'left', type: { kind: 'json', as: 'Geometry' } },
322
+ { name: 'right', type: { kind: 'json', as: 'Geometry' } }],
323
+ output: { kind: 'bool' }, // CONCRETE — never 'inferred'
324
+ instructions: 'Bounding-box overlap between two geometries. Cheap and GiST-index-assisted; use it as a pre-filter before an exact ST_Contains.', // REQUIRED
325
+ emit: { postgres: '({left} && {right})' }, // per `Dialect.name`; PARENTHESIZED
326
+ selectivity: 0.1, // WHERE fraction kept (default 1)
327
+ cost: { rows: 0, bytes: 0 }, // intrinsic per-call cost (default none)
328
+ examples: [ /* raw JSON strings, rendered under the signature */ ],
329
+ });
330
+ registry.registerOperatorRun('&&', (args, ctx) => Value.of(bboxOverlaps(args.left, args.right)));
331
+ ```
332
+
333
+ ```jsonc
334
+ { "kind": "operator", "op": "&&",
335
+ "args": { "left": { "kind": "field-ref", "source": "parcel", "field": "shape" },
336
+ "right": { "kind": "param", "name": "box" } } }
337
+ ```
338
+ ```sql
339
+ WHERE ("parcel"."shape" && ST_GeomFromGeoJSON($1))
340
+ ```
341
+
342
+ That is the emitted SQL verbatim, asserted by a test. **The operand's DECLARED type reaches emission**, so a document operand — a `literal`, or a param bound to one — binds through that type's own `cast` template instead of the dialect's default `CAST($1 AS jsonb)`, which Postgres refuses outright (`operator does not exist: geometry && jsonb`).
343
+
344
+ **A VALUE POSITION MAY ONLY ASSERT WHAT ITS DECLARATION WROTE**, which is why there is no typmod there. An operand is not a column: `{kind:'json', as:'Geometry'}` says "any geometry", so resolving the cast's `{subtype}` / `{srid}` from the refinement's DEFAULTS would pin a constraint the value never had to satisfy — and PostGIS then rejects a Polygon cast to `::geometry(Point,4326)`, on the NORMAL case, since `&&` is a bounding-box pre-filter. So an operand's cast resolves ONLY from the operand's own `with` bag; a cast interpolating an option the operand did not write is REFUSED at emit (`cast.unwritten-option`), naming both remedies: declare a `cast` that interpolates no option (one that says only "this IS a Geometry" — what a value position can honestly assert, and what the example above does), or write the options in the operand's own `with`, which makes the typmod a constraint you actually declared. A COLUMN is unaffected and still resolves from its own bag ELSE the declared default: a default is a fact about that column. The rule lives in `Dialect.jsonValue(value, fieldType?, site?)`, not at the operand, because a dialect binding a NATIVE array re-enters it per ELEMENT — so a rule checked once at the operand was skipped for everything inside an `array<json as …>` — and `ValueSite` carries the OPERATOR as well as the operand, so the refusal names the declaration to fix. `checkOperator` reports the same thing at the DECLARATION (`conformance.unwritable-operand-cast`, a warning, since the refusal fires only for a document operand), which is where you want to hear it rather than at the first query that binds one.
345
+
346
+ It is the same rule the model-facing renderer follows for an operand tag — show only what the declaration wrote. **One rule, two surfaces.**
347
+
348
+ **ONE new expr kind, not N registered Expr classes.** `ExprKind` gained exactly one member, once, at this package's own hand; the operator VOCABULARY is what a third party opens — precisely the relationship `function-call` has to `registerFunction`. The alternative, `defineExpr`, is parse DISPATCH for a whole `ExprDef.kind` (registering one re-points every program's parse in that registry) and asks a declarer for ten members where a function author writes one JSON object.
349
+
350
+ **The declaration is pure JSON and safe to persist and replay**; the `run` half is a separate `registerOperatorRun` call, exactly as `FunctionRun` sits beside `FunctionDef`. An operator with an `emit` and no `run` is a SQL-ROAD operator — a legitimate shape, and the same position `semantic` and `text-search` are in.
351
+
352
+ **A missing `run` REFUSES (`operator.no-run`) rather than answering `Value.null()`**, which is the one place this package's "a missing run answers NULL" rule does not apply. Two measured reasons, both about the asymmetry with a function: `emit` is REQUIRED while `run` is OPTIONAL, so an operator is far more likely to lack one; and an operator is usually a PREDICATE, where NULL is UNKNOWN for every row — so the query returns ZERO ROWS and looks exactly like one that ran. That is precisely the failure an unsupported dialect is refused for, and refusing it on one road while producing it on the other would be incoherent. Evaluate through `engine.toSQL`, or register a run.
353
+
354
+ **Operands are NAMED, and the arity is fixed.** `args` are keyed by the declared operand name (a positional list is the shape a model most reliably gets wrong), and there is no `optional`: the emit template names every operand, so a template that could drop one would emit a dangling `&&`. A bare bind param as an operand is TYPED BY the declaration (`shape && :box` types `:box` as the operand's declared type) — the same road a function argument takes, and order-independently. Calls report `operator.missing-arg` / `operator.unknown-arg` / `operator.arg-type`.
355
+
356
+ **`name` is SQL OPERATOR PUNCTUATION, and nothing an identifier could be** — `^[+\-*/<>=~!@#%^&|`?]{1,63}$`, which is the charset PostgreSQL's own `CREATE OPERATOR` allows (63 = `NAMEDATALEN - 1`). It is deliberately DISJOINT from `FUNCTION_NAME_PATTERN`, so one spelling can never mean two callables and a model reading the catalog can never wonder whether `overlaps` is the operator or the function. A WORD operator (`OVERLAPS`, `IS DISTINCT FROM`) is spelled either as a function or as the literal text of an emit template under a punctuation name. A comment opener (`--`, `/*`, `*/`) is refused separately in a name and in every template, because it is made of that same punctuation: `&&--` matches the charset exactly. In a TEMPLATE that comments out the rest of the emitted query; in a NAME it is defence-in-depth rather than a live hole — the name itself never reaches emitted SQL (`OperatorExpr.toSQL` emits template parts and operand fragments only), but a declarer writing the template pastes the name into it, and a rule that holds in one place and not the other is the kind nobody remembers.
357
+
358
+ **An `emit` template is checked at the DECLARATION, five ways.** Its slots are filled with already-emitted SQL fragments, not author values, so unlike a refinement's `sql`/`cast` there is no VALUE injection surface — what is guarded is the template BODY, and it is a name-and-shape gate rather than a sandbox:
359
+
360
+ 1. every `{slot}` names a declared operand (with a `didYouMean`);
361
+ 2. every declared operand appears at least once — a dropped operand is an argument the query supplied, validation type-checked and emission discarded;
362
+ 3. the template is **wrapped in its own balanced parentheses**. This is what makes a `precedence` declaration unnecessary rather than merely unread: a parenthesized fragment composes correctly inside ANY surrounding expression, so no declaration can be wrong about binding. A function-shaped emission is written with the redundant pair — `(ST_Intersects({left}, {right}))`;
363
+ 4. no comment sequence and no `;` — both silently swallow the rest of the emitted query;
364
+ 5. balanced parens, and an EVEN number of `'` quotes.
365
+
366
+ **A dialect with no `emit` entry is REFUSED at emit** (`operator.unsupported-dialect`), naming the dialects that ARE declared. That is deliberately unlike `BaseDialect.emitBuiltinCall`, which degrades silently for BUILTINS (`dateAdd` → the input date unchanged, `arrayContains` → `(1 = 0)`): a builtin's degrade is portable-SQL policy for a function whose semantics this package owns, documents and tests, and a third party cannot document a degrade this package never sees. `&&` degrading to `(1 = 0)` returns ZERO ROWS for a query the caller believed ran — a wrong answer that looks exactly like a right one.
367
+
368
+ **Operators and a type's declared `compare` are DISJOINT, deliberately.** `compare` says which arms of the CLOSED builtin comparison grammar apply to a type; an operator is not one of the nine — it declares its own operands and its own meaning. So a type declaring `equality: false` is exactly the type an operator is FOR: `Geometry` refuses `=` because comparing two geometries for equality is meaningless, and `&&` is what you reach for instead. Gating operators on `compare` would delete the mechanism that makes an honest declaration usable.
369
+
370
+ **A CONSEQUENCE worth knowing: an operator can RECONSTRUCT a refused arm.** Nothing stops you registering an operator NAMED `=` over a type declaring `equality: false` — it validates clean while the builtin `=` over the same column is refused. That is intended (your `=` means what you say it means, not what the builtin would have meant), but the two facts land in ONE catalog with nothing saying which wins: `describeTypes` prints `no =` on the column and `describeOperators` offers a `=` over it. Say in the operator's `instructions` how yours differs; `checkOperator` warns (`conformance.shadows-refused-arm`) when a name spells a builtin comparison token over an operand refusing that arm.
371
+
372
+ **What the model is told.** `describeOperators(engine)` renders an `operators:` block (and `describeEngine` includes it whenever any operator is registered, omitting it entirely otherwise) with each signature, its operand tags — the FULL ones, carrying the registered name, the declared options and the refused comparison arms — its result type, its `instructions` and its examples. In the generated schema, `op` is a `z.enum` of the registered names with that glossary inline (at `functions:'names'`), and each operator gets a STRICT operand object at `functions:'typed'`. The `operator` KIND is capability-gated out entirely unless some registered operator has an operand type an in-scope field could supply, so a geometry-free deployment carries no dead branch.
373
+
374
+ **Three things `OperatorDef` deliberately does NOT carry**, each refused at registration with the reason rather than as "unknown key": `precedence` (emission is always parenthesized and `toCode()` renders the wire shape `&&(left: …, right: …)`, so nothing would read it), `indexed` (the cost model's index probe means "bound to N POINT values", so crediting a bounding-box overlap would claim a prefix reduction that does not apply — declare `selectivity`), and `changes` (`QueryReferences` enumerates FUNCTIONS and has no operator channel, so a declared value would be silently ignored — which means `changeInterval` systematically OVER-estimates freshness for a query whose only volatile input sits behind an operator; adding the channel changes a public result shape, so it waits).
375
+
376
+ `checkOperator(decl, { registry })` from `@aeye/query/conformance` adds what registration cannot check: that every declared dialect is actually REGISTERED, that every shipped `examples` string parses and is a use of THIS operator with THIS operator's operand names, and the shadowed-arm warning above. It also re-runs the lattice laws over the operand / output types, which must be unchanged — an operator is a leaf and perturbs nothing.
377
+
378
+ **Why the dialect KEY is not checked at registration**, given everything else is. An `emit` key is an arbitrary string BY NECESSITY: a dialect may be registered after an operator (`defineDialect` is public and order-free), so refusing an unknown key at registration would make the two order-coupled for no reason — which is the same argument that keeps the operand types on the registry's unflagged parse road. Everything an operator can be judged on ALONE is refused at its declaration; a dialect key can only be judged against a registry that is finished, which is what a conformance run is. The cost is real and worth stating: `{ postgress: … }` registers cleanly, describes itself normally, and is refused at emit on every dialect that exists.
379
+
380
+ ### `@aeye/query/conformance` — run the builtins' own property tests on YOUR declaration
381
+
382
+ ```ts
383
+ import { checkFieldType } from '@aeye/query/conformance';
384
+
385
+ const report = checkFieldType(geometryDecl, { value: geoJsonSchema, samples: [aRealPoint] });
386
+ expect(report.problems).toEqual([]);
387
+ ```
388
+
389
+ A declarer cannot break the lattice by writing CODE — the library compiles the meet from the declaration. What a declarer CAN do is declare a shape whose consequences they did not follow through, and none of that is detectable at registration because each declaration is individually legal; it is only visible as a PROPERTY over a set of types. So the property runner ships rather than the properties being described.
390
+
391
+ - `checkOperator(decl, { registry? })` does the same for an OPERATOR declaration — see the section above for the three checks that are specific to one.
392
+ - `checkFieldType(decl, impl?)` registers `decl` in a fresh registry alongside a PEER refinement over the same base, builds a column per value of each declared option plus the unrefined top of every refinable kind, and runs every law over that set. It returns `Problem[]` — nothing throws.
393
+ - `checkLatticeLaws(types, { registry?, samples?, tops? })` is the runner itself, over any type set you hand it: **commutative, idempotent, associative, top-identity, meet-implies-comparable, sound**, plus **refinement-base** (a surviving `as` is on its own base kind), **refinement-instance** (it came from an OPERAND, not from a name), **round-trip** (every type and every meet re-parses to itself on the registry that produced it) and **total** (nothing throws — a defect is reported, never raised). `param-meet.test.ts` runs this same function over the widest type set in the package, so the export is exercised against a correct implementation on every run of this package's suite.
394
+ - With an `impl.value`, two cross-library checks: the gate must AGREE with the declared base bucket (a value only the gate accepts can never reach a column, and the disagreement means the bucket and the contract describe different types) and must not be VACUOUS (`z.any()` is what an unresolved schema degrades to, and it degrades silently). **Pass `samples`** — the default corpus spans JSON shapes and cannot guess what a well-formed value of your type looks like.
395
+ - It cannot tell whether the emitted SQL MEANS what you intended. That needs a live connection and belongs in your integration suite.
396
+ - `differentialCheck({ engine, dialect, execute, columns, operators?, functions? })` is the half of that a harness CAN do: it runs every probe both ways — `engine.run` and your database — and reports where they differ, which is the one failure mode nothing static can detect (a `run` that disagrees with the SQL). It probes ORDER BY in both directions, `DISTINCT` and `GROUP BY` (the roads a comparator is NOT wired into — see above), every comparison arm the type admits, and each named operator / function. **Every probe is validated by `engine.validateQuery` before it is emitted**, so a statement this package calls invalid is never sent to your server and filed as a divergence — `like` over a `json` column is `comparison.like`, which no `compare` declaration mentions. Those land in `report.unprobeable` (label + codes) and warn only when YOU named the probe. The ORDER probes compare the SEQUENCE; every other probe compares a sorted MULTISET, so a tie in the driving column is not read as a disagreement (`DifferentialProbe.comparison` says which). **Every probe is driven from COLUMNS** (`columns: { type, field, other? }`) and never from a bound sample: a bound value reaches a declared `cast` only in a write cell or an operator operand, so samples would report that known limit for every type on every run — seed the values you care about into the table instead, where every road types them. **`columns.other` must be the SAME field type as `columns.field`** — one of a different kind makes every arm illegal, and the report used to read `ok: true` with nothing compared; every arm refused **over two columns whose types differ** is now `conformance.differential-no-arms`. The MISMATCH is the signal, not the count: a SAME-type pairing that refuses every arm it enumerated is a correct declaration, not a finding — a `json` refinement declaring `compare: { equality: false, ordering: false, textMatch: true }` enumerates only the three arms its kind refuses, and a has-many `relation` pair refuses all nine with no declaration at all — so those refusals are recorded in `report.unprobeable` alone and `ok` stays true. `execute: (sql, params) => rows` is a callback because this package has no driver — and its rows are `unknown`-valued, deliberately: `pg` deserialises `timestamptz` to a `Date`, `numeric` and `bigint` to STRINGS and `bytea` to a `Buffer`, none of which are this package's JSON model, so register the type parsers that match it (`pg.types.setTypeParser(1700, Number)`) or project a text form, or a driver artifact reads as a divergence of your type. Measured, the artifacts that actually FIRE are `numeric` (`"1.5"` vs `1.5`) and `bytea` (a `Buffer`'s JSON vs a string); a `Date` renders byte-identically to its ISO string through `JSON.stringify` and agrees on every probe, so it is not the example to reach for. **Your engine's executor for that Type must hold the SAME rows the table does**, which is its one unverifiable premise. It needs a live connection, so it belongs in your integration suite (this package keeps its own harness in `integration/`, outside `npm test`, for exactly that reason) and nothing in this package's suite runs it against a database.
397
+ - The subpath and `@aeye/query` resolve to the SAME bundle. Prefer the subpath — it names what the surface is for — but know it is one artifact. A second SELF-CONTAINED bundle is disqualifying and measured: each entry gets its own copy of every class, so `instanceof ArrayFieldType` is false across them, a consumer's `array` type met against the harness's own `array` top answers `undefined`, and the harness reports a spurious `top-identity` violation for a correct type. The code-splitting alternative builds and runs, but puts this package's circular re-exports across a chunk boundary — rollup warns "will likely lead to broken execution order" — for no gain, since there is one module either way.
398
+
399
+ ## Schema depth & capability gating
400
+
401
+ `buildSchemas` / `querySchema` / `buildQueryTool` constrain the LLM-facing schema along **four independent axes**, each dialed by `depth`:
402
+
403
+ | axis | levels (loose → tight) | constrains |
404
+ | ---- | ---------------------- | ---------- |
405
+ | `refs` | `open` · `types` · `fields` · `both` · `paired` | every `{ source/type, field }` reference position — `field-ref`, a join's `on`, `semantic` / `text-search` / `text-score` / `filters` |
406
+ | `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
407
+ | `functions` | `open` · `names` · `typed` | function name + named-arg objects |
408
+ | `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
409
+
410
+ Pass a full/partial `SchemaDepth` object, or a preset string: `'open'` (every axis loose) / `'paired'` (every axis tight); the deprecated `strict: true`/`false` are sugar for those. A `FunctionSelector` (`{ scalar: [...], … }`) picks which functions appear; `maxEnumSize` auto-degrades any axis whose enumeration overflows the budget one level looser so a large catalog never yields an unusable schema.
411
+
412
+ **Capability gating** (independent of depth) omits any expr kind the available Types/functions can't use: `semantic` (some Type `isSemantic()`), `text-search`/`text-score` (`isSearchable()`), `array-op` (a Type has an array field), `joins` (a Type has a relation), `tabular-function-call` (≥1 tabular fn), `aggregate`/`window`/`function-call` (≥1 fn of that shape), `operator` (≥1 registered operator whose operand type some in-scope field could supply), `filters` (a Type has filterable fields). The always-usable core (`literal`/`param`/`binary`/`unary`/`comparison`/`logical`/`in`/`between`/`is-null`/`exists`/`case`/`field-ref`/`subquery`) is never gated.
413
+
414
+ ## Execution model
415
+
416
+ One contract: **run a query, optionally with params + filters, and get back `{ rows, fields, total }`.**
417
+
418
+ ```ts
419
+ const result = await engine.run(query, { params, filters, includeTotal });
420
+ // result.rows — output rows (objects; pass { rows: 'array' } for arrays)
421
+ // result.fields — resolved output fields (name + type + summary metadata)
422
+ // result.total — pre-limit count, when run with includeTotal: true
423
+ ```
424
+
425
+ Neither `run` nor `toSQL` validates the `params` it is handed — check them first with
426
+ `engine.checkParams(query, params)`, or by passing them to `validateQuery`'s 4th argument
427
+ (`validateQuery(query, scope, constraints, { params })`), which is the same check folded into the
428
+ usual gate.
429
+
430
+ - **An output field's `type`** is the full `ResolvedType`. A COMPUTED one carries `aggregate` (does a group collapse happen anywhere in this expression?) and `aggregateFn` — the APPLIED aggregate's name, present exactly when the value IS one aggregate call. `sum(hours) as total_hours` reports `aggregateFn: 'sum'` under any alias; `max(a) - min(b)` reports `aggregate: true` with NO `aggregateFn` (it contains aggregates but is none); a window over an aggregate-shaped function reports neither. Read it rather than inferring the function from the output column NAME, which cannot see through an alias and mistakes `hours * 2 as count` for an aggregate. Alongside it, and present on exactly the same nodes, are **`aggregateDistinct`** (was the call `DISTINCT`?) and **`aggregateMerge`** — the merge semantics OF THIS CALL, i.e. the function's declared `merge` with the DISTINCT rule already applied: `count(hours)` → `'sum'`, `count(DISTINCT hours)` → `'none'` (de-duplication is global, so two such values cannot be added), `min(DISTINCT hours)` → `'min'` (min/max/and/or are idempotent, so DISTINCT changes nothing). Before `0.6.5` `count(x)` and `count(DISTINCT x)` resolved to IDENTICAL output fields while answering different questions; a consumer folding a tail of groups into an "Other" residual reads `aggregateMerge` and gets a total answer, including for an aggregate a caller registered.
431
+ - **`includeTotal`** is an execution-time option (not a `SelectDef` field): `run` captures the pre-limit count; `toSQL(query, dialect, { includeTotal: true })` emits `COUNT(*) OVER () AS "$total"`. It applies to the **ENTRY query ONLY** — never a CTE body, a set-operation arm, or a FROM subquery — because `$total` is a PROJECTED column: inside a set-operation arm it participates in the set comparison and would change the **rows** (UNION would stop de-duplicating; INTERSECT / EXCEPT would compare per-arm counts they were never meant to see). So a query whose entry is a **set operation reports NO total** — `result.total` is `undefined` and the SQL carries no `$total` — rather than a wrong one. To page a set operation *and* count it, wrap it in a SELECT over a `subquery` source and ask for the total there.
432
+ - **`autoPaginate(query)`** adds `limit`/`offset` as bind params idempotently, so paging is just supplying values: `run(paged, { params: { limit, offset } })`. It pages exactly the kinds that HAVE a row bound: a `select`, a set operation (`union`/`intersect`/`except` — the SET-LEVEL bound over the combined rows, never an arm's), and a `cte` (paged through its `final`; a CTE body is an intermediate result). Every other kind (`insert`/`update`/`delete`/`expr`) **throws** `QueryTypeError` `paginate.unsupported-kind` — it used to silently return a query that looked paged and wasn't. `canAutoPaginate(query)` asks first.
433
+ - **Drill-down.** `drillDown(query, engine)` rebuilds the underlying-rows query behind an aggregate, parameterized (each GROUP BY key pinned to a bind param) — returns `{ query, params, warnings }`. `drillDownInto(query, groupRow, engine)` extracts one aggregated row's key values; then it is the same `run` call. Each aggregate becomes its row-level expression; `count(*)` expands to the FROM type's fields MINUS the ones the SELECT already projects (matched on the EXPRESSION, not the output name), so a group key is projected once. Failures return LLM-friendly `Problems` (`drill.no-aggregation` / `non-invertible` / `having-aggregate` / `window-unsupported`).
434
+ - **Standalone exprs.** `engine.evaluateExpr(expr, row?)` evaluates an `Expr`/`ExprDef` against a row; `engine.exprToSQL(expr, dialect)` emits `{ sql, params }` (params never interpolated).
435
+
436
+ ### SQL conversion
437
+
438
+ `engine.toSQL(query, dialect, options?)` emits `{ sql, params }` for any registered dialect. Base uses `?` placeholders; Postgres uses `$1, $2, …`. Relation joins synthesize their ON clause from the relation key. `toSQL` accepts the same `params` / `filters` / `includeTotal` options as `run`, so emitted SQL matches what would run.
439
+
440
+ - **Semantic text terms → vectors (extract → embed → sync build).** A `semantic(...)` term whose query is a TEXT literal (or a text `param` value) is TEXT, not an embedding, and cannot be bound as `'<text>'::vector`. Because SQL emission is SYNCHRONOUS, the caller embeds up front and passes the vectors in — `toSQL` (and `run`) stay sync for every caller:
441
+ 1. **Extract** — `engine.semanticTexts(query, opts?) → string[]` returns the DISTINCT plain-text semantic terms needing embedding, in a stable (first-seen) order. It reuses `toSQL`'s exact emit walk, so it finds terms at ANY depth (nested boolean AND/OR/NOT, a subquery WHERE, a computed-field expr, a function-call arg, a CASE/WHEN — anywhere an `Expr` sits) and never returns an already-`'[…]'` vector-text term. `opts` are the same `params` / `filters` a bind would see.
442
+ 2. **Embed** each returned term (the caller's model/network call) and fill a `text → vector` cache — a `ReadonlyMap<string, readonly number[]>` (a resolver function `(text) => readonly number[] | undefined` is accepted too; both are the `SemanticEmbeddings` type).
443
+ 3. **Build** — `engine.toSQL(query, dialect, { embeddings })` looks each term up, formats it with `toVectorText`, and binds `$n::vector` (all sync). A needed term MISSING from the cache **throws** (fail loud) rather than mis-binding; with NO cache a plain-text term likewise throws. A **pre-embedded `'[…]'` vector-text term / param is bound as-is** (never looked up), and a `vectorField` backing (query vector already a `$n::vector` param) is unchanged. The SAME `embeddings` cache is accepted by `engine.run(query, { embeddings })` for in-memory scoring (no embedder required). Helpers: `toVectorText(number[]) → '[…]'`, `parseVectorText('[…]') → number[]`, `isVectorText(string)`. (Replaces the former `convertSemanticText` seam + `toSQLAsync` — with vectors precomputed, nothing in `toSQL` is async.)
444
+
445
+ ## The LLM tool
446
+
447
+ The parse+validate pipeline is exposed **standalone**, so you can validate a query without building a `Tool` just to call `.parse` on it. All three entries share ONE implementation:
448
+
449
+ - **`parseQueryTool(engine, raw, options?) → Query | QueryToolError`** — the DIRECT parse entry. Given the conceptual `{ query }` envelope, it validates the envelope, parses the structured `query` into a runnable `Query`, and runs full engine validation (structure + params + per-Type validators). Clean ⇒ the built `Query`; any problem ⇒ a rich `QueryToolError` whose `.report` (also its `.message`) is a concise compiler-style report (`formatProblems`), so the model sees real diagnostics instead of Zod's.
450
+ - **`parseQueryRequest(engine, raw, options?) → { query, problems, report }`** — the same pipeline exposing the detailed result: the built `Query` (or `null`), the accumulated `Problems`, and the rendered `report`. (A SEMANTIC failure keeps the built `query` alongside its problems; a STRUCTURAL failure yields `query: null`.)
451
+ - **`buildQueryTool(engine, options?) → Tool`** — the tool WRAPPER, built only when you need a runnable `@aeye/core` `Tool` to drop into an agent's tool set. Its wire `schema` is the engine's query schema (depth-graduated + capability-gated), its custom `parse` DELEGATES to `parseQueryTool` (Zod is demoted to the model-facing wire schema only), and its `call` handler RUNS the validated query and returns a `QueryResult`. Its `instructions` reflect the active depth + selected functions, and (past `max` Types via `shouldUseStringSchema`) it falls back to a prose-description schema.
452
+
453
+ Because core wire-decodes the model's response **before** any custom `parse` hook runs (and a directly-parsed CLI/file def is already conceptual), the standalone functions operate on the **conceptual** value — they never need the wire schema for parsing.
454
+
455
+ ```ts
456
+ import { selectTypes, querySchema, parseQueryTool, parseQueryRequest, QueryToolError } from '@aeye/query';
457
+
458
+ const types = await selectTypes(engine, 'revenue by customer last month'); // narrow the schema
459
+
460
+ // DIRECT parse — no Tool built. Feed a def straight through (CLI / file / your own loop):
461
+ const parsed = parseQueryTool(engine, { query: someQueryDef }, { depth: 'paired', types });
462
+ if (parsed instanceof QueryToolError) console.log(parsed.report); // underlined diagnostics
463
+ else console.log(await engine.run(parsed)); // runnable Query → QueryResult
464
+
465
+ // Detailed result when you want the problems + report explicitly:
466
+ const { query, problems, report } = parseQueryRequest(engine, { query: someQueryDef }, { types });
467
+
468
+ // The model-facing schema for your own LLM loop (the model emits against it; core decodes with it):
469
+ const schema = querySchema(engine, { depth: 'paired', types });
470
+ ```
471
+
472
+ Build a `Tool` only when an agent must CALL and RUN it:
473
+
474
+ ```ts
475
+ import { buildQueryTool } from '@aeye/query';
476
+
477
+ const tool = buildQueryTool(engine, { depth: 'paired', types });
478
+ const query = await tool.parse(ctx, JSON.stringify({ query: someQueryDef })); // delegates to parseQueryTool (throws QueryToolError on failure)
479
+ const result = await tool.run(query, ctx); // runs it → QueryResult
480
+ ```
481
+
482
+ `buildSchemas` / `querySchema` expose the schema directly when you drive your own LLM loop.
483
+
484
+ ### Underlined, compiler-style problem reports
485
+
486
+ `QueryToolError.report` renders every problem — STRUCTURAL (the owned, zod-free parser `registry.parseCheckedQuery`, now the ACTIVE gate) *and* SEMANTIC (`validateWalk`: unknown fields, param conflicts, per-Type validators) — as underlined diagnostics over the model's **own** query JSON, so it sees exactly which value to fix:
487
+
488
+ ```
489
+ ── line 21 ──────────────────────────────────────────────
490
+ 21 │ "left": "oops",
491
+ │ ^^^^^^
492
+ │ error: expected an expression
493
+ ```
494
+
495
+ **Messages are aid-directed (domain-specific), not Zod-generic.** The owned parser's `Shape` combinators reuse the same `aids.ts` vocabulary (`aidInfo` for the label, `didYouMean` for suggestions) as the wire schema, so the structural diagnostics read in the query's own terms: `"left": "oops"` → "expected **an expression**, got a string"; `"args": "total"` → "expected **named arguments**, an object of { argName: <expr> }, got a string"; `"kind": "comparise"` → "unknown **expression kind** `comparise` — did you mean `comparison`?"; `"op": "equals"` → "expected a comparison operator: =, <>, <, <=, >, >=, like, notLike, ilike"; `"limit": "three"` → "expected a number or a param, got a string". **Structure vs semantics:** the owned parser accepts any REGISTERED kind with any string field (capability/depth is a wire-schema concern), so an unknown Type / field / function name is a SEMANTIC rejection instead — e.g. an unknown field surfaces from `validateWalk` as "Type 'user' (source 'user') has no field 'ghost'." (with its own `didYouMean`), still underlined at the offending field-ref.
496
+
497
+ How it works: `jsonSource(value)` (in `src/json-source.ts`) re-emits the canonical `JSON.stringify(value, null, 2)` text while recording, for every node (root, each property value, each array element), the `[start, end)` char offsets keyed by the node's structural path (the same `(string | number)[]` shape as `Problem.path`). `Code.fromJson(value)` builds a `Code` over that text with those spans pre-registered, and `formatProblems` resolves each `Problem.path → span → (line, col)` to draw the `^^^` underline with surrounding context. The owned parser records each structural problem DIRECTLY at the offending value's path (`problems.at(key, …)`, accumulating, never throwing), so — unlike zod's `.or`-folded union failures — there is no nesting/noise to collapse: one problem per offending value, already at the right path.
498
+
499
+ Both the owned parser AND the wire schema draw their DIRECTED text from the SAME `aid → { label, noun? }` `AID_REGISTRY` in `src/aids.ts` (so the two never diverge): the owned parser's `Shape`s call `aidInfo` / `didYouMean` directly, while the wire schema uses **`withAid`** — every generated schema node is tagged with a stable `aid` (`.meta({ aid })`, unchanged — it also names the JSON-schema `$defs` entry) plus a per-schema, captured **error map** that renders domain text off `AID_REGISTRY`. On an `invalid_type` it reads `expected <label>[, got <received>]`; on an enum failure `expected <label>: <allowed values>`; on a union `.or` no-match either the union's `<label>` or, when the value carries a typo'd string `kind`, "unknown `<noun>` kind `x` — did you mean `y`? (available: …)". The wire schema the model consumes is unchanged except the added `aid` metadata and the friendlier error text (never serialized into JSON-schema). A problem whose path matches no node degrades gracefully (nearest ancestor, or a plain `<severity>: <message> @ <path>` line) rather than crashing. Valid queries produce no problems ⇒ an empty report.
500
+
501
+ **"Did you mean?" on EVERY unknown-name diagnostic.** A single reusable suggester — `didYouMean(input, candidates, { max? })` in `src/aids.ts` — appends "` — did you mean \`X\`?`" (or "`\`X\` or \`Y\`?`" up to `max`, default 1) whenever a bad NAME is a genuine typo of a valid one, and appends nothing otherwise. It is **typo-only**: a case-insensitive edit distance under a length-scaled budget (`suggestionBudget(len) = min(3, max(1, floor(len/3)))`, exposed alongside the lower-level `nearest(input, candidates, budget?)` primitive), so a short word tolerates one edit and a long one up to three — never a false match on an unrelated word. It powers, uniformly:
502
+ - **schema-enum** failures — a near-miss `op` / `dir` / `nulls` / function-name / Type-name / field-name value gets the canonical spelling appended to `expected <label>: <allowed>` (e.g. `"op": "notlike"` → "… like, notLike, ilike — did you mean `notLike`?"), and the union-no-match `kind` suggestion (`nearestKind` now just calls `nearest`);
503
+ - **validation** (`validateWalk`) unknown-name diagnostics — **field** (`ref` / `filters` / `semantic` / `text-search` / `text-score` / `excluded` / `insert` / `update`, suggested from the resolved Type's field names), **source** (suggested from the bound source names in scope, via the new `QueryScope.sources()` accessor — every source bound anywhere up the chain), **Type** (`insert` / `update` / `delete` / `source` / relation-target, from the registry's Type names), **function** (`function-call` / `aggregate` / `window` / `tabular`, from the registry's function names of that shape), **named-arg** (from the function's declared param names), and **output** (`output` ref, from the SELECT's output field names). Candidates are gathered only when the error is emitted, so there is no hot-path cost.
504
+
505
+ **Tuning the report.** `buildQueryTool(engine, { report })` forwards a `FormatProblemsOptions` (`{ contextLines?, sectionHeaders?, lineNumbers?, maxProblems? }`) straight into `formatProblems`, so a caller can shape the diagnostics the model sees. Absent ⇒ the defaults (`contextLines: 2`, section headers + the `N │` line-number gutter on). E.g. `{ contextLines: 0 }` drops the surrounding context (just the underlined line), `{ contextLines: 4 }` widens it, `{ lineNumbers: false }` drops the gutter, and `{ maxProblems: 3 }` caps how many problems render.
506
+
507
+ ### Owned structural parser (zod-free, accumulating) — the ACTIVE gate
508
+
509
+ A model-authored query is now gated by ONE structural authority, the owned parser: `parseQueryInput` (in `src/llm/tool.ts`) validates the `{ query }` envelope without zod, then calls `registry.parseCheckedQuery(queryDef, problems)` — the zod-free STRUCTURAL parse — and, only if it is structurally sound, runs the owned `validateWalk` SEMANTIC check. Both halves have the properties we want: they NEVER throw and ACCUMULATE every problem in one pass. **Zod is demoted to the model-facing WIRE schema only** — `buildQueryTool` still exposes `querySchema` / `buildSchemas` as the tool's `schema` (what the model emits against, and what `compile` / strict mode consume), but it is NO LONGER a validator: the `schema.safeParse` gate and its zod-issue flattening (`problemsFromZod` / `flattenZodIssues`) are gone. The **`src/shape/` combinator module** is the machinery that let each expr/query OWN its shape validation the same way it owns its semantics.
510
+
511
+ A `Shape<T>` is a tiny structural schema: `check(json: unknown, ctx): T | INVALID`. It validates the untrusted `json` at the caller's current `Problems` path, RECORDS any problems (reusing `aids.ts` — `aidInfo` for the domain label, `didYouMean` for suggestions — never Zod, never `flattenZodIssues`), and returns the built value or the `INVALID` sentinel. It MUST NOT throw. Combinators: `lit` (a `kind` discriminant), `str` / `num` / `int` / `bool` / `scalar` (typeof / `Number.isInteger` guards → aid-directed `expected <label>, got <received>`), `enumOf` (membership → `expected <label>: a, b, c` + a `didYouMean` tail), `obj` / `optional` / `list` / `record` (composites — `record` is the named-argument map `{ [name]: value }`, returning an insertion-ordered `Map` to mirror `parseNamedArgs`), and the reference combinators `exprRef` / `queryRef` / `queryDefRef` / `sourceRef` (child-expr / child-query / raw-query-def / child-source slots, each defensively dispatched via the registry). **Accumulation, no throwing:** `obj` / `list` / `record` check ALL of their fields/elements before deciding — they never early-return on the first bad one — so a single `check` surfaces multiple problems in one pass (e.g. a `comparison` with a bad `op` AND a non-object `left` yields BOTH the `op` enum problem and the `left` not-object problem, each localized under its own path). Cross-field rules that a plain `obj` can't express (e.g. `logical`'s `not`-arity, or `in`'s list-vs-subquery dispatch) live in a thin hand-written `Shape` wrapper around the base `obj`.
512
+
513
+ **The combinators are on the public barrel, as the namespace `shape`** — `import { shape, type Shape } from '@aeye/query'`, then `shape.obj({ kind: shape.lit('…'), … })`. A namespace rather than flat names because `lit` would otherwise shadow the expression BUILDER's `lit`. This is what a class defined outside the package needs to own its `static SHAPE`: before `0.6.6` such a class could satisfy `defineExpr` — validating, costing, emitting SQL and self-describing correctly — and still be refused by `parseCheckedExpr` with `shape.unknown-kind`, which is the gate a model-authored query goes through. Note the scope: this makes a `SHAPE` AUTHORABLE, it does not open `ExprKind` (`ExprDef['kind']` is a closed union — parse dispatch for a whole kind stays the library's).
514
+
515
+ **Perfect type-safety, no casts.** The only `unknown` is the untrusted `json`, always narrowed by a type guard. `obj` is fully typed with NO `as`: rather than the usual `fields: Record<string, Shape<unknown>>` (whose indexed access erases each field's value type, forcing a cast in the assembler), the generic is INVERTED — `F` is the BUILT-VALUE record and the field map is the mapped type `{ [K in keyof F]: Shape<F[K]> }`, so `fields[key].check(...)` returns exactly `F[K] | INVALID`; the partial accumulator is promoted to the complete `F` for `build` by a user-defined completeness type GUARD (`acc is F`), not a cast.
516
+
517
+ Three DEFENSIVE dispatches — the zod-free parallels to `parseExpr` / `parseQuery` / `QuerySource.from` — walk the whole tree: `Registry.parseCheckedExpr(json, problems)`, `Registry.parseCheckedQuery(json, problems)`, and `Registry.parseCheckedSource(json, problems)`. Each mirrors its throwing twin but records problems (`shape.not-object` / `shape.missing-kind` / `shape.unknown-kind` with a `didYouMean` over the real kinds) and returns the built `Expr` / `Query` / `QuerySource` or `undefined`, dispatching to each class's owned `static SHAPE` (query dispatch auto-includes every registered class that declares one; source dispatch reads `QuerySource.SHAPES`, keyed by the four source kinds). Each `SHAPE` builds a value `.toJSON()`-equal to the existing `from(def)` output on a valid def; the SEMANTIC checks (comparability, arg types, aggregate placement, source duplicates, write-model, unknown names) stay in `validateWalk`.
518
+
519
+ The recursion is completed by four child-slot combinators alongside `exprRef`: **`queryRef`** (a parsed `Query` child — the set-operation arms, CTE bindings, subquery sources, `INSERT … SELECT`), **`queryDefRef`** (a subquery kept as a raw `QueryDef` — the value-position `subquery` / `exists` / `in`-subquery exprs re-parse it lazily, so it validates through `parseCheckedQuery` but returns the normalized `toJSON()` def), and **`sourceRef`** (a `QuerySource` child — a SELECT's `from`). The small building blocks are shared shapes in `queries/_shape.ts`: `selectFieldShape` (`{ expr, as? }`), `fieldValueShape` (`{ field, value }`), and `boundShape` (a limit/offset — a literal integer or a `{ kind:'param' }` def); `QueryOrder.SHAPE` and `QueryJoin.SHAPE` cover an ORDER BY term and a JOIN clause.
520
+
521
+ **The whole query tree now parses through the owned parser.** Expr kinds with a `static SHAPE`: the C1 exemplars (`comparison`, `field-ref`, `literal`, `param`, `logical`) + the C2 operators/predicates/functions/refs (`binary`, `unary`, `is-null`, `between`, `case`, `aggregate`, `window`, `function-call`, `array-op`, `output`, `excluded`, `text-search`, `text-score`) + the C3 finishers: `subquery`, `exists`, `in` (BOTH forms — its `SHAPE` dispatches on `in`: an array → the list form, an object → the subquery form via `queryDefRef`), `semantic` (whose `query` shape dispatches over the string / `param` / `{source,field}` / `{type,field}` forms), `tabular-function-call`, and `filters`. Query kinds with a `static SHAPE`: `select`, `insert` (incl. `onConflict`), `update`, `delete`, `union` / `intersect` / `except` (three `lit(kind)`-anchored shapes over the shared `SetOperationQuery`), `cte` (its entry shape structurally discriminates the plain vs recursive binding), and `expr`. Source kinds: `type`, `aliased`, `subquery`, `function`. Cross-field rules a plain `obj` can't express (e.g. `logical`'s `not`-arity, `in`'s list-vs-subquery dispatch, `cte`'s entry discrimination) live in a thin hand-written `Shape` wrapper around the base `obj`. An end-to-end test parses a complex SELECT (joins + where + groupBy + having + subquery + aggregate) to a `Query` `.toJSON()`-equal to the throwing `parseQuery`, and a SELECT malformed across several clauses surfaces every problem in ONE pass.
522
+
523
+ **This is the ACTIVE structural gate (C4 flipped).** `parseQueryInput` gates on `parseCheckedQuery` and feeds the sound result to `validateWalk`; the zod `safeParse` structural authority (and `problemsFromZod` / `flattenZodIssues`) has been retired. Zod remains ONLY the model-facing wire schema (`querySchema` / `buildSchemas`), unchanged. This is the intended structure-vs-semantics split: the owned parser accepts any registered kind + any string field, and unknown types / fields / functions are caught downstream by `validateWalk` with the existing aid-directed + `didYouMean` semantic messages.
524
+
525
+ ### Compact tool-call schema (shared `$defs`)
526
+
527
+ The model-facing JSON-Schema (what `z.toJSONSchema` — and core's `compile()` — emit from `querySchema`) is **structurally factored**: the largest repeated fragments are built ONCE per schema-generation (a `SchemaCache` threaded on `SchemaOptions.cache`) and REUSED by identity everywhere they occur, so the converter emits each as a single `$def` + `$ref`s instead of inlining every copy. Factored fragments: each Type's **field-name enum** (`$def` `Fields_<Type>`, shared by field-ref / order / group-by / having / filters / text-search / semantic), the shared **`param`** expr, the reused **`Limit`** (number-or-param), and — the biggest win — the per-function **typed-args** blocks, keyed by argument SIGNATURE so the 100+ builtin functions (which collapse to a few dozen distinct signatures — dozens share a lone `value` arg) reuse one `$def` each. Names come from each shared fragment's `aid`, stamped as `meta.id` (`Fields_user`, `param`, `Limit`, `Args…`) so `z.toJSONSchema` factors AND names them; the ids are salted per schema-generation to stay unique in zod's process-global registry. This is a pure size/structure win — the schema accepts and rejects exactly the same queries with the same aid-directed diagnostics (a golden invariance test guards that), only smaller: on the bundled example fixture the minified `z.toJSONSchema` drops from **21.3 KB → 20.2 KB** (`open`) and **105.6 KB → 95.5 KB** (`paired`), the paired reduction concentrated in the field enums + typed-args (the ~100 genuinely-distinct per-function branches of `typed` mode are irreducible). A size-threshold test catches any regression that re-inlines the shared fragments.
528
+
529
+ ## Self-describing the engine to a model
530
+
531
+ The `describe*` helpers render a compact, promptable capability summary (plain text, deliberately terse to protect the context budget):
532
+
533
+ - **`describeEngine(engine, { types?, functions?, maxExamples?, instructions?, examples? })`** composes ONE block a model can read to know everything it may use: every (supplied) Type, then `describeExprs`, then `describeFunctions`, then `describeQueryExamples`, then `describeDialects`. `functions` narrows both the expr gating and the function listing to the schema's selection; `types` narrows the Type list + gating; `maxExamples` caps how many WORKED examples render PER function / node (default `DEFAULT_MAX_EXAMPLES` = 2; `0` omits examples). It no longer needs a separate example-text call — worked examples now live ON the nodes/functions (see below) and are folded in here.
534
+ - **Bring your own instructions / examples (use your OWN Types).** `instructions?: Record<string, string>` and `examples?: Record<string, readonly string[]>` (also `DescribeOverrides`, threaded through `describeExprs` / `describeFunctions` / `describeQueryExamples`) let a caller REPLACE the shipped `INSTRUCTIONS` / `EXAMPLES` for a given item — keyed by function NAME (`sum`, `count`, …) or node KIND (`window`, `in`, `select`, `union`, `cte`, …); names and kinds share ONE flat namespace (they are distinct strings). A key that is PRESENT swaps in the caller's string(s) — e.g. worked examples written against the caller's real domain Types instead of the generic shipped ones — while every key NOT present keeps the shipped default; overridden example lists are still capped by `maxExamples`, and an absent / empty override map renders byte-identically to today. Override strings are the CALLER's responsibility (rendered VERBATIM, not validated at render time): a caller can structurally pre-check their own example strings the same way the shipped-example test does — `JSON.parse` then a bare `createRegistry().parseCheckedQuery(...)` (full queries) / `parseCheckedExpr(...)` (expr fragments) and assert zero problems — before passing them in.
535
+ - **`describeExprs(engine, types?, functions?, maxExamples?)`** lists the CAPABILITY-GATED expression kinds — one `kind — INSTRUCTIONS` line per kind actually usable for the current Types/functions, filtered by the SAME gate the schema uses (`exprKindApplicable`), each followed by up to `maxExamples` `e.g. <json>` lines from the kind's `static EXAMPLES`. The always-usable core is never gated; `semantic` / `text-search` / `text-score` / `array-op` / `tabular-function-call` appear only when an eligible Type/function exists (`excluded` / `output` are position-only and never listed).
536
+ - **`describeFunctions(engine, functions?, maxExamples?)`** renders each function as `name(a, b?): output — instructions` (named params, a trailing `?` marks optional), grouped by shape, each followed by up to `maxExamples` `e.g. <json>` lines from the function's `examples`.
537
+ - **`describeOperators(engine, maxExamples?)`** renders each REGISTERED operator as `&&(left: json(as Geometry), right: json(as Geometry)) → bool — instructions`, with its examples underneath. An operand tag names the registered TYPE and only the options the DECLARATION itself wrote — never the refinement's defaults, and never the refused-arm tail. An operand's type is a COMPARABILITY constraint, so rendering `subtype=Point` there beside a column reading `subtype=Polygon` gave a model every reason to conclude the column was not a legal operand; the refused arms belong to the COLUMN's grammar and the `types:` block already carries them per column (repeating them per operand is also most of a large vocabulary's prompt cost — ten two-operand operators is 20 copies of one tail). `describeEngine` folds the block in whenever ANY operator is registered and omits it entirely otherwise (unlike `functions:` / `dialects:`, which say "(none)"): an operator vocabulary is an opt-in a deployment either has or has not, and announcing its absence spends prompt on a feature the reader cannot use.
538
+ - **`describeQueryExamples(engine, maxExamples?)`** renders a query-examples section: each registered query KIND that ships `static EXAMPLES` (SELECT, UNION/INTERSECT/EXCEPT, WITH/CTE) as `kind — INSTRUCTIONS` plus up to `maxExamples` worked example queries. Query-level constructs have no expr-catalog entry, so they get their own section.
539
+ - **Worked examples are a shipped, first-class surface.** Every `FunctionDef` may carry `examples?: readonly string[]` (RAW JSON strings — expr fragments or full queries that CALL it), and every Expr/Query node class may carry a `static readonly EXAMPLES?: readonly string[]` (plus, for query kinds, an optional `static INSTRUCTIONS`). Examples are TYPE-AGNOSTIC (illustrative generic source/field names like `event.score` / `user.name`) — they teach SHAPE while the catalog supplies the caller's real Type names. The shipped high-confusion set: the window family (`rank` / `denseRank` / `lag` / `lead` / `firstValue` / `lastValue` / `nthValue` / `cumeDist`), `dateTrunc` / `age` / `replace`, `count`; and the `window` / `exists` / `in` / `subquery` / `function-call` exprs and `select` / `union` / `cte` queries. This is the ONE source of truth — `describeEngine` only renders them. A structural test parses EVERY shipped example through a bare `createRegistry()`'s `parseCheckedQuery` / `parseCheckedExpr` and asserts zero problems.
540
+ - **Generated Type / Field docs.** `describeType` / `describeField` always emit a short `label` + long `description`: the developer's `TypeDef.label` / `FieldDef.description` when set, otherwise a sensible default GENERATED on demand from the meta-model — a Field from its FieldType (kind, bounds, `casing` / `semantic` / `search` flags, array item/bounds, a relation's `to` + `count` + its DIRECTION → belongs-to / has-many, read from `isBelongsTo()` rather than `count` so a materialized inverse is never described as a belongs-to, nullability), a Type from its name + field/relation/index summary. Read the (possibly-generated) pair directly with `fieldMeta(field)` / `typeMeta(type)` (`{ label, description }`); nothing mutates the stored def — the strings are computed fresh per call.