@aeye/query 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -25
- package/aeye-query.md +48 -58
- package/dist/index.d.ts +6632 -6552
- package/dist/index.js +1249 -1708
- package/package.json +11 -8
package/README.md
CHANGED
|
@@ -8,7 +8,8 @@ expression. A built query resolves to an output type, has typed bind params,
|
|
|
8
8
|
can be cost-bounded, run in-memory, converted to SQL (base + Postgres),
|
|
9
9
|
auto-paginated, and **drilled down** (aggregate un-ravelling).
|
|
10
10
|
|
|
11
|
-
It
|
|
11
|
+
It depends on `@aeye/schema` (the model-facing grammar) and `zod` (its own
|
|
12
|
+
value checks), and is obsessively type-safe: no
|
|
12
13
|
`any`, no `unknown` in public APIs, no casts; every polymorphic node is a
|
|
13
14
|
discriminated union so handling is exhaustively checkable.
|
|
14
15
|
|
|
@@ -1173,49 +1174,70 @@ gracefully (a constant, or the first argument unchanged) and never throws.
|
|
|
1173
1174
|
|
|
1174
1175
|
## The LLM loop
|
|
1175
1176
|
|
|
1176
|
-
The `llm/` surface turns the engine into an LLM tool
|
|
1177
|
+
The `llm/` surface turns the engine into an LLM tool. The model-facing schema
|
|
1178
|
+
is **`@aeye/schema`**: one grammar module (`QueryGrammar`) bound per
|
|
1179
|
+
registry + options (cached), rendered for whichever model a request goes to,
|
|
1180
|
+
and decoding the model's answer back into the code shape in one pass.
|
|
1177
1181
|
|
|
1178
1182
|
```ts
|
|
1179
1183
|
import { selectTypes, buildSchemas, querySchema, buildQueryTool } from '@aeye/query';
|
|
1184
|
+
import { OPENAI_STRICT } from '@aeye/schema';
|
|
1180
1185
|
|
|
1181
1186
|
// 1. Narrow the schema to the Types a request needs (semantic ranking).
|
|
1182
1187
|
const types = await selectTypes(engine, 'revenue by customer last month');
|
|
1183
1188
|
|
|
1184
|
-
// 2.
|
|
1185
|
-
// every axis: Type-name positions are
|
|
1186
|
-
//
|
|
1187
|
-
|
|
1188
|
-
const
|
|
1189
|
+
// 2. Each part of the language at a per-axis `depth` (see "Schema depth" below),
|
|
1190
|
+
// as `@aeye/schema` binds. `'paired'` locks every axis: Type-name positions are
|
|
1191
|
+
// enum-locked, field refs are TYPE+FIELD pairs, function calls are typed.
|
|
1192
|
+
const { Query, Expr } = buildSchemas(engine, { depth: 'paired', types });
|
|
1193
|
+
const sent = Query.render(OPENAI_STRICT).jsonSchema; // what that model is sent
|
|
1194
|
+
const res = Query.render(OPENAI_STRICT).parse(modelAnswer); // { ok: true, value: QueryDef } | { ok: false, message }
|
|
1189
1195
|
|
|
1190
|
-
// 3. Or
|
|
1191
|
-
//
|
|
1192
|
-
// straight through to `buildSchemas`.
|
|
1196
|
+
// 3. Or the tool-input schema, which falls back to a string description past
|
|
1197
|
+
// `max` Types (shouldUseStringSchema). `depth` / `functions` thread through.
|
|
1193
1198
|
const schema = querySchema(engine, { types, depth: 'paired' });
|
|
1194
1199
|
|
|
1195
|
-
// 4. A ready-wired `@aeye/core` `Tool
|
|
1196
|
-
//
|
|
1197
|
-
//
|
|
1198
|
-
//
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
const
|
|
1202
|
-
const query = await tool.parse(ctx, JSON.stringify({ query: someQueryDef })); // built Query (throws QueryToolError on failure)
|
|
1203
|
-
const result = await tool.run(query, ctx); // runs it → QueryResult
|
|
1200
|
+
// 4. A ready-wired `@aeye/core` `Tool`: its schema decodes the model's answer,
|
|
1201
|
+
// then parses + validates it into a runnable `Query` (structural and semantic
|
|
1202
|
+
// problems are told to the model in @aeye/schema's format: its own JSON with
|
|
1203
|
+
// a marker under each mistake, "did you mean"); its `call` RUNS the query.
|
|
1204
|
+
const tool = buildQueryTool(engine, { depth: 'paired', errorFormat: 'full' });
|
|
1205
|
+
const query = await tool.parse(ctx, JSON.stringify({ query: someQueryDef })); // Query (throws SchemaParseError)
|
|
1206
|
+
const result = await tool.run(query, ctx); // → QueryResult
|
|
1204
1207
|
```
|
|
1205
1208
|
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
tool's `call` executes it.
|
|
1209
|
+
`parseQueryTool(engine, { query }, options)` runs the same structural + semantic
|
|
1210
|
+
pipeline on a value already in the code shape (a CLI, a file), returning the
|
|
1211
|
+
`Query` or a `QueryToolError` with a compiler-style `report`.
|
|
1210
1212
|
|
|
1211
1213
|
**Self-describing the engine.** `describeEngine(engine, { types?, functions? })` composes one terse, promptable block a model can read to know everything it may use: every (supplied) Type, then `describeExprs` (the capability-gated `kind — INSTRUCTIONS` list of usable expr kinds — `semantic` / `array-op` / … appear only when an eligible Type/function exists; the core is never gated), then `describeFunctions` (`name(a, b?): output — instructions`, grouped by shape), then `describeDialects`. `describeType` / `describeField` always render a short `label` + long `description` — the dev's `TypeDef` / `FieldDef` values when set, else defaults GENERATED on demand from the meta-model (a Field from its FieldType + flags + nullability + relation cardinality; a Type from its name + field/relation/index summary). Read the pair with `fieldMeta(field)` / `typeMeta(type)`; the stored def is never mutated.
|
|
1212
1214
|
|
|
1213
1215
|
See `examples/` for an end-to-end, runnable tour of all of the above.
|
|
1214
1216
|
|
|
1217
|
+
### Migrating from the zod schemas
|
|
1218
|
+
|
|
1219
|
+
- `buildSchemas(engine, options)` returns `@aeye/schema` binds, not zod:
|
|
1220
|
+
`schemas.Query.safeParse(v)` → `schemas.Query.render(profile).parse(v)`
|
|
1221
|
+
(`ok` / `value` / `message`); `z.toJSONSchema(schemas.Query)` →
|
|
1222
|
+
`schemas.Query.render(profileFor(model)).jsonSchema`. Hand `querySchema(...)`
|
|
1223
|
+
(or `QueryGrammar.result(...).adapt((ctx) => [registry, options])`) to a core
|
|
1224
|
+
`Tool` / `Prompt` directly.
|
|
1225
|
+
- `buildQueryTool`'s decoded value is the runnable `Query` (its schema is a
|
|
1226
|
+
codec); there is no custom `parse` hook, and a bad call throws
|
|
1227
|
+
`SchemaParseError` (was `QueryToolError`). `report` options apply to
|
|
1228
|
+
`parseQueryTool` only; the model's message is set with `errorFormat`.
|
|
1229
|
+
- The zod grammar is gone: each expr's `static toSchema`, `exprDefSchema`,
|
|
1230
|
+
`SchemaCache` / `enumOf` / `orFold` / `refSchema` / `functionExprSchema` /
|
|
1231
|
+
`insertRowSchema` / `updateSetSchema` / `sorterSchema`, `withAid`,
|
|
1232
|
+
`sharedIdRegistry`, `directedMessage`. A custom expr kind gives its branch
|
|
1233
|
+
with `static toA(build)`.
|
|
1234
|
+
- Calling `buildSchemas` every turn is now a cache lookup; it no longer
|
|
1235
|
+
grows the heap (~2 MB per call before).
|
|
1236
|
+
|
|
1215
1237
|
## Schema depth
|
|
1216
1238
|
|
|
1217
|
-
`buildSchemas` / `querySchema` / `buildQueryTool` constrain the
|
|
1218
|
-
|
|
1239
|
+
`buildSchemas` / `querySchema` / `buildQueryTool` constrain the model-facing
|
|
1240
|
+
grammar along **five independent axes**, each dialed by `depth`:
|
|
1219
1241
|
|
|
1220
1242
|
| axis | levels (loose → tight) | constrains |
|
|
1221
1243
|
| ----------- | -------------------------------------------- | ---------------------------------------- |
|
|
@@ -1223,6 +1245,7 @@ schema along **four independent axes**, each dialed by `depth`:
|
|
|
1223
1245
|
| `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
|
|
1224
1246
|
| `functions` | `open` · `names` · `typed` | function name + named-arg objects |
|
|
1225
1247
|
| `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
|
|
1248
|
+
| `writes` | `open` · `names` · `typed` | INSERT rows / UPDATE SET (free record, writable names, typed values) |
|
|
1226
1249
|
|
|
1227
1250
|
Pass a full `SchemaDepth` object, a partial one (unset axes stay loose), or a
|
|
1228
1251
|
preset string: `'open'` (every axis loose — free strings) and `'paired'` (every
|
package/aeye-query.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
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
4
|
|
|
5
|
-
It
|
|
5
|
+
It depends on `@aeye/schema` (the model-facing grammar) and `zod` (its own value checks), and is exhaustively type-safe: every polymorphic node is a discriminated union, so handling is compiler-checkable with no `any`/casts.
|
|
6
6
|
|
|
7
7
|
## When to use it
|
|
8
8
|
|
|
@@ -13,7 +13,7 @@ It is standalone (only depends on `zod`) and exhaustively type-safe: every polym
|
|
|
13
13
|
|
|
14
14
|
## The query/expr JSON contract (state once)
|
|
15
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`
|
|
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` give the `@aeye/schema` grammar the model emits against (rendered per model, decoded back in one pass), and that grammar 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
17
|
|
|
18
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
19
|
|
|
@@ -398,7 +398,7 @@ A declarer cannot break the lattice by writing CODE — the library compiles the
|
|
|
398
398
|
|
|
399
399
|
## Schema depth & capability gating
|
|
400
400
|
|
|
401
|
-
`buildSchemas` / `querySchema` / `buildQueryTool` constrain the
|
|
401
|
+
`buildSchemas` / `querySchema` / `buildQueryTool` constrain the model-facing grammar along **five independent axes**, each dialed by `depth`:
|
|
402
402
|
|
|
403
403
|
| axis | levels (loose → tight) | constrains |
|
|
404
404
|
| ---- | ---------------------- | ---------- |
|
|
@@ -406,6 +406,7 @@ A declarer cannot break the lattice by writing CODE — the library compiles the
|
|
|
406
406
|
| `typeNames` | `open` · `enum` | bare Type-name positions (`from`, `into`, …) |
|
|
407
407
|
| `functions` | `open` · `names` · `typed` | function name + named-arg objects |
|
|
408
408
|
| `filters` | `open` · `paired` | the `filters` clause `(field, op)` pairs |
|
|
409
|
+
| `writes` | `open` · `names` · `typed` | INSERT rows / UPDATE SET: a free record, the writable field names, or each field's typed value (`FieldType.toA()`) or an expression |
|
|
409
410
|
|
|
410
411
|
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
|
|
|
@@ -469,46 +470,57 @@ Bridges: `tableToGinType(table)` (the row's gin `obj`: `nullable<…>`, `enum` f
|
|
|
469
470
|
|
|
470
471
|
## The LLM tool
|
|
471
472
|
|
|
472
|
-
The
|
|
473
|
-
|
|
474
|
-
- **`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.
|
|
475
|
-
- **`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`.)
|
|
476
|
-
- **`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.
|
|
477
|
-
|
|
478
|
-
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.
|
|
473
|
+
The model-facing schema is **`@aeye/schema`** (`a`), not zod: one static grammar module (`QueryGrammar`) whose registry-dependent part is bound per `(registry, version, options)` and cached, rendered per model on demand (records as pairs for OpenAI strict, JSON text where recursion isn't allowed, …), and decoding the model's answer back into the code shape in one pass.
|
|
479
474
|
|
|
480
475
|
```ts
|
|
481
|
-
import {
|
|
482
|
-
|
|
483
|
-
const types = await selectTypes(engine, 'revenue by customer last month'); // narrow the schema
|
|
476
|
+
import { buildSchemas, querySchema, buildQueryTool, queryToolSchema, QueryGrammar } from '@aeye/query';
|
|
477
|
+
import { OPENAI_STRICT } from '@aeye/schema';
|
|
484
478
|
|
|
485
|
-
//
|
|
486
|
-
const
|
|
487
|
-
|
|
488
|
-
|
|
479
|
+
// Every part of the language, bound for this registry and these options (cached: calling it every turn is a lookup).
|
|
480
|
+
const { Query, Expr, Select } = buildSchemas(engine, { strict: true, maxEnumSize: 100 });
|
|
481
|
+
Query.render(OPENAI_STRICT).jsonSchema; // what the model is sent
|
|
482
|
+
const res = Query.render(OPENAI_STRICT).parse(wire); // { ok, value: QueryDef } | { ok: false, issues, message }
|
|
489
483
|
|
|
490
|
-
//
|
|
491
|
-
const
|
|
484
|
+
// A tool's arguments: `{ query: <structured> }`, or `{ query: string }` past `max` Types.
|
|
485
|
+
const args = querySchema(engine, { depth: 'paired', types });
|
|
492
486
|
|
|
493
|
-
// The
|
|
494
|
-
const
|
|
487
|
+
// The ready-made tool: decodes into a runnable `Query`, runs it.
|
|
488
|
+
const tool = buildQueryTool(engine, { depth: 'paired', types, errorFormat: 'full' });
|
|
495
489
|
```
|
|
496
490
|
|
|
497
|
-
|
|
491
|
+
- **`buildSchemas(engineOrRegistry, options?) → QuerySchemas`** — `{ Type, Expr, Source, Join, Order, SelectField, Select, Insert, Update, Delete, SetOperation, CTE, ExprQuery, Query }`, each a `Bound` (`render(profile)` → `jsonSchema`, `parse`, `encode`, …), bound lazily. The code type is query's own (`Query` decodes to `QueryDef`, `Expr` to `ModelExprDef` = `ExprDef` minus the position-only kinds).
|
|
492
|
+
- **`QueryGrammar`** — the module itself, for your own results: `QueryGrammar.result('Query_select')`, `QueryGrammar.result(a.object({ query: a.ref('Query'), why: a.string() }))`, bound with `(registry, options?)`; hand one to a core `Tool` / `Prompt` with `.adapt((ctx) => [ctx.registry, options])`. `QUERY_RESULTS` holds the named results `buildSchemas` binds.
|
|
493
|
+
- **`querySchema(engine, options?)`** — the tool arguments (`QueryArgs`, a bundle with no arguments left, or `QueryProseArgs` past `max`).
|
|
494
|
+
- **`queryToolSchema(engine, options?) → Bindable<Query>`** — the arguments wrapped in a codec whose decode parses the `QueryDef` with the owned structural parser (`registry.parseCheckedQuery`) and runs the engine's semantic validation (`validateQuery`): a clean query decodes to the runnable `Query`; problems are a `Rejection` at their paths under `query`, so the model is told in @aeye/schema's format like any other schema error.
|
|
495
|
+
- **`buildQueryTool(engine, options?) → Tool<…, Query, Promise<QueryResult>>`** — that schema as a core `Tool` whose `call` RUNS the query. No custom `parse` hook: `tool.parse(ctx, args, plan)` decodes through the request plan and throws a `SchemaParseError` whose `message` is what the model is told. Options: everything `buildSchemas` takes, `max` (string fallback), `name`, `description`, `runtime`, and `errorFormat` (the detail level / options of the model's message: `'summary'` · `'list'` · `'markers'` · `'full'`, default `'full'`, capped at 2000 characters).
|
|
496
|
+
- **`parseQueryTool(engine, raw, options?) → Query | QueryToolError`** / **`parseQueryRequest(engine, raw, options?) → { query, problems, report }`** — the same structural + semantic pipeline for a value already in the code shape (a CLI, a file, a harness) without a tool or a model, reporting with `Code.formatProblems` (`report` options below).
|
|
498
497
|
|
|
499
|
-
|
|
500
|
-
import { buildQueryTool } from '@aeye/query';
|
|
498
|
+
**What the model is told.** A structural mistake is caught by the schema (unknown kind, a misspelt enum value, a missing member, a wrong type), a semantic one by the codec (an unknown field at an open depth, a relation compared as a value, a param conflict) — both come back in the same format: the model's own JSON, trimmed to the paths that matter, a marker under each mistake, "did you mean" for misspelt names:
|
|
501
499
|
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
500
|
+
```
|
|
501
|
+
1 problem in the arguments of query:
|
|
502
|
+
|
|
503
|
+
{
|
|
504
|
+
"query": {
|
|
505
|
+
"kind": "select",
|
|
506
|
+
"fields": [{"expr":{"kind":"field-ref","source":"product","field":"id"}}],
|
|
507
|
+
"from": {"kind":"type","type":"product"},
|
|
508
|
+
"where": [
|
|
509
|
+
{
|
|
510
|
+
"kind": "comparison",
|
|
511
|
+
"op": "notlike",
|
|
512
|
+
^^^^^^^^^ query.where[0].op: Expected one of: =, <>, <, <=, >, >=, like, notLike, ilike — did you mean `notLike`?
|
|
505
513
|
```
|
|
506
514
|
|
|
507
|
-
`
|
|
515
|
+
`errorFormat: 'summary'` sends one line per problem; `'list'` adds the paths; `'markers'` the echo without expected types.
|
|
508
516
|
|
|
509
|
-
|
|
517
|
+
**Caching and memory.** The dynamic step is memoized per registry (a `WeakMap`, so a dropped registry frees its grammar) and each result keeps `QUERY_BIND_CACHE_SIZE` (4) binds: a query bind rendered on 4 profiles keeps ~8.8 MB, so the cap holds ~35 MB per result in use. `Registry.version` bumps on every registration, so a registry that changed gets a fresh grammar. Nothing is kept per call (the zod path's process-global `sharedIdRegistry`, ~2 MB per `buildSchemas` call, is gone).
|
|
510
518
|
|
|
511
|
-
|
|
519
|
+
**Extension.** A registered expr class that isn't a builtin kind contributes its branch through `static toA(build: QueryGrammarBuild)` (the build carries the Types offered, the resolved depth and functions, `build.ref(...)` / `build.fn(...)` for references and calls at the depth, `build.Expr` / `build.Query` for recursion); one without `toA` is left out of the model's grammar. A field type's model-facing value is `FieldType.toA()` (typed INSERT rows / UPDATE SET at `writes: 'typed'`); a refinement's declared zod `value` gate is checked on decode.
|
|
520
|
+
|
|
521
|
+
### Compiler-style problem reports (`parseQueryTool`)
|
|
522
|
+
|
|
523
|
+
`QueryToolError.report` renders every problem — STRUCTURAL (the owned, zod-free parser `registry.parseCheckedQuery`) *and* SEMANTIC (`validateWalk`: unknown fields, param conflicts, per-Type validators) — as underlined diagnostics over the query JSON:
|
|
512
524
|
|
|
513
525
|
```
|
|
514
526
|
── line 21 ──────────────────────────────────────────────
|
|
@@ -517,39 +529,17 @@ const result = await tool.run(query, ctx); //
|
|
|
517
529
|
│ error: expected an expression
|
|
518
530
|
```
|
|
519
531
|
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
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.
|
|
523
|
-
|
|
524
|
-
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.
|
|
525
|
-
|
|
526
|
-
**"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:
|
|
527
|
-
- **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`);
|
|
528
|
-
- **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.
|
|
529
|
-
|
|
530
|
-
**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.
|
|
531
|
-
|
|
532
|
-
### Owned structural parser (zod-free, accumulating) — the ACTIVE gate
|
|
533
|
-
|
|
534
|
-
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.
|
|
535
|
-
|
|
536
|
-
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`.
|
|
537
|
-
|
|
538
|
-
**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).
|
|
539
|
-
|
|
540
|
-
**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.
|
|
541
|
-
|
|
542
|
-
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`.
|
|
532
|
+
Messages are aid-directed: the owned parser's `Shape` combinators draw their labels from `AID_REGISTRY` (`aidInfo`) and their suggestions from `didYouMean` (`src/aids.ts`): `"left": "oops"` → "expected **an expression**, got a string"; `"kind": "comparise"` → "unknown **expression kind** `comparise` — did you mean `comparison`?"; an unknown field → "Type 'user' (source 'user') has no field 'ghost'." `parseQueryTool(engine, raw, { report })` forwards a `FormatProblemsOptions` (`{ contextLines?, sectionHeaders?, lineNumbers?, maxProblems? }`) into `formatProblems`.
|
|
543
533
|
|
|
544
|
-
|
|
534
|
+
**"Did you mean?" on every unknown-name diagnostic.** `didYouMean(input, candidates, { max? })` appends "` — did you mean \`X\`?`" when a bad NAME is a typo of a valid one (case-insensitive edit distance under `suggestionBudget(len) = min(3, max(1, floor(len/3)))`), for fields, sources, Types, functions, named args and output names. (@aeye/schema's own suggester is the same algorithm.)
|
|
545
535
|
|
|
546
|
-
|
|
536
|
+
### Owned structural parser (zod-free, accumulating)
|
|
547
537
|
|
|
548
|
-
|
|
538
|
+
`registry.parseCheckedQuery(def, problems)` / `parseCheckedExpr` / `parseCheckedSource` dispatch to each class's owned `static SHAPE` (`src/shape/`): never throwing, accumulating every problem in one pass, building a value `.toJSON()`-equal to `from(def)`. The query tool's codec and `parseQueryTool` both use it; through the tool it meets only what the schema already accepted. The combinators are on the public barrel as the namespace `shape` (`shape.obj({ kind: shape.lit('…'), … })`), so a class defined outside the package can own its `static SHAPE`.
|
|
549
539
|
|
|
550
|
-
### Compact
|
|
540
|
+
### Compact schema (shared `$defs`)
|
|
551
541
|
|
|
552
|
-
The
|
|
542
|
+
The largest repeated fragments are named types of the grammar, written once as `$defs`: each Type's field-name enum (`Fields_<Type>`), the shared `param` expr, `Limit` (number-or-param), and the typed-args objects, keyed by argument SIGNATURE (`Args`, `Args_2`, …) so the 100+ builtin functions share a few dozen. On the bundled example fixture: `open` 16 KB (lenient) / 22 KB (OpenAI strict), `paired` 77 KB / 94 KB; a size test guards re-inlining.
|
|
553
543
|
|
|
554
544
|
## Self-describing the engine to a model
|
|
555
545
|
|