@altopelago/sansa 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.
@@ -0,0 +1,788 @@
1
+ # SANSA Parser API Contract
2
+
3
+ Status: implementation contract for the address parser/model, resolver, query clause parser/model, query expression parser/model, bounded query evaluator, and standalone query tooling slices.
4
+
5
+ The parser validates SANSA address syntax and returns a structural model. The resolver applies the parsed selector model to a host-supplied namespace adapter. The query parser validates the SANSA.Query clause and expression surfaces and returns structural models. The query evaluator applies a bounded query subset over host-exposed binding metadata. The package does not inspect host values directly, check authorization, or assign semantics to qualifiers.
6
+
7
+ The implementation capability manifest is [capabilities.json](capabilities.json). It advertises `AEON.ValueSemantics`, `SANSA.Addressing`, `SANSA.Resolve`, `SANSA.Query`, Query budget controls, the experimental `validation` Query policy, and experimental `SANSA.Transform` extensions.
8
+
9
+ CTS lanes:
10
+
11
+ ```bash
12
+ npm run cts
13
+ npm run cts:value-semantics
14
+ npm run cts:query
15
+ npm run cts:query:experimental
16
+ ```
17
+
18
+ The default Query CTS lane is core conformance and skips experimental extension cases. The experimental lane includes those cases for implementations that advertise matching extensions.
19
+
20
+ ## Entry Points
21
+
22
+ ```js
23
+ parseAddress(input, options?)
24
+ parseAddressOrThrow(input, options?)
25
+ parseQuery(input, options?)
26
+ parseQueryOrThrow(input, options?)
27
+ parseQueryExpression(input, options?)
28
+ parseQueryExpressionOrThrow(input, options?)
29
+ evaluateQuery(input, namespace, options?)
30
+ evaluateValueSemanticsOperation(operation, input)
31
+ resolveAddress(input, namespace, options?)
32
+ renderAddress(address)
33
+ renderQuery(query)
34
+ renderQueryExpression(expression)
35
+ renderQualifierExpression(expression)
36
+ renderQualifierTerm(term)
37
+ ```
38
+
39
+ `parseAddress` returns a discriminated result:
40
+
41
+ ```js
42
+ { ok: true, address }
43
+ { ok: false, errors: [{ code, message, index }] }
44
+ ```
45
+
46
+ `parseAddressOrThrow` returns `address` or throws `SansaParseError`.
47
+
48
+ `parseQuery` returns a discriminated result:
49
+
50
+ ```js
51
+ { ok: true, query }
52
+ { ok: false, errors: [{ code, message, index }] }
53
+ ```
54
+
55
+ `parseQueryOrThrow` returns `query` or throws `SansaParseError`.
56
+
57
+ `parseQueryExpression` returns a discriminated result:
58
+
59
+ ```js
60
+ { ok: true, expression }
61
+ { ok: false, errors: [{ code, message, index }] }
62
+ ```
63
+
64
+ `parseQueryExpressionOrThrow` returns `expression` or throws `SansaParseError`.
65
+
66
+ `evaluateQuery` accepts either a query string or a parsed `SansaQuery` and returns:
67
+
68
+ ```js
69
+ { ok: true, results, diagnostics }
70
+ { ok: false, results: [], errors }
71
+ ```
72
+
73
+ Experimental extensions are enabled by default when the package advertises them. Callers can disable the transform-library surface with:
74
+
75
+ ```js
76
+ evaluateQuery(query, namespace, { extensions: { transform: false } })
77
+ ```
78
+
79
+ Callers can also provide an exact allow-list:
80
+
81
+ ```js
82
+ evaluateQuery(query, namespace, { enabledExtensions: ["sansa.transform.objectFrom"] })
83
+ ```
84
+
85
+ A disabled advertised extension fails with `SANSA_QUERY_EVALUATE_UNSUPPORTED_EXTENSION` and includes the extension id in the diagnostic.
86
+
87
+ The proposal-stage validation policy can be enabled with:
88
+
89
+ ```js
90
+ evaluateQuery(query, namespace, { policy: "validation" })
91
+ ```
92
+
93
+ This policy rejects presentation and transform behavior before evaluation: `order by`, `offset`, `limit`, object projection expressions, and transform-library helpers. Rejections use `SANSA_QUERY_POLICY_VIOLATION` with `phase: "policy"`.
94
+
95
+ Query evaluation budgets are optional and fail closed:
96
+
97
+ ```js
98
+ evaluateQuery(query, namespace, {
99
+ budget: {
100
+ maxFromBindings: 100000,
101
+ maxWhereCandidates: 100000,
102
+ maxOrderCandidates: 100000,
103
+ maxResultRecords: 10000
104
+ }
105
+ })
106
+ ```
107
+
108
+ Budget exhaustion returns `SANSA_QUERY_BUDGET_EXCEEDED` with `phase`, `budget`, `limit`, and `observed`. It never implicitly truncates the Binding Set or returns partial results.
109
+
110
+ The standalone query CLI exposes these budgets as `--max-from-bindings`, `--max-where-candidates`, `--max-order-candidates`, and `--max-result-records`. The browser workbench exposes the same four limits as optional evaluation budget fields.
111
+
112
+ `evaluateValueSemanticsOperation` evaluates the Shared AEON Value Semantics minimum consumer operation shape used by the CTS scaffold:
113
+
114
+ ```js
115
+ evaluateValueSemanticsOperation("equal", {
116
+ left: { category: "finiteNumber", value: "42" },
117
+ right: { category: "finiteNumber", value: "42" }
118
+ })
119
+
120
+ evaluateValueSemanticsOperation("compare", {
121
+ left: { category: "negativeInfinity" },
122
+ right: { category: "finiteNumber", value: "0" }
123
+ })
124
+
125
+ evaluateValueSemanticsOperation("isValue", {
126
+ value: { category: "string", value: "active" }
127
+ })
128
+ ```
129
+
130
+ The supported operations are `equal`, `notEqual`, `compare`, and `isValue`. The supported minimum-profile categories are `finiteNumber`, `positiveInfinity`, `negativeInfinity`, `nan`, `string`, `boolean`, `explicitNull`, `explicitAbsence`, `missing`, `container`, and `bindingSet`.
131
+
132
+ `resolveAddress` accepts either an address string or a parsed `SansaAddress` and returns:
133
+
134
+ ```js
135
+ { ok: true, bindings, diagnostics }
136
+ { ok: false, bindings: [], errors }
137
+ ```
138
+
139
+ Parse errors are returned through the same `ok: false` shape. Normal no-match resolution returns `ok: true` with an empty `bindings` array.
140
+
141
+ Resolve distinguishes a **resolution miss** from a **resolution failure**. A miss occurs when a valid, supported selector applies to the namespace but finds no exposed structure on one or more branches; that branch contributes no bindings. A failure occurs when resolution cannot safely or validly continue, such as an unsupported selector capability, missing contextual root, forbidden boundary escape, implementation limit failure, or exact-expression multiplicity violation.
142
+
143
+ Resolve invariants:
144
+
145
+ - Selectors are applied left to right.
146
+ - Each selector consumes and produces an ordered Binding Set.
147
+ - Current bindings are processed in Binding Set order.
148
+ - Per-binding results are appended in deterministic local structural order.
149
+ - Resolve does not implicitly deduplicate bindings; repeated traversal routes may produce repeated binding occurrences.
150
+ - A supported selector that is structurally inapplicable to one input binding produces no bindings for that branch.
151
+ - Unsupported or forbidden operations fail explicitly.
152
+ - Every output binding is expected to retain a canonical address when the host adapter exposes one.
153
+ - An exact expression must not produce more than one binding; multiplicity violations fail with `SANSA_RESOLVE_EXACT_MULTIPLICITY_VIOLATION`.
154
+ - Resolve performs no value evaluation, predicate evaluation, projection, sorting, slicing, aggregation, or mutation.
155
+
156
+ Parent traversal defaults to the conservative structural model: traversal from the effective resolution root resolves to an empty Binding Set. The effective resolution root is the root binding established by `$`, `?`, or the root of a dynamic resolution context for the current branch. Callers that need stricter boundary diagnostics can pass:
157
+
158
+ ```js
159
+ resolveAddress('?.^', namespace, {
160
+ contextualRoot,
161
+ failOnParentFromEffectiveRoot: true
162
+ })
163
+ ```
164
+
165
+ This reports `SANSA_RESOLVE_BOUNDARY_ESCAPE_FORBIDDEN` instead of an empty Binding Set. Callers that forbid parent traversal entirely can pass:
166
+
167
+ ```js
168
+ resolveAddress('$.items[0].^', namespace, {
169
+ parentTraversal: 'forbid'
170
+ })
171
+ ```
172
+
173
+ This reports `SANSA_RESOLVE_PARENT_TRAVERSAL_FORBIDDEN`, distinct from `SANSA_RESOLVE_UNSUPPORTED_PARENT`, which means the namespace adapter does not expose parent traversal.
174
+
175
+ Query evaluation diagnostics include query context when available:
176
+
177
+ ```js
178
+ {
179
+ code,
180
+ message,
181
+ phase,
182
+ candidateAddress,
183
+ extension,
184
+ budget,
185
+ limit,
186
+ observed
187
+ }
188
+ ```
189
+
190
+ `phase` is one of `parse`, `policy`, `from`, `where`, `order`, or `select`. `candidateAddress` is present when the failure occurs while evaluating a specific candidate binding. `extension` identifies disabled or unsupported extension surfaces. `budget`, `limit`, and `observed` identify budget exhaustion context.
191
+
192
+ ## Command Line Tool
193
+
194
+ The package exposes `sansa-query` and the local `npm run query` script. The tool is intended for development fixtures and language exploration rather than host integration.
195
+
196
+ ```bash
197
+ npm run query -- --query 'from $.inventory.items.* where .qty >= 2 select .sku'
198
+ npm run query -- --mode parse --format json --query 'from $.inventory.items.* select .sku'
199
+ npm run query -- --policy validation --query 'from $.inventory.items.* where .qty >= 4 select .sku'
200
+ npm run query -- --disable-transform --query 'from $.table.content.* select objectFrom($.table.header.*, .*)'
201
+ npm run query -- --params '{"source":{"type":"SansaAddressLiteral","address":"$.inventory.items[3]"},"field":{"type":"SansaAddressLiteral","address":"?.sku"}}' --query 'from path($.<"params">.source) select path($.<"params">.field)'
202
+ ```
203
+
204
+ Evaluate-mode text output renders values in an AEON-like display form. Strings remain quoted, constructed objects render compactly, and explicit null bindings with a surfaced `nullReason` render as `!reason`, for example `!notSet`. JSON output is unchanged and remains the stable structured result envelope for tooling.
205
+
206
+ Options:
207
+
208
+ - `--query`, `-q`: query source
209
+ - `--query-file`: read query source from a file
210
+ - `--fixture`, `-f`: AEON or JSON namespace fixture, defaulting to `fixtures/query-inventory.json`
211
+ - `--fixture-kind`: force fixture kind as `aeon` or `json`; otherwise inferred from the file extension
212
+ - `--params`: JSON params mounted at `$.<"params">`
213
+ - `--params-file`: read JSON params from a file and mount them at `$.<"params">`
214
+ - `--mode`: `evaluate` or `parse`
215
+ - `--format`: `text` or `json`
216
+ - `--policy`: optional query policy, currently `validation`
217
+ - `--disable-transform`: disable experimental `SANSA.Transform` helpers during evaluation
218
+ - `--max-from-bindings`: fail if the from source resolves more than this many bindings
219
+ - `--max-where-candidates`: fail if where would evaluate more than this many candidates
220
+ - `--max-order-candidates`: fail if order by would sort more than this many candidates
221
+ - `--max-result-records`: fail if select would produce more than this many result records
222
+
223
+ The default CLI fixture is JSON so `sansa-query` can run without optional host integrations after package install. AEON fixtures are compiled with an optional AEON TypeScript Core runtime and adapted into a SANSA resolver namespace. JSON fixture bindings remain host-neutral objects. The built-in JSON adapter reads `root`, `children`, `attributeSpace` or `attributes`, `localSpaces`, and scalar values through `value` or `scalar`.
224
+
225
+ AEON fixture support is optional. The tool resolves AEON Core from `SANSA_AEON_CORE_MODULE`, from an installed `@altopelago/aeon-core` visible to the calling project, or from the sibling aeon-family development workspace path. JSON fixtures and Query parsing do not require AEON Core.
226
+
227
+ Params may be supplied either as a full local-space fixture binding with `children`, or as a simple object map. Structured SANSA Address Literal values use `{ "type": "SansaAddressLiteral", "address": "..." }`; these are preserved as `sansa` bindings so query expressions can activate them with `path(...)`.
228
+
229
+ The package also includes a browser workbench:
230
+
231
+ ```bash
232
+ npm run query:web
233
+ ```
234
+
235
+ The workbench serves [tools/query-web](../tools/query-web), defaults to `.aeon` source input, and exposes a local `/api/query` endpoint. For `.aeon` source, the endpoint uses the optional AEON TypeScript core compiler to derive a host-neutral SANSA resolver namespace before running SANSA.Query. A params editor mounts a small AEON source snippet as `$.<"params">`; top-level params bindings become children of that local address space. JSON fixture mode remains available for direct resolver-shape debugging. The browser UI includes a Normal/Validation policy toggle, a Transform extension toggle, and evaluation budget inputs. `/api/query` accepts `policy: "validation"`, `transformExtensions: false`, and `budget` for evaluate requests.
236
+
237
+ Workbench responses include `text` for successful results and diagnostics. Successful parse and evaluate responses also include `inspect`, a scan-friendly diagnostic view for the browser workbench. Text mode is intended for compact inspection, Inspect mode shows candidate/value metadata, and JSON mode exposes the structured result or diagnostic payload.
238
+
239
+ Workbench example queries are defined as grouped catalog data in [tools/query-web/examples.mjs](../tools/query-web/examples.mjs). The UI renders its example menu from that module, and tests use the same catalog to keep labels, queries, and expected behavior in sync.
240
+
241
+ ## Address Model
242
+
243
+ ```js
244
+ {
245
+ type: "SansaAddress",
246
+ root,
247
+ selectors,
248
+ qualifierExpression,
249
+ isExact,
250
+ canonical
251
+ }
252
+ ```
253
+
254
+ `root.kind` is `absolute` for `$` or `contextual` for `?`.
255
+
256
+ `isExact` is true only when every selector is one of:
257
+
258
+ - `member`
259
+ - `position`
260
+ - `attributeSpace`
261
+ - `localSpace`
262
+
263
+ Parent traversal, position ranges, expansion selectors, filters, and name patterns make the address expression non-exact.
264
+
265
+ ## Selector Nodes
266
+
267
+ ```js
268
+ { type: "member", name, quoted }
269
+ { type: "position", index }
270
+ { type: "positionRange", start, end }
271
+ { type: "parent" }
272
+ { type: "attributeSpace" }
273
+ { type: "localSpace", name }
274
+ { type: "directExpansion" }
275
+ { type: "descendantExpansion" }
276
+ { type: "namePattern", pattern }
277
+ { type: "semanticTypeFilter", name }
278
+ { type: "representationKindFilter", name }
279
+ ```
280
+
281
+ Selector names and patterns are decoded string values. Renderers choose the shortest unambiguous canonical form.
282
+
283
+ ## Resolve Namespace Adapter
284
+
285
+ Resolve is host-adapted. A namespace must expose a root binding:
286
+
287
+ ```js
288
+ {
289
+ root,
290
+ contextualRoot?,
291
+ children?(binding),
292
+ parent?(binding),
293
+ member?(binding, name),
294
+ position?(binding, index),
295
+ attributeSpace?(binding),
296
+ localSpace?(binding, name),
297
+ name?(binding),
298
+ index?(binding),
299
+ semanticType?(binding),
300
+ representationKind?(binding),
301
+ value?(binding),
302
+ nullReason?(binding),
303
+ semanticTypeMatches?(binding, expected),
304
+ representationKindMatches?(binding, expected)
305
+ }
306
+ ```
307
+
308
+ For simple hosts, bindings may expose fields directly:
309
+
310
+ ```js
311
+ {
312
+ address,
313
+ name,
314
+ index,
315
+ semanticType,
316
+ datatype,
317
+ representationKind,
318
+ kind,
319
+ type,
320
+ scalarKind,
321
+ valueKind,
322
+ literalKind,
323
+ nullReason,
324
+ value,
325
+ scalar,
326
+ children,
327
+ parent,
328
+ attributeSpace,
329
+ attributes
330
+ }
331
+ ```
332
+
333
+ `scalarKind`, `valueKind`, or `literalKind` may be used by host-neutral fixtures to preserve scalar forms that JSON cannot express directly, such as `nan`, `infinity`, and explicit `null`. `nullReason` carries the surfaced AEON null reason, such as `notSet` or `notApplicable`.
334
+
335
+ Exact member and position selectors select direct children. This implementation caps position indexes and position range endpoints at `999999`; SANSA v1 portability requires implementations to support at least one million addressable positions, expressed as indexes `0` through `999999` inclusive. Larger accepted values are implementation-defined and non-portable. Implementations that accept larger values should surface `SANSA_NON_PORTABLE_POSITION_INDEX` when their host API supports non-fatal diagnostics. Position ranges select inclusive positional children exposed by the host binding; open start means position `0`, open end means through the final exposed positional child, and reversed ranges resolve to an empty binding set. `.^` selects an exposed parent binding, resolves empty at the effective resolution root unless stricter policy is requested, and fails explicitly when parent traversal is unsupported or forbidden. `.*` returns direct children. `.**` returns descendants in deterministic preorder, excluding the current binding. Descendant expansion follows structural children only; it does not implicitly enter attribute or local address spaces. `.("pattern")` selects direct children whose binding name matches the complete glob pattern, where `?` matches one Unicode code point and `*` matches zero or more Unicode code points. Within the decoded pattern payload, `\?`, `\*`, and `\\` match literal question mark, asterisk, and backslash characters respectively. Pattern matching operates on the exact exposed binding name without normalization or locale-sensitive comparison.
336
+
337
+ `#name` filters the current binding set by semantic type. The default matcher accepts exact semantic type names and base names before `<...>` or `[...]`. `%name` filters the current binding set by representation kind.
338
+
339
+ `?` uses a binding supplied through `options.contextualRoot` or `namespace.contextualRoot`. Unlike `root`, `contextualRoot` is a binding value, not a callback. Hosts that need a dynamic contextual root should resolve it before calling `resolveAddress`. Attribute and local address-space traversal are explicit transitions through `.@` and `.<"name">`. They fail explicitly unless exposed by the namespace adapter or binding model. When local-space traversal is supported but a binding does not expose the named local space, normal resolution returns an empty binding set.
340
+
341
+ Qualifiers are preserved by the parser but ignored by generic structural resolution.
342
+
343
+ ## Query Parser Model
344
+
345
+ ```js
346
+ {
347
+ type: "SansaQuery",
348
+ from,
349
+ where,
350
+ orderBy,
351
+ offset,
352
+ limit,
353
+ select,
354
+ clauses,
355
+ canonical
356
+ }
357
+ ```
358
+
359
+ Query parsing validates query structure and expression syntax only. It does not evaluate query expressions, resolve candidate bindings, apply filters, sort bindings, slice results, or construct projection output.
360
+
361
+ The accepted clause order is:
362
+
363
+ ```text
364
+ from
365
+ where
366
+ order by
367
+ offset
368
+ limit
369
+ select
370
+ ```
371
+
372
+ `from` is required and must contain either one valid SANSA address expression or a `path(...)` source expression. `select` is required and terminal. `where`, `select`, and order-key expression bodies carry both a canonical source string and an expression AST. `order by` is split into top-level keys, each with an `asc` or `desc` direction; omitted directions canonicalize to `asc`. `offset` and `limit` accept non-negative integers without leading zeroes up to this implementation's query integer cap, `9007199254740991`.
373
+
374
+ Query comments are lexical trivia:
375
+
376
+ ```text
377
+ // line comment
378
+ /* block comment */
379
+ ```
380
+
381
+ Comments are removed from canonical query rendering.
382
+
383
+ Query clause nodes:
384
+
385
+ ```js
386
+ { type: "fromClause", source: "address", address }
387
+ { type: "fromClause", source: "expression", expression, ast }
388
+ { type: "whereClause", expression, ast }
389
+ { type: "orderByClause", keys }
390
+ { type: "offsetClause", value }
391
+ { type: "limitClause", value }
392
+ { type: "selectClause", expression, ast }
393
+ ```
394
+
395
+ Order keys:
396
+
397
+ ```js
398
+ { type: "orderKey", expression, ast, direction }
399
+ ```
400
+
401
+ ## Query Expression Model
402
+
403
+ The expression parser produces a syntax AST only. It does not assign semantic meaning to functions, compare values, collapse Binding Sets, resolve addresses, or decide whether a query is authorized.
404
+
405
+ Expression nodes:
406
+
407
+ ```js
408
+ { type: "literalExpression", kind, value, canonical }
409
+ { type: "resolutionExpression", scope, address, canonical }
410
+ { type: "groupExpression", expression, canonical }
411
+ { type: "unaryExpression", operator, argument, canonical }
412
+ { type: "binaryExpression", operator, left, right, canonical }
413
+ { type: "functionCallExpression", name, arguments, canonical }
414
+ { type: "existenceExpression", operator, argument, canonical }
415
+ { type: "cardinalityExpression", operator, argument, canonical }
416
+ { type: "projectionExpression", fields, canonical }
417
+ ```
418
+
419
+ Projection fields:
420
+
421
+ ```js
422
+ { type: "projectionField", name, expression }
423
+ ```
424
+
425
+ Resolution expression scopes:
426
+
427
+ - `current`: a leading dot expression such as `.name`
428
+ - `absolute`: a leading `$` SANSA address
429
+ - `contextual`: a leading `?` SANSA address
430
+
431
+ Recognized expression syntax:
432
+
433
+ - resolution expressions: `.name`, `.roles.*`, `$.users.*`, `$.<"params">.username`
434
+ - literals: double-quoted strings, numbers, `true`, `false`
435
+ - comparisons and membership: `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`
436
+ - Boolean operators: `not`, `and`, `or`
437
+ - parenthesized groups
438
+ - cardinality operators: `any(...)`, `all(...)`, `none(...)`
439
+ - function-call shape: `contains(.name, "x")`
440
+ - projection shape: `{ name = .name status = .status }`
441
+
442
+ Operator precedence:
443
+
444
+ ```text
445
+ parenthesized expression
446
+ not
447
+ comparison
448
+ and
449
+ or
450
+ ```
451
+
452
+ ## Query Evaluator
453
+
454
+ The evaluator is intentionally narrower than the query grammar. It exists to prove the parser, resolver, and expression model can execute together over host-neutral bindings.
455
+
456
+ Currently evaluated:
457
+
458
+ - `from` through SANSA Resolve or `path(...)` source activation
459
+ - `where` expressions that produce explicit Boolean values
460
+ - `order by` over string and number scalar keys
461
+ - `offset`
462
+ - `limit`
463
+ - `select` expressions
464
+ - scalar literals
465
+ - resolution expressions
466
+ - comparisons between same-type scalar values
467
+ - membership over Binding Sets with `in`
468
+ - Boolean `not`, `and`, `or`
469
+ - existence predicates over resolution expressions: `exists`, `absent`
470
+ - cardinality predicates over resolved binding sets: `any`, `all`, `none`
471
+ - built-in string functions: `contains`, `startsWith`, `endsWith`, `lower`, `upper`, `concat`
472
+ - dynamic address activation in expression positions with `path`
473
+ - missing-aware fallback with `fallback`
474
+ - dynamic direct-child resolution over addressable containers with `resolveChild`
475
+ - experimental transform-library object construction with `objectFrom`
476
+ - experimental transform-library field projection with `fieldsFrom`
477
+ - built-in value predicates: `isValue`, `isNull`, `isNullReason`, `isNaN`, `isInfinity`
478
+ - projection expressions
479
+
480
+ Boolean context accepts explicit Boolean scalar values and single resolved bindings that expose a Boolean scalar. It does not apply host-language truthiness to strings, numbers, nulls, objects, or Binding Sets. Boolean `not` evaluates its operand in Boolean context and returns the negated value. Boolean `and` and `or` short-circuit from left to right. `a and b` does not evaluate `b` when `a` is false; `a or b` does not evaluate `b` when `a` is true.
481
+
482
+ Membership uses comparison-style syntax but explicitly consumes the right operand as a Binding Set:
483
+
484
+ ```text
485
+ where "admin" in .roles.*
486
+ ```
487
+
488
+ The left operand is consumed in scalar context. Right-side bindings are evaluated in Binding Set order. Each right-side binding is consumed as a scalar and compared using equality comparison rules. Membership returns true on the first successful match and does not evaluate later bindings. Empty Binding Sets and fully evaluated non-matching sets evaluate to false. Membership does not skip incompatible bindings before a match: explicit null, NaN, missing scalar, cardinality, and mixed-type comparison failures surface as diagnostics. The right operand must evaluate to a Binding Set; string containment remains the `contains(...)` function.
489
+
490
+ Existence predicates inspect binding presence rather than scalar value:
491
+
492
+ ```text
493
+ exists(.email) == true when .email resolves one or more bindings
494
+ absent(.email) == true when .email resolves zero bindings
495
+ ```
496
+
497
+ Use semantic or representation filters inside the existence operand to guard later scalar comparisons:
498
+
499
+ ```text
500
+ where exists(.id#number) and .id > 2
501
+ ```
502
+
503
+ Without the `#number` filter, `.id > 2` may fail on a present non-number binding.
504
+
505
+ Missing bindings, explicit null values, and special numeric values are distinct:
506
+
507
+ ```text
508
+ absent(.status) == true when .status resolves zero bindings
509
+ isValue(.status) == true when .status resolves one ordinary scalar binding
510
+ isNull(.status) == true when .status resolves one explicit null binding
511
+ isNullReason(.status, "notSet") == true when the null reason matches
512
+ isNaN(.metric) == true when the scalar is explicit NaN
513
+ isInfinity(.limit) == true when the scalar is positive or negative infinity
514
+ ```
515
+
516
+ `isValue(...)` is a missing-aware ordinary scalar guard. It returns true when its operand evaluates to one string, Boolean, or finite number. It may inspect scalar expressions directly or consume a Binding Set produced by resolution or `path(...)`. It returns false for zero bindings, non-scalar bindings, explicit null, NaN, and infinity. More than one binding remains a cardinality error.
517
+
518
+ `isNull(...)`, `isNullReason(...)`, `isNaN(...)`, and `isInfinity(...)` consume their first operand in single-binding scalar context. A missing operand therefore fails unless the query guards it with `exists(...)` or another missing-aware operator.
519
+
520
+ `NaN` is not comparable. Scalar comparison and ordering over `NaN` fail with `SANSA_QUERY_EVALUATE_INVALID_COMPARISON`; use `isNaN(...)` for explicit tests. Infinity values remain numeric bounds and may participate in same-type numeric comparisons and ordering.
521
+
522
+ Current comparison policy:
523
+
524
+ | Operands | Equality | Ordering | Result |
525
+ | --- | --- | --- | --- |
526
+ | number and number | allowed | allowed | numeric comparison |
527
+ | string and string | allowed | allowed | Unicode scalar-value ordering |
528
+ | boolean and boolean | allowed | error | ordering emits `SANSA_QUERY_EVALUATE_INVALID_COMPARISON` |
529
+ | explicit null | error | error | use `isNull(...)` / `isNullReason(...)` |
530
+ | NaN | error | error | use `isNaN(...)` |
531
+ | infinity and number | allowed | allowed | numeric bound comparison |
532
+ | mixed types | error | error | no implicit coercion |
533
+
534
+ Until the shared value-semantics string-ordering profile is locked, this implementation slice compares strings by Unicode scalar value. It must not use host locale, process locale, database collation, or `localeCompare`-style host defaults for query comparison or `order by`.
535
+
536
+ Ordinary value-producing functions evaluate their arguments before invocation. Resolution-expression arguments are consumed in single-binding scalar context:
537
+
538
+ | Argument outcome | Diagnostic |
539
+ | --- | --- |
540
+ | zero bindings | `SANSA_QUERY_EVALUATE_MISSING_SCALAR` |
541
+ | multiple bindings | `SANSA_QUERY_EVALUATE_CARDINALITY` |
542
+ | unsupported scalar type | `SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL` |
543
+
544
+ The current built-in string functions are `contains`, `startsWith`, `endsWith`, `lower`, `upper`, and `concat`. Function-name matching is case-sensitive. They require string arguments and reject explicit null, NaN, infinity, Boolean, number, object, and Binding Set arguments unless a future function contract explicitly accepts one of those forms. Value predicates such as `isValue(...)`, `isNull(...)`, `isNullReason(...)`, `isNaN(...)`, and `isInfinity(...)` define their own argument contracts.
545
+
546
+ `path(value)` is a function-like structural operator. Its operand is consumed in scalar context and must be a structured SANSA Address Literal value. The initial representation is an object such as `{ type: "SansaAddressLiteral", address: "?.sku" }` or `{ type: "SansaAddressLiteral", address: parsedAddress }`. Plain strings are rejected and are not parsed as address syntax. In expression positions such as `select`, `where`, and `order by`, the activated address resolves in the current candidate context and returns a Binding Set. In `from path(...)`, the activated address supplies the source Binding Set for the query.
547
+
548
+ `fallback(primary, replacement)` is a function-like operator with lazy missing handling. The primary operand is consumed in scalar value context. If it resolves zero bindings, or raises a missing-scalar diagnostic, the replacement operand is evaluated and consumed in the same scalar value context. If the primary operand succeeds, the replacement operand is not evaluated. Explicit null values, cardinality errors, type errors, comparison errors, and unsupported-function errors do not trigger fallback.
549
+
550
+ `resolveChild(base, key)` is a function-like structural operator with a distinct argument contract. The base argument must be a resolution expression resolving exactly one addressable container. The key argument is consumed in scalar context; string keys select a direct member of the base, and non-negative integer keys select a direct positional child. A missing target returns an empty Binding Set. Multiple base bindings, multiple key bindings, unsupported key types, and multiple target bindings fail with diagnostics. It does not parse traversal strings, scan collections, or perform join semantics.
551
+
552
+ `objectFrom(keys, values)` is an experimental transform-library helper with a distinct argument contract. Both arguments must be resolution expressions. The key and value Binding Sets must have equal length. Key bindings must expose unique string scalar values. Value bindings must expose scalar values. The helper pairs keys and values by resolved order and returns one derived object. Mismatched lengths, duplicate keys, non-string keys, and non-scalar values fail with diagnostics. It is not part of the required SANSA.Query v1 core surface.
553
+
554
+ `fieldsFrom(keys, values, field, ...)` is an experimental transform-library helper. It uses the same ordered pairing model as `objectFrom`, then returns only the requested string-named fields. It is implemented for workbench and conformance experimentation, but is not part of the required SANSA.Query v1 core surface.
555
+
556
+ Cardinality predicates follow conventional quantified logic:
557
+
558
+ ```text
559
+ any(empty) = false
560
+ all(empty) = true
561
+ none(empty) = true
562
+ ```
563
+
564
+ `all(...)` therefore means every resolved binding satisfies the predicate; it does not by itself require that at least one binding exists. A non-empty all-match condition is expressed by combining `any(...)` and `all(...)`:
565
+
566
+ ```text
567
+ where any(.roles.* == "admin") and all(.roles.* == "admin")
568
+ ```
569
+
570
+ `only(...)` may parse as a generic function-call expression, but it is not part of the current evaluator surface. It is reserved as a possible future shorthand for the non-empty all-match pattern and currently evaluates as `SANSA_QUERY_EVALUATE_UNSUPPORTED_FUNCTION`.
571
+
572
+ ## Query Recipes
573
+
574
+ Recipes are non-normative examples that exercise multiple query features together. They are useful as implementation and workbench smoke tests.
575
+
576
+ Dynamic address literals can parameterize source, predicate, ordering, and projection:
577
+
578
+ ```text
579
+ from path($.<"params">.source)
580
+ where isValue(path($.<"params">.statusField)) and path($.<"params">.statusField) == "active"
581
+ order by path($.<"params">.sortField) asc
582
+ select path($.<"params">.field)
583
+ ```
584
+
585
+ `isValue(...)`, `exists(...)`, and explicit null predicates can distinguish ordinary values, explicit nulls, and missing bindings:
586
+
587
+ ```text
588
+ from $.inventory.items.*
589
+ where isValue(.status) or (exists(.status) and isNull(.status))
590
+ select { sku = .sku status = fallback(.status, "missing") }
591
+ ```
592
+
593
+ `resolveChild(...)` and `fallback(...)` can compose inside projections:
594
+
595
+ ```text
596
+ from $.inventory.items.*
597
+ where .qty >= 4
598
+ select { sku = .sku category = resolveChild($.inventory.categoryLabels, .category) status = fallback(.status, "missing") }
599
+ ```
600
+
601
+ Experimental `SANSA.Transform` helpers can construct row-shaped objects from table-like positional data. `objectFrom(...)` pairs all fields:
602
+
603
+ ```text
604
+ from $.table.content.*
605
+ select objectFrom($.table.header.*, .*)
606
+ ```
607
+
608
+ `fieldsFrom(...)` selects a subset of row-shaped fields:
609
+
610
+ ```text
611
+ from $.table.content.*
612
+ select fieldsFrom($.table.header.*, .*, "age")
613
+ ```
614
+
615
+ Currently rejected with explicit diagnostics:
616
+
617
+ - unsupported function names
618
+ - invalid built-in function arity or argument types
619
+ - cardinality expressions that do not contain a supported binding-set predicate
620
+ - cross-type comparisons
621
+ - missing scalar values in scalar context
622
+ - multiple bindings in scalar context
623
+
624
+ Query results:
625
+
626
+ ```js
627
+ {
628
+ type: "queryResult",
629
+ address,
630
+ candidateAddress,
631
+ valueAddress,
632
+ kind,
633
+ binding,
634
+ value
635
+ }
636
+ ```
637
+
638
+ `address` is a backwards-compatible alias for `candidateAddress`. `candidateAddress` is optional and records the canonical source address of the candidate binding when the namespace exposes one. It is the address selected by `from`, after `where`, ordering, and slicing.
639
+
640
+ `valueAddress` is present only when projection preserves one existing selected binding identity. For example, `from $.items.* select .sku` can carry `candidateAddress = $.items[0]` and `valueAddress = $.items[0].sku`. If the selected value is a multi-binding Binding Set, each binding retains its own address inside the value instead of collapsing to one `valueAddress`.
641
+
642
+ `kind` is `binding` when the selected value is a Binding Set that preserves existing namespace binding identity. `valueAddress` is still present only for the single-binding case. `kind` is `derived` for constructed objects and scalar function results. Derived values do not become addressable namespace bindings.
643
+
644
+ Query values:
645
+
646
+ ```js
647
+ { type: "scalar", value }
648
+ { type: "bindingSet", bindings }
649
+ { type: "object", value }
650
+ ```
651
+
652
+ Bindings expose scalar values through `namespace.value(binding)`, `binding.value`, or `binding.scalar`.
653
+
654
+ The evaluator does not execute host-supplied functions. Function support is limited to the built-ins listed above.
655
+
656
+ ## Qualifier Model
657
+
658
+ ```js
659
+ {
660
+ type: "QualifierExpression",
661
+ terms: [QualifierTerm]
662
+ }
663
+ ```
664
+
665
+ ```js
666
+ {
667
+ type: "QualifierTerm",
668
+ name,
669
+ parameters,
670
+ parameterGroups,
671
+ arguments
672
+ }
673
+ ```
674
+
675
+ Arguments are either:
676
+
677
+ ```js
678
+ { kind: "token", value }
679
+ { kind: "quoted", value }
680
+ ```
681
+
682
+ Top-level qualifier unions are represented by multiple `terms`. Nested qualifier unions inside generic parameters are rejected.
683
+
684
+ Qualifier terms may contain zero or more parameter groups and zero or more argument groups:
685
+
686
+ ```text
687
+ name<parameter,parameter><parameter>[argument][argument]
688
+ ```
689
+
690
+ `parameters` is a flattened convenience view. `parameterGroups` preserves how the term should render. Repeated parameter and argument groups allow host embeddings to avoid raw comma where comma would conflict with the host parser.
691
+
692
+ ## Canonical Rendering
693
+
694
+ Canonical rendering:
695
+
696
+ - preserves `$` and `?` root kind
697
+ - renders identifier-safe members as `.name`
698
+ - renders other member names as `.["..."]`
699
+ - renders parent traversal as `.^`
700
+ - renders local spaces as `.<"...">`
701
+ - renders name patterns as `.("...")`
702
+ - renders quoted payload escapes using AEON double-quoted string escape forms
703
+ - renders qualifier unions without spaces, for example `number|nan`
704
+ - renders qualifier parameters without spaces, for example `list<string>`
705
+ - preserves repeated qualifier parameter groups, for example `tuple<x><y>`
706
+ - renders quoted qualifier arguments when the argument was parsed as quoted
707
+
708
+ ## Current Error Codes
709
+
710
+ - `SANSA_EMPTY_ADDRESS`
711
+ - `SANSA_EXPECTED_ROOT`
712
+ - `SANSA_EXPECTED_TOKEN`
713
+ - `SANSA_EXPECTED_IDENTIFIER`
714
+ - `SANSA_EXPECTED_INDEX`
715
+ - `SANSA_EXPECTED_QUALIFIER`
716
+ - `SANSA_EXPECTED_QUALIFIER_ARGUMENT`
717
+ - `SANSA_UNEXPECTED_CHARACTER`
718
+ - `SANSA_UNEXPECTED_WHITESPACE`
719
+ - `SANSA_TRAILING_INPUT`
720
+ - `SANSA_EMPTY_MEMBER_NAME`
721
+ - `SANSA_EMPTY_LOCAL_SPACE_NAME`
722
+ - `SANSA_LEADING_ZERO_INDEX`
723
+ - `SANSA_POSITION_INDEX_LIMIT_EXCEEDED`
724
+ - `SANSA_INVALID_QUALIFIER`
725
+ - `SANSA_INVALID_QUALIFIER_ARGUMENT`
726
+ - `SANSA_INVALID_QUALIFIER_ARGUMENT_CHAR`
727
+ - `SANSA_RAW_NEWLINE_IN_QUOTED_PAYLOAD`
728
+ - `SANSA_UNTERMINATED_QUOTED_PAYLOAD`
729
+ - `SANSA_UNTERMINATED_ESCAPE`
730
+ - `SANSA_INVALID_ESCAPE`
731
+ - `SANSA_UNTERMINATED_UNICODE_ESCAPE`
732
+ - `SANSA_INVALID_UNICODE_ESCAPE`
733
+ - `SANSA_INVALID_UNICODE_SCALAR`
734
+ - `SANSA_QUERY_EMPTY`
735
+ - `SANSA_QUERY_EXPECTED_FROM`
736
+ - `SANSA_QUERY_EXPECTED_SELECT`
737
+ - `SANSA_QUERY_SELECT_MUST_BE_TERMINAL`
738
+ - `SANSA_QUERY_DUPLICATE_CLAUSE`
739
+ - `SANSA_QUERY_INVALID_CLAUSE_ORDER`
740
+ - `SANSA_QUERY_UNTERMINATED_BLOCK_COMMENT`
741
+ - `SANSA_QUERY_EXPECTED_FROM_ADDRESS`
742
+ - `SANSA_QUERY_INVALID_FROM_ADDRESS`
743
+ - `SANSA_QUERY_INVALID_FROM_SOURCE`
744
+ - `SANSA_QUERY_EXPECTED_WHERE_EXPRESSION`
745
+ - `SANSA_QUERY_EXPECTED_SELECT_EXPRESSION`
746
+ - `SANSA_QUERY_EXPECTED_ORDER_EXPRESSION`
747
+ - `SANSA_QUERY_INVALID_OFFSET`
748
+ - `SANSA_QUERY_INVALID_LIMIT`
749
+ - `SANSA_QUERY_EXPECTED_EXPRESSION`
750
+ - `SANSA_QUERY_UNEXPECTED_EXPRESSION_TOKEN`
751
+ - `SANSA_QUERY_UNTERMINATED_EXPRESSION`
752
+ - `SANSA_QUERY_INVALID_NUMBER_LITERAL`
753
+ - `SANSA_QUERY_INVALID_RESOLUTION_EXPRESSION`
754
+ - `SANSA_QUERY_INVALID_FUNCTION_CALL`
755
+ - `SANSA_QUERY_INVALID_PROJECTION`
756
+
757
+ ## Current Query Evaluate Error Codes
758
+
759
+ Evaluation diagnostics may also include context fields such as `phase`, `candidateAddress`, `extension`, `budget`, `limit`, and `observed`. These fields are context, not distinct error categories.
760
+
761
+ - `SANSA_QUERY_POLICY_VIOLATION`
762
+ - `SANSA_QUERY_BUDGET_EXCEEDED`
763
+ - `SANSA_QUERY_EVALUATE_UNSUPPORTED_FUNCTION`
764
+ - `SANSA_QUERY_EVALUATE_UNSUPPORTED_EXTENSION`
765
+ - `SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL`
766
+ - `SANSA_QUERY_EVALUATE_UNSUPPORTED_EXPRESSION`
767
+ - `SANSA_QUERY_EVALUATE_EXPECTED_BOOLEAN`
768
+ - `SANSA_QUERY_EVALUATE_EXPECTED_SCALAR`
769
+ - `SANSA_QUERY_EVALUATE_MISSING_SCALAR`
770
+ - `SANSA_QUERY_EVALUATE_CARDINALITY`
771
+ - `SANSA_QUERY_EVALUATE_INVALID_COMPARISON`
772
+ - `SANSA_QUERY_EVALUATE_INVALID_FROM_SOURCE`
773
+ - `SANSA_QUERY_EVALUATE_INVALID_PATH_LITERAL`
774
+ - `SANSA_QUERY_EVALUATE_INVALID_EXISTENCE_ARGUMENT`
775
+ - `SANSA_QUERY_EVALUATE_INVALID_CARDINALITY_ARGUMENT`
776
+
777
+ ## Current Resolve Error Codes
778
+
779
+ - `SANSA_RESOLVE_EXPECTED_NAMESPACE`
780
+ - `SANSA_RESOLVE_MISSING_ROOT`
781
+ - `SANSA_RESOLVE_UNSUPPORTED_CONTEXTUAL_ROOT`
782
+ - `SANSA_RESOLVE_UNSUPPORTED_ATTRIBUTE_SPACE`
783
+ - `SANSA_RESOLVE_UNSUPPORTED_LOCAL_SPACE`
784
+ - `SANSA_RESOLVE_UNSUPPORTED_PARENT`
785
+ - `SANSA_RESOLVE_PARENT_TRAVERSAL_FORBIDDEN`
786
+ - `SANSA_RESOLVE_BOUNDARY_ESCAPE_FORBIDDEN`
787
+ - `SANSA_RESOLVE_EXACT_MULTIPLICITY_VIOLATION`
788
+ - `SANSA_RESOLVE_UNSUPPORTED_SELECTOR`