@niscorp/vex 0.2.0 → 0.2.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/schemas/request.schema.ts","../../../src/schemas/value.schema.ts","../../../src/schemas/identifier.schema.ts","../../../src/schemas/filter.schema.ts","../../../src/schemas/compute.schema.ts","../../../src/schemas/aggregate.schema.ts","../../../src/schemas/query.schema.ts","../../../src/cache/util.ts","../../../src/cache/hash.ts","../../../src/errors.ts","../../../src/engine/optional.ts","../../../src/adapters/postgres/operators.ts","../../../src/scope/scope.types.ts","../../../src/scope/apply.ts","../../../src/utils/context.ts","../../../src/engine/executor.ts","../../../src/mutations/schema.ts","../../../src/mutations/signature.ts","../../../src/mutations/engine.ts","../../../src/handler.ts","../../../src/adapters/express/index.ts"],"names":["z","createHash","fieldPath","where","gate","exceedsDepth","depthRefusal"],"mappings":";;;;;;;AAMO,IAAM,wCAAwB,IAAI,GAAA,CAAY,CAAC,QAAA,EAAU,SAAS,CAAC,CAAA;AAEnE,IAAM,aAAA,GAAgBA,MAC1B,MAAA,CAAO;AAAA,EACN,MAAA,EAAQA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC5B,OAAA,EAASA,MAAE,IAAA,CAAK,CAAC,OAAO,MAAM,CAAC,EAAE,QAAA;AACnC,CAAC,CAAA,CACA,QAAA,CAASA,KAAA,CAAE,OAAA,EAAS,CAAA,CACpB,QAAA;AAAA,EACC;AACF,CAAA;AAEK,IAAM,kBAAA,GAAqBA,MAAE,MAAA,CAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMzC,aAAaA,KAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;AAAA,EACxC,MAAA,EAAQA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC5B,KAAA,EAAOA,KAAA,CAAE,OAAA,EAA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AAW;AAAC,OAC5D,CAAA;AACD,MAAA,GAAA,CAAI,OAAO,MAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAK,OAAO,IAAI,CAAA;AAC1C,MAAA;AAAA,IACF;AAEA,IAAA,IAAI,GAAA,CAAI,WAAW,QAAA,EAAU;AAC3B,MAAA,MAAM,WAAA,GAAc,mBAAA,CAAoB,GAAA,CAAI,IAAI,CAAA;AAChD,MAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,QAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,iBAAA,EAAmB,OAAA,EAAS,mCAAA,EAAqC,CAAA;AAC/F,QAAA;AAAA,MACF;AACA,MAAA,MAAM,MAAA,GAAS,MAAM,uBAAA,CAAwB,aAAA,EAAe,WAAW,CAAA;AACvE,MAAA,GAAA,CAAI,OAAO,MAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAK,OAAO,IAAI,CAAA;AAC1C,MAAA;AAAA,IACF;AAEA,IAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK;AAAA,MACnB,KAAA,EAAO,oBAAA;AAAA,MACP,OAAA,EAAS;AAAA,KACV,CAAA;AAAA,EACH,CAAA;AACF","file":"index.cjs","sourcesContent":["import { z } from 'zod';\nimport type { JsonValue } from '@niscorp/prism';\n\n// Context keys the engine consumes directly (for ORDER BY) instead of binding as\n// SQL parameters. A `{ $context: 'sortBy' }` ref is rejected at compile so these\n// can never reach the param path.\nexport const RESERVED_CONTEXT_KEYS = new Set<string>(['sortBy', 'sortDir']);\n\nexport const ContextSchema = z\n .object({\n sortBy: z.string().optional(),\n sortDir: z.enum(['asc', 'desc']).optional(),\n })\n .catchall(z.unknown())\n .describe(\n 'Caller runtime values. Keys referenced from the DSL via { $context: \"key\" } are bound as SQL parameters. `sortBy` (an entity.field, schema-validated) and `sortDir` (\"asc\"|\"desc\") are reserved keys that drive ORDER BY directly and are never bound as parameters.',\n );\n\nexport const QueryRequestSchema = z.object({\n // The ONE cache identity. Server-minted (`fp_…`) when absent — returned in\n // meta.cache.fingerprint, an immutable pin. Caller-chosen strings are\n // mutable named slots: the name is yours, its content follows your request.\n // Alone → replay-or-error. With intent/shape → hit when the stored request\n // matches, regenerate-and-replace when it differs (409 when protected).\n fingerprint: z.string().min(1).optional(),\n intent: z.string().optional(),\n shape: z.unknown().optional(),\n context: ContextSchema.default({}),\n});\n\nexport type QueryRequest = z.infer<typeof QueryRequestSchema>;\n\nexport type CacheMeta = {\n hit: boolean;\n // The entry's identity — minted (`fp_…`) or the caller's own name.\n fingerprint?: string;\n // True when this execution regenerated and REPLACED a named slot whose\n // stored request no longer matched.\n replaced?: boolean;\n // The intent stored with the cached query (on a hit) or the request's own intent\n // (on a miss) — descriptive only, so a caller can see what the query is for.\n intent?: string;\n};\n\nexport type TimingMeta = {\n agentMs?: number;\n executionMs: number;\n mappingMs?: number;\n transformMs?: number;\n};\n\nexport type ContextMeta = {\n // Mirrors ParamSlot['type'] (adapters/adapter.types.ts) — the contract a\n // caller reads is built from the slots the compiler bound, one for one.\n // Absent on a key that is optional and was not supplied: nothing bound it\n // this run, so there is no slot to read a type off.\n type?: 'string' | 'number' | 'boolean' | 'string[]' | 'number[]' | 'json';\n kind: 'context' | 'scope' | 'semantic';\n // True when the key controls an `optional` condition — supply it and the\n // condition applies, omit it and the condition is not in the query. DERIVED\n // from the stored DSL rather than declared beside it, for the same reason\n // mutation signatures are (see \"Derived context signatures\" in DOCS.md): a\n // contract somebody maintains by hand is a contract that eventually lies.\n optional?: true;\n // True when this run did not supply the key, so its condition was pruned.\n // The key is still published — that is the point of listing it — so a caller\n // can discover what a fingerprint accepts without failing a request first.\n absent?: true;\n};\n\nexport type QueryResponse = {\n // Whatever the Prism mapping produced over the full row set: an array (the\n // common case — a `$map` or identity over `$.result`), a single object (a\n // detail picking `$.result[0]`), or a scalar (an aggregate). Vex no longer\n // forces an array — the mapping owns the output shape.\n result: JsonValue;\n meta: {\n cache: CacheMeta;\n context: Record<string, ContextMeta>;\n timing?: TimingMeta;\n warnings?: string[];\n missingContext?: string[];\n };\n};\n\nexport type QueryErrorResponse = {\n error: string;\n message: string;\n details?: {\n suggestion?: string;\n options?: string[];\n };\n};\n\nexport type QueryErrorCode =\n | 'invalid_request'\n | 'invalid_dsl'\n | 'missing_scope'\n | 'scope_denied'\n | 'missing_context'\n | 'execution_error'\n | 'agent_failed'\n | 'cache_miss'\n | 'fingerprint_protected'\n | 'locked'\n | 'unsatisfiable';\n","import { z } from 'zod';\n\nexport const ContextRefSchema = z\n .object({\n $context: z.string().describe('Key to look up in the request context object'),\n })\n .strict()\n .describe('Reference to a caller-provided context value');\n\nexport const ScopeRefSchema = z\n .object({\n $scope: z.string().describe('Key to look up in the server-side scope values'),\n })\n .strict()\n .describe('Reference to a server-injected scope value (access control)');\n\nexport const FieldOrValueSchema = z\n .union([\n z.string().describe('A field path (entity.field format) or a literal string'),\n z.number().describe('A literal number'),\n z.boolean().describe('A literal boolean'),\n z.null().describe('A literal null'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A field path, literal value, or dynamic reference');\n\nexport type ContextRef = z.infer<typeof ContextRefSchema>;\nexport type ScopeRef = z.infer<typeof ScopeRefSchema>;\nexport type FieldOrValue = z.infer<typeof FieldOrValueSchema>;\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// THE NAMES A QUERY MAY SAY — and the one rule for telling them apart.\n//\n// Every string an author (a person, a seed, a model) puts in a NAME position\n// ends up in SQL text: a column reference, an output alias, a subquery alias.\n// Values never do — they bind as parameters or are quoted as literals. So a\n// name is the only place authored text meets the statement, and it is held to\n// a grammar that cannot carry anything but a name: letters, digits and\n// underscores, not starting with a digit.\n//\n// This is the parse-time half. The resolver checks the same predicates again,\n// because `engine.compile()` and `engine.test()` take a DSL that never went\n// through Zod, and the compiler refuses to emit a field position that did not\n// resolve against the introspected schema. Three layers, one grammar.\n//\n// `isFieldPathShape` is also what decides, in a value position, whether a\n// string is a column or a literal. It used to be \"contains a dot\", which made\n// every email address an unknown entity and every string with a dot a column\n// reference — so a literal like \"u1@x.com\" threw, and a string that merely\n// looked dotted went to SQL as a name. Now a column is exactly `ident.ident`,\n// and everything else is a literal.\n// ═══════════════════════════════════════════════════════════════\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*\\.[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport const isIdentifier = (value: string): boolean => IDENTIFIER.test(value);\n\nexport const isFieldPathShape = (value: unknown): value is string => typeof value === 'string' && FIELD_PATH.test(value);\n\nexport const IdentifierSchema = z\n .string()\n .regex(IDENTIFIER, 'A name is letters, digits and underscores, not starting with a digit');\n\nexport const FieldPathSchema = z\n .string()\n .regex(FIELD_PATH, 'A field path is entity.field — each part letters, digits and underscores, not starting with a digit');\n","import { z } from 'zod';\nimport { ContextRefSchema, ScopeRefSchema, FieldOrValueSchema } from './value.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\nimport type { ContextRef, ScopeRef, FieldOrValue } from './value.schema.js';\n\n// EXISTS — \"is there a row over there that points back at this one\".\n//\n// It is the same `{ from, filter }` a query already is, and deliberately no\n// more than that: no fields, no sort, no limit, nothing to select. EXISTS asks\n// whether a row is there, so anything that shapes output would be noise the\n// planner discards, and refusing it is what keeps this an operator rather than\n// an invitation to nest arbitrary SQL.\n//\n// The CORRELATION needs no new vocabulary. A dotted string on either side of a\n// comparison is already a field path, so pointing the inner table at the outer\n// one is an ordinary `eq` between two columns:\n//\n// { exists: { from: ['tasks'], filter: { eq: ['tasks.issue_id', 'issues.id'] } } }\n//\n// and `not` composes for NOT EXISTS. Whoever writes SQL writes this on the\n// first try, which is the entire design goal.\nexport type ExistsQuery = {\n from: string[];\n filter?: Filter;\n};\n\nexport type Filter =\n | { exists: ExistsQuery }\n | { eq: [FieldOrValue, FieldOrValue] }\n | { neq: [FieldOrValue, FieldOrValue] }\n | { gt: [FieldOrValue, FieldOrValue] }\n | { gte: [FieldOrValue, FieldOrValue] }\n | { lt: [FieldOrValue, FieldOrValue] }\n | { lte: [FieldOrValue, FieldOrValue] }\n | { in: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { notIn: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { like: [string, FieldOrValue] }\n | { ilike: [string, FieldOrValue] }\n | { isNull: string }\n | { isNotNull: string }\n | { and: Filter[] }\n | { or: Filter[] }\n | { not: Filter }\n | { semantic: { field: string; query: ContextRef | ScopeRef; minScore?: number } }\n | { fuzzy: { field: string; query: ContextRef | ScopeRef; maxDistance?: number } }\n | { optional: { key: string | string[]; then: Filter } };\n\nconst comparisonPair = z\n .tuple([FieldOrValueSchema, FieldOrValueSchema])\n .describe('[left, right] — both can be field paths, literals, or references');\n\nconst fieldString = FieldPathSchema.describe('Field path in entity.field format');\n\nconst collectionTarget = z\n .union([\n z.array(FieldOrValueSchema).min(1).describe('Array of literal values or references'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A set of values or a reference that resolves to an array');\n\nconst ExistsSchema: z.ZodType<ExistsQuery> = z.lazy(() =>\n z\n .object({\n from: z.array(z.string()).min(1).describe('Entities the subquery reads. Joined by foreign key like any other from.'),\n filter: FilterSchema.optional().describe('The correlation, and any extra condition. Reference the outer query by its own entity path: { eq: [\"<inner>.<fk>\", \"<outer>.id\"] }.'),\n })\n .strict(),\n);\n\nexport const FilterSchema: z.ZodType<Filter> = z.lazy(() =>\n z.union([\n z.object({ exists: ExistsSchema }).strict().describe('EXISTS: true when the subquery matches at least one row. Wrap in `not` for NOT EXISTS.'),\n z.object({ eq: comparisonPair }).strict().describe('Equals: tests equality between two values'),\n z.object({ neq: comparisonPair }).strict().describe('Not equals'),\n z.object({ gt: comparisonPair }).strict().describe('Greater than'),\n z.object({ gte: comparisonPair }).strict().describe('Greater than or equal'),\n z.object({ lt: comparisonPair }).strict().describe('Less than'),\n z.object({ lte: comparisonPair }).strict().describe('Less than or equal'),\n z.object({ in: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is in a set'),\n z.object({ notIn: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is not in a set'),\n z.object({ like: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-sensitive LIKE pattern match (use % as wildcard)'),\n z.object({ ilike: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-insensitive ILIKE pattern match (use % as wildcard)'),\n z.object({ isNull: fieldString }).strict().describe('Field value is NULL'),\n z.object({ isNotNull: fieldString }).strict().describe('Field value is NOT NULL'),\n z.object({ and: z.array(FilterSchema).min(2) }).strict().describe('Logical AND: all conditions must be true'),\n z.object({ or: z.array(FilterSchema).min(2) }).strict().describe('Logical OR: at least one condition must be true'),\n z.object({ not: FilterSchema }).strict().describe('Logical NOT: negates the condition'),\n z.object({\n semantic: z.object({\n field: FieldPathSchema.describe('Vector column field path (entity.field)'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to embed and compare'),\n minScore: z.number().min(0).max(1).optional().describe('Minimum cosine similarity (0–1)'),\n }).strict(),\n }).strict().describe('Semantic vector similarity search'),\n z.object({\n fuzzy: z.object({\n field: FieldPathSchema.describe('String field path'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to fuzzy-match'),\n maxDistance: z.number().int().nonnegative().optional().describe('Maximum Levenshtein edit distance'),\n }).strict(),\n }).strict().describe('Fuzzy string match'),\n z.object({\n optional: z.object({\n key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both — gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply.'),\n // BARE, never `.describe()`d. That call CLONES the schema, and zod\n // detects a recursive reference by instance identity — a clone is a\n // different instance, so `to-json-schema` stops seeing the cycle and\n // expands the filter union into itself until the stack goes. Every\n // other recursive slot here (`not`, `and`, `or`) uses it bare for the\n // same reason; the description belongs on the wrapper below.\n then: FilterSchema,\n }).strict(),\n }).strict().describe(\n 'A condition the caller turns on by supplying context keys. When any named key is absent the condition is REMOVED from the query before it compiles — it does not match everything, it is not there. Absent means missing, undefined or null; \"\" is a value and keeps the condition. Direction follows position: under `and` supplying the key NARROWS, under `or` it WIDENS. Either way an absent key reads exactly as if the condition had never been written, and scope is injected afterwards regardless. Reads only: a mutation may not contain one, and neither may the inside of an `exists` (its correlation must be unconditional).',\n ),\n ]),\n);\n","import { z } from 'zod';\nimport { FieldOrValueSchema } from './value.schema.js';\nimport { FilterSchema } from './filter.schema.js';\n\nconst CaseWhenSchema = z\n .object({\n condition: FilterSchema,\n then: FieldOrValueSchema.describe('Value when condition is true'),\n })\n .strict();\n\nexport const ComputeExpressionSchema = z\n .union([\n z.object({ add: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Addition: a + b'),\n z.object({ subtract: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Subtraction: a - b'),\n z.object({ multiply: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Multiplication: a * b'),\n z.object({ divide: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Division: a / b'),\n z.object({ concat: z.array(FieldOrValueSchema).min(2) }).strict().describe('String concatenation'),\n z.object({ coalesce: z.array(FieldOrValueSchema).min(2) }).strict().describe('Returns first non-null value'),\n z.object({\n case: z\n .object({\n when: z.array(CaseWhenSchema).min(1).describe('Condition/result pairs evaluated in order'),\n else: FieldOrValueSchema.describe('Default value when no condition matches'),\n })\n .strict(),\n }).strict().describe('CASE WHEN conditional expression'),\n ])\n .describe('Computed expression: arithmetic, string, or conditional');\n\nexport type ComputeExpression = z.infer<typeof ComputeExpressionSchema>;\n","import { z } from 'zod';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\n\nconst fieldPath = FieldPathSchema.describe('Field path in entity.field format');\n\n// SUM/AVG/MIN/MAX take either a field path or a compute expression — so the\n// argument can be a derived value (e.g. SUM(value * win_probability / 100)),\n// not just a column. A bare string stays valid (non-breaking).\nconst fieldOrExpr = z.union([fieldPath, ComputeExpressionSchema]).describe('A field path or a compute expression');\n\nexport const AggregateExpressionSchema = z\n .union([\n z.object({ count: z.union([FieldPathSchema, z.literal('*')]).describe('Field path or \"*\" for COUNT(*)') }).strict().describe('COUNT'),\n z.object({ countDistinct: FieldPathSchema.describe('Field path whose distinct non-null values are counted') }).strict().describe('COUNT(DISTINCT field)'),\n z.object({ sum: fieldOrExpr }).strict().describe('SUM'),\n z.object({ avg: fieldOrExpr }).strict().describe('AVG'),\n z.object({ min: fieldOrExpr }).strict().describe('MIN'),\n z.object({ max: fieldOrExpr }).strict().describe('MAX'),\n ])\n .describe('Aggregate function applied to a field or expression');\n\nexport type AggregateExpression = z.infer<typeof AggregateExpressionSchema>;\n","import { z } from 'zod';\nimport { FilterSchema } from './filter.schema.js';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { AggregateExpressionSchema } from './aggregate.schema.js';\nimport { FieldPathSchema, IdentifierSchema } from './identifier.schema.js';\nimport type { Filter } from './filter.schema.js';\nimport type { ComputeExpression } from './compute.schema.js';\nimport type { AggregateExpression } from './aggregate.schema.js';\n\nexport const SortEntrySchema = z\n .object({\n field: z.union([FieldPathSchema, IdentifierSchema]).describe('Field path (entity.field), computed field name, or aggregate alias'),\n dir: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })\n .strict()\n .describe('Sort specification');\n\nexport type SortEntry = z.infer<typeof SortEntrySchema>;\n\nexport type Source = string | { as: string; query: Query };\n\n// A selected field: a bare `entity.field` path, or an aliased one whose output\n// key is `as` (so joined columns that would collide — three `name`s — get\n// distinct keys without a compute hack).\nexport type FieldRef = string | { field: string; as: string };\n\nexport type Query = {\n from: Source[];\n // Optional: a query may select only aggregates (e.g. a bare `COUNT(*)`); the\n // schema requires at least one of `fields` / `aggregate`.\n fields?: FieldRef[];\n filter?: Filter;\n compute?: Record<string, ComputeExpression>;\n aggregate?: Record<string, AggregateExpression>;\n groupBy?: string[];\n sort?: SortEntry[];\n limit?: number;\n distinct?: boolean;\n};\n\nconst SubquerySourceSchema = z\n .object({\n as: IdentifierSchema.describe('Alias for subquery results — use as prefix in field paths'),\n query: z.lazy((): z.ZodType<Query> => QuerySchema).describe('A nested query'),\n })\n .strict()\n .describe('Subquery data source: a nested query read as a table under `as`, its columns referenced as `<as>.<field>` anywhere in the outer query. Joined by foreign key like an entity when one links them; otherwise every outer row is paired with every subquery row (a cross join), so a one-row subquery puts its values beside each outer row.');\n\nconst SourceSchema = z\n .union([\n z.string().describe('Entity name from the database schema'),\n SubquerySourceSchema,\n ])\n .describe('Data source: entity name or subquery');\n\nconst FieldRefSchema = z\n .union([\n FieldPathSchema.describe('A column in entity.field format'),\n z\n .object({\n field: FieldPathSchema.describe('A column in entity.field format'),\n as: IdentifierSchema.describe('Output key for this column'),\n })\n .strict()\n .describe('An aliased column: output under `as` instead of the column name'),\n ])\n .describe('A selected field — a bare `entity.field`, or `{ field, as }` to alias the output key');\n\nexport const QuerySchema: z.ZodType<Query> = z.lazy(() =>\n z\n .object({\n from: z.array(SourceSchema).min(1).describe('Data sources — entity names or subqueries. Every entity used anywhere in the query must be listed here. Listed entities are JOINED FOR YOU along their foreign keys — a nullable key as a LEFT JOIN, so a row whose key is empty is kept, with the joined columns null. Never restate a join as a filter comparing the two keys: that throws those rows away.'),\n fields: z.array(FieldRefSchema).optional().describe('Raw columns to select — each `entity.field`, or `{ field, as }` to alias the output key (no SELECT *). Optional: omit it for an aggregate-only query (e.g. a bare COUNT). Do not list compute or aggregate aliases here — those are added automatically.'),\n filter: FilterSchema.optional().describe('Filter conditions'),\n compute: z.record(IdentifierSchema, ComputeExpressionSchema).optional().describe('Computed fields — key is output alias, value is the expression'),\n aggregate: z.record(IdentifierSchema, AggregateExpressionSchema).optional().describe('Aggregate functions — key is output alias, value is the function'),\n groupBy: z.array(FieldPathSchema).optional().describe('Fields to group by for aggregation'),\n sort: z.array(SortEntrySchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Maximum rows to return'),\n distinct: z.boolean().optional().describe('Eliminate duplicate rows'),\n })\n .strict()\n .refine(\n (q) => (q.fields?.length ?? 0) > 0 || Object.keys(q.aggregate ?? {}).length > 0,\n { message: 'A query must select at least one of `fields` or `aggregate`.' },\n ),\n);\n\nexport { SubquerySourceSchema, SourceSchema };\n","import type { CacheEntry } from './cache.types.js';\n\n/**\n * Run a promise we don't want to await (background writes, hit bumps,\n * evictions). Failures are routed to `onError` or logged, never thrown\n * into the caller's path.\n */\nexport const fireAndForget = (p: Promise<unknown>, onError?: (err: unknown) => void): void => {\n void p.catch((err) => {\n if (onError) onError(err);\n else console.error('[vex:cache]', err);\n });\n};\n\n/**\n * How often a replay stamps `lastUsedAt`. The stamp rewrites the entry, and\n * a stamp on EVERY replay made every read a write too; once a minute keeps\n * what reads it — the sweep (idle limits of days), discovery's \"last used\" —\n * accurate to the minute, for a write per fingerprint per minute at most.\n */\nexport const TOUCH_EVERY_MS = 60_000;\n\n/** Whether a replay at `now` should stamp this entry's `lastUsedAt`. */\nexport const isTouchDue = (entry: CacheEntry, now: number): boolean =>\n entry.lastUsedAt === undefined || now - entry.lastUsedAt >= TOUCH_EVERY_MS;\n\n/**\n * Pure freshness check (no side effects). An entry is fresh when it is\n * not past its TTL and was written against the current schema. A\n * different fingerprint means the entry's DSL may reference columns that\n * have since changed. Callers decide whether to evict a non-fresh entry.\n */\nexport const isEntryFresh = (entry: CacheEntry, currentFingerprint?: string): boolean => {\n const expired = entry.expiresAt !== undefined && entry.expiresAt <= Date.now();\n const stale =\n entry.schemaFingerprint !== undefined &&\n currentFingerprint !== undefined &&\n entry.schemaFingerprint !== currentFingerprint;\n return !expired && !stale;\n};\n\n/**\n * Lifetime = usage. Evicts unprotected entries that have not been\n * replayed within `maxIdleMs` (falling back to createdAt for entries\n * never touched). Protected entries never sweep. Run it on whatever\n * cadence suits the app (startup, a timer, a cron) — it is hygiene,\n * not a correctness requirement: entries are single-digit KB.\n */\nexport const sweepCache = async (\n cache: {\n entries?: () => Promise<Array<{ key: string; entry: CacheEntry }>>;\n keys: () => Promise<string[]>;\n get: (key: string) => Promise<CacheEntry | undefined>;\n delete: (key: string) => Promise<void>;\n },\n options: { maxIdleMs: number },\n): Promise<number> => {\n const cutoff = Date.now() - options.maxIdleMs;\n const rows = cache.entries !== undefined\n ? await cache.entries()\n : await Promise.all((await cache.keys()).map(async (key) => ({ key, entry: await cache.get(key) })));\n\n let evicted = 0;\n for (const { key, entry } of rows) {\n if (entry === undefined) continue;\n if (entry.protected === true) continue;\n const lastAlive = entry.lastUsedAt ?? entry.createdAt;\n if (lastAlive < cutoff) {\n await cache.delete(key);\n evicted += 1;\n }\n }\n return evicted;\n};\n","import { createHash } from 'node:crypto';\nimport type { DatabaseSchema } from '../schemas/database.schema.js';\n\n// ───────────────────────────────────────────────────────────────\n// Shape normalization\n// ───────────────────────────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nexport const normalizeShape = (shape: unknown): unknown => {\n if (shape === null) return 'null';\n if (shape === undefined) return 'unknown';\n\n if (Array.isArray(shape)) {\n // Collapse to first-element shape (all elements assumed same shape)\n const first: unknown = shape[0];\n return first !== undefined ? [normalizeShape(first)] : [];\n }\n\n if (isRecord(shape)) {\n const sortedKeys = Object.keys(shape).sort();\n const normalized: Record<string, unknown> = {};\n for (const key of sortedKeys) {\n normalized[key] = normalizeShape(shape[key]);\n }\n return normalized;\n }\n\n if (typeof shape === 'string') return 'string';\n if (typeof shape === 'number') return 'number';\n if (typeof shape === 'boolean') return 'boolean';\n\n // functions, symbols, bigint, etc.\n return 'unknown';\n};\n\n// ───────────────────────────────────────────────────────────────\n// Fingerprints\n//\n// The ONE cache identity. Minted (`fp_…`) when a request arrives\n// without one — an immutable pin the caller can embed and replay.\n// Caller-chosen strings are mutable named slots. Shape hashes are no\n// longer keys anywhere; normalizeShape survives only inside\n// computeRequestHash (request-identity comparison).\n// ───────────────────────────────────────────────────────────────\n\nexport const mintFingerprint = (): string =>\n `fp_${createHash('sha256').update(`${Date.now()}:${Math.random()}`).digest('hex').slice(0, 16)}`;\n\n// ───────────────────────────────────────────────────────────────\n// Schema fingerprint\n//\n// A hash of the *structural* (DDL) shape of the database schema, stored\n// on each cache entry so a cached DSL — which references concrete\n// columns — can be invalidated when the schema changes out from under it\n// (a dropped/renamed column would otherwise compile to broken SQL on a\n// cache hit).\n//\n// Critically, this must be STABLE across restarts for an unchanged\n// schema, or warm-up entries would be wrongly judged stale and thrown\n// away on first read. So we project to a canonical, sorted form and\n// deliberately exclude volatile data: rowCount (a drifting pg estimate)\n// and cosmetic fields (description, defaultValue). A row-count change is\n// not a schema change — the cached SQL is still valid.\n// ───────────────────────────────────────────────────────────────\n\n// ───────────────────────────────────────────────────────────────\n// Request identity hash\n//\n// Unlike the shape hash (which keys the positive cache and intentionally\n// ignores intent), this identifies the *whole request*: intent + shape\n// class + the set of context keys. It keys things where intent matters —\n// the negative cache (whether a request is satisfiable depends on the\n// intent, not just the output shape) and single-flight de-duplication of\n// concurrent identical misses. Context *values* are excluded (runtime\n// data, potentially sensitive); only the key names participate.\n// ───────────────────────────────────────────────────────────────\n\nexport const computeRequestHash = (request: {\n intent?: string;\n shape?: unknown;\n context?: Record<string, unknown>;\n}): string => {\n const identity = {\n intent: request.intent ?? null,\n shape: normalizeShape(request.shape),\n contextKeys: Object.keys(request.context ?? {}).sort(),\n };\n return createHash('sha256').update(JSON.stringify(identity)).digest('hex');\n};\n\n// Which POLICY a generation ran under — part of the single-flight and\n// negative-cache keys, because an agent that can see different tables is a\n// different agent. Key order is normalised so two structurally equal policies\n// built in different orders share a key. `none` is the engine with no policy.\nconst canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (isRecord(value)) {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) out[key] = canonical(value[key]);\n return out;\n }\n return value;\n};\n\nexport const computePolicyKey = (policy: unknown): string =>\n policy === undefined ? 'none' : createHash('sha256').update(JSON.stringify(canonical(policy))).digest('hex').slice(0, 16);\n\nexport const computeSchemaFingerprint = (schema: DatabaseSchema): string => {\n const byName = (a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name);\n\n const stable = {\n entities: [...schema.entities].sort(byName).map((e) => ({\n name: e.name,\n table: e.table,\n fields: [...e.fields].sort(byName).map((f) => ({\n name: f.name,\n type: f.type,\n normalizedType: f.normalizedType,\n nullable: f.nullable,\n primaryKey: f.primaryKey,\n ...(f.vectorDimensions !== undefined ? { vectorDimensions: f.vectorDimensions } : {}),\n })),\n // Column order within a relation is the key's own order, so it is\n // preserved; relations are sorted by target and columns. This shape\n // changed when keys became composite, so every entry cached before\n // revalidates once on the next boot — the drift eviction, by design.\n relations: [...e.relations]\n .sort((a, b) => `${a.entity}.${a.localFields.join(',')}`.localeCompare(`${b.entity}.${b.localFields.join(',')}`))\n .map((r) => ({ type: r.type, entity: r.entity, localFields: r.localFields, foreignFields: r.foreignFields })),\n // Index field order is significant (composite indexes) and stable\n // from introspection, so it is preserved; indexes are sorted by name.\n indexes: [...e.indexes].sort(byName).map((i) => ({\n name: i.name,\n fields: i.fields,\n unique: i.unique,\n type: i.type,\n })),\n })),\n };\n\n return createHash('sha256').update(JSON.stringify(stable)).digest('hex');\n};\n","import type { QueryErrorCode } from './schemas/request.schema.js';\n\nexport class VexError extends Error {\n readonly code: QueryErrorCode;\n readonly details?: Record<string, unknown>;\n\n constructor(code: QueryErrorCode, message: string, details?: Record<string, unknown>) {\n super(message);\n this.name = 'VexError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { Query, Source } from '../schemas/query.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport { VexError } from '../errors.js';\n\n// ═══════════════════════════════════════════════════════════════\n// OPTIONAL CONDITIONS — resolved BEFORE the pipeline, never inside it.\n//\n// `{ optional: { key, then } }` is the one thing a caller can do to the SHAPE\n// of a query rather than to its values: supply the key and the condition is\n// there, omit it and the condition is gone. That is what makes one entry able\n// to answer \"everybody\", \"everybody matching a search\", and \"one person by id\"\n// — questions that were three entries because every `$context` ref was\n// mandatory (`executor.ts` findMissingContext).\n//\n// It is a DSL→DSL rewrite, run at the same point as `applySortContext`, and\n// that placement is the whole safety argument. The resolver, the compiler and\n// the scope walker never see this node. They cannot: by the time any of them\n// runs, every optional has already become either its condition or nothing at\n// all. So there is no third walker to teach, and — crucially — no way for an\n// entity to enter the query AFTER `discoverEntities` has decided what to scope.\n// All three throw if they ever meet one, so a future caller that reaches past\n// this pass gets an error rather than an unscoped read.\n//\n// WHAT IS DELIBERATELY NOT DONE HERE: the joins stay. `from` is untouched when\n// a condition drops, so which keys a caller sends can never change the row\n// multiplicity of the result — only how many rows survive the WHERE. A pruned\n// query is the same query with fewer conditions, never a differently-shaped one.\n// ═══════════════════════════════════════════════════════════════\n\n/** The keys one optional gate names — one, or all of several. A condition that\n * reads two context values depends on BOTH, and gating it on one would leave\n * the other conditionally required: supply `after` without `afterId` and the\n * clause survives with a hole in it, which surfaces as an empty result and\n * `missingContext`, not as a condition that quietly did not apply. On a paging\n * cursor an empty result reads as \"end of list\", which is the wrong answer\n * arrived at silently. */\nconst gateKeys = (key: string | string[]): string[] => (Array.isArray(key) ? key : [key]);\n\n/** Every optional key mentioned anywhere in a query, in declaration order. */\nexport const optionalKeysOf = (dsl: Query): string[] => {\n const keys: string[] = [];\n const walk = (filter: Filter): void => {\n if ('optional' in filter) {\n for (const key of gateKeys(filter.optional.key)) {\n if (!keys.includes(key)) keys.push(key);\n }\n walk(filter.optional.then);\n return;\n }\n if ('and' in filter) { for (const sub of filter.and) walk(sub); return; }\n if ('or' in filter) { for (const sub of filter.or) walk(sub); return; }\n if ('not' in filter) { walk(filter.not); return; }\n };\n if (dsl.filter !== undefined) walk(dsl.filter);\n for (const source of dsl.from) {\n if (typeof source !== 'string') keys.push(...optionalKeysOf(source.query).filter((k) => !keys.includes(k)));\n }\n return keys;\n};\n\n/** Which context keys the caller actually supplied.\n *\n * ABSENT MEANS MISSING, `undefined`, OR `null`. The empty string is a value —\n * searching for `''` is a real search — but null is not, for two reasons that\n * agree:\n *\n * · SQL. A bound null in a comparison can never match: `col = NULL` and\n * `col ILIKE NULL` are both NULL, never true. So \"send null\" could only ever\n * have meant \"I have nothing\", and vex already has `isNull`/`isNotNull` for\n * the question people actually mean by it. Nothing is lost.\n *\n * · The wire. JSON has no `undefined`, and a request prism assembles a fixed\n * object — it cannot conditionally omit a key. Without null counting as\n * absent, every caller with an empty search box would have to bind a\n * sentinel again, which is the exact thing this feature removes.\n *\n * This is deliberately WIDER than `findMissingContext`'s test, which stays on\n * `undefined` alone. A required key sent as null still binds null and matches\n * nothing; an optional key sent as null drops its condition. That reads like a\n * contradiction and is not: the author chose which keys are optional, and for\n * those they have already said absence means \"this does not apply\". A caller\n * gains nothing by it either — omitting the key does the same thing, and scope\n * is injected after this either way. */\nexport const presenceOf = (context: Record<string, unknown>): ReadonlySet<string> => {\n const present = new Set<string>();\n for (const [key, value] of Object.entries(context)) {\n if (value !== undefined && value !== null) present.add(key);\n }\n return present;\n};\n\n/** A stable name for \"which optionals were live on this run\" — used to report\n * how many distinct shapes one entry is being asked for. `all` is the compile\n * and test path, where there is no caller. */\nexport const presenceSignature = (dsl: Query, present: ReadonlySet<string> | 'all'): string => {\n const keys = optionalKeysOf(dsl);\n if (keys.length === 0) return '';\n if (present === 'all') return keys.join(',');\n return keys.filter((k) => present.has(k)).join(',');\n};\n\n// `undefined` means THIS NODE IS GONE — not \"false\", not \"true\". The caller of\n// each recursion decides what its absence means in context, which is the only\n// way `and` (identity true) and `or` (identity false) can both be correct.\nconst prune = (filter: Filter, present: ReadonlySet<string> | 'all', insideExists: boolean): Filter | undefined => {\n if ('optional' in filter) {\n // The correlation of an EXISTS is what ties it to the outer row. Let a\n // caller switch that off and `exists` stops asking \"is there one of these\n // for THIS row\" and starts asking \"is there one of these at all\" — a\n // different question that happens to be true far more often. Refused\n // outright rather than defended per-case.\n const keys = gateKeys(filter.optional.key);\n if (insideExists) {\n throw new VexError('invalid_dsl', `An optional condition (\"${keys.join(', ')}\") cannot live inside an exists — its correlation must hold on every run.`);\n }\n // ALL of them, not any: a condition needing two values and given one is a\n // condition that cannot run.\n if (present !== 'all' && !keys.every((key) => present.has(key))) return undefined;\n return prune(filter.optional.then, present, insideExists);\n }\n\n if ('exists' in filter) {\n const inner = filter.exists.filter === undefined ? undefined : prune(filter.exists.filter, present, true);\n return inner === undefined\n ? { exists: { from: filter.exists.from } }\n : { exists: { from: filter.exists.from, filter: inner } };\n }\n\n if ('and' in filter || 'or' in filter) {\n const isAnd = 'and' in filter;\n const kept = (isAnd ? filter.and : filter.or)\n .map((sub) => prune(sub, present, insideExists))\n .filter((sub): sub is Filter => sub !== undefined);\n // The schema requires two arms, so a pruned pair has to collapse rather\n // than emit a one-armed `and` that would fail its own validation.\n if (kept.length === 0) return undefined;\n if (kept.length === 1) return kept[0];\n return isAnd ? { and: kept } : { or: kept };\n }\n\n if ('not' in filter) {\n const inner = prune(filter.not, present, insideExists);\n // `not` of a condition that is not there is not \"true\" or \"false\" — it is\n // a question nobody asked. An author who wants \"exclude these when the key\n // is given\" writes `{ optional: { key, then: { not: … } } }`, which says it.\n if (inner === undefined) {\n throw new VexError('invalid_dsl', 'An optional condition cannot be the whole body of a `not` — wrap the `not` in the optional instead.');\n }\n return { not: inner };\n }\n\n return filter;\n};\n\n/** Resolve every optional condition against the keys a caller supplied.\n *\n * A query whose filter prunes away entirely comes back with NO filter, which\n * is the point: `people/list` with no lens, no search and no cursor is the\n * whole roll, and it says so by having nothing to say. Scope is injected\n * after this, so \"no filter\" still never means \"every tenant\". */\nexport const pruneOptional = (dsl: Query, present: ReadonlySet<string> | 'all'): Query => {\n const from: Source[] = dsl.from.map((source) =>\n typeof source === 'string' ? source : { as: source.as, query: pruneOptional(source.query, present) },\n );\n\n if (dsl.filter === undefined) return { ...dsl, from };\n\n const filter = prune(dsl.filter, present, false);\n if (filter === undefined) {\n const { filter: _dropped, ...rest } = dsl;\n return { ...rest, from };\n }\n return { ...dsl, from, filter };\n};\n\n/** Belt and braces for the three walkers that must never meet this node. */\nexport const refuseOptional = (where: string): never => {\n throw new VexError(\n 'invalid_dsl',\n `An optional condition reached ${where}. It should have been resolved by pruneOptional before the pipeline ran — reaching this point means a query was compiled without knowing which context keys the caller supplied.`,\n );\n};\n","import type { Filter } from '../../schemas/filter.schema.js';\nimport type { ComputeExpression } from '../../schemas/compute.schema.js';\nimport type { AggregateExpression } from '../../schemas/aggregate.schema.js';\nimport type { FieldOrValue } from '../../schemas/value.schema.js';\nimport type { ParamSlot } from '../adapter.types.js';\nimport type { FieldSchema } from '../../schemas/database.schema.js';\nimport type { ResolvedExists, ResolvedJoin } from '../../engine/engine.types.js';\nimport { RESERVED_CONTEXT_KEYS } from '../../schemas/request.schema.js';\nimport { refuseOptional } from '../../engine/optional.js';\nimport { VexError } from '../../errors.js';\nimport { isFieldPathShape } from '../../schemas/identifier.schema.js';\n\n// A `$context` ref naming a reserved sort key would otherwise become a bound\n// param; reject it at compile so reserved keys only ever drive ORDER BY.\nconst assertNotReserved = (key: string): void => {\n if (RESERVED_CONTEXT_KEYS.has(key))\n throw new VexError(\n 'invalid_dsl',\n `\"${key}\" is a reserved sort key (applied to ORDER BY); it cannot be bound as a parameter.`,\n );\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Types\n// ═══════════════════════════════════════════════════════════════\n\ntype PathResolution = { alias: string; column: string; schema: FieldSchema };\n\ntype CompilationContext = {\n resolvedPaths: Map<string, PathResolution>;\n aliasMap: Map<string, string>;\n paramSlots: ParamSlot[];\n paramCounter: { value: number };\n // Every `exists` in this query's filter, resolved. Keyed by the node, because\n // the compiler walks the raw filter tree and needs to find the resolution for\n // the node in front of it.\n existsMap?: Map<object, ResolvedExists>;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// FieldOrValue compilation\n// ═══════════════════════════════════════════════════════════════\n\n// ═══════════════════════════════════════════════════════════════\n// SQL TEXT — the only three ways authored input reaches a statement.\n//\n// · a COLUMN, which must have resolved against the introspected schema —\n// `columnOf` emits the resolver's alias.column or refuses. There is no\n// \"pass it through\" branch, anywhere: the fallback that used to exist here\n// pasted whatever string sat in a field position into the statement.\n// · a LITERAL, quoted by `quoteLiteral` exactly as Postgres's own\n// quote_literal() does, so it is safe whatever standard_conforming_strings\n// says.\n// · an OUTPUT NAME, quoted by `quoteIdent`.\n//\n// Values from a request never reach text at all: they bind as parameters.\n// ═══════════════════════════════════════════════════════════════\n\nexport const quoteLiteral = (s: string): string => {\n const doubled = s.replace(/'/g, \"''\");\n // With standard_conforming_strings off, a backslash in '…' is an escape and\n // `\\'` closes the string. The E'' form escapes backslashes explicitly, so the\n // literal means the same thing under either setting.\n return s.includes('\\\\') ? `E'${doubled.replace(/\\\\/g, '\\\\\\\\')}'` : `'${doubled}'`;\n};\n\nexport const quoteIdent = (name: string): string => `\"${name.replace(/\"/g, '\"\"')}\"`;\n\n// A number that is not finite has no SQL spelling — `NaN` would read as a name.\nexport const numberLiteral = (n: number): string => {\n if (!Number.isFinite(n)) throw new VexError('invalid_dsl', `${String(n)} is not a number SQL can hold.`);\n return String(n);\n};\n\nconst columnOf = (path: string, ctx: CompilationContext): string => {\n const mapped = ctx.aliasMap.get(path);\n if (mapped !== undefined) return mapped;\n const res = ctx.resolvedPaths.get(path);\n if (res !== undefined) return `${res.alias}.${res.column}`;\n throw new VexError('invalid_dsl', `\"${path}\" is not a column this query reads.`);\n};\n\nconst isFieldPath = isFieldPathShape;\n\nconst inferParamType = (path: string, resolvedPaths: Map<string, PathResolution>): ParamSlot['type'] => {\n const res = resolvedPaths.get(path);\n if (res === undefined) return 'string';\n const nt = res.schema.normalizedType;\n if (nt === 'number') return 'number';\n if (nt === 'boolean') return 'boolean';\n return 'string';\n};\n\nexport const compileFieldOrValue = (\n fov: FieldOrValue,\n ctx: CompilationContext,\n): string => {\n if (fov === null) return 'NULL';\n if (typeof fov === 'boolean') return fov ? 'TRUE' : 'FALSE';\n if (typeof fov === 'number') return numberLiteral(fov);\n\n if (typeof fov === 'string') {\n // Shaped like a column → it is one, and it resolved (or this refuses).\n // Anything else is a literal.\n return isFieldPath(fov) ? columnOf(fov, ctx) : quoteLiteral(fov);\n }\n\n // Object: $context or $scope — after eliminating primitives, only these remain\n if (typeof fov === 'object' && fov !== null && '$context' in fov) {\n const key = fov.$context;\n assertNotReserved(key);\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({\n key,\n kind: 'context',\n type: inferParamType(key, ctx.resolvedPaths),\n });\n return `$${ctx.paramCounter.value}`;\n }\n\n if (typeof fov === 'object' && fov !== null && '$scope' in fov) {\n const key = fov.$scope;\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({\n key,\n kind: 'scope',\n type: inferParamType(key, ctx.resolvedPaths),\n });\n return `$${ctx.paramCounter.value}`;\n }\n\n return 'NULL';\n};\n\n\n// ═══════════════════════════════════════════════════════════════\n// Join pairs\n//\n// The whole key, one equality per column pair, for the query's joins and\n// the joins inside an `exists` alike — two emitters, one rule, so a\n// composite key can never be half-joined in one of them.\n// ═══════════════════════════════════════════════════════════════\n\nexport const compileJoinPairs = (join: ResolvedJoin): string[] =>\n join.fromColumns.map((column, i) => {\n const to = join.toColumns[i];\n if (to === undefined) {\n throw new VexError(\n 'invalid_dsl',\n `The join from \"${join.fromAlias}\" to \"${join.toAlias}\" pairs \"${column}\" with no column.`,\n );\n }\n return `${join.fromAlias}.${column} = ${join.toAlias}.${to}`;\n });\n\n// ═══════════════════════════════════════════════════════════════\n// Filter compilation\n// ═══════════════════════════════════════════════════════════════\n\nconst compileComparisonFilter = (\n op: string,\n pair: [FieldOrValue, FieldOrValue],\n ctx: CompilationContext,\n): string => {\n const left = compileFieldOrValue(pair[0], ctx);\n const right = compileFieldOrValue(pair[1], ctx);\n return `${left} ${op} ${right}`;\n};\n\nexport const compileFilter = (\n filter: Filter,\n ctx: CompilationContext,\n): string => {\n // EXISTS compiles INLINE, into the parent's own parameter counter and slot\n // list. That is deliberate: the other subquery path compiles independently\n // and then tries to renumber, which is how two parameterised subqueries came\n // to collide on $1. There is nothing to renumber if nothing was numbered\n // separately.\n //\n // `SELECT 1` because EXISTS asks whether a row is there, not what is in it.\n if ('exists' in filter) {\n const resolved = ctx.existsMap?.get(filter.exists);\n if (resolved === undefined) throw new VexError('invalid_dsl', 'An \"exists\" filter was not resolved. It must appear in a query\\'s own filter.');\n\n const inner: CompilationContext = {\n ...ctx,\n resolvedPaths: resolved.filter?.resolvedPaths ?? ctx.resolvedPaths,\n // The inner map LAYERS OVER the outer one, so an inner path resolves to\n // the inner alias and an outer path — the correlation — still resolves.\n aliasMap: new Map([...ctx.aliasMap, ...resolved.aliasMap]),\n };\n\n const parts: string[] = ['SELECT 1'];\n const first = resolved.sources[0];\n if (first?.table !== undefined) parts.push(`FROM ${first.table} AS ${first.alias}`);\n for (const join of resolved.joins) {\n const source = resolved.sources.find((s) => s.alias === join.toAlias);\n if (source?.table === undefined) continue;\n const keyword = join.kind === 'left' ? 'LEFT JOIN' : 'JOIN';\n const conditions = [\n ...compileJoinPairs(join),\n ...(join.on ?? []).map((extra) => compileFilter(extra.original, inner)),\n ];\n parts.push(`${keyword} ${source.table} AS ${join.toAlias} ON ${conditions.join(' AND ')}`);\n }\n if (resolved.filter !== undefined) parts.push(`WHERE ${compileFilter(resolved.filter.original, inner)}`);\n\n return `EXISTS (${parts.join(' ')})`;\n }\n\n if ('eq' in filter) return compileComparisonFilter('=', filter.eq, ctx);\n if ('neq' in filter) return compileComparisonFilter('<>', filter.neq, ctx);\n if ('gt' in filter) return compileComparisonFilter('>', filter.gt, ctx);\n if ('gte' in filter) return compileComparisonFilter('>=', filter.gte, ctx);\n if ('lt' in filter) return compileComparisonFilter('<', filter.lt, ctx);\n if ('lte' in filter) return compileComparisonFilter('<=', filter.lte, ctx);\n\n if ('in' in filter) {\n const col = columnOf(filter.in[0], ctx);\n const target = filter.in[1];\n\n if (Array.isArray(target)) {\n const values = target.map((v) => compileFieldOrValue(v, ctx));\n return `${col} IN (${values.join(', ')})`;\n }\n\n // ContextRef or ScopeRef → array parameter\n if ('$context' in target) {\n assertNotReserved(target.$context);\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$context, kind: 'context', type: 'string[]' });\n return `${col} = ANY($${ctx.paramCounter.value})`;\n }\n if ('$scope' in target) {\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$scope, kind: 'scope', type: 'string[]' });\n return `${col} = ANY($${ctx.paramCounter.value})`;\n }\n\n return `${col} IN ()`;\n }\n\n if ('notIn' in filter) {\n const col = columnOf(filter.notIn[0], ctx);\n const target = filter.notIn[1];\n\n if (Array.isArray(target)) {\n const values = target.map((v) => compileFieldOrValue(v, ctx));\n return `${col} NOT IN (${values.join(', ')})`;\n }\n\n if ('$context' in target) {\n assertNotReserved(target.$context);\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$context, kind: 'context', type: 'string[]' });\n return `${col} <> ALL($${ctx.paramCounter.value})`;\n }\n if ('$scope' in target) {\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$scope, kind: 'scope', type: 'string[]' });\n return `${col} <> ALL($${ctx.paramCounter.value})`;\n }\n\n return `${col} NOT IN ()`;\n }\n\n if ('like' in filter) {\n const col = columnOf(filter.like[0], ctx);\n const pattern = compileFieldOrValue(filter.like[1], ctx);\n return `${col} LIKE ${pattern}`;\n }\n\n if ('ilike' in filter) {\n const col = columnOf(filter.ilike[0], ctx);\n const pattern = compileFieldOrValue(filter.ilike[1], ctx);\n return `${col} ILIKE ${pattern}`;\n }\n\n if ('isNull' in filter) {\n return `${columnOf(filter.isNull, ctx)} IS NULL`;\n }\n\n if ('isNotNull' in filter) {\n return `${columnOf(filter.isNotNull, ctx)} IS NOT NULL`;\n }\n\n if ('and' in filter) {\n const parts = filter.and.map((sub) => compileFilter(sub, ctx));\n return `(${parts.join(' AND ')})`;\n }\n\n if ('or' in filter) {\n const parts = filter.or.map((sub) => compileFilter(sub, ctx));\n return `(${parts.join(' OR ')})`;\n }\n\n if ('not' in filter) {\n const inner = compileFilter(filter.not, ctx);\n return `NOT (${inner})`;\n }\n\n if ('semantic' in filter) {\n // Semantic filter: cosine distance using pgvector <=> operator\n const fieldPath = filter.semantic.field;\n const col = columnOf(fieldPath, ctx);\n\n const queryRef = filter.semantic.query;\n const key = '$context' in queryRef ? queryRef.$context : queryRef.$scope;\n if ('$context' in queryRef) assertNotReserved(queryRef.$context);\n\n // Look up vector dimensions from resolved paths\n const res = ctx.resolvedPaths.get(fieldPath);\n const dimensions = res?.schema.vectorDimensions;\n\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({\n key,\n kind: 'semantic',\n type: 'string',\n dimensions,\n });\n\n const paramRef = `$${ctx.paramCounter.value}`;\n const minScore = numberLiteral(filter.semantic.minScore ?? 0);\n return `1 - (${col} <=> ${paramRef}) >= ${minScore}`;\n }\n\n if ('fuzzy' in filter) {\n const col = columnOf(filter.fuzzy.field, ctx);\n\n const queryRef = filter.fuzzy.query;\n const key = '$context' in queryRef ? queryRef.$context : queryRef.$scope;\n const kind = '$context' in queryRef ? 'context' as const : 'scope' as const;\n if ('$context' in queryRef) assertNotReserved(queryRef.$context);\n\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key, kind, type: 'string' });\n\n const paramRef = `$${ctx.paramCounter.value}`;\n const maxDistance = filter.fuzzy.maxDistance;\n\n if (maxDistance !== undefined) {\n return `levenshtein(${col}, ${paramRef}) <= ${numberLiteral(maxDistance)}`;\n }\n // pg_trgm similarity\n return `${col} % ${paramRef}`;\n }\n\n // Resolved away before the pipeline — see engine/optional.ts. Named\n // explicitly because the fallthrough below is `TRUE`: an unrecognised node\n // would quietly compile to \"match everything\", which for an optional\n // condition is the right answer reached by the wrong route, and for anything\n // else is a filter that silently stopped filtering.\n if ('optional' in filter) refuseOptional('SQL compilation');\n\n // Should not reach here if the filter was validated\n return 'TRUE';\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Compute expression compilation\n// ═══════════════════════════════════════════════════════════════\n\nexport const compileCompute = (\n expr: ComputeExpression,\n ctx: CompilationContext,\n): string => {\n if ('add' in expr) {\n const a = compileFieldOrValue(expr.add[0], ctx);\n const b = compileFieldOrValue(expr.add[1], ctx);\n return `(${a} + ${b})`;\n }\n\n if ('subtract' in expr) {\n const a = compileFieldOrValue(expr.subtract[0], ctx);\n const b = compileFieldOrValue(expr.subtract[1], ctx);\n return `(${a} - ${b})`;\n }\n\n if ('multiply' in expr) {\n const a = compileFieldOrValue(expr.multiply[0], ctx);\n const b = compileFieldOrValue(expr.multiply[1], ctx);\n return `(${a} * ${b})`;\n }\n\n if ('divide' in expr) {\n const a = compileFieldOrValue(expr.divide[0], ctx);\n const b = compileFieldOrValue(expr.divide[1], ctx);\n return `(${a} / ${b})`;\n }\n\n if ('concat' in expr) {\n const parts = expr.concat.map((v) => compileFieldOrValue(v, ctx));\n return `(${parts.join(' || ')})`;\n }\n\n if ('coalesce' in expr) {\n const parts = expr.coalesce.map((v) => compileFieldOrValue(v, ctx));\n return `COALESCE(${parts.join(', ')})`;\n }\n\n if ('case' in expr) {\n const whenClauses = expr.case.when.map((w) => {\n const cond = compileFilter(w.condition, ctx);\n const val = compileFieldOrValue(w.then, ctx);\n return `WHEN ${cond} THEN ${val}`;\n });\n const elseVal = compileFieldOrValue(expr.case.else, ctx);\n return `CASE ${whenClauses.join(' ')} ELSE ${elseVal} END`;\n }\n\n return 'NULL';\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Aggregate expression compilation\n// ═══════════════════════════════════════════════════════════════\n\n// SUM/AVG/MIN/MAX take a field path (mapped to its qualified column) OR a\n// compute expression (compiled to SQL). count stays a plain field/`*`.\nconst aggArg = (arg: string | ComputeExpression, ctx: CompilationContext): string =>\n typeof arg === 'string' ? columnOf(arg, ctx) : compileCompute(arg, ctx);\n\nexport const compileAggregate = (\n expr: AggregateExpression,\n ctx: CompilationContext,\n): string => {\n if ('count' in expr) {\n if (expr.count === '*') return 'COUNT(*)';\n return `COUNT(${columnOf(expr.count, ctx)})`;\n }\n if ('countDistinct' in expr) return `COUNT(DISTINCT ${columnOf(expr.countDistinct, ctx)})`;\n if ('sum' in expr) return `SUM(${aggArg(expr.sum, ctx)})`;\n if ('avg' in expr) return `AVG(${aggArg(expr.avg, ctx)})`;\n if ('min' in expr) return `MIN(${aggArg(expr.min, ctx)})`;\n if ('max' in expr) return `MAX(${aggArg(expr.max, ctx)})`;\n return 'NULL';\n};\n\nexport type { CompilationContext };\n","// Scope is server-side, LLM-invisible access control, applied to the resolved\n// query/mutation AFTER it is authored — so a generated or injected DSL can never\n// reference, dodge, or forge it. There are two roles, named for the SQL they\n// produce:\n// • match — RLS: the row's column must equal a scope value (a WHERE filter,\n// and on INSERT the column is pinned to that value so you can't write\n// outside your boundary).\n// • set — identity: the engine writes the column from a scope value on\n// EVERY column-writing op — INSERT values and UPDATE set alike (`write`\n// means every write; delete writes no columns, so it is structurally\n// exempt). It doesn't touch reads.\n\n// Caller runtime values, injected at execute via options.scope, keyed by name\n// (e.g. { userId, accountId }). A rule's `to` names one of these keys.\nexport type ScopeValues = Record<string, unknown>;\n\n// RLS filter: `<entity>.<match>` must equal the `to` scope value — or, in the\n// set-valued form, must be ONE OF the `in` scope value.\n//\n// THE SET IS FOR READS. A reach that covers several rows is a real concept —\n// \"mine, and the people I am answerable for\" — and the scalar form cannot say\n// it. What the set deliberately CANNOT do is pin a write: a `match` on an\n// INSERT writes the column (engine.ts), and a set has no single value to\n// write. That is not a gap to fill later; it is the property that keeps a\n// write's subject unforgeable. The mutation engine throws rather than\n// guessing, so a set-valued write rule is unauthorable rather than merely\n// discouraged.\n//\n// Fail-closed comes from SQL rather than from a guard here: the set compiles\n// to `col = ANY($n)`, an absent scope value binds NULL (`= ANY(NULL)` is NULL,\n// so the row drops) and an empty one binds `{}` (false). Neither can be\n// forgotten, because neither was written.\nexport type ScopeMatchOne = { match: string; to: string };\nexport type ScopeMatchAny = { match: string; in: string };\nexport type ScopeMatch = ScopeMatchOne | ScopeMatchAny;\n\n/** The set-valued form, told apart by its key — `to` and `in` never coexist. */\nexport const isSetMatch = (m: ScopeMatch): m is ScopeMatchAny => 'in' in m;\n\n// Identity write: `<set>` is filled from the `to` scope value on every\n// column-writing mutation (INSERT and UPDATE).\nexport type ScopeSet = { set: string; to: string };\n\nexport type ScopeRule = ScopeMatch | ScopeSet;\n\nexport type ScopeEntityRule =\n | { public: true } // fully open (read + write, no rules)\n | { deny: true } // fully closed\n | {\n // Reads (SELECT): each match becomes a WHERE filter. Match only — there is\n // nothing to stamp on a read.\n read?: ScopeMatch[];\n // Writes. `write` is the UMBRELLA: its presence grants insert, update\n // and delete, and its rules apply to every one of them. The specific\n // phases refine it: their presence grants just that op, and their rules\n // apply ON TOP of the umbrella's. An op is allowed iff its specific\n // phase or `write` exists. Rule mechanics per op: a `match` filters\n // UPDATE/DELETE and pins the column on INSERT; a `set` writes the\n // column on INSERT and UPDATE (delete writes no columns, so `delete`\n // is match-only at the type level).\n write?: ScopeRule[];\n insert?: ScopeRule[];\n update?: ScopeRule[];\n delete?: ScopeMatch[];\n };\n\nexport type ScopePolicy = {\n // Fallback for an entity that isn't listed, and for a listed entity's absent\n // phase: 'allow' = unrestricted, 'deny' = no access.\n default: 'allow' | 'deny';\n entities: Record<string, ScopeEntityRule>;\n};\n","import type { Query } from '../schemas/query.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { ResolvedQuery, ResolvedFilter, ResolvedSource, ResolvedJoin } from '../engine/engine.types.js';\nimport type { ScopePolicy, ScopeEntityRule, ScopeMatch } from './scope.types.js';\nimport { isSetMatch } from './scope.types.js';\nimport { VexError } from '../errors.js';\n\n// ───────────────────────────────────────────────────────────────\n// Error\n// ───────────────────────────────────────────────────────────────\n\n// A scope denial IS a VexError (code 'scope_denied') so the HTTP layer maps\n// it to a 400 like every other request error — a denied read or write is the\n// caller's problem, not a 500. `entity` is kept for callers that inspect it.\nexport class VexScopeError extends VexError {\n readonly entity: string;\n\n constructor(entity: string, message: string) {\n super('scope_denied', message);\n this.name = 'VexScopeError';\n this.entity = entity;\n }\n}\n\n// ───────────────────────────────────────────────────────────────\n// TWO QUESTIONS, DELIBERATELY SEPARATED\n// ───────────────────────────────────────────────────────────────\n//\n// Scope answers two things that used to be answered in one pass, and\n// conflating them produced a silent, universal row-loss bug:\n//\n// 1. MAY this caller touch this table at all? — a pure allow/deny over\n// entity names. Needs no schema, no aliases, no joins. Runs before\n// resolution, over every entity discovered anywhere in the tree.\n//\n// 2. WHERE does the row rule go? — needs to know HOW the table is reached,\n// because a row rule on a LEFT-joined table belongs in that join's ON\n// clause. It used to be merged into the DSL's `filter`, which compiles to\n// WHERE, which turns every LEFT join into an INNER one: a driving row\n// whose optional FK is null gets null-padded columns, `null = $tenant` is\n// null rather than true, and the row vanishes. No error, no warning, a\n// shorter list. It hid for as long as no data had a null FK.\n//\n// Only the resolver knows join kinds, so (2) moved after resolution. That also\n// means scope no longer writes anything into the authored `Query` — the\n// document integrations ship over the wire carries no engine-trusted field,\n// which is a property worth having on its own.\n\nconst matchesFor = (entity: string, rule: ScopeEntityRule | undefined, def: 'allow' | 'deny'): ScopeMatch[] => {\n if (rule === undefined) {\n if (def === 'deny') throw new VexScopeError(entity, `Entity \"${entity}\" is not allowed by scope policy (default: deny)`);\n return [];\n }\n if ('public' in rule) return [];\n if ('deny' in rule) throw new VexScopeError(entity, `Entity \"${entity}\" is denied by scope policy`);\n if (rule.read === undefined) {\n if (def === 'deny') throw new VexScopeError(entity, `Reads of \"${entity}\" are not allowed by scope policy (default: deny)`);\n return [];\n }\n return rule.read;\n};\n\n// Whether a policy lets a caller read a table at all — the same answer\n// `checkScope` enforces, as a predicate for anything that must decide what to\n// SHOW (discovery, the schema a generating agent is handed) rather than what\n// to refuse.\nexport const canReadTable = (policy: ScopePolicy, table: string): boolean => {\n const rule = policy.entities[table];\n if (rule === undefined) return policy.default === 'allow';\n if ('public' in rule) return true;\n if ('deny' in rule) return false;\n return rule.read !== undefined || policy.default === 'allow';\n};\n\n// ───────────────────────────────────────────────────────────────\n// 1. May they touch it\n// ───────────────────────────────────────────────────────────────\n\n// Throws on the first denied entity. A denied entity ANYWHERE denies the query,\n// including inside a subquery or an `exists` — `discoverEntities` walks the\n// whole tree, so a table cannot be reached by hiding it one level down.\nexport const checkScope = (entities: Set<string>, policy: ScopePolicy): void => {\n for (const entity of entities) matchesFor(entity, policy.entities[entity], policy.default);\n};\n\n// ───────────────────────────────────────────────────────────────\n// 2. Where the row rule goes\n// ───────────────────────────────────────────────────────────────\n\nconst andMerge = (existing: ResolvedFilter | undefined, additions: ResolvedFilter[]): ResolvedFilter | undefined => {\n if (additions.length === 0) return existing;\n const all = existing === undefined ? additions : [existing, ...additions];\n if (all.length === 1) return all[0];\n\n const paths = new Map<string, { alias: string; column: string; schema: never }>();\n for (const part of all) for (const [key, value] of part.resolvedPaths) paths.set(key, value as never);\n return { original: { and: all.map((f) => f.original) }, resolvedPaths: paths as never };\n};\n\n// One row rule, resolved against the alias the table actually got.\nconst predicateFor = (\n entityName: string,\n alias: string,\n match: ScopeMatch,\n fields: { name: string; nullable: boolean }[],\n): ResolvedFilter | undefined => {\n const field = fields.find((f) => f.name === match.match);\n // A rule naming a column the table does not have is a policy bug, not a\n // request bug — but failing the read closed is the only safe reading of it.\n if (field === undefined) throw new VexScopeError(entityName, `Scope rule for \"${entityName}\" names column \"${match.match}\", which the table does not have`);\n const path = `${entityName}.${match.match}`;\n // The set-valued form compiles to `col = ANY($n)`, which the operator table\n // already emits for `in` against a scope ref — so a reach covering several\n // rows needs no compile branch of its own, and binds through the same slot\n // machinery. An absent or empty set matches nothing (see scope.types.ts).\n const original: Filter = isSetMatch(match)\n ? { in: [path, { $scope: match.in }] }\n : { eq: [path, { $scope: match.to }] };\n return { original, resolvedPaths: new Map([[path, { alias, column: match.match, schema: field as never }]]) as never };\n};\n\n// One LEVEL of a resolved tree — an outer query, a subquery, or an `exists`.\n// They differ in what else they carry; for placing row rules they are the same\n// four things, so they get the same code and cannot drift apart.\ntype ScopeLevel = {\n sources: ResolvedSource[];\n joins: ResolvedJoin[];\n aliasMap: Map<string, string>;\n filter?: ResolvedFilter;\n};\n\nconst placeInto = (level: ScopeLevel, policy: ScopePolicy): void => {\n const whereAdditions: ResolvedFilter[] = [];\n\n for (const source of level.sources) {\n const entity = source.entity;\n if (entity === undefined) continue;\n\n const join = level.joins.find((j) => j.toAlias === source.alias);\n for (const match of matchesFor(entity.name, policy.entities[entity.name], policy.default)) {\n const predicate = predicateFor(entity.name, source.alias, match, entity.fields);\n if (predicate === undefined) continue;\n\n // The compiler resolves `entity.column` through the alias map, and these\n // predicates never went through the resolver's field pass, so they say\n // where they point.\n level.aliasMap.set(`${entity.name}.${match.match}`, `${source.alias}.${match.match}`);\n\n if (join !== undefined && join.kind === 'left') join.on = [...(join.on ?? []), predicate];\n else whereAdditions.push(predicate);\n }\n }\n\n const merged = andMerge(level.filter, whereAdditions);\n if (merged !== undefined) level.filter = merged;\n};\n\n// Walk the resolved tree and place every row rule. Subqueries and `exists`\n// nodes recurse: a rule on `tasks` lands inside the level whose FROM actually\n// reads tasks, never on an outer query that only sees an alias.\n//\n// The `exists` recursion is not tidiness — it is the boundary. An EXISTS\n// returns a boolean, but a boolean about somebody else's rows is still an\n// answer about somebody else's rows: an uncorrelated `exists` over a scoped\n// table would report whether ANY tenant has such a row. Access-checking the\n// table is not enough; the rule has to be inside the subquery too.\nexport const scopeResolved = (resolved: ResolvedQuery, policy: ScopePolicy): ResolvedQuery => {\n for (const source of resolved.sources) {\n if (source.subquery !== undefined) scopeResolved(source.subquery, policy);\n }\n\n // Every `exists` at every depth — the resolver collects nested ones into the\n // same flat map, so one pass covers the tree.\n for (const node of resolved.existsMap?.values() ?? []) {\n placeInto(node, policy);\n }\n\n placeInto(resolved, policy);\n return resolved;\n};\n\n// ───────────────────────────────────────────────────────────────\n// Deprecated shape, kept so a caller that only wanted the access check still\n// gets one. It no longer returns a filtered DSL, because scope is not a DSL\n// concern any more — `scopeResolved` does the placing.\n// ───────────────────────────────────────────────────────────────\nexport const applyScope = (dsl: Query, entities: Set<string>, policy: ScopePolicy): Query => {\n checkScope(entities, policy);\n return dsl;\n};\n","import type { ContextContract, ParamSlot } from '../adapters/adapter.types.js';\n\n// ───────────────────────────────────────────────────────────────\n// Validation context builder\n// ───────────────────────────────────────────────────────────────\n\nconst defaultForType = (type: ParamSlot['type']): unknown => {\n if (type === 'string') return '';\n if (type === 'number') return 0;\n if (type === 'boolean') return false;\n if (type === 'string[]') return [''];\n if (type === 'number[]') return [0];\n if (type === 'json') return [];\n return '';\n};\n\nexport const buildValidationContext = (contract: ContextContract): Record<string, unknown> => {\n const ctx: Record<string, unknown> = {};\n for (const key of Object.keys(contract)) {\n const slot = contract[key];\n if (slot === undefined) continue;\n // Skip semantic slots — handled separately by the test path\n if (slot.kind === 'semantic') continue;\n ctx[key] = defaultForType(slot.type);\n }\n return ctx;\n};\n\n// ───────────────────────────────────────────────────────────────\n// Parameter resolution\n// ───────────────────────────────────────────────────────────────\n\nexport const resolveParams = async (\n slots: ParamSlot[],\n context: Record<string, unknown>,\n scope: Record<string, unknown>,\n embed?: (text: string, dimensions?: number) => Promise<number[]>,\n): Promise<unknown[]> => {\n const results: unknown[] = [];\n\n for (const slot of slots) {\n if (slot.kind === 'context') {\n results.push(context[slot.key]);\n continue;\n }\n\n if (slot.kind === 'scope') {\n results.push(scope[slot.key]);\n continue;\n }\n\n // kind === 'semantic'\n if (embed === undefined) {\n throw new Error(`Semantic parameter \"${slot.key}\" requires an embed function`);\n }\n const text = context[slot.key];\n if (typeof text !== 'string') {\n throw new Error(`Semantic parameter \"${slot.key}\" requires a string value in context`);\n }\n const vector = await embed(text, slot.dimensions);\n results.push(`[${vector.join(',')}]`);\n }\n\n return results;\n};\n","import type { CompiledQuery, Row, DatabaseAdapter } from '../adapters/adapter.types.js';\nimport type { ContextMeta } from '../schemas/request.schema.js';\nimport { resolveParams } from '../utils/context.js';\nimport { VexError } from '../errors.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Execution\n// ═══════════════════════════════════════════════════════════════\n\nexport const executeQuery = async (\n compiled: CompiledQuery,\n context: Record<string, unknown>,\n scope: Record<string, unknown>,\n adapter: DatabaseAdapter,\n embed?: (text: string, dimensions?: number) => Promise<number[]>,\n): Promise<Row[]> => {\n const boundParams = await resolveParams(\n compiled.paramSlots,\n context,\n scope,\n embed,\n );\n return adapter.execute(compiled, boundParams);\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Context contract builder\n// ═══════════════════════════════════════════════════════════════\n\nexport const buildContextContract = (\n compiled: CompiledQuery,\n // Every key that controls an `optional` condition anywhere in the STORED\n // dsl — including the ones this run pruned away, which have no slot and so\n // would otherwise be invisible to the caller who most needs to know they\n // exist: the one who did not send them.\n optionalKeys: readonly string[] = [],\n): Record<string, ContextMeta> => {\n const contract: Record<string, ContextMeta> = {};\n\n for (const slot of compiled.paramSlots) {\n contract[slot.key] = {\n type: slot.type,\n kind: slot.kind,\n ...(optionalKeys.includes(slot.key) ? { optional: true as const } : {}),\n };\n }\n\n for (const key of optionalKeys) {\n if (contract[key] !== undefined) continue;\n contract[key] = { kind: 'context', optional: true, absent: true };\n }\n\n return contract;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Missing context detection\n// ═══════════════════════════════════════════════════════════════\n\n// The CALLER's half: context keys the request did not supply. A read with\n// holes answers empty and hands back the contract it missed — the caller can\n// fix that. Scope is not in here; see requireScope.\nexport const findMissingContext = (\n compiled: CompiledQuery,\n context: Record<string, unknown>,\n): string[] => {\n const missing: string[] = [];\n\n for (const slot of compiled.paramSlots) {\n if ((slot.kind === 'context' || slot.kind === 'semantic') && context[slot.key] === undefined) {\n missing.push(slot.key);\n }\n }\n\n return missing;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Missing scope — the HOST's half\n// ═══════════════════════════════════════════════════════════════\n\n// A `$scope` slot the host did not fill is not a hole a caller can mend: the\n// caller cannot supply scope, and binding it would bind NULL — which matches\n// no row on a read and STAMPS NULL on a write. So it refuses, loudly, before\n// anything runs. The keys ride in `details` for the host's logs; the HTTP\n// layer does not hand them to the client.\nexport const requireScope = (compiled: { paramSlots: readonly { kind: string; key: string }[] }, scope: Record<string, unknown>): void => {\n const missing = [...new Set(compiled.paramSlots.filter((slot) => slot.kind === 'scope' && scope[slot.key] === undefined).map((slot) => slot.key))];\n if (missing.length > 0) {\n throw new VexError('missing_scope', `This statement is scoped by ${missing.join(', ')}, which the host did not supply.`, { keys: missing });\n }\n};\n","import { z } from 'zod';\nimport { FilterSchema } from '../schemas/filter.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { FieldOrValue } from '../schemas/value.schema.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Mutation grammar — the WRITE sibling of the query DSL.\n//\n// Closed on purpose. A mutation is authored data (a cache entry seeded by a\n// developer), never generated and never client-supplied: the wire replays a\n// fingerprint, and the def the fingerprint names lives server-side. The\n// grammar rejects the dangerous shapes at parse: `$scope` is unauthorable\n// (identity/tenant is engine-injected — see scopeMutation), and update/delete\n// REQUIRE a `where` (a write with no WHERE touches every row).\n// ═══════════════════════════════════════════════════════════════\n\n// A scalar subquery in value position: read ONE value from another table at\n// write time — `(SELECT field FROM from WHERE ...)`. This is how a statement\n// references a row it cannot otherwise name (e.g. a person found by email).\n// The lookup READS, so the read-phase scope rules of `from` are applied to its\n// WHERE by the engine — a write entry is never a read-scope bypass. The WHERE\n// should hit a unique key: more than one matching row is a runtime error\n// (deliberately — silently picking an arbitrary row would be worse).\nconst LookupSchema = z\n .object({\n $lookup: z\n .object({\n from: z.string().describe('Table the value is read from'),\n field: z.string().describe('Column the subquery returns'),\n where: FilterSchema.describe('Bounds the lookup — should match at most one row'),\n })\n .strict(),\n })\n .strict()\n .describe('Scalar subquery: reads one value from another table at write time; read scope rules apply');\n\n// A value an AUTHORED mutation may set: a literal, a `{ $context }` ref to\n// the caller's runtime values, or a `{ $lookup }` scalar subquery. NOT\n// `$scope` — the engine injects it post-parse, so a stored or injected\n// mutation cannot place, omit, or redirect it. NOT a field path either — a\n// write sets values, it does not read columns.\nconst ValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.object({ $context: z.string() }).strict(),\n LookupSchema,\n]);\n\nconst Columns = z\n .record(z.string(), ValueSchema)\n .refine((r) => Object.keys(r).length > 0, { message: 'a write must set at least one column' });\n\n// ── ON CONFLICT ────────────────────────────────────────────────\n// The DB-arbitrated sibling of the `upsert` sugar below. `upsert` branches on\n// what the CALLER sent (key present → update); `onConflict` branches on what\n// the DATABASE holds (row exists → update/nothing), atomically. `target` must\n// name a unique constraint — validated against the introspected schema, so an\n// ON CONFLICT that arrests nothing is an authoring error, not a runtime\n// surprise. `set` present → DO UPDATE SET (RETURNING yields the row on both\n// paths — re-setting one inserted value as a no-op \"touch\" is the idiom for\n// create-or-fetch). `set` absent → DO NOTHING, which returns NO row on\n// conflict; callers can read that absence as \"already existed\".\nconst OnConflictSchema = z\n .object({\n target: z.array(z.string()).min(1).describe('Conflict columns — must match a unique index or the primary key'),\n set: Columns.optional().describe('DO UPDATE SET when the row already exists; omitted → DO NOTHING (no row returned on conflict)'),\n })\n .strict();\n\n// `where` is a real vex `Filter` — `$context`/`$scope` and scope injection\n// behave exactly as they do for reads.\nconst InsertSchema = z.object({ op: z.literal('insert'), table: z.string(), values: Columns, onConflict: OnConflictSchema.optional() }).strict();\nconst UpdateSchema = z.object({ op: z.literal('update'), table: z.string(), set: Columns, where: FilterSchema }).strict();\nconst DeleteSchema = z.object({ op: z.literal('delete'), table: z.string(), where: FilterSchema }).strict();\n\n// ── insertEach ─────────────────────────────────────────────────\n// One INSERT for a caller-sized list — `INSERT ... SELECT ... FROM\n// jsonb_array_elements($items)`. `items` names a context key holding an array\n// of objects; a `{ $item }` value reads a key from the current element (cast\n// to the column's type from the schema); every other value (literal,\n// `$context`, `$lookup`, engine-injected `$scope`) is constant across rows.\n// This is how \"one template row per ticked weekday\" stays a single authored\n// statement instead of a code loop.\nconst ItemRefSchema = z\n .object({ $item: z.string() })\n .strict()\n .describe('insertEach only: a key read from the current element of `items`');\n\nconst EachColumns = z\n .record(z.string(), z.union([ValueSchema, ItemRefSchema]))\n .refine((r) => Object.keys(r).length > 0, { message: 'a write must set at least one column' });\n\nconst InsertEachSchema = z\n .object({\n op: z.literal('insertEach'),\n table: z.string(),\n items: z.object({ $context: z.string() }).strict().describe('Context key holding an array of objects — one inserted row per element'),\n values: EachColumns,\n onConflict: OnConflictSchema.optional(),\n })\n .strict();\n\n// ── Sugar ──────────────────────────────────────────────────────\n// A sugar op rewrites to the core ops above before anything runs (see\n// desugarMutation). `upsert` is insert-or-update keyed on `key`: present in\n// the call's context → update that row, absent/empty → insert.\nconst UpsertSchema = z\n .object({\n op: z.literal('upsert'),\n table: z.string(),\n columns: Columns, // set on BOTH branches (update SET, and part of the insert)\n insert: Columns.optional(), // extra columns set ONLY on insert — immutable-on-create (e.g. a FK)\n key: z.string(),\n })\n .strict()\n .describe('Sugar: insert-or-update by `key` (e.g. \"id\"). Desugars to update (SET columns WHERE key) when the key is present, else insert (columns + `insert`-only).');\n\nexport const MutationSchema = z.discriminatedUnion('op', [InsertSchema, InsertEachSchema, UpdateSchema, DeleteSchema, UpsertSchema]);\nexport type Mutation = z.infer<typeof MutationSchema>;\n\n// The core ops a sugar desugars TO — what the pipeline (scope/validate/\n// compile) actually handles. `upsert` never reaches them.\nexport type CoreMutation = Exclude<Mutation, { op: 'upsert' }>;\n\n// One write, or a batch run together in a single transaction.\nexport const MutationDefinitionSchema = z.union([MutationSchema, MutationSchema.array().min(1)]);\nexport type MutationDefinition = z.infer<typeof MutationDefinitionSchema>;\n\n// The value shapes as the ENGINE sees them (authored + injected).\nexport type LookupValue = { $lookup: { from: string; field: string; where: Filter } };\nexport type ItemRef = { $item: string };\nexport type MutationValue = FieldOrValue | LookupValue;\n\n// After scopeMutation the engine may have injected `{ $scope }` refs that the\n// authored grammar forbids — so the resolved form's columns widen to the full\n// `MutationValue`. It may also have widened `onConflict` with a `where` (the\n// RLS filter on the DO UPDATE half — `match` rules land there when the\n// conflict target does not already pin them). Authored (`Mutation`) →\n// resolved is a pure widening.\nexport type ResolvedOnConflict = { target: string[]; set?: Record<string, MutationValue>; where?: Filter };\nexport type ResolvedMutation =\n | { op: 'insert'; table: string; values: Record<string, MutationValue>; onConflict?: ResolvedOnConflict }\n | { op: 'insertEach'; table: string; items: { $context: string }; values: Record<string, MutationValue | ItemRef>; onConflict?: ResolvedOnConflict }\n | { op: 'update'; table: string; set: Record<string, MutationValue>; where: Filter }\n | { op: 'delete'; table: string; where: Filter };\n","import type { Query } from '../schemas/query.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { DatabaseSchema } from '../schemas/database.schema.js';\nimport type { Mutation, MutationDefinition, CoreMutation } from './schema.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Context signatures — the derived input contract of a cache entry.\n//\n// A fingerprint hides the def; the def contains `{ $context }` refs; the refs\n// sit at positions whose column types the schema knows. So the contract of\n// \"what do I pass this fingerprint\" is COMPUTED from the artifact — walked\n// out of the stored DSL/def — never authored, and therefore never stale.\n// Discovery serves it; the mutation error path teaches it.\n// ═══════════════════════════════════════════════════════════════\n\nexport type ContextField = { type: string; column?: string; note?: string };\nexport type ContextSignature = Record<string, ContextField>;\nexport type MutationEffect = { op: Mutation['op']; table: string; columns: string[] };\n\nconst isContextRef = (v: unknown): v is { $context: string } =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && typeof (v as Record<string, unknown>)['$context'] === 'string';\n\nconst columnInfo = (path: string, schema: DatabaseSchema | undefined): ContextField => {\n const [table, field] = path.split('.');\n const entity = schema?.entities.find((e) => e.table === table || e.name === table);\n const f = entity?.fields.find((x) => x.name === field);\n return { type: f?.normalizedType ?? 'unknown', column: path };\n};\n\n// First specific description wins; a later, better-typed sighting upgrades an\n// 'unknown' one. Notes stick once set.\nconst addField = (sig: ContextSignature, key: string, field: ContextField): void => {\n const existing = sig[key];\n if (existing === undefined) {\n sig[key] = field;\n return;\n }\n if (existing.type === 'unknown' && field.type !== 'unknown') {\n sig[key] = { ...field, ...(existing.note !== undefined ? { note: existing.note } : {}) };\n }\n};\n\n// Last-resort sweep: find `{ $context }` anywhere in a value (compute args,\n// exotic filter ops) and record the key with an unknown type.\nconst deepScan = (value: unknown, sig: ContextSignature): void => {\n if (isContextRef(value)) {\n addField(sig, value.$context, { type: 'unknown' });\n return;\n }\n if (Array.isArray(value)) {\n for (const v of value) deepScan(v, sig);\n return;\n }\n if (value !== null && typeof value === 'object') {\n for (const v of Object.values(value)) deepScan(v, sig);\n }\n};\n\n// Comparison positions pair a field path with a value — when the value is a\n// `{ $context }` ref, the path's column gives the ref its type.\nconst COMPARISONS = ['eq', 'neq', 'gt', 'gte', 'lt', 'lte'] as const;\n\nconst walkFilter = (filter: Filter, schema: DatabaseSchema | undefined, sig: ContextSignature): void => {\n const f = filter as Record<string, unknown>;\n for (const op of COMPARISONS) {\n const pair = f[op];\n if (Array.isArray(pair) && pair.length === 2) {\n const [a, b] = pair as [unknown, unknown];\n if (typeof a === 'string' && isContextRef(b)) addField(sig, b.$context, columnInfo(a, schema));\n else if (typeof b === 'string' && isContextRef(a)) addField(sig, a.$context, columnInfo(b, schema));\n else deepScan(pair, sig);\n return;\n }\n }\n if ('in' in f || 'notIn' in f) {\n const [path, target] = (f['in'] ?? f['notIn']) as [string, unknown];\n if (isContextRef(target)) addField(sig, target.$context, { ...columnInfo(path, schema), type: `${columnInfo(path, schema).type}[]` });\n else deepScan(target, sig);\n return;\n }\n if ('like' in f || 'ilike' in f) {\n const [path, v] = (f['like'] ?? f['ilike']) as [string, unknown];\n if (isContextRef(v)) addField(sig, v.$context, { type: 'string', column: path, note: 'pattern' });\n return;\n }\n if ('and' in f || 'or' in f) {\n for (const sub of (f['and'] ?? f['or']) as Filter[]) walkFilter(sub, schema, sig);\n return;\n }\n if ('not' in f) {\n walkFilter(f['not'] as Filter, schema, sig);\n return;\n }\n // isNull / isNotNull carry no values; semantic/fuzzy and anything future get\n // the generic sweep so no ref is ever silently dropped.\n deepScan(f, sig);\n};\n\nconst isLookupRef = (v: unknown): v is { $lookup: { from: string; field: string; where: Filter } } =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && '$lookup' in v;\n\nconst columnsOf = (m: Mutation): Record<string, unknown> =>\n m.op === 'insert' || m.op === 'insertEach'\n ? { ...m.values, ...(m.onConflict?.set ?? {}) }\n : m.op === 'update'\n ? m.set\n : m.op === 'upsert'\n ? { ...m.columns, ...(m.insert ?? {}) }\n : {};\n\nexport const collectMutationContext = (def: MutationDefinition, schema?: DatabaseSchema): ContextSignature => {\n const sig: ContextSignature = {};\n const list = Array.isArray(def) ? def : [def];\n for (const m of list) {\n for (const [col, v] of Object.entries(columnsOf(m))) {\n if (isLookupRef(v)) {\n // The lookup's WHERE binds context like any filter does.\n walkFilter(v.$lookup.where, schema, sig);\n continue;\n }\n if (!isContextRef(v)) continue;\n const insertOnly = m.op === 'upsert' && m.insert !== undefined && col in m.insert;\n addField(sig, v.$context, { ...columnInfo(`${m.table}.${col}`, schema), ...(insertOnly ? { note: 'insert only' } : {}) });\n }\n if (m.op === 'update' || m.op === 'delete') walkFilter(m.where, schema, sig);\n if (m.op === 'insertEach') {\n const itemKeys = Object.values(m.values)\n .filter((v): v is { $item: string } => v !== null && typeof v === 'object' && '$item' in v)\n .map((v) => v.$item);\n sig[m.items.$context] = { type: 'json', note: `array of objects — one inserted row per element${itemKeys.length > 0 ? ` (keys: ${itemKeys.join(', ')})` : ''}` };\n }\n if (m.op === 'upsert') {\n sig[m.key] = { ...columnInfo(`${m.table}.${m.key}`, schema), note: 'upsert key — present updates that row, absent/empty inserts' };\n }\n }\n return sig;\n};\n\nexport const collectQueryContext = (dsl: Query, schema?: DatabaseSchema): ContextSignature => {\n const sig: ContextSignature = {};\n const walkQuery = (q: Query): void => {\n for (const source of q.from) {\n if (typeof source !== 'string') walkQuery(source.query);\n }\n if (q.filter !== undefined) walkFilter(q.filter, schema, sig);\n if (q.compute !== undefined) deepScan(q.compute, sig);\n if (q.aggregate !== undefined) deepScan(q.aggregate, sig);\n };\n walkQuery(dsl);\n return sig;\n};\n\nexport const mutationEffect = (def: MutationDefinition): MutationEffect[] => {\n const list = Array.isArray(def) ? def : [def];\n return list.flatMap((m) => {\n const base: MutationEffect = { op: m.op, table: m.table, columns: Object.keys(columnsOf(m)).sort() };\n // ON CONFLICT DO UPDATE also updates — declare it, so visibility and\n // grants treat the entry as the insert-plus-update it really is.\n const conflictSet = (m.op === 'insert' || m.op === 'insertEach') && m.onConflict?.set !== undefined ? m.onConflict.set : undefined;\n if (conflictSet === undefined) return [base];\n return [base, { op: 'update', table: m.table, columns: Object.keys(conflictSet).sort() }];\n });\n};\n\n// The keys a DESUGARED core mutation actually binds — the hard requirement\n// checked before execution (an upsert's absent key is legal: it selects the\n// insert branch, so requirement is computed after desugaring).\nexport const requiredContextKeys = (m: CoreMutation): string[] => {\n const keys = new Set<string>();\n const cols = m.op === 'insert' || m.op === 'insertEach' ? { ...m.values, ...(m.onConflict?.set ?? {}) } : m.op === 'update' ? m.set : {};\n for (const v of Object.values(cols)) {\n if (isContextRef(v)) keys.add(v.$context);\n else if (isLookupRef(v)) {\n const sub: ContextSignature = {};\n deepScan(v.$lookup.where, sub);\n for (const k of Object.keys(sub)) keys.add(k);\n }\n }\n if (m.op === 'insertEach') keys.add(m.items.$context);\n if (m.op === 'update' || m.op === 'delete') {\n const sub: ContextSignature = {};\n deepScan(m.where, sub);\n for (const k of Object.keys(sub)) keys.add(k);\n }\n return [...keys].sort();\n};\n\n// Authoring lint (run by the seed path): an update/delete whose WHERE binds no\n// `$context` is not caller-bounded — its only row limit is the scope policy.\n// Loud at boot, never at runtime.\n// An `optional` condition is a READ construct. In a WHERE it would mean \"this\n// bound disappears when the caller omits a key\" — which is precisely the\n// unkeyed update the lint below exists to refuse, only reachable by omission\n// rather than by authoring. Writes keep the rule they have always had: every\n// key is mandatory, and a missing one is a hard `missing_context` (see\n// mutations/engine.ts), never a wider statement.\nconst findOptional = (value: unknown): boolean => {\n if (Array.isArray(value)) return value.some(findOptional);\n if (value === null || typeof value !== 'object') return false;\n if ('optional' in value) return true;\n return Object.values(value).some(findOptional);\n};\n\nexport const lintMutation = (def: MutationDefinition): string[] => {\n const issues: string[] = [];\n const list = Array.isArray(def) ? def : [def];\n for (const m of list) {\n if (findOptional(m)) {\n issues.push(`${m.op} on \"${m.table}\" contains an optional condition — a write's bounds cannot depend on what the caller chose to send`);\n }\n if (m.op !== 'update' && m.op !== 'delete') continue;\n const sub: ContextSignature = {};\n deepScan(m.where, sub);\n if (Object.keys(sub).length === 0) {\n issues.push(`${m.op} on \"${m.table}\" has no $context-keyed WHERE — the write is not caller-bounded`);\n }\n }\n return issues;\n};\n","import { compileFilter, compileFieldOrValue, quoteLiteral } from '../adapters/postgres/operators.js';\nimport type { CompilationContext } from '../adapters/postgres/operators.js';\nimport type { ParamSlot, Row } from '../adapters/adapter.types.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { DatabaseSchema } from '../schemas/database.schema.js';\nimport type { ScopePolicy, ScopeValues, ScopeMatch, ScopeRule } from '../scope/scope.types.js';\nimport { isSetMatch } from '../scope/scope.types.js';\nimport { VexScopeError } from '../scope/apply.js';\nimport { VexError } from '../errors.js';\nimport { isFieldPathShape } from '../schemas/identifier.schema.js';\nimport { resolveParams } from '../utils/context.js';\nimport { requireScope } from '../engine/executor.js';\nimport { MutationDefinitionSchema } from './schema.js';\nimport type { Mutation, MutationDefinition, CoreMutation, ResolvedMutation, ResolvedOnConflict, MutationValue, LookupValue, ItemRef } from './schema.js';\nimport { collectMutationContext, requiredContextKeys } from './signature.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Mutation engine — the write pipeline. Validate (closed grammar, bounded\n// WHERE) → desugar → require context → scope (RLS + identity stamp) → check\n// columns → compile → execute. Every gate runs before a single statement\n// does. Reuses the read pipeline's own machinery for SQL and params\n// (compileFilter / compileFieldOrValue / resolveParams), so values bind as\n// SQL parameters exactly as they do for reads — never inlined.\n// ═══════════════════════════════════════════════════════════════\n\n// The database the writes run against — structural, so PGlite, a pg Pool\n// wrapper, or a test double all fit without vex importing any driver.\nexport type MutationTx = {\n query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[] }>;\n};\nexport type MutationClient = MutationTx & {\n transaction?: <T>(fn: (tx: MutationTx) => Promise<T>) => Promise<T>;\n};\n\n// ─── Value guards ──────────────────────────────────────────────\nconst isLookup = (v: unknown): v is LookupValue =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && '$lookup' in v;\nconst isItemRef = (v: unknown): v is ItemRef =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && '$item' in v;\n\nconst collectLookups = (m: ResolvedMutation): LookupValue['$lookup'][] => {\n const out: LookupValue['$lookup'][] = [];\n const scan = (cols: Record<string, unknown> | undefined): void => {\n for (const v of Object.values(cols ?? {})) if (isLookup(v)) out.push(v.$lookup);\n };\n if (m.op === 'insert' || m.op === 'insertEach') {\n scan(m.values);\n scan(m.onConflict?.set);\n }\n if (m.op === 'update') scan(m.set);\n return out;\n};\n\n// ─── Schema validation (anti-hallucination) ────────────────────\n// The engine already introspected for reads; reject an unknown table or a\n// written column not in it. A misauthored `contats` / `naem` fails closed,\n// before any SQL runs.\nconst findEntity = (table: string, schema: DatabaseSchema) =>\n schema.entities.find((e) => e.table === table || e.name === table);\n\n// An ON CONFLICT whose target names no unique constraint never arrests\n// anything — the insert would simply throw on the real constraint, or worse,\n// never conflict at all. The schema knows the unique column sets (PK +\n// introspected unique indexes), so a mismatched target is an AUTHORING error,\n// caught before any SQL runs, with the real options in the message.\nconst assertConflictTarget = (table: string, target: string[], entity: { fields: { name: string; primaryKey: boolean }[]; indexes: { fields: string[]; unique: boolean }[] }): void => {\n const uniqueSets = [\n entity.fields.filter((f) => f.primaryKey).map((f) => f.name),\n ...entity.indexes.filter((i) => i.unique).map((i) => [...i.fields]),\n ].filter((s) => s.length > 0);\n if (uniqueSets.length === 0) return; // the schema carries no uniqueness info — nothing to check against\n const want = new Set(target);\n const ok = uniqueSets.some((s) => s.length === want.size && s.every((c) => want.has(c)));\n if (!ok) {\n throw new VexError(\n 'invalid_dsl',\n `onConflict target (${target.join(', ')}) does not match a unique constraint on \"${table}\". Unique column sets: ${uniqueSets.map((s) => `(${s.join(', ')})`).join(' ')}.`,\n );\n }\n};\n\n// Every column a write's filter names — field positions, and value positions\n// shaped like a column (the same rule the read compiler uses to tell a column\n// from a literal). A field position is collected whatever it looks like, so a\n// string that is not a column is refused by the check below instead of being\n// compiled.\nconst filterColumns = (filter: Filter): string[] => {\n const out: string[] = [];\n const value = (v: unknown): void => {\n if (isFieldPathShape(v)) out.push(v);\n };\n const walk = (f: Filter): void => {\n if ('and' in f) return f.and.forEach(walk);\n if ('or' in f) return f.or.forEach(walk);\n if ('not' in f) return walk(f.not);\n if ('eq' in f) return f.eq.forEach(value);\n if ('neq' in f) return f.neq.forEach(value);\n if ('gt' in f) return f.gt.forEach(value);\n if ('gte' in f) return f.gte.forEach(value);\n if ('lt' in f) return f.lt.forEach(value);\n if ('lte' in f) return f.lte.forEach(value);\n if ('in' in f || 'notIn' in f) {\n const [field, target] = 'in' in f ? f.in : f.notIn;\n out.push(field);\n if (Array.isArray(target)) target.forEach(value);\n return;\n }\n if ('like' in f || 'ilike' in f) {\n const [field, pattern] = 'like' in f ? f.like : f.ilike;\n out.push(field);\n return value(pattern);\n }\n if ('isNull' in f) return void out.push(f.isNull);\n if ('isNotNull' in f) return void out.push(f.isNotNull);\n if ('semantic' in f) return void out.push(f.semantic.field);\n if ('fuzzy' in f) return void out.push(f.fuzzy.field);\n // `exists` and `optional` have no single-table meaning in a write; the\n // compiler refuses both loudly.\n };\n walk(filter);\n return out;\n};\n\n// A write's filter reads ONE table — the one it writes, or the one a `$lookup`\n// reads — and every column it names must be that table's. This is what makes\n// the compiler's identity mapping below safe: nothing reaches it that the\n// schema does not have.\nconst assertFilterColumns = (filter: Filter, table: string, schema: DatabaseSchema, where: string): void => {\n const entity = findEntity(table, schema);\n if (entity === undefined) throw new VexError('invalid_dsl', `Unknown table \"${table}\" in ${where}.`);\n for (const path of filterColumns(filter)) {\n const dot = path.indexOf('.');\n const owner = path.slice(0, dot);\n const column = path.slice(dot + 1);\n if (!isFieldPathShape(path) || owner !== table || !entity.fields.some((f) => f.name === column)) {\n throw new VexError('invalid_dsl', `\"${path}\" in ${where} is not a column of \"${table}\".`);\n }\n }\n};\n\nconst assertWritableColumns = (m: ResolvedMutation, schema: DatabaseSchema): void => {\n const entity = findEntity(m.table, schema);\n if (entity === undefined) throw new VexError('invalid_dsl', `Unknown table \"${m.table}\".`);\n if (m.op === 'update' || m.op === 'delete') assertFilterColumns(m.where, m.table, schema, 'the WHERE');\n const known = new Set(entity.fields.map((f) => f.name));\n const cols = m.op === 'insert' || m.op === 'insertEach' ? Object.keys(m.values) : m.op === 'update' ? Object.keys(m.set) : [];\n for (const c of cols) {\n if (!known.has(c)) throw new VexError('invalid_dsl', `Unknown column \"${m.table}.${c}\".`);\n }\n // A lookup reads a real table and column, or fails closed like any other\n // misauthored name.\n for (const l of collectLookups(m)) {\n const le = findEntity(l.from, schema);\n if (le === undefined) throw new VexError('invalid_dsl', `Unknown table \"${l.from}\" in $lookup.`);\n if (!le.fields.some((f) => f.name === l.field)) throw new VexError('invalid_dsl', `Unknown column \"${l.from}.${l.field}\" in $lookup.`);\n assertFilterColumns(l.where, l.from, schema, 'a $lookup');\n }\n if ((m.op === 'insert' || m.op === 'insertEach') && m.onConflict !== undefined) {\n for (const c of [...m.onConflict.target, ...Object.keys(m.onConflict.set ?? {})]) {\n if (!known.has(c)) throw new VexError('invalid_dsl', `Unknown column \"${m.table}.${c}\" in onConflict.`);\n }\n assertConflictTarget(m.table, m.onConflict.target, entity);\n if (m.onConflict.where !== undefined) assertFilterColumns(m.onConflict.where, m.table, schema, 'onConflict');\n }\n};\n\n// ─── Scope — applied by the ENGINE, never authored in the DSL ──\n// The same `ScopePolicy` reads use, its write-phase rules applied AFTER the\n// entry is parsed — so identity/tenant binding can't be touched by a stored\n// or injected mutation. `write` is the UMBRELLA phase (grants + rules for\n// insert/update/delete); the specific phases refine it — an op is allowed\n// iff its specific phase or `write` exists, and its rules are the umbrella's\n// plus the specific's. Mechanics: a `set` writes its column from scope on\n// each column-writing op (insert values, update set) — delete writes no\n// columns, so it is structurally exempt, not special-cased. A `match` pins\n// its column on insert and ANDs a filter into update/delete WHERE (the RLS\n// boundary). No applicable phase (or unlisted table) falls to `default`:\n// deny throws, allow leaves the mutation ungoverned.\n// A `$lookup` READS its table, so the read-phase rules of THAT table apply —\n// a mutation entry is never a read-scope bypass. Match rules AND into the\n// lookup's WHERE; a table the principal cannot read refuses the whole write.\nconst readMatchesFor = (table: string, policy: ScopePolicy): ScopeMatch[] => {\n const rule = policy.entities[table];\n if (rule === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `A $lookup reads \"${table}\", which is not allowed by scope policy (default: deny).`);\n return [];\n }\n if ('public' in rule) return [];\n if ('deny' in rule) throw new VexScopeError(table, `A $lookup reads \"${table}\", which is denied by scope policy.`);\n if (rule.read === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `A $lookup reads \"${table}\", which this principal has no read grant for.`);\n return [];\n }\n return rule.read;\n};\n\n// ONE SPELLING of the RLS boundary, for every place a match rule becomes a\n// WHERE — a `$lookup`'s filter, an ON CONFLICT DO UPDATE, an UPDATE and a\n// DELETE. Four copies of `{ eq: [...] }` is four places a new match shape has\n// to be remembered, and the one that was forgotten would be the hole.\nconst boundaryOf = (table: string, r: ScopeMatch): Filter =>\n isSetMatch(r) ? { in: [`${table}.${r.match}`, { $scope: r.in }] } : { eq: [`${table}.${r.match}`, { $scope: r.to }] };\n\nconst scopeLookups = <V extends MutationValue | ItemRef>(cols: Record<string, V>, policy: ScopePolicy): Record<string, V> => {\n const out: Record<string, V> = {};\n for (const [k, v] of Object.entries(cols)) {\n if (!isLookup(v)) {\n out[k] = v;\n continue;\n }\n let where: Filter = v.$lookup.where;\n for (const r of readMatchesFor(v.$lookup.from, policy)) {\n where = { and: [where, boundaryOf(v.$lookup.from, r)] };\n }\n // A scoped lookup is still a lookup — the transform is type-preserving.\n out[k] = { $lookup: { ...v.$lookup, where } } as V;\n }\n return out;\n};\n\n// The gate every write passes: throws when denied, returns `undefined` when\n// the table is ungoverned (public / default allow), else the entity rule and\n// the applicable phase rules (umbrella + specific).\ntype WriteGate = { rule: Extract<ScopePolicy['entities'][string], { read?: unknown }>; rules: readonly ScopeRule[] };\n\nconst writeGate = (table: string, op: 'insert' | 'update' | 'delete', policy: ScopePolicy): WriteGate | undefined => {\n const rule = policy.entities[table];\n if (rule === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `Writes to \"${table}\" are not allowed by scope policy (default: deny).`);\n return undefined;\n }\n if ('public' in rule) return undefined;\n if ('deny' in rule) throw new VexScopeError(table, `Writes to \"${table}\" are denied by scope policy.`);\n const specific = op === 'insert' ? rule.insert : op === 'update' ? rule.update : rule.delete;\n if (rule.write === undefined && specific === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `\"${op}\" on \"${table}\" is not allowed by scope policy (default: deny).`);\n return undefined;\n }\n return { rule, rules: [...(rule.write ?? []), ...(specific ?? [])] };\n};\n\n// The shared insert-shaped half: lookups scoped, insert rules applied to the\n// values, and the ON CONFLICT half gated and governed as the UPDATE it is.\n// `set` rules stamp identity into the DO UPDATE SET; `match` rules whose\n// column the conflict target already pins are inherently satisfied (the\n// inserted, scope-pinned value must equal the existing row's for a conflict\n// to arise at all); any other `match` becomes a WHERE on the DO UPDATE half —\n// the RLS boundary again.\nconst scopeInsertParts = <V extends MutationValue | ItemRef>(\n table: string,\n rawValues: Record<string, V>,\n rawConflict: ResolvedOnConflict | undefined,\n policy: ScopePolicy,\n): { values: Record<string, V | { $scope: string }>; conflict: ResolvedOnConflict | undefined } => {\n let values: Record<string, V | { $scope: string }> = scopeLookups(rawValues, policy);\n let conflict: ResolvedOnConflict | undefined =\n rawConflict === undefined || rawConflict.set === undefined ? rawConflict : { ...rawConflict, set: scopeLookups(rawConflict.set, policy) };\n\n const gate = writeGate(table, 'insert', policy);\n if (gate === undefined) return { values, conflict };\n\n for (const r of gate.rules) {\n // A WRITE'S SUBJECT IS ONE VALUE, AND THIS IS WHERE THAT IS ENFORCED.\n //\n // A `match` on an INSERT does not filter — there is no row yet — it WRITES\n // the column, which is what makes \"insert outside your boundary\"\n // unsayable rather than merely refused. A set has no single value to\n // write, so there is no honest thing to do with one here.\n //\n // Throwing rather than picking, ignoring, or compiling a guard: a reach\n // that covers several rows for READING must not silently become a reach\n // that lets a caller CHOOSE which of them to write as. A write's subject\n // comes from scope (one value) or through a `$lookup` whose own read\n // rules the engine applies — never from a set the caller indexes into.\n if ('match' in r && isSetMatch(r)) {\n throw new VexScopeError(\n table,\n `Scope rule for \"${table}\" is set-valued (\"${r.match}\" in \"${r.in}\") and cannot pin an INSERT — a write's subject must be a single value. Use a scalar match, or carry the subject in a $lookup whose own read rules bound it.`,\n );\n }\n // A `set` writes identity; a scalar `match` pins the RLS boundary — on an\n // INSERT both land in the values.\n values = { ...values, ['set' in r ? r.set : r.match]: { $scope: r.to } };\n }\n\n if (conflict?.set !== undefined) {\n if (gate.rule.write === undefined && gate.rule.update === undefined) {\n throw new VexScopeError(table, `onConflict on \"${table}\" declares DO UPDATE, but this principal has no update grant.`);\n }\n for (const r of [...(gate.rule.write ?? []), ...(gate.rule.update ?? [])]) {\n if ('set' in r) {\n conflict = { ...conflict, set: { ...(conflict.set ?? {}), [r.set]: { $scope: r.to } } };\n } else if (!conflict.target.includes(r.match)) {\n const boundary = boundaryOf(table, r);\n conflict = { ...conflict, where: conflict.where === undefined ? boundary : { and: [conflict.where, boundary] } };\n }\n }\n }\n\n return { values, conflict };\n};\n\nconst scopeMutation = (m: CoreMutation, policy: ScopePolicy): ResolvedMutation => {\n if (m.op === 'insert') {\n const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);\n return { op: 'insert', table: m.table, values, ...(conflict === undefined ? {} : { onConflict: conflict }) };\n }\n if (m.op === 'insertEach') {\n const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);\n return { op: 'insertEach', table: m.table, items: m.items, values, ...(conflict === undefined ? {} : { onConflict: conflict }) };\n }\n if (m.op === 'update') {\n let set: Record<string, MutationValue> = scopeLookups(m.set, policy);\n let where: Filter = m.where;\n const gate = writeGate(m.table, 'update', policy);\n if (gate !== undefined) {\n for (const r of gate.rules) {\n // The column is written from scope on insert AND update alike.\n if ('set' in r) set = { ...set, [r.set]: { $scope: r.to } };\n // RLS boundary on update — AND the scope filter into WHERE. A set is\n // safe HERE, unlike on insert: the rows already exist and this only\n // narrows which of them may be touched.\n else where = { and: [where, boundaryOf(m.table, r)] };\n }\n }\n return { op: 'update', table: m.table, set, where };\n }\n // delete — writes no columns, so `set` rules are structurally exempt.\n let where: Filter = m.where;\n const gate = writeGate(m.table, 'delete', policy);\n if (gate !== undefined) {\n for (const r of gate.rules) {\n if ('match' in r) where = { and: [where, boundaryOf(m.table, r)] };\n }\n }\n return { op: 'delete', table: m.table, where };\n};\n\n// ─── Compile (reuses the read pipeline's SQL + param machinery) ─\n// Only the INSERT/UPDATE/DELETE skeleton is assembled here; vex's\n// `compileFieldOrValue` / `compileFilter` fill the fragments and accumulate\n// the param slots, which `resolveParams` then binds. One catch: for a\n// comparison, vex quotes an unmapped `entity.field` as a STRING LITERAL (it\n// can't know it's a column). A single-table write has no resolver to build\n// the alias map, so we seed it ourselves — identity-mapping each `where`\n// field path to itself, which a single-table UPDATE/DELETE qualifies fine.\ntype Compiled = { sql: string; slots: ParamSlot[] };\n\nconst newCtx = (): CompilationContext => ({\n resolvedPaths: new Map(),\n aliasMap: new Map(),\n paramSlots: [],\n paramCounter: { value: 0 },\n});\n\n// Every column the filter names maps to itself — a single-table statement\n// qualifies `table.column` fine. Only ever called on a filter\n// `assertFilterColumns` has already held to the table's real columns.\nconst indexFilterFields = (filter: Filter, aliasMap: Map<string, string>): void => {\n for (const path of filterColumns(filter)) aliasMap.set(path, path);\n};\n\n// A value that may be a `$lookup` compiles to a scalar subquery INLINE, into\n// the parent's own parameter counter and slot list — the same no-renumbering\n// rule EXISTS follows on the read side.\nconst compileValue = (v: MutationValue, ctx: CompilationContext): string => {\n if (isLookup(v)) {\n indexFilterFields(v.$lookup.where, ctx.aliasMap);\n const where = compileFilter(v.$lookup.where, ctx);\n return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;\n }\n return compileFieldOrValue(v, ctx);\n};\n\n// A value written into a json/jsonb column: the slot its context value binds\n// through is marked, so the array or object goes over the wire as JSON text.\nconst compileColumnValue = (table: string, column: string, v: MutationValue, ctx: CompilationContext, schema: DatabaseSchema): string => {\n const before = ctx.paramSlots.length;\n const sql = compileValue(v, ctx);\n const json = findEntity(table, schema)?.fields.find((f) => f.name === column)?.normalizedType === 'json';\n if (json && typeof v === 'object' && v !== null && '$context' in v) {\n const slot = ctx.paramSlots[before];\n if (slot !== undefined) ctx.paramSlots[before] = { ...slot, encode: 'json' };\n }\n return sql;\n};\n\nconst compileConflict = (m: { table: string; onConflict?: ResolvedOnConflict }, ctx: CompilationContext, schema: DatabaseSchema): string => {\n const c = m.onConflict;\n if (c === undefined) return '';\n if (c.set === undefined) return ` ON CONFLICT (${c.target.join(', ')}) DO NOTHING`;\n const sets = Object.entries(c.set).map(([col, v]) => `${col} = ${compileColumnValue(m.table, col, v, ctx, schema)}`);\n let where = '';\n if (c.where !== undefined) {\n indexFilterFields(c.where, ctx.aliasMap);\n where = ` WHERE ${compileFilter(c.where, ctx)}`;\n }\n return ` ON CONFLICT (${c.target.join(', ')}) DO UPDATE SET ${sets.join(', ')}${where}`;\n};\n\n// jsonb `->>` yields text; the cast restores the column's type so the INSERT\n// binds like any other. `json` columns keep `->` (stays jsonb, no cast).\nconst ITEM_CAST: Record<string, string> = {\n number: 'numeric',\n boolean: 'boolean',\n date: 'date',\n timestamp: 'timestamptz',\n uuid: 'uuid',\n};\n\n\nconst compileMutation = (m: ResolvedMutation, schema: DatabaseSchema): Compiled => {\n const ctx = newCtx();\n if (m.op === 'insert') {\n const entries = Object.entries(m.values);\n const cols = entries.map(([c]) => c);\n const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));\n return { sql: `INSERT INTO ${m.table} (${cols.join(', ')}) VALUES (${vals.join(', ')})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots };\n }\n if (m.op === 'insertEach') {\n const entity = findEntity(m.table, schema);\n const entries = Object.entries(m.values);\n const cols = entries.map(([c]) => c);\n const exprs = entries.map(([col, v]) => {\n if (isItemRef(v)) {\n const nt = entity?.fields.find((f) => f.name === col)?.normalizedType ?? 'string';\n if (nt === 'json') return `(item.value->${quoteLiteral(v.$item)})`;\n const cast = ITEM_CAST[nt];\n const raw = `(item.value->>${quoteLiteral(v.$item)})`;\n return cast === undefined ? raw : `${raw}::${cast}`;\n }\n return compileValue(v, ctx);\n });\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: m.items.$context, kind: 'context', type: 'json' });\n const source = `jsonb_array_elements($${ctx.paramCounter.value}::jsonb) AS item`;\n return {\n sql: `INSERT INTO ${m.table} (${cols.join(', ')}) SELECT ${exprs.join(', ')} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,\n slots: ctx.paramSlots,\n };\n }\n if (m.op === 'update') {\n const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);\n indexFilterFields(m.where, ctx.aliasMap);\n const where = compileFilter(m.where, ctx);\n return { sql: `UPDATE ${m.table} SET ${sets.join(', ')} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };\n }\n indexFilterFields(m.where, ctx.aliasMap);\n const where = compileFilter(m.where, ctx);\n return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };\n};\n\n// ─── Desugar (sugar → core) ────────────────────────────────────\n// Rewrite each sugar op to a core insert/update/delete BEFORE context/scope/\n// validate/compile, so those stages only ever see the three primitives.\nconst SUGAR: { [K in Mutation['op']]?: (m: Extract<Mutation, { op: K }>, context: Record<string, unknown>) => CoreMutation } = {\n upsert: (m, context) => {\n const keyed = context[m.key] !== undefined && context[m.key] !== '';\n return keyed\n ? { op: 'update', table: m.table, set: m.columns, where: { eq: [`${m.table}.${m.key}`, { $context: m.key }] } }\n : { op: 'insert', table: m.table, values: { ...m.columns, ...m.insert } };\n },\n};\n\nconst desugarMutation = (m: Mutation, context: Record<string, unknown>): CoreMutation => {\n const rewrite = SUGAR[m.op] as ((m: Mutation, c: Record<string, unknown>) => CoreMutation) | undefined;\n return rewrite === undefined ? (m as CoreMutation) : rewrite(m, context);\n};\n\n// ─── Execute ───────────────────────────────────────────────────\nexport type MutationContext = {\n context: Record<string, unknown>; // dynamic values for `$context` refs (the caller's data)\n scope: ScopeValues; // server-injected values for `$scope` refs (identity / tenant)\n policy: ScopePolicy;\n schema: DatabaseSchema;\n};\n\n// One executed statement, named by what it did: the table, the op that\n// actually ran (post-desugar — an upsert reports the branch it took, an\n// insertEach reports 'insert' because that is what it is), and the rows the\n// database returned. This is the grain a write observer needs: a two-\n// statement mutation is two writes, each with its own rows.\nexport type WriteResult = { table: string; op: 'insert' | 'update' | 'delete'; rows: Row[] };\n\nexport const executeWrites = async (client: MutationClient, def: MutationDefinition, mctx: MutationContext): Promise<WriteResult[]> => {\n const parsed = MutationDefinitionSchema.parse(def);\n const entries = Array.isArray(parsed) ? parsed : [parsed];\n const compiled = entries.map((entry) => {\n const core = desugarMutation(entry, mctx.context);\n // A write never executes with holes: every `$context` the (desugared)\n // statement binds must be present. The error teaches the WHOLE contract.\n const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === undefined);\n if (missing.length > 0) {\n throw new VexError('missing_context', `Mutation is missing context: ${missing.join(', ')}.`, {\n expected: collectMutationContext(parsed, mctx.schema),\n });\n }\n const m = scopeMutation(core, mctx.policy);\n assertWritableColumns(m, mctx.schema);\n const statement = compileMutation(m, mctx.schema);\n // A `set` rule with no value would STAMP NULL — an insert owned by nobody,\n // written anyway. Every scope slot is filled or nothing runs.\n requireScope({ paramSlots: statement.slots }, mctx.scope);\n return { ...statement, table: m.table, op: (m.op === 'insertEach' ? 'insert' : m.op) as WriteResult['op'] };\n });\n\n const runAll = async (q: MutationTx): Promise<WriteResult[]> => {\n const results: WriteResult[] = [];\n for (const c of compiled) {\n const params = await resolveParams(c.slots, mctx.context, mctx.scope);\n // A `json` slot (insertEach items) is bound as a JSON string — drivers\n // would otherwise turn a JS array into a postgres ARRAY literal, which\n // `::jsonb` refuses. Anything but an array fails loudly here.\n const bound = params.map((value, i) => {\n if (c.slots[i]?.encode === 'json') return value !== null && typeof value === 'object' ? JSON.stringify(value) : value;\n if (c.slots[i]?.type !== 'json') return value;\n if (!Array.isArray(value)) {\n throw new VexError('invalid_request', `\"${c.slots[i]?.key ?? ''}\" must be an array of objects (one inserted row per element).`);\n }\n return JSON.stringify(value);\n });\n const res = await q.query(c.sql, bound as unknown[]);\n results.push({ table: c.table, op: c.op, rows: res.rows as Row[] });\n }\n return results;\n };\n\n // A batch runs atomically; a single write needs no transaction.\n if (compiled.length === 1) return runAll(client);\n if (client.transaction === undefined) {\n throw new VexError('execution_error', 'Batch mutations require a transactional client.');\n }\n return client.transaction((tx) => runAll(tx));\n};\n\n// The rows alone, statement order preserved — the shape every existing\n// caller wants when it does not care which statement returned what.\nexport const executeMutation = async (client: MutationClient, def: MutationDefinition, mctx: MutationContext): Promise<Row[]> =>\n (await executeWrites(client, def, mctx)).flatMap((w) => w.rows);\n","import { z } from 'zod';\nimport type { QueryEngine } from './types.js';\nimport type { ScopePolicy, ScopeValues } from './scope/scope.types.js';\nimport type { DatabaseSchema, EntitySchema } from './schemas/database.schema.js';\nimport { QueryRequestSchema } from './schemas/request.schema.js';\nimport { QuerySchema } from './schemas/query.schema.js';\nimport { isEntryFresh, isTouchDue, fireAndForget } from './cache/util.js';\nimport { computeSchemaFingerprint } from './cache/hash.js';\nimport { executeWrites } from './mutations/engine.js';\nimport type { MutationClient, WriteResult } from './mutations/engine.js';\nimport { collectMutationContext, collectQueryContext, mutationEffect } from './mutations/signature.js';\nimport type { ContextSignature, MutationEffect } from './mutations/signature.js';\nimport type { CacheEntry } from './cache/cache.types.js';\nimport type { QueryResponse } from './schemas/request.schema.js';\nimport type { Query } from './schemas/query.schema.js';\nimport { VexError } from './errors.js';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { canReadTable } from './scope/apply.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Types\n// ═══════════════════════════════════════════════════════════════\n\nexport type VexHandlerConfig = {\n engine: QueryEngine;\n entities?: string[];\n // Replay-only posture (production): requests needing generation fail\n // with 'locked'; fingerprint management (PATCH/DELETE) is refused too.\n // Mutation replay is unaffected — writes are ALWAYS replay-only.\n locked?: boolean;\n // Per-request read policy — overrides the engine default for reads on\n // this request (the read-side twin of `mutations.policy`). A host that\n // resolves a policy per principal passes the SAME policy here and in\n // `mutations.policy`, so reads and writes enforce one principal's phases.\n scopePolicy?: ScopePolicy;\n // Compiles the SAME principal's policy at a named reach, for entries that\n // declare one (`OkCacheEntry.reach`). Vex holds neither grants nor behaviors,\n // so it cannot build this itself — the host does, and returning `undefined`\n // refuses the read rather than serving it at the caller's own, wider reach.\n policyForReach?: (reach: string) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;\n // Enables replay of `kind: 'mutation'` cache entries. The client is\n // structural (PGlite, a pg wrapper, a test double); the policy is the\n // same ScopePolicy reads use, its `write` rules applied by the engine.\n mutations?: {\n client: MutationClient;\n policy: ScopePolicy;\n // The write observer. Fired once per successful mutation replay, AFTER\n // the commit — per-statement writes with the rows the database returned,\n // plus the scope the request could not forge. Vex is the choke point\n // every write passes through, so this is where a host learns about all\n // of them; what the host does with the news (mint facts, wake shells)\n // is not the engine's business. A listener that throws cannot unwrite\n // a committed write, so its error is contained, never the request's.\n onWrite?: (event: WriteEvent) => void;\n };\n // The execution observer — the read/write twin of `mutations.onWrite`, and\n // vex's whole telemetry surface. Fired once per `handleQuery`, AFTER the\n // outcome is known, with vex-vocabulary facts (fingerprint, reach, cache,\n // rows, status, timing) and the unforgeable scope. Vex knows nothing of spans\n // or OTLP; a host maps this record to whatever it emits. Absent → not even the\n // record is built (see `handleQuery`), so an unobserved endpoint pays nothing.\n // A listener that throws is contained, never the request's.\n onExecute?: (record: ExecuteRecord) => void;\n};\n\nexport type WriteEvent = { fingerprint: string; writes: WriteResult[]; scope: ScopeValues };\n\n// A CALLER THAT FOLLOWS THE ANSWER. In-process only: an HTTP request cannot\n// carry a callback, so a host that runs its own clients next to the handler\n// (moss's server shells) passes one here, and a reactive entry keeps\n// answering through it until `signal` aborts. See `refresh` on an entry.\nexport type VexLive = {\n signal: AbortSignal;\n onChange: (response: QueryResponse) => void;\n};\n\n// WHICH TABLES A WRITE CHANGED. The statements' own tables, plus — for a\n// delete — every table that references one of them, transitively: an\n// `ON DELETE CASCADE` or `SET NULL` changes rows vex never wrote. The\n// introspected schema carries the reference but not its rule, so a delete is\n// assumed to reach every referencing table. Over-telling costs a refetch;\n// under-telling leaves a screen stale.\nexport const tablesChangedBy = (writes: readonly WriteResult[], schema: DatabaseSchema | undefined): string[] => {\n const changed = new Set<string>();\n const referencing = (table: string): string[] =>\n (schema?.entities.find((entity) => entity.name === table)?.relations ?? [])\n .filter((relation) => relation.type !== 'belongsTo')\n .map((relation) => relation.entity);\n for (const write of writes) {\n if (write.rows.length === 0) continue;\n changed.add(write.table);\n if (write.op !== 'delete') continue;\n const pending = [write.table];\n for (let next = pending.pop(); next !== undefined; next = pending.pop()) {\n for (const table of referencing(next)) {\n if (changed.has(table)) continue;\n changed.add(table);\n pending.push(table);\n }\n }\n }\n return [...changed];\n};\n\n// What one execution DID, in vex's own vocabulary — the record `onExecute`\n// hands a host. Not a span: vex holds no telemetry model, so a host maps these\n// facts to whatever it emits. `startUnixNano`/`endUnixNano` are epoch nanos at\n// millisecond anchoring with a sub-millisecond monotonic span between them —\n// exact enough for durations, coarse in the low bits — copied through verbatim.\nexport type ExecuteRecord = {\n kind: 'query' | 'mutation';\n status: 'ok' | 'error' | 'refused';\n fingerprint?: string;\n reach?: string;\n // Reads: whether the entry was already compiled. Mutations always replay.\n cacheHit?: boolean;\n // Rows returned (reads) or written (mutations).\n rows?: number;\n startUnixNano: number;\n endUnixNano: number;\n // The scope the request could not forge, passed exactly as `onWrite` passes\n // it — for a host to read principal PRESENCE from, never a value into a span.\n scope: ScopeValues;\n};\n\n// The mutable half of the record, filled by `runQuery` as it goes and read once\n// by `handleQuery`. Built only when an observer is attached.\ntype ExecuteProbe = {\n kind: 'query' | 'mutation';\n fingerprint?: string;\n reach?: string;\n cacheHit?: boolean;\n rows?: number;\n};\n\nexport type DiscoveryFingerprint = {\n fingerprint: string;\n kind: 'query' | 'mutation';\n protected: boolean;\n schemaFresh: boolean;\n intent?: string;\n createdAt: number;\n lastUsedAt?: number;\n // The derived input contract: every `$context` key the stored def binds,\n // typed from the schema by its position. Computed, never authored.\n context?: ContextSignature;\n // Reads: the stored result shape. Mutations: what the write changes.\n shape?: unknown;\n effect?: MutationEffect[];\n};\n\nexport type DiscoveryResponse = {\n vex: string;\n description: string;\n entities: DiscoveryEntity[];\n // Governance summary + the endpoint's known queries — self-description\n // an agent (or a management UI) can read before generating anything.\n protection: 'all' | 'some' | 'none';\n locked: boolean;\n fingerprints: DiscoveryFingerprint[];\n query: {\n method: string;\n accepts: string;\n body: Record<string, DiscoveryField>;\n };\n dsl: object;\n};\n\ntype DiscoveryEntity = {\n name: string;\n fields: Array<{\n name: string;\n type: string;\n nullable: boolean;\n primaryKey: boolean;\n }>;\n relations: Array<{\n entity: string;\n type: string;\n via: string[];\n }>;\n rowCount?: number;\n};\n\ntype DiscoveryField = {\n type: string;\n required: boolean;\n description: string;\n};\n// (queryParams are gone — the request body carries all cache semantics.)\n\n// ═══════════════════════════════════════════════════════════════\n// Discovery\n// ═══════════════════════════════════════════════════════════════\n\nconst filterSchema = (schema: DatabaseSchema | undefined, entities?: string[]): EntitySchema[] => {\n if (schema === undefined) return [];\n if (entities === undefined || entities.length === 0) return schema.entities;\n return schema.entities.filter(e => entities.includes(e.name));\n};\n\n// ─── Visibility under a policy — discovery advertises only what the\n// policy can touch. These mirror the ENFORCEMENT semantics (applyScope /\n// scopeMutation) as pure predicates: a phase exists, is public, or falls\n// to the default. Enforcement still runs on every request; this only\n// keeps the catalog honest per principal. ───────────────────────\nconst canWriteTable = (policy: ScopePolicy, table: string, op: string): boolean => {\n const rule = policy.entities[table];\n if (rule === undefined) return policy.default === 'allow';\n if ('public' in rule) return true;\n if ('deny' in rule) return false;\n if (rule.write !== undefined || policy.default === 'allow') return true;\n // insertEach is an insert that happens N times — same phase.\n if (op === 'insert' || op === 'insertEach') return rule.insert !== undefined;\n if (op === 'update') return rule.update !== undefined;\n if (op === 'delete') return rule.delete !== undefined;\n // upsert desugars to insert or update per call — advertise if either exists\n if (op === 'upsert') return rule.insert !== undefined || rule.update !== undefined;\n return false;\n};\n\n// Every table a read touches — string sources, recursing into subquery\n// sources (`{ as, query }`).\nconst collectTables = (dsl: Query): string[] => {\n const out: string[] = [];\n const walk = (q: Query): void => {\n for (const src of q.from) {\n if (typeof src === 'string') out.push(src);\n else walk(src.query);\n }\n };\n walk(dsl);\n return out;\n};\n\nconst entryVisible = (policy: ScopePolicy, entry: CacheEntry): boolean => {\n if (entry.kind === 'ok') return collectTables(entry.dsl).every((t) => canReadTable(policy, t));\n if (entry.kind === 'mutation') return mutationEffect(entry.mutation).every((e) => canWriteTable(policy, e.table, e.op));\n return false;\n};\n\nconst listFingerprints = async (engine: QueryEngine, policy?: ScopePolicy): Promise<DiscoveryFingerprint[]> => {\n if (engine.cache.entries === undefined) return [];\n const schema = engine.getSchema();\n const current = schema !== undefined ? computeSchemaFingerprint(schema) : undefined;\n const rows = await engine.cache.entries();\n return rows\n .filter(({ key, entry }) => (entry.kind === 'ok' || entry.kind === 'mutation') && !key.startsWith('neg:'))\n .filter(({ entry }) => policy === undefined || entryVisible(policy, entry))\n .map(({ key, entry }) => ({\n fingerprint: key,\n kind: entry.kind === 'mutation' ? ('mutation' as const) : ('query' as const),\n protected: entry.protected === true,\n schemaFresh: isEntryFresh(entry, current),\n ...(entry.intent !== undefined ? { intent: entry.intent } : {}),\n createdAt: entry.createdAt,\n ...(entry.lastUsedAt !== undefined ? { lastUsedAt: entry.lastUsedAt } : {}),\n // The derived contract — what to pass, straight from the stored def.\n ...(entry.kind === 'ok'\n ? {\n context: collectQueryContext(entry.dsl, schema),\n ...(entry.shape !== undefined ? { shape: entry.shape } : {}),\n }\n : entry.kind === 'mutation'\n ? {\n context: collectMutationContext(entry.mutation, schema),\n effect: mutationEffect(entry.mutation),\n }\n : {}),\n }));\n};\n\nexport const handleDiscovery = async (config: VexHandlerConfig): Promise<DiscoveryResponse> => {\n const { engine, entities: entityFilter, scopePolicy } = config;\n // Under a scopePolicy, discovery is per-principal: entities and entries\n // the policy cannot touch are not advertised (what you can't reach\n // doesn't exist for you — deny by absence, in the catalog too).\n const filtered = filterSchema(engine.getSchema(), entityFilter).filter(\n (e) => scopePolicy === undefined || canReadTable(scopePolicy, e.name),\n );\n const fingerprints = await listFingerprints(engine, scopePolicy);\n const protectedCount = fingerprints.filter((f) => f.protected).length;\n\n return {\n protection: protectedCount === 0 ? 'none' : protectedCount === fingerprints.length ? 'all' : 'some',\n locked: config.locked === true,\n fingerprints,\n vex: '1.0',\n description: 'Query this resource using natural language or structured DSL',\n entities: filtered.map(e => ({\n name: e.name,\n fields: e.fields.map(f => ({\n name: f.name,\n type: f.normalizedType,\n nullable: f.nullable,\n primaryKey: f.primaryKey,\n })),\n relations: e.relations.map(r => ({\n entity: r.entity,\n type: r.type,\n via: r.localFields,\n })),\n rowCount: e.rowCount,\n })),\n query: {\n method: 'POST',\n accepts: 'application/json',\n body: {\n fingerprint: {\n type: 'string',\n required: false,\n description:\n 'Cache identity. Alone → replay a known query (no generation). With intent+shape → a named slot: ' +\n 'matching request hits, differing request regenerates and replaces (409 when protected). ' +\n 'Omitted → generate fresh; the minted fingerprint returns in meta.cache.fingerprint.',\n },\n intent: {\n type: 'string',\n required: false,\n description: 'Natural language description of what data you need',\n },\n shape: {\n type: 'any',\n required: false,\n description: 'Example of the response structure — use empty strings, zeros, booleans as type indicators. Required unless replaying by fingerprint.',\n },\n context: {\n type: 'Record<string, unknown>',\n required: false,\n description: 'Runtime parameters referenced in filters as { $context: \"key\" }',\n },\n },\n },\n dsl: z.toJSONSchema(QuerySchema, { target: 'draft-7', reused: 'ref' }),\n };\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Query execution\n// ═══════════════════════════════════════════════════════════════\n\nexport type QueryResult = {\n status: number;\n body: unknown;\n};\n\n// Rows an execution touched, for the observer's `rows` — an array's length, a\n// single object as one, nothing as zero. Never inspects the values.\nconst rowsOf = (result: unknown): number =>\n Array.isArray(result) ? result.length : result === null || result === undefined ? 0 : 1;\n\nexport const handleQuery = async (\n config: VexHandlerConfig,\n body: unknown,\n scope: ScopeValues,\n live?: VexLive,\n): Promise<QueryResult> => {\n // Unobserved: the fast path builds no probe, takes no timestamps, allocates\n // no record. An endpoint with no telemetry pays exactly nothing.\n if (config.onExecute === undefined) return runQuery(config, body, scope, undefined, live);\n\n const startUnixNano = Date.now() * 1e6;\n const t0 = elapsedClock();\n const probe: ExecuteProbe = { kind: 'query' };\n const result = await runQuery(config, body, scope, probe, live);\n const record: ExecuteRecord = {\n kind: probe.kind,\n // 200 succeeded; 403 is a policy/reach refusal (a normal outcome, not a\n // fault); everything else is an error.\n status: result.status === 200 ? 'ok' : result.status === 403 ? 'refused' : 'error',\n startUnixNano,\n endUnixNano: startUnixNano + (elapsedClock() - t0) * 1e6,\n scope,\n ...(probe.fingerprint !== undefined ? { fingerprint: probe.fingerprint } : {}),\n ...(probe.reach !== undefined ? { reach: probe.reach } : {}),\n ...(probe.cacheHit !== undefined ? { cacheHit: probe.cacheHit } : {}),\n ...(probe.rows !== undefined ? { rows: probe.rows } : {}),\n };\n try {\n config.onExecute(record);\n } catch (err) {\n console.error('[vex:onExecute]', err);\n }\n return result;\n};\n\n// Sub-millisecond monotonic reading in milliseconds. `performance` is present\n// on every runtime vex targets; the wall clock is the fallback that keeps the\n// duration honest (0) rather than throwing where it is not.\nconst elapsedClock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nconst runQuery = async (\n config: VexHandlerConfig,\n body: unknown,\n scope: ScopeValues,\n probe: ExecuteProbe | undefined,\n live: VexLive | undefined,\n): Promise<QueryResult> => {\n const { engine } = config;\n\n // Before the schema: a deep enough body overflows it (strata depth.ts).\n if (exceedsDepth(body)) return { status: 400, body: { error: 'invalid_request', message: depthRefusal() } };\n const parsed = QueryRequestSchema.safeParse(body);\n if (!parsed.success) {\n return {\n status: 400,\n body: {\n error: 'invalid_request',\n message: parsed.error.message,\n },\n };\n }\n\n const hasShape = parsed.data.shape !== undefined && parsed.data.shape !== null;\n if (!hasShape && parsed.data.fingerprint === undefined) {\n return {\n status: 400,\n body: {\n error: 'invalid_request',\n message: 'Pass a fingerprint (replay) or intent + shape (generate) — or both (named slot).',\n },\n };\n }\n\n // Recorded before anything can refuse, so a refusal span still carries the\n // fingerprint it refused. A read that mints one overwrites this from meta.\n if (probe !== undefined && parsed.data.fingerprint !== undefined) probe.fingerprint = parsed.data.fingerprint;\n\n try {\n // ONE wire shape: `{ fingerprint, context }`. The entry's kind decides\n // the pipeline — a mutation fingerprint replays the write path; anything\n // else is the read path (which owns misses, generation, and locked).\n let entryReach: string | undefined;\n if (parsed.data.fingerprint !== undefined) {\n const entry = await engine.cache.get(parsed.data.fingerprint);\n if (entry !== undefined && entry.kind === 'ok') entryReach = entry.reach;\n if (probe !== undefined && entryReach !== undefined) probe.reach = entryReach;\n if (entry !== undefined && entry.kind === 'mutation') {\n if (probe !== undefined) {\n probe.kind = 'mutation';\n if (entry.reach !== undefined) probe.reach = entry.reach;\n }\n if (config.mutations === undefined) {\n return {\n status: 500,\n body: { error: 'execution_error', message: 'This endpoint serves no mutations — handler has no mutation client configured.' },\n };\n }\n const schema = engine.getSchema();\n if (schema === undefined) {\n return { status: 500, body: { error: 'execution_error', message: 'Vex schema not introspected.' } };\n }\n // A WRITE MAY DEMAND A NARROWER REACH TOO, and the stakes are higher\n // than for a read: too wide here changes somebody else's row rather\n // than merely showing it.\n let writePolicy = config.mutations.policy;\n if (entry.reach !== undefined) {\n if (config.policyForReach === undefined) {\n return {\n status: 500,\n body: {\n error: 'execution_error',\n message: `Entry \"${parsed.data.fingerprint ?? ''}\" requires reach \"${entry.reach}\" and this handler has no policyForReach.`,\n },\n };\n }\n const narrowed = await config.policyForReach(entry.reach);\n if (narrowed === undefined) {\n return {\n status: 403,\n body: { error: 'scope_denied', message: `Reach \"${entry.reach}\" is not available to this principal.` },\n };\n }\n writePolicy = narrowed;\n }\n\n const writes = await executeWrites(config.mutations.client, entry.mutation, {\n context: parsed.data.context,\n scope,\n policy: writePolicy,\n schema,\n });\n const rows = writes.flatMap((w) => w.rows);\n // Every reactive read over these tables is now stale. Here, not in\n // any host's observer: this is the one door every vex write passes —\n // a request, a server function's `executeAs`, a reflex's effect — and\n // a read that heard about only some of them would be live only\n // sometimes, which is worse than a snapshot that says what it is.\n engine.invalidate(tablesChangedBy(writes, schema));\n // The commit happened; the observer hears about it now, and its\n // failure is its own — the response must tell the truth about a\n // write that already landed.\n if (config.mutations.onWrite !== undefined) {\n try {\n config.mutations.onWrite({ fingerprint: parsed.data.fingerprint, writes, scope });\n } catch (err) {\n console.error('[vex:onWrite]', err);\n }\n }\n // Lifetime = usage, for writes exactly as for reads: stamp\n // lastUsedAt (off the hot path, at most once per TOUCH_EVERY_MS) so\n // the GC sweep sees replays.\n const now = Date.now();\n if (isTouchDue(entry, now)) fireAndForget(engine.cache.set(parsed.data.fingerprint, { ...entry, lastUsedAt: now }));\n if (probe !== undefined) probe.rows = rows.length;\n // A single statement returns its one affected row; a batch returns\n // the array — the same `{ result }` envelope a query reply uses.\n return { status: 200, body: { result: rows.length === 1 ? rows[0] : rows } };\n }\n }\n\n // AN ENTRY MAY REQUIRE A NARROWER REACH THAN ITS CALLER HAS.\n //\n // \"The classes you have booked\" means the caller's own, and a principal\n // holding two roles reaches as wide as either grants. So the entry names\n // the profile it must be served at and the host recompiles the same grants\n // under it — narrowing rows, never widening verbs.\n //\n // Fail closed: a declared reach the host cannot compile refuses the read.\n // Serving it at the caller's own reach is the exact failure the field\n // exists to prevent, and it would be invisible.\n let readPolicy = config.scopePolicy;\n if (entryReach !== undefined) {\n if (config.policyForReach === undefined) {\n return {\n status: 500,\n body: {\n error: 'execution_error',\n message: `Entry \"${parsed.data.fingerprint ?? ''}\" requires reach \"${entryReach}\" and this handler has no policyForReach.`,\n },\n };\n }\n readPolicy = await config.policyForReach(entryReach);\n if (readPolicy === undefined) {\n return {\n status: 403,\n body: { error: 'scope_denied', message: `Reach \"${entryReach}\" is not available to this principal.` },\n };\n }\n }\n\n const response = await engine.execute(parsed.data, {\n scope,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n ...(readPolicy !== undefined ? { scopePolicy: readPolicy } : {}),\n ...(live !== undefined ? { signal: live.signal, onChange: live.onChange } : {}),\n });\n if (probe !== undefined) {\n probe.cacheHit = response.meta.cache.hit;\n // The identity actually served — the caller's replay key, or the one just\n // minted for a miss.\n if (response.meta.cache.fingerprint !== undefined) probe.fingerprint = response.meta.cache.fingerprint;\n probe.rows = rowsOf(response.result);\n }\n return { status: 200, body: response };\n } catch (err) {\n // The host did not say who is asking. That is the server's fault, not the\n // request's, and the names of the missing keys are the host's business —\n // they go to the log, not over the wire.\n if (err instanceof VexError && err.code === 'missing_scope') {\n console.error('[vex] refused a statement the host did not scope:', err.message);\n return { status: 500, body: { error: 'missing_scope', message: 'The server did not supply the scope this request needs.' } };\n }\n if (err instanceof VexError) {\n const status = err.code === 'fingerprint_protected' ? 409 : err.code === 'cache_miss' ? 404 : 400;\n return {\n status,\n body: {\n error: err.code,\n message: err.message,\n details: err.details,\n },\n };\n }\n console.error('[vex] unhandled error:', err);\n const errObj = err as Record<string, unknown> | null;\n const message = err instanceof Error\n ? err.message\n : (typeof errObj?.message === 'string' ? errObj.message : 'Unknown error');\n const code = typeof errObj?.code === 'string' ? errObj.code : 'execution_error';\n return {\n status: 500,\n body: { error: code, message },\n };\n }\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Fingerprint management — protect (PATCH) and evict (DELETE).\n// The ONLY writers of the `protected` bit besides the seed path.\n// ═══════════════════════════════════════════════════════════════\n\nexport const handleFingerprintPatch = async (\n config: VexHandlerConfig,\n fingerprint: string,\n patch: { protected?: boolean },\n): Promise<QueryResult> => {\n if (config.locked === true) {\n return { status: 403, body: { error: 'locked', message: 'This endpoint is locked — fingerprints cannot be managed here.' } };\n }\n const entry = await config.engine.cache.get(fingerprint);\n if (entry === undefined || (entry.kind !== 'ok' && entry.kind !== 'mutation')) {\n return { status: 404, body: { error: 'cache_miss', message: `Unknown fingerprint \"${fingerprint}\"` } };\n }\n if (typeof patch.protected !== 'boolean') {\n return { status: 400, body: { error: 'invalid_request', message: 'Body must be { protected: boolean }' } };\n }\n await config.engine.cache.set(fingerprint, { ...entry, protected: patch.protected });\n return { status: 200, body: { fingerprint, protected: patch.protected } };\n};\n\nexport const handleFingerprintDelete = async (\n config: VexHandlerConfig,\n fingerprint: string,\n): Promise<QueryResult> => {\n if (config.locked === true) {\n return { status: 403, body: { error: 'locked', message: 'This endpoint is locked — fingerprints cannot be managed here.' } };\n }\n const entry = await config.engine.cache.get(fingerprint);\n if (entry === undefined) {\n return { status: 404, body: { error: 'cache_miss', message: `Unknown fingerprint \"${fingerprint}\"` } };\n }\n if ((entry.kind === 'ok' || entry.kind === 'mutation') && entry.protected === true) {\n return { status: 409, body: { error: 'fingerprint_protected', message: `\"${fingerprint}\" is protected — unprotect it first.` } };\n }\n await config.engine.cache.delete(fingerprint);\n return { status: 200, body: { fingerprint, deleted: true } };\n};\n","import type { QueryEngine } from '../../types.js';\nimport type { ScopeValues } from '../../scope/scope.types.js';\nimport type { VexHandlerConfig } from '../../handler.js';\nimport { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../handler.js';\n\n// Minimal structural types — Express.Request/Response satisfy these\n// without requiring express as a runtime dependency.\n\nexport type VexExpressRequest = {\n method: string;\n body: unknown;\n query: Record<string, unknown>;\n};\n\nexport type VexExpressResponse = {\n json(body: unknown): unknown;\n status(code: number): VexExpressResponse;\n};\n\nexport type VexExpressConfig<TReq extends VexExpressRequest = VexExpressRequest> = {\n engine: QueryEngine;\n entities?: string[];\n // Replay-only posture: no generation, no fingerprint management.\n // (Writes are unaffected — mutation replay is always replay-only.)\n locked?: boolean;\n getScope?: (req: TReq) => Promise<ScopeValues> | ScopeValues;\n // Enables replay of `kind: 'mutation'` cache entries on this endpoint.\n mutations?: VexHandlerConfig['mutations'];\n};\n\n// Fingerprints may contain '/' (named slots like \"deals/table\"), so\n// management rides the request BODY, not the path.\nconst fingerprintFromBody = (body: unknown): string | undefined => {\n if (body === null || typeof body !== 'object') return undefined;\n const fp = (body as Record<string, unknown>)['fingerprint'];\n return typeof fp === 'string' && fp.length > 0 ? fp : undefined;\n};\n\nexport const vex = <TReq extends VexExpressRequest = VexExpressRequest>(\n config: VexExpressConfig<TReq>,\n): ((req: TReq, res: VexExpressResponse) => Promise<void>) => {\n const handlerConfig = {\n engine: config.engine,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n ...(config.mutations !== undefined ? { mutations: config.mutations } : {}),\n };\n\n return async (req: TReq, res: VexExpressResponse): Promise<void> => {\n if (req.method === 'GET') {\n res.json(await handleDiscovery(handlerConfig));\n return;\n }\n\n if (req.method === 'POST') {\n const scope = config.getScope ? await config.getScope(req) : {};\n const result = await handleQuery(handlerConfig, req.body, scope);\n res.status(result.status).json(result.body);\n return;\n }\n\n if (req.method === 'PATCH') {\n const fingerprint = fingerprintFromBody(req.body);\n if (fingerprint === undefined) {\n res.status(400).json({ error: 'invalid_request', message: 'Body must include { fingerprint }' });\n return;\n }\n const wanted = (req.body as Record<string, unknown>)['protected'];\n const result = await handleFingerprintPatch(handlerConfig, fingerprint, {\n ...(typeof wanted === 'boolean' ? { protected: wanted } : {}),\n });\n res.status(result.status).json(result.body);\n return;\n }\n\n if (req.method === 'DELETE') {\n const fingerprint = fingerprintFromBody(req.body);\n if (fingerprint === undefined) {\n res.status(400).json({ error: 'invalid_request', message: 'Body must include { fingerprint }' });\n return;\n }\n const result = await handleFingerprintDelete(handlerConfig, fingerprint);\n res.status(result.status).json(result.body);\n return;\n }\n\n res.status(405).json({\n error: 'method_not_allowed',\n message: 'GET discovery · POST query · PATCH/DELETE fingerprint management',\n });\n };\n};\n"]}
1
+ {"version":3,"sources":["../../../src/schemas/request.schema.ts","../../../src/schemas/value.schema.ts","../../../src/schemas/identifier.schema.ts","../../../src/schemas/filter.schema.ts","../../../src/schemas/compute.schema.ts","../../../src/schemas/aggregate.schema.ts","../../../src/schemas/query.schema.ts","../../../src/cache/util.ts","../../../src/utils/sha256.ts","../../../src/utils/canonical.ts","../../../src/cache/hash.ts","../../../src/errors.ts","../../../src/engine/optional.ts","../../../src/adapters/postgres/operators.ts","../../../src/scope/scope.types.ts","../../../src/scope/apply.ts","../../../src/utils/context.ts","../../../src/engine/executor.ts","../../../src/mutations/schema.ts","../../../src/mutations/signature.ts","../../../src/mutations/engine.ts","../../../src/handler.ts","../../../src/adapters/express/index.ts"],"names":["z","fieldPath","where","gate","exceedsDepth","depthRefusal"],"mappings":";;;;;;AAMO,IAAM,wCAAwB,IAAI,GAAA,CAAY,CAAC,QAAA,EAAU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AA,CAAK,OAAO,IAAI,CAAA;AAC1C,MAAA;AAAA,IACF;AAEA,IAAA,IAAI,GAAA,CAAI,WAAW,QAAA,EAAU;AAC3B,MAAA,MAAM,WAAA,GAAc,mBAAA,CAAoB,GAAA,CAAI,IAAI,CAAA;AAChD,MAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,QAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,iBAAA,EAAmB,OAAA,EAAS,mCAAA,EAAqC,CAAA;AAC/F,QAAA;AAAA,MACF;AACA,MAAA,MAAM,MAAA,GAAS,MAAM,uBAAA,CAAwB,aAAA,EAAe,WAAW,CAAA;AACvE,MAAA,GAAA,CAAI,OAAO,MAAA,CAAO,MAAM,CAAA,CAAE,IAAA,CAAK,OAAO,IAAI,CAAA;AAC1C,MAAA;AAAA,IACF;AAEA,IAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK;AAAA,MACnB,KAAA,EAAO,oBAAA;AAAA,MACP,OAAA,EAAS;AAAA,KACV,CAAA;AAAA,EACH,CAAA;AACF","file":"index.cjs","sourcesContent":["import { z } from 'zod';\nimport type { JsonValue } from '@niscorp/prism';\n\n// Context keys the engine consumes directly (for ORDER BY) instead of binding as\n// SQL parameters. A `{ $context: 'sortBy' }` ref is rejected at compile so these\n// can never reach the param path.\nexport const RESERVED_CONTEXT_KEYS = new Set<string>(['sortBy', 'sortDir']);\n\nexport const ContextSchema = z\n .object({\n sortBy: z.string().optional(),\n sortDir: z.enum(['asc', 'desc']).optional(),\n })\n .catchall(z.unknown())\n .describe(\n 'Caller runtime values. Keys referenced from the DSL via { $context: \"key\" } are bound as SQL parameters. `sortBy` (an entity.field, schema-validated) and `sortDir` (\"asc\"|\"desc\") are reserved keys that drive ORDER BY directly and are never bound as parameters.',\n );\n\nexport const QueryRequestSchema = z.object({\n // The ONE cache identity. Server-minted (`fp_…`) when absent — returned in\n // meta.cache.fingerprint, an immutable pin. Caller-chosen strings are\n // mutable named slots: the name is yours, its content follows your request.\n // Alone → replay-or-error. With intent/shape → hit when the stored request\n // matches, regenerate-and-replace when it differs (409 when protected).\n fingerprint: z.string().min(1).optional(),\n intent: z.string().optional(),\n shape: z.unknown().optional(),\n context: ContextSchema.default({}),\n});\n\nexport type QueryRequest = z.infer<typeof QueryRequestSchema>;\n\nexport type CacheMeta = {\n hit: boolean;\n // The entry's identity — minted (`fp_…`) or the caller's own name.\n fingerprint?: string;\n // True when this execution regenerated and REPLACED a named slot whose\n // stored request no longer matched.\n replaced?: boolean;\n // The intent stored with the cached query (on a hit) or the request's own intent\n // (on a miss) — descriptive only, so a caller can see what the query is for.\n intent?: string;\n};\n\nexport type TimingMeta = {\n agentMs?: number;\n executionMs: number;\n mappingMs?: number;\n transformMs?: number;\n};\n\nexport type ContextMeta = {\n // Mirrors ParamSlot['type'] (adapters/adapter.types.ts) — the contract a\n // caller reads is built from the slots the compiler bound, one for one.\n // Absent on a key that is optional and was not supplied: nothing bound it\n // this run, so there is no slot to read a type off.\n type?: 'string' | 'number' | 'boolean' | 'string[]' | 'number[]' | 'json';\n kind: 'context' | 'scope' | 'semantic';\n // True when the key controls an `optional` condition — supply it and the\n // condition applies, omit it and the condition is not in the query. DERIVED\n // from the stored DSL rather than declared beside it, for the same reason\n // mutation signatures are (see \"Derived context signatures\" in DOCS.md): a\n // contract somebody maintains by hand is a contract that eventually lies.\n optional?: true;\n // True when this run did not supply the key, so its condition was pruned.\n // The key is still published — that is the point of listing it — so a caller\n // can discover what a fingerprint accepts without failing a request first.\n absent?: true;\n};\n\nexport type QueryResponse = {\n // Whatever the Prism mapping produced over the full row set: an array (the\n // common case — a `$map` or identity over `$.result`), a single object (a\n // detail picking `$.result[0]`), or a scalar (an aggregate). Vex no longer\n // forces an array — the mapping owns the output shape.\n result: JsonValue;\n meta: {\n cache: CacheMeta;\n context: Record<string, ContextMeta>;\n timing?: TimingMeta;\n warnings?: string[];\n missingContext?: string[];\n };\n};\n\nexport type QueryErrorResponse = {\n error: string;\n message: string;\n details?: {\n suggestion?: string;\n options?: string[];\n };\n};\n\nexport type QueryErrorCode =\n | 'invalid_request'\n | 'invalid_dsl'\n | 'missing_scope'\n | 'scope_denied'\n | 'missing_context'\n | 'execution_error'\n | 'agent_failed'\n | 'cache_miss'\n | 'fingerprint_protected'\n | 'locked'\n | 'unsatisfiable';\n","import { z } from 'zod';\n\nexport const ContextRefSchema = z\n .object({\n $context: z.string().describe('Key to look up in the request context object'),\n })\n .strict()\n .describe('Reference to a caller-provided context value');\n\nexport const ScopeRefSchema = z\n .object({\n $scope: z.string().describe('Key to look up in the server-side scope values'),\n })\n .strict()\n .describe('Reference to a server-injected scope value (access control)');\n\nexport const FieldOrValueSchema = z\n .union([\n z.string().describe('A field path (entity.field format) or a literal string'),\n z.number().describe('A literal number'),\n z.boolean().describe('A literal boolean'),\n z.null().describe('A literal null'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A field path, literal value, or dynamic reference');\n\nexport type ContextRef = z.infer<typeof ContextRefSchema>;\nexport type ScopeRef = z.infer<typeof ScopeRefSchema>;\nexport type FieldOrValue = z.infer<typeof FieldOrValueSchema>;\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// THE NAMES A QUERY MAY SAY — and the one rule for telling them apart.\n//\n// Every string an author (a person, a seed, a model) puts in a NAME position\n// ends up in SQL text: a column reference, an output alias, a subquery alias.\n// Values never do — they bind as parameters or are quoted as literals. So a\n// name is the only place authored text meets the statement, and it is held to\n// a grammar that cannot carry anything but a name: letters, digits and\n// underscores, not starting with a digit.\n//\n// This is the parse-time half. The resolver checks the same predicates again,\n// because `engine.compile()` and `engine.test()` take a DSL that never went\n// through Zod, and the compiler refuses to emit a field position that did not\n// resolve against the introspected schema. Three layers, one grammar.\n//\n// `isFieldPathShape` is also what decides, in a value position, whether a\n// string is a column or a literal. It used to be \"contains a dot\", which made\n// every email address an unknown entity and every string with a dot a column\n// reference — so a literal like \"u1@x.com\" threw, and a string that merely\n// looked dotted went to SQL as a name. Now a column is exactly `ident.ident`,\n// and everything else is a literal.\n// ═══════════════════════════════════════════════════════════════\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*\\.[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport const isIdentifier = (value: string): boolean => IDENTIFIER.test(value);\n\nexport const isFieldPathShape = (value: unknown): value is string => typeof value === 'string' && FIELD_PATH.test(value);\n\nexport const IdentifierSchema = z\n .string()\n .regex(IDENTIFIER, 'A name is letters, digits and underscores, not starting with a digit');\n\nexport const FieldPathSchema = z\n .string()\n .regex(FIELD_PATH, 'A field path is entity.field — each part letters, digits and underscores, not starting with a digit');\n","import { z } from 'zod';\nimport { ContextRefSchema, ScopeRefSchema, FieldOrValueSchema } from './value.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\nimport type { ContextRef, ScopeRef, FieldOrValue } from './value.schema.js';\n\n// EXISTS — \"is there a row over there that points back at this one\".\n//\n// It is the same `{ from, filter }` a query already is, and deliberately no\n// more than that: no fields, no sort, no limit, nothing to select. EXISTS asks\n// whether a row is there, so anything that shapes output would be noise the\n// planner discards, and refusing it is what keeps this an operator rather than\n// an invitation to nest arbitrary SQL.\n//\n// The CORRELATION needs no new vocabulary. A dotted string on either side of a\n// comparison is already a field path, so pointing the inner table at the outer\n// one is an ordinary `eq` between two columns:\n//\n// { exists: { from: ['tasks'], filter: { eq: ['tasks.issue_id', 'issues.id'] } } }\n//\n// and `not` composes for NOT EXISTS. Whoever writes SQL writes this on the\n// first try, which is the entire design goal.\nexport type ExistsQuery = {\n from: string[];\n filter?: Filter;\n};\n\nexport type Filter =\n | { exists: ExistsQuery }\n | { eq: [FieldOrValue, FieldOrValue] }\n | { neq: [FieldOrValue, FieldOrValue] }\n | { gt: [FieldOrValue, FieldOrValue] }\n | { gte: [FieldOrValue, FieldOrValue] }\n | { lt: [FieldOrValue, FieldOrValue] }\n | { lte: [FieldOrValue, FieldOrValue] }\n | { in: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { notIn: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { like: [string, FieldOrValue] }\n | { ilike: [string, FieldOrValue] }\n | { isNull: string }\n | { isNotNull: string }\n | { and: Filter[] }\n | { or: Filter[] }\n | { not: Filter }\n | { semantic: { field: string; query: ContextRef | ScopeRef; minScore?: number } }\n | { fuzzy: { field: string; query: ContextRef | ScopeRef; maxDistance?: number } }\n | { optional: { key: string | string[]; then: Filter } };\n\nconst comparisonPair = z\n .tuple([FieldOrValueSchema, FieldOrValueSchema])\n .describe('[left, right] — both can be field paths, literals, or references');\n\nconst fieldString = FieldPathSchema.describe('Field path in entity.field format');\n\nconst collectionTarget = z\n .union([\n z.array(FieldOrValueSchema).min(1).describe('Array of literal values or references'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A set of values or a reference that resolves to an array');\n\nconst ExistsSchema: z.ZodType<ExistsQuery> = z.lazy(() =>\n z\n .object({\n from: z.array(z.string()).min(1).describe('Entities the subquery reads. Joined by foreign key like any other from.'),\n filter: FilterSchema.optional().describe('The correlation, and any extra condition. Reference the outer query by its own entity path: { eq: [\"<inner>.<fk>\", \"<outer>.id\"] }.'),\n })\n .strict(),\n);\n\nexport const FilterSchema: z.ZodType<Filter> = z.lazy(() =>\n z.union([\n z.object({ exists: ExistsSchema }).strict().describe('EXISTS: true when the subquery matches at least one row. Wrap in `not` for NOT EXISTS.'),\n z.object({ eq: comparisonPair }).strict().describe('Equals: tests equality between two values'),\n z.object({ neq: comparisonPair }).strict().describe('Not equals'),\n z.object({ gt: comparisonPair }).strict().describe('Greater than'),\n z.object({ gte: comparisonPair }).strict().describe('Greater than or equal'),\n z.object({ lt: comparisonPair }).strict().describe('Less than'),\n z.object({ lte: comparisonPair }).strict().describe('Less than or equal'),\n z.object({ in: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is in a set'),\n z.object({ notIn: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is not in a set'),\n z.object({ like: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-sensitive LIKE pattern match (use % as wildcard)'),\n z.object({ ilike: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-insensitive ILIKE pattern match (use % as wildcard)'),\n z.object({ isNull: fieldString }).strict().describe('Field value is NULL'),\n z.object({ isNotNull: fieldString }).strict().describe('Field value is NOT NULL'),\n z.object({ and: z.array(FilterSchema).min(2) }).strict().describe('Logical AND: all conditions must be true'),\n z.object({ or: z.array(FilterSchema).min(2) }).strict().describe('Logical OR: at least one condition must be true'),\n z.object({ not: FilterSchema }).strict().describe('Logical NOT: negates the condition'),\n z.object({\n semantic: z.object({\n field: FieldPathSchema.describe('Vector column field path (entity.field)'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to embed and compare'),\n minScore: z.number().min(0).max(1).optional().describe('Minimum cosine similarity (0–1)'),\n }).strict(),\n }).strict().describe('Semantic vector similarity search'),\n z.object({\n fuzzy: z.object({\n field: FieldPathSchema.describe('String field path'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to fuzzy-match'),\n maxDistance: z.number().int().nonnegative().optional().describe('Maximum Levenshtein edit distance'),\n }).strict(),\n }).strict().describe('Fuzzy string match'),\n z.object({\n optional: z.object({\n key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both — gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply.'),\n // BARE, never `.describe()`d. That call CLONES the schema, and zod\n // detects a recursive reference by instance identity — a clone is a\n // different instance, so `to-json-schema` stops seeing the cycle and\n // expands the filter union into itself until the stack goes. Every\n // other recursive slot here (`not`, `and`, `or`) uses it bare for the\n // same reason; the description belongs on the wrapper below.\n then: FilterSchema,\n }).strict(),\n }).strict().describe(\n 'A condition the caller turns on by supplying context keys. When any named key is absent the condition is REMOVED from the query before it compiles — it does not match everything, it is not there. Absent means missing, undefined or null; \"\" is a value and keeps the condition. Direction follows position: under `and` supplying the key NARROWS, under `or` it WIDENS. Either way an absent key reads exactly as if the condition had never been written, and scope is injected afterwards regardless. Reads only: a mutation may not contain one, and neither may the inside of an `exists` (its correlation must be unconditional).',\n ),\n ]),\n);\n","import { z } from 'zod';\nimport { FieldOrValueSchema } from './value.schema.js';\nimport { FilterSchema } from './filter.schema.js';\n\nconst CaseWhenSchema = z\n .object({\n condition: FilterSchema,\n then: FieldOrValueSchema.describe('Value when condition is true'),\n })\n .strict();\n\nexport const ComputeExpressionSchema = z\n .union([\n z.object({ add: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Addition: a + b'),\n z.object({ subtract: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Subtraction: a - b'),\n z.object({ multiply: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Multiplication: a * b'),\n z.object({ divide: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Division: a / b'),\n z.object({ concat: z.array(FieldOrValueSchema).min(2) }).strict().describe('String concatenation'),\n z.object({ coalesce: z.array(FieldOrValueSchema).min(2) }).strict().describe('Returns first non-null value'),\n z.object({\n case: z\n .object({\n when: z.array(CaseWhenSchema).min(1).describe('Condition/result pairs evaluated in order'),\n else: FieldOrValueSchema.describe('Default value when no condition matches'),\n })\n .strict(),\n }).strict().describe('CASE WHEN conditional expression'),\n ])\n .describe('Computed expression: arithmetic, string, or conditional');\n\nexport type ComputeExpression = z.infer<typeof ComputeExpressionSchema>;\n","import { z } from 'zod';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\n\nconst fieldPath = FieldPathSchema.describe('Field path in entity.field format');\n\n// SUM/AVG/MIN/MAX take either a field path or a compute expression — so the\n// argument can be a derived value (e.g. SUM(value * win_probability / 100)),\n// not just a column. A bare string stays valid (non-breaking).\nconst fieldOrExpr = z.union([fieldPath, ComputeExpressionSchema]).describe('A field path or a compute expression');\n\nexport const AggregateExpressionSchema = z\n .union([\n z.object({ count: z.union([FieldPathSchema, z.literal('*')]).describe('Field path or \"*\" for COUNT(*)') }).strict().describe('COUNT'),\n z.object({ countDistinct: FieldPathSchema.describe('Field path whose distinct non-null values are counted') }).strict().describe('COUNT(DISTINCT field)'),\n z.object({ sum: fieldOrExpr }).strict().describe('SUM'),\n z.object({ avg: fieldOrExpr }).strict().describe('AVG'),\n z.object({ min: fieldOrExpr }).strict().describe('MIN'),\n z.object({ max: fieldOrExpr }).strict().describe('MAX'),\n ])\n .describe('Aggregate function applied to a field or expression');\n\nexport type AggregateExpression = z.infer<typeof AggregateExpressionSchema>;\n","import { z } from 'zod';\nimport { FilterSchema } from './filter.schema.js';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { AggregateExpressionSchema } from './aggregate.schema.js';\nimport { FieldPathSchema, IdentifierSchema } from './identifier.schema.js';\nimport type { Filter } from './filter.schema.js';\nimport type { ComputeExpression } from './compute.schema.js';\nimport type { AggregateExpression } from './aggregate.schema.js';\n\nexport const SortEntrySchema = z\n .object({\n field: z.union([FieldPathSchema, IdentifierSchema]).describe('Field path (entity.field), computed field name, or aggregate alias'),\n dir: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })\n .strict()\n .describe('Sort specification');\n\nexport type SortEntry = z.infer<typeof SortEntrySchema>;\n\nexport type Source = string | { as: string; query: Query };\n\n// A selected field: a bare `entity.field` path, or an aliased one whose output\n// key is `as` (so joined columns that would collide — three `name`s — get\n// distinct keys without a compute hack).\nexport type FieldRef = string | { field: string; as: string };\n\nexport type Query = {\n from: Source[];\n // Optional: a query may select only aggregates (e.g. a bare `COUNT(*)`); the\n // schema requires at least one of `fields` / `aggregate`.\n fields?: FieldRef[];\n filter?: Filter;\n compute?: Record<string, ComputeExpression>;\n aggregate?: Record<string, AggregateExpression>;\n groupBy?: string[];\n sort?: SortEntry[];\n limit?: number;\n distinct?: boolean;\n};\n\nconst SubquerySourceSchema = z\n .object({\n as: IdentifierSchema.describe('Alias for subquery results — use as prefix in field paths'),\n query: z.lazy((): z.ZodType<Query> => QuerySchema).describe('A nested query'),\n })\n .strict()\n .describe('Subquery data source: a nested query read as a table under `as`, its columns referenced as `<as>.<field>` anywhere in the outer query. Joined by foreign key like an entity when one links them; otherwise every outer row is paired with every subquery row (a cross join), so a one-row subquery puts its values beside each outer row.');\n\nconst SourceSchema = z\n .union([\n z.string().describe('Entity name from the database schema'),\n SubquerySourceSchema,\n ])\n .describe('Data source: entity name or subquery');\n\nconst FieldRefSchema = z\n .union([\n FieldPathSchema.describe('A column in entity.field format'),\n z\n .object({\n field: FieldPathSchema.describe('A column in entity.field format'),\n as: IdentifierSchema.describe('Output key for this column'),\n })\n .strict()\n .describe('An aliased column: output under `as` instead of the column name'),\n ])\n .describe('A selected field — a bare `entity.field`, or `{ field, as }` to alias the output key');\n\nexport const QuerySchema: z.ZodType<Query> = z.lazy(() =>\n z\n .object({\n from: z.array(SourceSchema).min(1).describe('Data sources — entity names or subqueries. Every entity used anywhere in the query must be listed here. Listed entities are JOINED FOR YOU along their foreign keys — a nullable key as a LEFT JOIN, so a row whose key is empty is kept, with the joined columns null. Never restate a join as a filter comparing the two keys: that throws those rows away.'),\n fields: z.array(FieldRefSchema).optional().describe('Raw columns to select — each `entity.field`, or `{ field, as }` to alias the output key (no SELECT *). Optional: omit it for an aggregate-only query (e.g. a bare COUNT). Do not list compute or aggregate aliases here — those are added automatically.'),\n filter: FilterSchema.optional().describe('Filter conditions'),\n compute: z.record(IdentifierSchema, ComputeExpressionSchema).optional().describe('Computed fields — key is output alias, value is the expression'),\n aggregate: z.record(IdentifierSchema, AggregateExpressionSchema).optional().describe('Aggregate functions — key is output alias, value is the function'),\n groupBy: z.array(FieldPathSchema).optional().describe('Fields to group by for aggregation'),\n sort: z.array(SortEntrySchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Maximum rows to return'),\n distinct: z.boolean().optional().describe('Eliminate duplicate rows'),\n })\n .strict()\n .refine(\n (q) => (q.fields?.length ?? 0) > 0 || Object.keys(q.aggregate ?? {}).length > 0,\n { message: 'A query must select at least one of `fields` or `aggregate`.' },\n ),\n);\n\nexport { SubquerySourceSchema, SourceSchema };\n","import type { CacheEntry } from './cache.types.js';\n\n/**\n * Run a promise we don't want to await (background writes, hit bumps,\n * evictions). Failures are routed to `onError` or logged, never thrown\n * into the caller's path.\n */\nexport const fireAndForget = (p: Promise<unknown>, onError?: (err: unknown) => void): void => {\n void p.catch((err) => {\n if (onError) onError(err);\n else console.error('[vex:cache]', err);\n });\n};\n\n/**\n * How often a replay stamps `lastUsedAt`. The stamp rewrites the entry, and\n * a stamp on EVERY replay made every read a write too; once a minute keeps\n * what reads it — the sweep (idle limits of days), discovery's \"last used\" —\n * accurate to the minute, for a write per fingerprint per minute at most.\n */\nexport const TOUCH_EVERY_MS = 60_000;\n\n/** Whether a replay at `now` should stamp this entry's `lastUsedAt`. */\nexport const isTouchDue = (entry: CacheEntry, now: number): boolean =>\n entry.lastUsedAt === undefined || now - entry.lastUsedAt >= TOUCH_EVERY_MS;\n\n/**\n * Pure freshness check (no side effects). An entry is fresh when it is\n * not past its TTL and was written against the current schema. A\n * different fingerprint means the entry's DSL may reference columns that\n * have since changed. Callers decide whether to evict a non-fresh entry.\n */\nexport const isEntryFresh = (entry: CacheEntry, currentFingerprint?: string): boolean => {\n const expired = entry.expiresAt !== undefined && entry.expiresAt <= Date.now();\n const stale =\n entry.schemaFingerprint !== undefined &&\n currentFingerprint !== undefined &&\n entry.schemaFingerprint !== currentFingerprint;\n return !expired && !stale;\n};\n\n/**\n * Lifetime = usage. Evicts unprotected entries that have not been\n * replayed within `maxIdleMs` (falling back to createdAt for entries\n * never touched). Protected entries never sweep. Run it on whatever\n * cadence suits the app (startup, a timer, a cron) — it is hygiene,\n * not a correctness requirement: entries are single-digit KB.\n */\nexport const sweepCache = async (\n cache: {\n entries?: () => Promise<Array<{ key: string; entry: CacheEntry }>>;\n keys: () => Promise<string[]>;\n get: (key: string) => Promise<CacheEntry | undefined>;\n delete: (key: string) => Promise<void>;\n },\n options: { maxIdleMs: number },\n): Promise<number> => {\n const cutoff = Date.now() - options.maxIdleMs;\n const rows = cache.entries !== undefined\n ? await cache.entries()\n : await Promise.all((await cache.keys()).map(async (key) => ({ key, entry: await cache.get(key) })));\n\n let evicted = 0;\n for (const { key, entry } of rows) {\n if (entry === undefined) continue;\n if (entry.protected === true) continue;\n const lastAlive = entry.lastUsedAt ?? entry.createdAt;\n if (lastAlive < cutoff) {\n await cache.delete(key);\n evicted += 1;\n }\n }\n return evicted;\n};\n","// ═══════════════════════════════════════════════════════════════\n// SHA-256 of a text's UTF-8 bytes, as lowercase hex — the hash behind every\n// identity vex computes: request hashes, schema fingerprints, policy keys,\n// and the row and answer hashes a reactive read compares.\n//\n// Written out (FIPS 180-4) rather than taken from `node:crypto`, because vex\n// also runs in a page — PGlite in the browser, the client-degrade posture —\n// where that module does not exist and a bundler refuses the import.\n//\n// SYNCHRONOUS, which is why it is not WebCrypto's `subtle.digest` (prism and\n// strata hash there, where they already await): three exported functions\n// answer with a hash directly, and a follower's `deliver` compares two inside\n// a callback.\n//\n// The digests are node's, byte for byte, so nothing already stored under one\n// moves — a request hash, a schema fingerprint, a negative-cache key.\n// test/utils/sha256.test.ts holds the two to each other.\n// ═══════════════════════════════════════════════════════════════\n\nconst ROUND_CONSTANTS = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nconst BLOCK_BYTES = 64;\n\nconst rotateRight = (word: number, bits: number): number => (word >>> bits) | (word << (32 - bits));\n\nconst wordHex = (word: number): string => (word >>> 0).toString(16).padStart(8, '0');\n\nexport const sha256Hex = (text: string): string => {\n const bytes = new TextEncoder().encode(text);\n\n // Whole blocks: the text, one 0x80 byte, zeros, then the text's length in\n // bits as a 64-bit big-endian number.\n const padded = new Uint8Array(Math.ceil((bytes.length + 9) / BLOCK_BYTES) * BLOCK_BYTES);\n padded.set(bytes);\n padded[bytes.length] = 0x80;\n const view = new DataView(padded.buffer);\n const bitLength = bytes.length * 8;\n view.setUint32(padded.length - 8, Math.floor(bitLength / 0x1_0000_0000));\n view.setUint32(padded.length - 4, bitLength >>> 0);\n\n let h0 = 0x6a09e667;\n let h1 = 0xbb67ae85;\n let h2 = 0x3c6ef372;\n let h3 = 0xa54ff53a;\n let h4 = 0x510e527f;\n let h5 = 0x9b05688c;\n let h6 = 0x1f83d9ab;\n let h7 = 0x5be0cd19;\n\n // A typed array keeps every word to 32 bits on write; reading one back is\n // `?? 0` only because an index is never proven in range to the compiler.\n const schedule = new Uint32Array(64);\n\n for (let offset = 0; offset < padded.length; offset += BLOCK_BYTES) {\n for (let i = 0; i < 16; i += 1) schedule[i] = view.getUint32(offset + i * 4);\n for (let i = 16; i < 64; i += 1) {\n const w15 = schedule[i - 15] ?? 0;\n const w2 = schedule[i - 2] ?? 0;\n const s0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ (w15 >>> 3);\n const s1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ (w2 >>> 10);\n schedule[i] = (schedule[i - 16] ?? 0) + s0 + (schedule[i - 7] ?? 0) + s1;\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n let f = h5;\n let g = h6;\n let h = h7;\n for (let i = 0; i < 64; i += 1) {\n const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);\n const choice = (e & f) ^ (~e & g);\n const temp1 = (h + sum1 + choice + (ROUND_CONSTANTS[i] ?? 0) + (schedule[i] ?? 0)) | 0;\n const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n const temp2 = (sum0 + majority) | 0;\n h = g;\n g = f;\n f = e;\n e = (d + temp1) | 0;\n d = c;\n c = b;\n b = a;\n a = (temp1 + temp2) | 0;\n }\n\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n h5 = (h5 + f) | 0;\n h6 = (h6 + g) | 0;\n h7 = (h7 + h) | 0;\n }\n\n return wordHex(h0) + wordHex(h1) + wordHex(h2) + wordHex(h3) + wordHex(h4) + wordHex(h5) + wordHex(h6) + wordHex(h7);\n};\n","import { sha256Hex } from './sha256.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Canonical JSON — one text per value, whatever order its keys arrived in.\n//\n// Stored definitions round-trip through jsonb, which reorders object keys,\n// and a value compared by its first serialisation would call every such row\n// \"changed\". Keys are sorted recursively; arrays keep their order, because\n// their order is part of what they mean.\n// ═══════════════════════════════════════════════════════════════\n\nexport const canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (value !== null && typeof value === 'object' && !(value instanceof Date)) {\n const sorted: Record<string, unknown> = {};\n for (const [key, inner] of Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) sorted[key] = canonical(inner);\n return sorted;\n }\n return value;\n};\n\nexport const canonicalText = (value: unknown): string => JSON.stringify(canonical(value)) ?? 'undefined';\n\nexport const hashText = (text: string): string => sha256Hex(text);\n\nexport const canonicalHash = (value: unknown): string => hashText(canonicalText(value));\n","import type { DatabaseSchema } from '../schemas/database.schema.js';\nimport { hashText } from '../utils/canonical.js';\n\n// ───────────────────────────────────────────────────────────────\n// Shape normalization\n// ───────────────────────────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nexport const normalizeShape = (shape: unknown): unknown => {\n if (shape === null) return 'null';\n if (shape === undefined) return 'unknown';\n\n if (Array.isArray(shape)) {\n // Collapse to first-element shape (all elements assumed same shape)\n const first: unknown = shape[0];\n return first !== undefined ? [normalizeShape(first)] : [];\n }\n\n if (isRecord(shape)) {\n const sortedKeys = Object.keys(shape).sort();\n const normalized: Record<string, unknown> = {};\n for (const key of sortedKeys) {\n normalized[key] = normalizeShape(shape[key]);\n }\n return normalized;\n }\n\n if (typeof shape === 'string') return 'string';\n if (typeof shape === 'number') return 'number';\n if (typeof shape === 'boolean') return 'boolean';\n\n // functions, symbols, bigint, etc.\n return 'unknown';\n};\n\n// ───────────────────────────────────────────────────────────────\n// Fingerprints\n//\n// The ONE cache identity. Minted (`fp_…`) when a request arrives\n// without one — an immutable pin the caller can embed and replay.\n// Caller-chosen strings are mutable named slots. Shape hashes are no\n// longer keys anywhere; normalizeShape survives only inside\n// computeRequestHash (request-identity comparison).\n// ───────────────────────────────────────────────────────────────\n\nexport const mintFingerprint = (): string =>\n `fp_${hashText(`${Date.now()}:${Math.random()}`).slice(0, 16)}`;\n\n// ───────────────────────────────────────────────────────────────\n// Schema fingerprint\n//\n// A hash of the *structural* (DDL) shape of the database schema, stored\n// on each cache entry so a cached DSL — which references concrete\n// columns — can be invalidated when the schema changes out from under it\n// (a dropped/renamed column would otherwise compile to broken SQL on a\n// cache hit).\n//\n// Critically, this must be STABLE across restarts for an unchanged\n// schema, or warm-up entries would be wrongly judged stale and thrown\n// away on first read. So we project to a canonical, sorted form and\n// deliberately exclude volatile data: rowCount (a drifting pg estimate)\n// and cosmetic fields (description, defaultValue). A row-count change is\n// not a schema change — the cached SQL is still valid.\n// ───────────────────────────────────────────────────────────────\n\n// ───────────────────────────────────────────────────────────────\n// Request identity hash\n//\n// Unlike the shape hash (which keys the positive cache and intentionally\n// ignores intent), this identifies the *whole request*: intent + shape\n// class + the set of context keys. It keys things where intent matters —\n// the negative cache (whether a request is satisfiable depends on the\n// intent, not just the output shape) and single-flight de-duplication of\n// concurrent identical misses. Context *values* are excluded (runtime\n// data, potentially sensitive); only the key names participate.\n// ───────────────────────────────────────────────────────────────\n\nexport const computeRequestHash = (request: {\n intent?: string;\n shape?: unknown;\n context?: Record<string, unknown>;\n}): string => {\n const identity = {\n intent: request.intent ?? null,\n shape: normalizeShape(request.shape),\n contextKeys: Object.keys(request.context ?? {}).sort(),\n };\n return hashText(JSON.stringify(identity));\n};\n\n// Which POLICY a generation ran under — part of the single-flight and\n// negative-cache keys, because an agent that can see different tables is a\n// different agent. Key order is normalised so two structurally equal policies\n// built in different orders share a key. `none` is the engine with no policy.\nconst canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (isRecord(value)) {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) out[key] = canonical(value[key]);\n return out;\n }\n return value;\n};\n\nexport const computePolicyKey = (policy: unknown): string =>\n policy === undefined ? 'none' : hashText(JSON.stringify(canonical(policy))).slice(0, 16);\n\nexport const computeSchemaFingerprint = (schema: DatabaseSchema): string => {\n const byName = (a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name);\n\n const stable = {\n entities: [...schema.entities].sort(byName).map((e) => ({\n name: e.name,\n table: e.table,\n fields: [...e.fields].sort(byName).map((f) => ({\n name: f.name,\n type: f.type,\n normalizedType: f.normalizedType,\n nullable: f.nullable,\n primaryKey: f.primaryKey,\n ...(f.vectorDimensions !== undefined ? { vectorDimensions: f.vectorDimensions } : {}),\n })),\n // Column order within a relation is the key's own order, so it is\n // preserved; relations are sorted by target and columns. This shape\n // changed when keys became composite, so every entry cached before\n // revalidates once on the next boot — the drift eviction, by design.\n relations: [...e.relations]\n .sort((a, b) => `${a.entity}.${a.localFields.join(',')}`.localeCompare(`${b.entity}.${b.localFields.join(',')}`))\n .map((r) => ({ type: r.type, entity: r.entity, localFields: r.localFields, foreignFields: r.foreignFields })),\n // Index field order is significant (composite indexes) and stable\n // from introspection, so it is preserved; indexes are sorted by name.\n indexes: [...e.indexes].sort(byName).map((i) => ({\n name: i.name,\n fields: i.fields,\n unique: i.unique,\n type: i.type,\n })),\n })),\n };\n\n return hashText(JSON.stringify(stable));\n};\n","import type { QueryErrorCode } from './schemas/request.schema.js';\n\nexport class VexError extends Error {\n readonly code: QueryErrorCode;\n readonly details?: Record<string, unknown>;\n\n constructor(code: QueryErrorCode, message: string, details?: Record<string, unknown>) {\n super(message);\n this.name = 'VexError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { Query, Source } from '../schemas/query.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport { VexError } from '../errors.js';\n\n// ═══════════════════════════════════════════════════════════════\n// OPTIONAL CONDITIONS — resolved BEFORE the pipeline, never inside it.\n//\n// `{ optional: { key, then } }` is the one thing a caller can do to the SHAPE\n// of a query rather than to its values: supply the key and the condition is\n// there, omit it and the condition is gone. That is what makes one entry able\n// to answer \"everybody\", \"everybody matching a search\", and \"one person by id\"\n// — questions that were three entries because every `$context` ref was\n// mandatory (`executor.ts` findMissingContext).\n//\n// It is a DSL→DSL rewrite, run at the same point as `applySortContext`, and\n// that placement is the whole safety argument. The resolver, the compiler and\n// the scope walker never see this node. They cannot: by the time any of them\n// runs, every optional has already become either its condition or nothing at\n// all. So there is no third walker to teach, and — crucially — no way for an\n// entity to enter the query AFTER `discoverEntities` has decided what to scope.\n// All three throw if they ever meet one, so a future caller that reaches past\n// this pass gets an error rather than an unscoped read.\n//\n// WHAT IS DELIBERATELY NOT DONE HERE: the joins stay. `from` is untouched when\n// a condition drops, so which keys a caller sends can never change the row\n// multiplicity of the result — only how many rows survive the WHERE. A pruned\n// query is the same query with fewer conditions, never a differently-shaped one.\n// ═══════════════════════════════════════════════════════════════\n\n/** The keys one optional gate names — one, or all of several. A condition that\n * reads two context values depends on BOTH, and gating it on one would leave\n * the other conditionally required: supply `after` without `afterId` and the\n * clause survives with a hole in it, which surfaces as an empty result and\n * `missingContext`, not as a condition that quietly did not apply. On a paging\n * cursor an empty result reads as \"end of list\", which is the wrong answer\n * arrived at silently. */\nconst gateKeys = (key: string | string[]): string[] => (Array.isArray(key) ? key : [key]);\n\n/** Every optional key mentioned anywhere in a query, in declaration order. */\nexport const optionalKeysOf = (dsl: Query): string[] => {\n const keys: string[] = [];\n const walk = (filter: Filter): void => {\n if ('optional' in filter) {\n for (const key of gateKeys(filter.optional.key)) {\n if (!keys.includes(key)) keys.push(key);\n }\n walk(filter.optional.then);\n return;\n }\n if ('and' in filter) { for (const sub of filter.and) walk(sub); return; }\n if ('or' in filter) { for (const sub of filter.or) walk(sub); return; }\n if ('not' in filter) { walk(filter.not); return; }\n };\n if (dsl.filter !== undefined) walk(dsl.filter);\n for (const source of dsl.from) {\n if (typeof source !== 'string') keys.push(...optionalKeysOf(source.query).filter((k) => !keys.includes(k)));\n }\n return keys;\n};\n\n/** Which context keys the caller actually supplied.\n *\n * ABSENT MEANS MISSING, `undefined`, OR `null`. The empty string is a value —\n * searching for `''` is a real search — but null is not, for two reasons that\n * agree:\n *\n * · SQL. A bound null in a comparison can never match: `col = NULL` and\n * `col ILIKE NULL` are both NULL, never true. So \"send null\" could only ever\n * have meant \"I have nothing\", and vex already has `isNull`/`isNotNull` for\n * the question people actually mean by it. Nothing is lost.\n *\n * · The wire. JSON has no `undefined`, and a request prism assembles a fixed\n * object — it cannot conditionally omit a key. Without null counting as\n * absent, every caller with an empty search box would have to bind a\n * sentinel again, which is the exact thing this feature removes.\n *\n * This is deliberately WIDER than `findMissingContext`'s test, which stays on\n * `undefined` alone. A required key sent as null still binds null and matches\n * nothing; an optional key sent as null drops its condition. That reads like a\n * contradiction and is not: the author chose which keys are optional, and for\n * those they have already said absence means \"this does not apply\". A caller\n * gains nothing by it either — omitting the key does the same thing, and scope\n * is injected after this either way. */\nexport const presenceOf = (context: Record<string, unknown>): ReadonlySet<string> => {\n const present = new Set<string>();\n for (const [key, value] of Object.entries(context)) {\n if (value !== undefined && value !== null) present.add(key);\n }\n return present;\n};\n\n/** A stable name for \"which optionals were live on this run\" — used to report\n * how many distinct shapes one entry is being asked for. `all` is the compile\n * and test path, where there is no caller. */\nexport const presenceSignature = (dsl: Query, present: ReadonlySet<string> | 'all'): string => {\n const keys = optionalKeysOf(dsl);\n if (keys.length === 0) return '';\n if (present === 'all') return keys.join(',');\n return keys.filter((k) => present.has(k)).join(',');\n};\n\n// `undefined` means THIS NODE IS GONE — not \"false\", not \"true\". The caller of\n// each recursion decides what its absence means in context, which is the only\n// way `and` (identity true) and `or` (identity false) can both be correct.\nconst prune = (filter: Filter, present: ReadonlySet<string> | 'all', insideExists: boolean): Filter | undefined => {\n if ('optional' in filter) {\n // The correlation of an EXISTS is what ties it to the outer row. Let a\n // caller switch that off and `exists` stops asking \"is there one of these\n // for THIS row\" and starts asking \"is there one of these at all\" — a\n // different question that happens to be true far more often. Refused\n // outright rather than defended per-case.\n const keys = gateKeys(filter.optional.key);\n if (insideExists) {\n throw new VexError('invalid_dsl', `An optional condition (\"${keys.join(', ')}\") cannot live inside an exists — its correlation must hold on every run.`);\n }\n // ALL of them, not any: a condition needing two values and given one is a\n // condition that cannot run.\n if (present !== 'all' && !keys.every((key) => present.has(key))) return undefined;\n return prune(filter.optional.then, present, insideExists);\n }\n\n if ('exists' in filter) {\n const inner = filter.exists.filter === undefined ? undefined : prune(filter.exists.filter, present, true);\n return inner === undefined\n ? { exists: { from: filter.exists.from } }\n : { exists: { from: filter.exists.from, filter: inner } };\n }\n\n if ('and' in filter || 'or' in filter) {\n const isAnd = 'and' in filter;\n const kept = (isAnd ? filter.and : filter.or)\n .map((sub) => prune(sub, present, insideExists))\n .filter((sub): sub is Filter => sub !== undefined);\n // The schema requires two arms, so a pruned pair has to collapse rather\n // than emit a one-armed `and` that would fail its own validation.\n if (kept.length === 0) return undefined;\n if (kept.length === 1) return kept[0];\n return isAnd ? { and: kept } : { or: kept };\n }\n\n if ('not' in filter) {\n const inner = prune(filter.not, present, insideExists);\n // `not` of a condition that is not there is not \"true\" or \"false\" — it is\n // a question nobody asked. An author who wants \"exclude these when the key\n // is given\" writes `{ optional: { key, then: { not: … } } }`, which says it.\n if (inner === undefined) {\n throw new VexError('invalid_dsl', 'An optional condition cannot be the whole body of a `not` — wrap the `not` in the optional instead.');\n }\n return { not: inner };\n }\n\n return filter;\n};\n\n/** Resolve every optional condition against the keys a caller supplied.\n *\n * A query whose filter prunes away entirely comes back with NO filter, which\n * is the point: `people/list` with no lens, no search and no cursor is the\n * whole roll, and it says so by having nothing to say. Scope is injected\n * after this, so \"no filter\" still never means \"every tenant\". */\nexport const pruneOptional = (dsl: Query, present: ReadonlySet<string> | 'all'): Query => {\n const from: Source[] = dsl.from.map((source) =>\n typeof source === 'string' ? source : { as: source.as, query: pruneOptional(source.query, present) },\n );\n\n if (dsl.filter === undefined) return { ...dsl, from };\n\n const filter = prune(dsl.filter, present, false);\n if (filter === undefined) {\n const { filter: _dropped, ...rest } = dsl;\n return { ...rest, from };\n }\n return { ...dsl, from, filter };\n};\n\n/** Belt and braces for the three walkers that must never meet this node. */\nexport const refuseOptional = (where: string): never => {\n throw new VexError(\n 'invalid_dsl',\n `An optional condition reached ${where}. It should have been resolved by pruneOptional before the pipeline ran — reaching this point means a query was compiled without knowing which context keys the caller supplied.`,\n );\n};\n","import type { Filter } from '../../schemas/filter.schema.js';\nimport type { ComputeExpression } from '../../schemas/compute.schema.js';\nimport type { AggregateExpression } from '../../schemas/aggregate.schema.js';\nimport type { FieldOrValue } from '../../schemas/value.schema.js';\nimport type { ParamSlot } from '../adapter.types.js';\nimport type { FieldSchema } from '../../schemas/database.schema.js';\nimport type { ResolvedExists, ResolvedJoin } from '../../engine/engine.types.js';\nimport { RESERVED_CONTEXT_KEYS } from '../../schemas/request.schema.js';\nimport { refuseOptional } from '../../engine/optional.js';\nimport { VexError } from '../../errors.js';\nimport { isFieldPathShape } from '../../schemas/identifier.schema.js';\n\n// A `$context` ref naming a reserved sort key would otherwise become a bound\n// param; reject it at compile so reserved keys only ever drive ORDER BY.\nconst assertNotReserved = (key: string): void => {\n if (RESERVED_CONTEXT_KEYS.has(key))\n throw new VexError(\n 'invalid_dsl',\n `\"${key}\" is a reserved sort key (applied to ORDER BY); it cannot be bound as a parameter.`,\n );\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Types\n// ═══════════════════════════════════════════════════════════════\n\ntype PathResolution = { alias: string; column: string; schema: FieldSchema };\n\ntype CompilationContext = {\n resolvedPaths: Map<string, PathResolution>;\n aliasMap: Map<string, string>;\n paramSlots: ParamSlot[];\n paramCounter: { value: number };\n // Every `exists` in this query's filter, resolved. Keyed by the node, because\n // the compiler walks the raw filter tree and needs to find the resolution for\n // the node in front of it.\n existsMap?: Map<object, ResolvedExists>;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// FieldOrValue compilation\n// ═══════════════════════════════════════════════════════════════\n\n// ═══════════════════════════════════════════════════════════════\n// SQL TEXT — the only three ways authored input reaches a statement.\n//\n// · a COLUMN, which must have resolved against the introspected schema —\n// `columnOf` emits the resolver's alias.column or refuses. There is no\n// \"pass it through\" branch, anywhere: the fallback that used to exist here\n// pasted whatever string sat in a field position into the statement.\n// · a LITERAL, quoted by `quoteLiteral` exactly as Postgres's own\n// quote_literal() does, so it is safe whatever standard_conforming_strings\n// says.\n// · an OUTPUT NAME, quoted by `quoteIdent`.\n//\n// Values from a request never reach text at all: they bind as parameters.\n// ═══════════════════════════════════════════════════════════════\n\nexport const quoteLiteral = (s: string): string => {\n const doubled = s.replace(/'/g, \"''\");\n // With standard_conforming_strings off, a backslash in '…' is an escape and\n // `\\'` closes the string. The E'' form escapes backslashes explicitly, so the\n // literal means the same thing under either setting.\n return s.includes('\\\\') ? `E'${doubled.replace(/\\\\/g, '\\\\\\\\')}'` : `'${doubled}'`;\n};\n\nexport const quoteIdent = (name: string): string => `\"${name.replace(/\"/g, '\"\"')}\"`;\n\n// A number that is not finite has no SQL spelling — `NaN` would read as a name.\nexport const numberLiteral = (n: number): string => {\n if (!Number.isFinite(n)) throw new VexError('invalid_dsl', `${String(n)} is not a number SQL can hold.`);\n return String(n);\n};\n\nconst columnOf = (path: string, ctx: CompilationContext): string => {\n const mapped = ctx.aliasMap.get(path);\n if (mapped !== undefined) return mapped;\n const res = ctx.resolvedPaths.get(path);\n if (res !== undefined) return `${res.alias}.${res.column}`;\n throw new VexError('invalid_dsl', `\"${path}\" is not a column this query reads.`);\n};\n\nconst isFieldPath = isFieldPathShape;\n\nconst inferParamType = (path: string, resolvedPaths: Map<string, PathResolution>): ParamSlot['type'] => {\n const res = resolvedPaths.get(path);\n if (res === undefined) return 'string';\n const nt = res.schema.normalizedType;\n if (nt === 'number') return 'number';\n if (nt === 'boolean') return 'boolean';\n return 'string';\n};\n\nexport const compileFieldOrValue = (\n fov: FieldOrValue,\n ctx: CompilationContext,\n): string => {\n if (fov === null) return 'NULL';\n if (typeof fov === 'boolean') return fov ? 'TRUE' : 'FALSE';\n if (typeof fov === 'number') return numberLiteral(fov);\n\n if (typeof fov === 'string') {\n // Shaped like a column → it is one, and it resolved (or this refuses).\n // Anything else is a literal.\n return isFieldPath(fov) ? columnOf(fov, ctx) : quoteLiteral(fov);\n }\n\n // Object: $context or $scope — after eliminating primitives, only these remain\n if (typeof fov === 'object' && fov !== null && '$context' in fov) {\n const key = fov.$context;\n assertNotReserved(key);\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({\n key,\n kind: 'context',\n type: inferParamType(key, ctx.resolvedPaths),\n });\n return `$${ctx.paramCounter.value}`;\n }\n\n if (typeof fov === 'object' && fov !== null && '$scope' in fov) {\n const key = fov.$scope;\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({\n key,\n kind: 'scope',\n type: inferParamType(key, ctx.resolvedPaths),\n });\n return `$${ctx.paramCounter.value}`;\n }\n\n return 'NULL';\n};\n\n\n// ═══════════════════════════════════════════════════════════════\n// Join pairs\n//\n// The whole key, one equality per column pair, for the query's joins and\n// the joins inside an `exists` alike — two emitters, one rule, so a\n// composite key can never be half-joined in one of them.\n// ═══════════════════════════════════════════════════════════════\n\nexport const compileJoinPairs = (join: ResolvedJoin): string[] =>\n join.fromColumns.map((column, i) => {\n const to = join.toColumns[i];\n if (to === undefined) {\n throw new VexError(\n 'invalid_dsl',\n `The join from \"${join.fromAlias}\" to \"${join.toAlias}\" pairs \"${column}\" with no column.`,\n );\n }\n return `${join.fromAlias}.${column} = ${join.toAlias}.${to}`;\n });\n\n// ═══════════════════════════════════════════════════════════════\n// Filter compilation\n// ═══════════════════════════════════════════════════════════════\n\nconst compileComparisonFilter = (\n op: string,\n pair: [FieldOrValue, FieldOrValue],\n ctx: CompilationContext,\n): string => {\n const left = compileFieldOrValue(pair[0], ctx);\n const right = compileFieldOrValue(pair[1], ctx);\n return `${left} ${op} ${right}`;\n};\n\nexport const compileFilter = (\n filter: Filter,\n ctx: CompilationContext,\n): string => {\n // EXISTS compiles INLINE, into the parent's own parameter counter and slot\n // list. That is deliberate: the other subquery path compiles independently\n // and then tries to renumber, which is how two parameterised subqueries came\n // to collide on $1. There is nothing to renumber if nothing was numbered\n // separately.\n //\n // `SELECT 1` because EXISTS asks whether a row is there, not what is in it.\n if ('exists' in filter) {\n const resolved = ctx.existsMap?.get(filter.exists);\n if (resolved === undefined) throw new VexError('invalid_dsl', 'An \"exists\" filter was not resolved. It must appear in a query\\'s own filter.');\n\n const inner: CompilationContext = {\n ...ctx,\n resolvedPaths: resolved.filter?.resolvedPaths ?? ctx.resolvedPaths,\n // The inner map LAYERS OVER the outer one, so an inner path resolves to\n // the inner alias and an outer path — the correlation — still resolves.\n aliasMap: new Map([...ctx.aliasMap, ...resolved.aliasMap]),\n };\n\n const parts: string[] = ['SELECT 1'];\n const first = resolved.sources[0];\n if (first?.table !== undefined) parts.push(`FROM ${first.table} AS ${first.alias}`);\n for (const join of resolved.joins) {\n const source = resolved.sources.find((s) => s.alias === join.toAlias);\n if (source?.table === undefined) continue;\n const keyword = join.kind === 'left' ? 'LEFT JOIN' : 'JOIN';\n const conditions = [\n ...compileJoinPairs(join),\n ...(join.on ?? []).map((extra) => compileFilter(extra.original, inner)),\n ];\n parts.push(`${keyword} ${source.table} AS ${join.toAlias} ON ${conditions.join(' AND ')}`);\n }\n if (resolved.filter !== undefined) parts.push(`WHERE ${compileFilter(resolved.filter.original, inner)}`);\n\n return `EXISTS (${parts.join(' ')})`;\n }\n\n if ('eq' in filter) return compileComparisonFilter('=', filter.eq, ctx);\n if ('neq' in filter) return compileComparisonFilter('<>', filter.neq, ctx);\n if ('gt' in filter) return compileComparisonFilter('>', filter.gt, ctx);\n if ('gte' in filter) return compileComparisonFilter('>=', filter.gte, ctx);\n if ('lt' in filter) return compileComparisonFilter('<', filter.lt, ctx);\n if ('lte' in filter) return compileComparisonFilter('<=', filter.lte, ctx);\n\n if ('in' in filter) {\n const col = columnOf(filter.in[0], ctx);\n const target = filter.in[1];\n\n if (Array.isArray(target)) {\n const values = target.map((v) => compileFieldOrValue(v, ctx));\n return `${col} IN (${values.join(', ')})`;\n }\n\n // ContextRef or ScopeRef → array parameter\n if ('$context' in target) {\n assertNotReserved(target.$context);\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$context, kind: 'context', type: 'string[]' });\n return `${col} = ANY($${ctx.paramCounter.value})`;\n }\n if ('$scope' in target) {\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$scope, kind: 'scope', type: 'string[]' });\n return `${col} = ANY($${ctx.paramCounter.value})`;\n }\n\n return `${col} IN ()`;\n }\n\n if ('notIn' in filter) {\n const col = columnOf(filter.notIn[0], ctx);\n const target = filter.notIn[1];\n\n if (Array.isArray(target)) {\n const values = target.map((v) => compileFieldOrValue(v, ctx));\n return `${col} NOT IN (${values.join(', ')})`;\n }\n\n if ('$context' in target) {\n assertNotReserved(target.$context);\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$context, kind: 'context', type: 'string[]' });\n return `${col} <> ALL($${ctx.paramCounter.value})`;\n }\n if ('$scope' in target) {\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: target.$scope, kind: 'scope', type: 'string[]' });\n return `${col} <> ALL($${ctx.paramCounter.value})`;\n }\n\n return `${col} NOT IN ()`;\n }\n\n if ('like' in filter) {\n const col = columnOf(filter.like[0], ctx);\n const pattern = compileFieldOrValue(filter.like[1], ctx);\n return `${col} LIKE ${pattern}`;\n }\n\n if ('ilike' in filter) {\n const col = columnOf(filter.ilike[0], ctx);\n const pattern = compileFieldOrValue(filter.ilike[1], ctx);\n return `${col} ILIKE ${pattern}`;\n }\n\n if ('isNull' in filter) {\n return `${columnOf(filter.isNull, ctx)} IS NULL`;\n }\n\n if ('isNotNull' in filter) {\n return `${columnOf(filter.isNotNull, ctx)} IS NOT NULL`;\n }\n\n if ('and' in filter) {\n const parts = filter.and.map((sub) => compileFilter(sub, ctx));\n return `(${parts.join(' AND ')})`;\n }\n\n if ('or' in filter) {\n const parts = filter.or.map((sub) => compileFilter(sub, ctx));\n return `(${parts.join(' OR ')})`;\n }\n\n if ('not' in filter) {\n const inner = compileFilter(filter.not, ctx);\n return `NOT (${inner})`;\n }\n\n if ('semantic' in filter) {\n // Semantic filter: cosine distance using pgvector <=> operator\n const fieldPath = filter.semantic.field;\n const col = columnOf(fieldPath, ctx);\n\n const queryRef = filter.semantic.query;\n const key = '$context' in queryRef ? queryRef.$context : queryRef.$scope;\n if ('$context' in queryRef) assertNotReserved(queryRef.$context);\n\n // Look up vector dimensions from resolved paths\n const res = ctx.resolvedPaths.get(fieldPath);\n const dimensions = res?.schema.vectorDimensions;\n\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({\n key,\n kind: 'semantic',\n type: 'string',\n dimensions,\n });\n\n const paramRef = `$${ctx.paramCounter.value}`;\n const minScore = numberLiteral(filter.semantic.minScore ?? 0);\n return `1 - (${col} <=> ${paramRef}) >= ${minScore}`;\n }\n\n if ('fuzzy' in filter) {\n const col = columnOf(filter.fuzzy.field, ctx);\n\n const queryRef = filter.fuzzy.query;\n const key = '$context' in queryRef ? queryRef.$context : queryRef.$scope;\n const kind = '$context' in queryRef ? 'context' as const : 'scope' as const;\n if ('$context' in queryRef) assertNotReserved(queryRef.$context);\n\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key, kind, type: 'string' });\n\n const paramRef = `$${ctx.paramCounter.value}`;\n const maxDistance = filter.fuzzy.maxDistance;\n\n if (maxDistance !== undefined) {\n return `levenshtein(${col}, ${paramRef}) <= ${numberLiteral(maxDistance)}`;\n }\n // pg_trgm similarity\n return `${col} % ${paramRef}`;\n }\n\n // Resolved away before the pipeline — see engine/optional.ts. Named\n // explicitly because the fallthrough below is `TRUE`: an unrecognised node\n // would quietly compile to \"match everything\", which for an optional\n // condition is the right answer reached by the wrong route, and for anything\n // else is a filter that silently stopped filtering.\n if ('optional' in filter) refuseOptional('SQL compilation');\n\n // Should not reach here if the filter was validated\n return 'TRUE';\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Compute expression compilation\n// ═══════════════════════════════════════════════════════════════\n\nexport const compileCompute = (\n expr: ComputeExpression,\n ctx: CompilationContext,\n): string => {\n if ('add' in expr) {\n const a = compileFieldOrValue(expr.add[0], ctx);\n const b = compileFieldOrValue(expr.add[1], ctx);\n return `(${a} + ${b})`;\n }\n\n if ('subtract' in expr) {\n const a = compileFieldOrValue(expr.subtract[0], ctx);\n const b = compileFieldOrValue(expr.subtract[1], ctx);\n return `(${a} - ${b})`;\n }\n\n if ('multiply' in expr) {\n const a = compileFieldOrValue(expr.multiply[0], ctx);\n const b = compileFieldOrValue(expr.multiply[1], ctx);\n return `(${a} * ${b})`;\n }\n\n if ('divide' in expr) {\n const a = compileFieldOrValue(expr.divide[0], ctx);\n const b = compileFieldOrValue(expr.divide[1], ctx);\n return `(${a} / ${b})`;\n }\n\n if ('concat' in expr) {\n const parts = expr.concat.map((v) => compileFieldOrValue(v, ctx));\n return `(${parts.join(' || ')})`;\n }\n\n if ('coalesce' in expr) {\n const parts = expr.coalesce.map((v) => compileFieldOrValue(v, ctx));\n return `COALESCE(${parts.join(', ')})`;\n }\n\n if ('case' in expr) {\n const whenClauses = expr.case.when.map((w) => {\n const cond = compileFilter(w.condition, ctx);\n const val = compileFieldOrValue(w.then, ctx);\n return `WHEN ${cond} THEN ${val}`;\n });\n const elseVal = compileFieldOrValue(expr.case.else, ctx);\n return `CASE ${whenClauses.join(' ')} ELSE ${elseVal} END`;\n }\n\n return 'NULL';\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Aggregate expression compilation\n// ═══════════════════════════════════════════════════════════════\n\n// SUM/AVG/MIN/MAX take a field path (mapped to its qualified column) OR a\n// compute expression (compiled to SQL). count stays a plain field/`*`.\nconst aggArg = (arg: string | ComputeExpression, ctx: CompilationContext): string =>\n typeof arg === 'string' ? columnOf(arg, ctx) : compileCompute(arg, ctx);\n\nexport const compileAggregate = (\n expr: AggregateExpression,\n ctx: CompilationContext,\n): string => {\n if ('count' in expr) {\n if (expr.count === '*') return 'COUNT(*)';\n return `COUNT(${columnOf(expr.count, ctx)})`;\n }\n if ('countDistinct' in expr) return `COUNT(DISTINCT ${columnOf(expr.countDistinct, ctx)})`;\n if ('sum' in expr) return `SUM(${aggArg(expr.sum, ctx)})`;\n if ('avg' in expr) return `AVG(${aggArg(expr.avg, ctx)})`;\n if ('min' in expr) return `MIN(${aggArg(expr.min, ctx)})`;\n if ('max' in expr) return `MAX(${aggArg(expr.max, ctx)})`;\n return 'NULL';\n};\n\nexport type { CompilationContext };\n","// Scope is server-side, LLM-invisible access control, applied to the resolved\n// query/mutation AFTER it is authored — so a generated or injected DSL can never\n// reference, dodge, or forge it. There are two roles, named for the SQL they\n// produce:\n// • match — RLS: the row's column must equal a scope value (a WHERE filter,\n// and on INSERT the column is pinned to that value so you can't write\n// outside your boundary).\n// • set — identity: the engine writes the column from a scope value on\n// EVERY column-writing op — INSERT values and UPDATE set alike (`write`\n// means every write; delete writes no columns, so it is structurally\n// exempt). It doesn't touch reads.\n\n// Caller runtime values, injected at execute via options.scope, keyed by name\n// (e.g. { userId, accountId }). A rule's `to` names one of these keys.\nexport type ScopeValues = Record<string, unknown>;\n\n// RLS filter: `<entity>.<match>` must equal the `to` scope value — or, in the\n// set-valued form, must be ONE OF the `in` scope value.\n//\n// THE SET IS FOR READS. A reach that covers several rows is a real concept —\n// \"mine, and the people I am answerable for\" — and the scalar form cannot say\n// it. What the set deliberately CANNOT do is pin a write: a `match` on an\n// INSERT writes the column (engine.ts), and a set has no single value to\n// write. That is not a gap to fill later; it is the property that keeps a\n// write's subject unforgeable. The mutation engine throws rather than\n// guessing, so a set-valued write rule is unauthorable rather than merely\n// discouraged.\n//\n// Fail-closed comes from SQL rather than from a guard here: the set compiles\n// to `col = ANY($n)`, an absent scope value binds NULL (`= ANY(NULL)` is NULL,\n// so the row drops) and an empty one binds `{}` (false). Neither can be\n// forgotten, because neither was written.\nexport type ScopeMatchOne = { match: string; to: string };\nexport type ScopeMatchAny = { match: string; in: string };\nexport type ScopeMatch = ScopeMatchOne | ScopeMatchAny;\n\n/** The set-valued form, told apart by its key — `to` and `in` never coexist. */\nexport const isSetMatch = (m: ScopeMatch): m is ScopeMatchAny => 'in' in m;\n\n// Identity write: `<set>` is filled from the `to` scope value on every\n// column-writing mutation (INSERT and UPDATE).\nexport type ScopeSet = { set: string; to: string };\n\nexport type ScopeRule = ScopeMatch | ScopeSet;\n\nexport type ScopeEntityRule =\n | { public: true } // fully open (read + write, no rules)\n | { deny: true } // fully closed\n | {\n // Reads (SELECT): each match becomes a WHERE filter. Match only — there is\n // nothing to stamp on a read.\n read?: ScopeMatch[];\n // Writes. `write` is the UMBRELLA: its presence grants insert, update\n // and delete, and its rules apply to every one of them. The specific\n // phases refine it: their presence grants just that op, and their rules\n // apply ON TOP of the umbrella's. An op is allowed iff its specific\n // phase or `write` exists. Rule mechanics per op: a `match` filters\n // UPDATE/DELETE and pins the column on INSERT; a `set` writes the\n // column on INSERT and UPDATE (delete writes no columns, so `delete`\n // is match-only at the type level).\n write?: ScopeRule[];\n insert?: ScopeRule[];\n update?: ScopeRule[];\n delete?: ScopeMatch[];\n };\n\nexport type ScopePolicy = {\n // Fallback for an entity that isn't listed, and for a listed entity's absent\n // phase: 'allow' = unrestricted, 'deny' = no access.\n default: 'allow' | 'deny';\n entities: Record<string, ScopeEntityRule>;\n};\n","import type { Query } from '../schemas/query.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { ResolvedQuery, ResolvedFilter, ResolvedSource, ResolvedJoin } from '../engine/engine.types.js';\nimport type { ScopePolicy, ScopeEntityRule, ScopeMatch } from './scope.types.js';\nimport { isSetMatch } from './scope.types.js';\nimport { VexError } from '../errors.js';\n\n// ───────────────────────────────────────────────────────────────\n// Error\n// ───────────────────────────────────────────────────────────────\n\n// A scope denial IS a VexError (code 'scope_denied') so the HTTP layer maps\n// it to a 400 like every other request error — a denied read or write is the\n// caller's problem, not a 500. `entity` is kept for callers that inspect it.\nexport class VexScopeError extends VexError {\n readonly entity: string;\n\n constructor(entity: string, message: string) {\n super('scope_denied', message);\n this.name = 'VexScopeError';\n this.entity = entity;\n }\n}\n\n// ───────────────────────────────────────────────────────────────\n// TWO QUESTIONS, DELIBERATELY SEPARATED\n// ───────────────────────────────────────────────────────────────\n//\n// Scope answers two things that used to be answered in one pass, and\n// conflating them produced a silent, universal row-loss bug:\n//\n// 1. MAY this caller touch this table at all? — a pure allow/deny over\n// entity names. Needs no schema, no aliases, no joins. Runs before\n// resolution, over every entity discovered anywhere in the tree.\n//\n// 2. WHERE does the row rule go? — needs to know HOW the table is reached,\n// because a row rule on a LEFT-joined table belongs in that join's ON\n// clause. It used to be merged into the DSL's `filter`, which compiles to\n// WHERE, which turns every LEFT join into an INNER one: a driving row\n// whose optional FK is null gets null-padded columns, `null = $tenant` is\n// null rather than true, and the row vanishes. No error, no warning, a\n// shorter list. It hid for as long as no data had a null FK.\n//\n// Only the resolver knows join kinds, so (2) moved after resolution. That also\n// means scope no longer writes anything into the authored `Query` — the\n// document integrations ship over the wire carries no engine-trusted field,\n// which is a property worth having on its own.\n\nconst matchesFor = (entity: string, rule: ScopeEntityRule | undefined, def: 'allow' | 'deny'): ScopeMatch[] => {\n if (rule === undefined) {\n if (def === 'deny') throw new VexScopeError(entity, `Entity \"${entity}\" is not allowed by scope policy (default: deny)`);\n return [];\n }\n if ('public' in rule) return [];\n if ('deny' in rule) throw new VexScopeError(entity, `Entity \"${entity}\" is denied by scope policy`);\n if (rule.read === undefined) {\n if (def === 'deny') throw new VexScopeError(entity, `Reads of \"${entity}\" are not allowed by scope policy (default: deny)`);\n return [];\n }\n return rule.read;\n};\n\n// Whether a policy lets a caller read a table at all — the same answer\n// `checkScope` enforces, as a predicate for anything that must decide what to\n// SHOW (discovery, the schema a generating agent is handed) rather than what\n// to refuse.\nexport const canReadTable = (policy: ScopePolicy, table: string): boolean => {\n const rule = policy.entities[table];\n if (rule === undefined) return policy.default === 'allow';\n if ('public' in rule) return true;\n if ('deny' in rule) return false;\n return rule.read !== undefined || policy.default === 'allow';\n};\n\n// ───────────────────────────────────────────────────────────────\n// 1. May they touch it\n// ───────────────────────────────────────────────────────────────\n\n// Throws on the first denied entity. A denied entity ANYWHERE denies the query,\n// including inside a subquery or an `exists` — `discoverEntities` walks the\n// whole tree, so a table cannot be reached by hiding it one level down.\nexport const checkScope = (entities: Set<string>, policy: ScopePolicy): void => {\n for (const entity of entities) matchesFor(entity, policy.entities[entity], policy.default);\n};\n\n// ───────────────────────────────────────────────────────────────\n// 2. Where the row rule goes\n// ───────────────────────────────────────────────────────────────\n\nconst andMerge = (existing: ResolvedFilter | undefined, additions: ResolvedFilter[]): ResolvedFilter | undefined => {\n if (additions.length === 0) return existing;\n const all = existing === undefined ? additions : [existing, ...additions];\n if (all.length === 1) return all[0];\n\n const paths = new Map<string, { alias: string; column: string; schema: never }>();\n for (const part of all) for (const [key, value] of part.resolvedPaths) paths.set(key, value as never);\n return { original: { and: all.map((f) => f.original) }, resolvedPaths: paths as never };\n};\n\n// One row rule, resolved against the alias the table actually got.\nconst predicateFor = (\n entityName: string,\n alias: string,\n match: ScopeMatch,\n fields: { name: string; nullable: boolean }[],\n): ResolvedFilter | undefined => {\n const field = fields.find((f) => f.name === match.match);\n // A rule naming a column the table does not have is a policy bug, not a\n // request bug — but failing the read closed is the only safe reading of it.\n if (field === undefined) throw new VexScopeError(entityName, `Scope rule for \"${entityName}\" names column \"${match.match}\", which the table does not have`);\n const path = `${entityName}.${match.match}`;\n // The set-valued form compiles to `col = ANY($n)`, which the operator table\n // already emits for `in` against a scope ref — so a reach covering several\n // rows needs no compile branch of its own, and binds through the same slot\n // machinery. An absent or empty set matches nothing (see scope.types.ts).\n const original: Filter = isSetMatch(match)\n ? { in: [path, { $scope: match.in }] }\n : { eq: [path, { $scope: match.to }] };\n return { original, resolvedPaths: new Map([[path, { alias, column: match.match, schema: field as never }]]) as never };\n};\n\n// One LEVEL of a resolved tree — an outer query, a subquery, or an `exists`.\n// They differ in what else they carry; for placing row rules they are the same\n// four things, so they get the same code and cannot drift apart.\ntype ScopeLevel = {\n sources: ResolvedSource[];\n joins: ResolvedJoin[];\n aliasMap: Map<string, string>;\n filter?: ResolvedFilter;\n};\n\nconst placeInto = (level: ScopeLevel, policy: ScopePolicy): void => {\n const whereAdditions: ResolvedFilter[] = [];\n\n for (const source of level.sources) {\n const entity = source.entity;\n if (entity === undefined) continue;\n\n const join = level.joins.find((j) => j.toAlias === source.alias);\n for (const match of matchesFor(entity.name, policy.entities[entity.name], policy.default)) {\n const predicate = predicateFor(entity.name, source.alias, match, entity.fields);\n if (predicate === undefined) continue;\n\n // The compiler resolves `entity.column` through the alias map, and these\n // predicates never went through the resolver's field pass, so they say\n // where they point.\n level.aliasMap.set(`${entity.name}.${match.match}`, `${source.alias}.${match.match}`);\n\n if (join !== undefined && join.kind === 'left') join.on = [...(join.on ?? []), predicate];\n else whereAdditions.push(predicate);\n }\n }\n\n const merged = andMerge(level.filter, whereAdditions);\n if (merged !== undefined) level.filter = merged;\n};\n\n// Walk the resolved tree and place every row rule. Subqueries and `exists`\n// nodes recurse: a rule on `tasks` lands inside the level whose FROM actually\n// reads tasks, never on an outer query that only sees an alias.\n//\n// The `exists` recursion is not tidiness — it is the boundary. An EXISTS\n// returns a boolean, but a boolean about somebody else's rows is still an\n// answer about somebody else's rows: an uncorrelated `exists` over a scoped\n// table would report whether ANY tenant has such a row. Access-checking the\n// table is not enough; the rule has to be inside the subquery too.\nexport const scopeResolved = (resolved: ResolvedQuery, policy: ScopePolicy): ResolvedQuery => {\n for (const source of resolved.sources) {\n if (source.subquery !== undefined) scopeResolved(source.subquery, policy);\n }\n\n // Every `exists` at every depth — the resolver collects nested ones into the\n // same flat map, so one pass covers the tree.\n for (const node of resolved.existsMap?.values() ?? []) {\n placeInto(node, policy);\n }\n\n placeInto(resolved, policy);\n return resolved;\n};\n\n// ───────────────────────────────────────────────────────────────\n// Deprecated shape, kept so a caller that only wanted the access check still\n// gets one. It no longer returns a filtered DSL, because scope is not a DSL\n// concern any more — `scopeResolved` does the placing.\n// ───────────────────────────────────────────────────────────────\nexport const applyScope = (dsl: Query, entities: Set<string>, policy: ScopePolicy): Query => {\n checkScope(entities, policy);\n return dsl;\n};\n","import type { ContextContract, ParamSlot } from '../adapters/adapter.types.js';\n\n// ───────────────────────────────────────────────────────────────\n// Validation context builder\n// ───────────────────────────────────────────────────────────────\n\nconst defaultForType = (type: ParamSlot['type']): unknown => {\n if (type === 'string') return '';\n if (type === 'number') return 0;\n if (type === 'boolean') return false;\n if (type === 'string[]') return [''];\n if (type === 'number[]') return [0];\n if (type === 'json') return [];\n return '';\n};\n\nexport const buildValidationContext = (contract: ContextContract): Record<string, unknown> => {\n const ctx: Record<string, unknown> = {};\n for (const key of Object.keys(contract)) {\n const slot = contract[key];\n if (slot === undefined) continue;\n // Skip semantic slots — handled separately by the test path\n if (slot.kind === 'semantic') continue;\n ctx[key] = defaultForType(slot.type);\n }\n return ctx;\n};\n\n// ───────────────────────────────────────────────────────────────\n// Parameter resolution\n// ───────────────────────────────────────────────────────────────\n\nexport const resolveParams = async (\n slots: ParamSlot[],\n context: Record<string, unknown>,\n scope: Record<string, unknown>,\n embed?: (text: string, dimensions?: number) => Promise<number[]>,\n): Promise<unknown[]> => {\n const results: unknown[] = [];\n\n for (const slot of slots) {\n if (slot.kind === 'context') {\n results.push(context[slot.key]);\n continue;\n }\n\n if (slot.kind === 'scope') {\n results.push(scope[slot.key]);\n continue;\n }\n\n // kind === 'semantic'\n if (embed === undefined) {\n throw new Error(`Semantic parameter \"${slot.key}\" requires an embed function`);\n }\n const text = context[slot.key];\n if (typeof text !== 'string') {\n throw new Error(`Semantic parameter \"${slot.key}\" requires a string value in context`);\n }\n const vector = await embed(text, slot.dimensions);\n results.push(`[${vector.join(',')}]`);\n }\n\n return results;\n};\n","import type { CompiledQuery, Row, DatabaseAdapter } from '../adapters/adapter.types.js';\nimport type { ContextMeta } from '../schemas/request.schema.js';\nimport { resolveParams } from '../utils/context.js';\nimport { VexError } from '../errors.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Execution\n// ═══════════════════════════════════════════════════════════════\n\nexport const executeQuery = async (\n compiled: CompiledQuery,\n context: Record<string, unknown>,\n scope: Record<string, unknown>,\n adapter: DatabaseAdapter,\n embed?: (text: string, dimensions?: number) => Promise<number[]>,\n): Promise<Row[]> => {\n const boundParams = await resolveParams(\n compiled.paramSlots,\n context,\n scope,\n embed,\n );\n return adapter.execute(compiled, boundParams);\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Context contract builder\n// ═══════════════════════════════════════════════════════════════\n\nexport const buildContextContract = (\n compiled: CompiledQuery,\n // Every key that controls an `optional` condition anywhere in the STORED\n // dsl — including the ones this run pruned away, which have no slot and so\n // would otherwise be invisible to the caller who most needs to know they\n // exist: the one who did not send them.\n optionalKeys: readonly string[] = [],\n): Record<string, ContextMeta> => {\n const contract: Record<string, ContextMeta> = {};\n\n for (const slot of compiled.paramSlots) {\n contract[slot.key] = {\n type: slot.type,\n kind: slot.kind,\n ...(optionalKeys.includes(slot.key) ? { optional: true as const } : {}),\n };\n }\n\n for (const key of optionalKeys) {\n if (contract[key] !== undefined) continue;\n contract[key] = { kind: 'context', optional: true, absent: true };\n }\n\n return contract;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Missing context detection\n// ═══════════════════════════════════════════════════════════════\n\n// The CALLER's half: context keys the request did not supply. A read with\n// holes answers empty and hands back the contract it missed — the caller can\n// fix that. Scope is not in here; see requireScope.\nexport const findMissingContext = (\n compiled: CompiledQuery,\n context: Record<string, unknown>,\n): string[] => {\n const missing: string[] = [];\n\n for (const slot of compiled.paramSlots) {\n if ((slot.kind === 'context' || slot.kind === 'semantic') && context[slot.key] === undefined) {\n missing.push(slot.key);\n }\n }\n\n return missing;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Missing scope — the HOST's half\n// ═══════════════════════════════════════════════════════════════\n\n// A `$scope` slot the host did not fill is not a hole a caller can mend: the\n// caller cannot supply scope, and binding it would bind NULL — which matches\n// no row on a read and STAMPS NULL on a write. So it refuses, loudly, before\n// anything runs. The keys ride in `details` for the host's logs; the HTTP\n// layer does not hand them to the client.\nexport const requireScope = (compiled: { paramSlots: readonly { kind: string; key: string }[] }, scope: Record<string, unknown>): void => {\n const missing = [...new Set(compiled.paramSlots.filter((slot) => slot.kind === 'scope' && scope[slot.key] === undefined).map((slot) => slot.key))];\n if (missing.length > 0) {\n throw new VexError('missing_scope', `This statement is scoped by ${missing.join(', ')}, which the host did not supply.`, { keys: missing });\n }\n};\n","import { z } from 'zod';\nimport { FilterSchema } from '../schemas/filter.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { FieldOrValue } from '../schemas/value.schema.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Mutation grammar — the WRITE sibling of the query DSL.\n//\n// Closed on purpose. A mutation is authored data (a cache entry seeded by a\n// developer), never generated and never client-supplied: the wire replays a\n// fingerprint, and the def the fingerprint names lives server-side. The\n// grammar rejects the dangerous shapes at parse: `$scope` is unauthorable\n// (identity/tenant is engine-injected — see scopeMutation), and update/delete\n// REQUIRE a `where` (a write with no WHERE touches every row).\n// ═══════════════════════════════════════════════════════════════\n\n// A scalar subquery in value position: read ONE value from another table at\n// write time — `(SELECT field FROM from WHERE ...)`. This is how a statement\n// references a row it cannot otherwise name (e.g. a person found by email).\n// The lookup READS, so the read-phase scope rules of `from` are applied to its\n// WHERE by the engine — a write entry is never a read-scope bypass. The WHERE\n// should hit a unique key: more than one matching row is a runtime error\n// (deliberately — silently picking an arbitrary row would be worse).\nconst LookupSchema = z\n .object({\n $lookup: z\n .object({\n from: z.string().describe('Table the value is read from'),\n field: z.string().describe('Column the subquery returns'),\n where: FilterSchema.describe('Bounds the lookup — should match at most one row'),\n })\n .strict(),\n })\n .strict()\n .describe('Scalar subquery: reads one value from another table at write time; read scope rules apply');\n\n// A value an AUTHORED mutation may set: a literal, a `{ $context }` ref to\n// the caller's runtime values, or a `{ $lookup }` scalar subquery. NOT\n// `$scope` — the engine injects it post-parse, so a stored or injected\n// mutation cannot place, omit, or redirect it. NOT a field path either — a\n// write sets values, it does not read columns.\nconst ValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.object({ $context: z.string() }).strict(),\n LookupSchema,\n]);\n\nconst Columns = z\n .record(z.string(), ValueSchema)\n .refine((r) => Object.keys(r).length > 0, { message: 'a write must set at least one column' });\n\n// ── ON CONFLICT ────────────────────────────────────────────────\n// The DB-arbitrated sibling of the `upsert` sugar below. `upsert` branches on\n// what the CALLER sent (key present → update); `onConflict` branches on what\n// the DATABASE holds (row exists → update/nothing), atomically. `target` must\n// name a unique constraint — validated against the introspected schema, so an\n// ON CONFLICT that arrests nothing is an authoring error, not a runtime\n// surprise. `set` present → DO UPDATE SET (RETURNING yields the row on both\n// paths — re-setting one inserted value as a no-op \"touch\" is the idiom for\n// create-or-fetch). `set` absent → DO NOTHING, which returns NO row on\n// conflict; callers can read that absence as \"already existed\".\nconst OnConflictSchema = z\n .object({\n target: z.array(z.string()).min(1).describe('Conflict columns — must match a unique index or the primary key'),\n set: Columns.optional().describe('DO UPDATE SET when the row already exists; omitted → DO NOTHING (no row returned on conflict)'),\n })\n .strict();\n\n// `where` is a real vex `Filter` — `$context`/`$scope` and scope injection\n// behave exactly as they do for reads.\nconst InsertSchema = z.object({ op: z.literal('insert'), table: z.string(), values: Columns, onConflict: OnConflictSchema.optional() }).strict();\nconst UpdateSchema = z.object({ op: z.literal('update'), table: z.string(), set: Columns, where: FilterSchema }).strict();\nconst DeleteSchema = z.object({ op: z.literal('delete'), table: z.string(), where: FilterSchema }).strict();\n\n// ── insertEach ─────────────────────────────────────────────────\n// One INSERT for a caller-sized list — `INSERT ... SELECT ... FROM\n// jsonb_array_elements($items)`. `items` names a context key holding an array\n// of objects; a `{ $item }` value reads a key from the current element (cast\n// to the column's type from the schema); every other value (literal,\n// `$context`, `$lookup`, engine-injected `$scope`) is constant across rows.\n// This is how \"one template row per ticked weekday\" stays a single authored\n// statement instead of a code loop.\nconst ItemRefSchema = z\n .object({ $item: z.string() })\n .strict()\n .describe('insertEach only: a key read from the current element of `items`');\n\nconst EachColumns = z\n .record(z.string(), z.union([ValueSchema, ItemRefSchema]))\n .refine((r) => Object.keys(r).length > 0, { message: 'a write must set at least one column' });\n\nconst InsertEachSchema = z\n .object({\n op: z.literal('insertEach'),\n table: z.string(),\n items: z.object({ $context: z.string() }).strict().describe('Context key holding an array of objects — one inserted row per element'),\n values: EachColumns,\n onConflict: OnConflictSchema.optional(),\n })\n .strict();\n\n// ── Sugar ──────────────────────────────────────────────────────\n// A sugar op rewrites to the core ops above before anything runs (see\n// desugarMutation). `upsert` is insert-or-update keyed on `key`: present in\n// the call's context → update that row, absent/empty → insert.\nconst UpsertSchema = z\n .object({\n op: z.literal('upsert'),\n table: z.string(),\n columns: Columns, // set on BOTH branches (update SET, and part of the insert)\n insert: Columns.optional(), // extra columns set ONLY on insert — immutable-on-create (e.g. a FK)\n key: z.string(),\n })\n .strict()\n .describe('Sugar: insert-or-update by `key` (e.g. \"id\"). Desugars to update (SET columns WHERE key) when the key is present, else insert (columns + `insert`-only).');\n\nexport const MutationSchema = z.discriminatedUnion('op', [InsertSchema, InsertEachSchema, UpdateSchema, DeleteSchema, UpsertSchema]);\nexport type Mutation = z.infer<typeof MutationSchema>;\n\n// The core ops a sugar desugars TO — what the pipeline (scope/validate/\n// compile) actually handles. `upsert` never reaches them.\nexport type CoreMutation = Exclude<Mutation, { op: 'upsert' }>;\n\n// One write, or a batch run together in a single transaction.\nexport const MutationDefinitionSchema = z.union([MutationSchema, MutationSchema.array().min(1)]);\nexport type MutationDefinition = z.infer<typeof MutationDefinitionSchema>;\n\n// The value shapes as the ENGINE sees them (authored + injected).\nexport type LookupValue = { $lookup: { from: string; field: string; where: Filter } };\nexport type ItemRef = { $item: string };\nexport type MutationValue = FieldOrValue | LookupValue;\n\n// After scopeMutation the engine may have injected `{ $scope }` refs that the\n// authored grammar forbids — so the resolved form's columns widen to the full\n// `MutationValue`. It may also have widened `onConflict` with a `where` (the\n// RLS filter on the DO UPDATE half — `match` rules land there when the\n// conflict target does not already pin them). Authored (`Mutation`) →\n// resolved is a pure widening.\nexport type ResolvedOnConflict = { target: string[]; set?: Record<string, MutationValue>; where?: Filter };\nexport type ResolvedMutation =\n | { op: 'insert'; table: string; values: Record<string, MutationValue>; onConflict?: ResolvedOnConflict }\n | { op: 'insertEach'; table: string; items: { $context: string }; values: Record<string, MutationValue | ItemRef>; onConflict?: ResolvedOnConflict }\n | { op: 'update'; table: string; set: Record<string, MutationValue>; where: Filter }\n | { op: 'delete'; table: string; where: Filter };\n","import type { Query } from '../schemas/query.schema.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { DatabaseSchema } from '../schemas/database.schema.js';\nimport type { Mutation, MutationDefinition, CoreMutation } from './schema.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Context signatures — the derived input contract of a cache entry.\n//\n// A fingerprint hides the def; the def contains `{ $context }` refs; the refs\n// sit at positions whose column types the schema knows. So the contract of\n// \"what do I pass this fingerprint\" is COMPUTED from the artifact — walked\n// out of the stored DSL/def — never authored, and therefore never stale.\n// Discovery serves it; the mutation error path teaches it.\n// ═══════════════════════════════════════════════════════════════\n\nexport type ContextField = { type: string; column?: string; note?: string };\nexport type ContextSignature = Record<string, ContextField>;\nexport type MutationEffect = { op: Mutation['op']; table: string; columns: string[] };\n\nconst isContextRef = (v: unknown): v is { $context: string } =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && typeof (v as Record<string, unknown>)['$context'] === 'string';\n\nconst columnInfo = (path: string, schema: DatabaseSchema | undefined): ContextField => {\n const [table, field] = path.split('.');\n const entity = schema?.entities.find((e) => e.table === table || e.name === table);\n const f = entity?.fields.find((x) => x.name === field);\n return { type: f?.normalizedType ?? 'unknown', column: path };\n};\n\n// First specific description wins; a later, better-typed sighting upgrades an\n// 'unknown' one. Notes stick once set.\nconst addField = (sig: ContextSignature, key: string, field: ContextField): void => {\n const existing = sig[key];\n if (existing === undefined) {\n sig[key] = field;\n return;\n }\n if (existing.type === 'unknown' && field.type !== 'unknown') {\n sig[key] = { ...field, ...(existing.note !== undefined ? { note: existing.note } : {}) };\n }\n};\n\n// Last-resort sweep: find `{ $context }` anywhere in a value (compute args,\n// exotic filter ops) and record the key with an unknown type.\nconst deepScan = (value: unknown, sig: ContextSignature): void => {\n if (isContextRef(value)) {\n addField(sig, value.$context, { type: 'unknown' });\n return;\n }\n if (Array.isArray(value)) {\n for (const v of value) deepScan(v, sig);\n return;\n }\n if (value !== null && typeof value === 'object') {\n for (const v of Object.values(value)) deepScan(v, sig);\n }\n};\n\n// Comparison positions pair a field path with a value — when the value is a\n// `{ $context }` ref, the path's column gives the ref its type.\nconst COMPARISONS = ['eq', 'neq', 'gt', 'gte', 'lt', 'lte'] as const;\n\nconst walkFilter = (filter: Filter, schema: DatabaseSchema | undefined, sig: ContextSignature): void => {\n const f = filter as Record<string, unknown>;\n for (const op of COMPARISONS) {\n const pair = f[op];\n if (Array.isArray(pair) && pair.length === 2) {\n const [a, b] = pair as [unknown, unknown];\n if (typeof a === 'string' && isContextRef(b)) addField(sig, b.$context, columnInfo(a, schema));\n else if (typeof b === 'string' && isContextRef(a)) addField(sig, a.$context, columnInfo(b, schema));\n else deepScan(pair, sig);\n return;\n }\n }\n if ('in' in f || 'notIn' in f) {\n const [path, target] = (f['in'] ?? f['notIn']) as [string, unknown];\n if (isContextRef(target)) addField(sig, target.$context, { ...columnInfo(path, schema), type: `${columnInfo(path, schema).type}[]` });\n else deepScan(target, sig);\n return;\n }\n if ('like' in f || 'ilike' in f) {\n const [path, v] = (f['like'] ?? f['ilike']) as [string, unknown];\n if (isContextRef(v)) addField(sig, v.$context, { type: 'string', column: path, note: 'pattern' });\n return;\n }\n if ('and' in f || 'or' in f) {\n for (const sub of (f['and'] ?? f['or']) as Filter[]) walkFilter(sub, schema, sig);\n return;\n }\n if ('not' in f) {\n walkFilter(f['not'] as Filter, schema, sig);\n return;\n }\n // isNull / isNotNull carry no values; semantic/fuzzy and anything future get\n // the generic sweep so no ref is ever silently dropped.\n deepScan(f, sig);\n};\n\nconst isLookupRef = (v: unknown): v is { $lookup: { from: string; field: string; where: Filter } } =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && '$lookup' in v;\n\nconst columnsOf = (m: Mutation): Record<string, unknown> =>\n m.op === 'insert' || m.op === 'insertEach'\n ? { ...m.values, ...(m.onConflict?.set ?? {}) }\n : m.op === 'update'\n ? m.set\n : m.op === 'upsert'\n ? { ...m.columns, ...(m.insert ?? {}) }\n : {};\n\nexport const collectMutationContext = (def: MutationDefinition, schema?: DatabaseSchema): ContextSignature => {\n const sig: ContextSignature = {};\n const list = Array.isArray(def) ? def : [def];\n for (const m of list) {\n for (const [col, v] of Object.entries(columnsOf(m))) {\n if (isLookupRef(v)) {\n // The lookup's WHERE binds context like any filter does.\n walkFilter(v.$lookup.where, schema, sig);\n continue;\n }\n if (!isContextRef(v)) continue;\n const insertOnly = m.op === 'upsert' && m.insert !== undefined && col in m.insert;\n addField(sig, v.$context, { ...columnInfo(`${m.table}.${col}`, schema), ...(insertOnly ? { note: 'insert only' } : {}) });\n }\n if (m.op === 'update' || m.op === 'delete') walkFilter(m.where, schema, sig);\n if (m.op === 'insertEach') {\n const itemKeys = Object.values(m.values)\n .filter((v): v is { $item: string } => v !== null && typeof v === 'object' && '$item' in v)\n .map((v) => v.$item);\n sig[m.items.$context] = { type: 'json', note: `array of objects — one inserted row per element${itemKeys.length > 0 ? ` (keys: ${itemKeys.join(', ')})` : ''}` };\n }\n if (m.op === 'upsert') {\n sig[m.key] = { ...columnInfo(`${m.table}.${m.key}`, schema), note: 'upsert key — present updates that row, absent/empty inserts' };\n }\n }\n return sig;\n};\n\nexport const collectQueryContext = (dsl: Query, schema?: DatabaseSchema): ContextSignature => {\n const sig: ContextSignature = {};\n const walkQuery = (q: Query): void => {\n for (const source of q.from) {\n if (typeof source !== 'string') walkQuery(source.query);\n }\n if (q.filter !== undefined) walkFilter(q.filter, schema, sig);\n if (q.compute !== undefined) deepScan(q.compute, sig);\n if (q.aggregate !== undefined) deepScan(q.aggregate, sig);\n };\n walkQuery(dsl);\n return sig;\n};\n\nexport const mutationEffect = (def: MutationDefinition): MutationEffect[] => {\n const list = Array.isArray(def) ? def : [def];\n return list.flatMap((m) => {\n const base: MutationEffect = { op: m.op, table: m.table, columns: Object.keys(columnsOf(m)).sort() };\n // ON CONFLICT DO UPDATE also updates — declare it, so visibility and\n // grants treat the entry as the insert-plus-update it really is.\n const conflictSet = (m.op === 'insert' || m.op === 'insertEach') && m.onConflict?.set !== undefined ? m.onConflict.set : undefined;\n if (conflictSet === undefined) return [base];\n return [base, { op: 'update', table: m.table, columns: Object.keys(conflictSet).sort() }];\n });\n};\n\n// The keys a DESUGARED core mutation actually binds — the hard requirement\n// checked before execution (an upsert's absent key is legal: it selects the\n// insert branch, so requirement is computed after desugaring).\nexport const requiredContextKeys = (m: CoreMutation): string[] => {\n const keys = new Set<string>();\n const cols = m.op === 'insert' || m.op === 'insertEach' ? { ...m.values, ...(m.onConflict?.set ?? {}) } : m.op === 'update' ? m.set : {};\n for (const v of Object.values(cols)) {\n if (isContextRef(v)) keys.add(v.$context);\n else if (isLookupRef(v)) {\n const sub: ContextSignature = {};\n deepScan(v.$lookup.where, sub);\n for (const k of Object.keys(sub)) keys.add(k);\n }\n }\n if (m.op === 'insertEach') keys.add(m.items.$context);\n if (m.op === 'update' || m.op === 'delete') {\n const sub: ContextSignature = {};\n deepScan(m.where, sub);\n for (const k of Object.keys(sub)) keys.add(k);\n }\n return [...keys].sort();\n};\n\n// Authoring lint (run by the seed path): an update/delete whose WHERE binds no\n// `$context` is not caller-bounded — its only row limit is the scope policy.\n// Loud at boot, never at runtime.\n// An `optional` condition is a READ construct. In a WHERE it would mean \"this\n// bound disappears when the caller omits a key\" — which is precisely the\n// unkeyed update the lint below exists to refuse, only reachable by omission\n// rather than by authoring. Writes keep the rule they have always had: every\n// key is mandatory, and a missing one is a hard `missing_context` (see\n// mutations/engine.ts), never a wider statement.\nconst findOptional = (value: unknown): boolean => {\n if (Array.isArray(value)) return value.some(findOptional);\n if (value === null || typeof value !== 'object') return false;\n if ('optional' in value) return true;\n return Object.values(value).some(findOptional);\n};\n\nexport const lintMutation = (def: MutationDefinition): string[] => {\n const issues: string[] = [];\n const list = Array.isArray(def) ? def : [def];\n for (const m of list) {\n if (findOptional(m)) {\n issues.push(`${m.op} on \"${m.table}\" contains an optional condition — a write's bounds cannot depend on what the caller chose to send`);\n }\n if (m.op !== 'update' && m.op !== 'delete') continue;\n const sub: ContextSignature = {};\n deepScan(m.where, sub);\n if (Object.keys(sub).length === 0) {\n issues.push(`${m.op} on \"${m.table}\" has no $context-keyed WHERE — the write is not caller-bounded`);\n }\n }\n return issues;\n};\n","import { compileFilter, compileFieldOrValue, quoteLiteral } from '../adapters/postgres/operators.js';\nimport type { CompilationContext } from '../adapters/postgres/operators.js';\nimport type { ParamSlot, Row } from '../adapters/adapter.types.js';\nimport type { Filter } from '../schemas/filter.schema.js';\nimport type { DatabaseSchema } from '../schemas/database.schema.js';\nimport type { ScopePolicy, ScopeValues, ScopeMatch, ScopeRule } from '../scope/scope.types.js';\nimport { isSetMatch } from '../scope/scope.types.js';\nimport { VexScopeError } from '../scope/apply.js';\nimport { VexError } from '../errors.js';\nimport { isFieldPathShape } from '../schemas/identifier.schema.js';\nimport { resolveParams } from '../utils/context.js';\nimport { requireScope } from '../engine/executor.js';\nimport { MutationDefinitionSchema } from './schema.js';\nimport type { Mutation, MutationDefinition, CoreMutation, ResolvedMutation, ResolvedOnConflict, MutationValue, LookupValue, ItemRef } from './schema.js';\nimport { collectMutationContext, requiredContextKeys } from './signature.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Mutation engine — the write pipeline. Validate (closed grammar, bounded\n// WHERE) → desugar → require context → scope (RLS + identity stamp) → check\n// columns → compile → execute. Every gate runs before a single statement\n// does. Reuses the read pipeline's own machinery for SQL and params\n// (compileFilter / compileFieldOrValue / resolveParams), so values bind as\n// SQL parameters exactly as they do for reads — never inlined.\n// ═══════════════════════════════════════════════════════════════\n\n// The database the writes run against — structural, so PGlite, a pg Pool\n// wrapper, or a test double all fit without vex importing any driver.\nexport type MutationTx = {\n query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[] }>;\n};\nexport type MutationClient = MutationTx & {\n transaction?: <T>(fn: (tx: MutationTx) => Promise<T>) => Promise<T>;\n};\n\n// ─── Value guards ──────────────────────────────────────────────\nconst isLookup = (v: unknown): v is LookupValue =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && '$lookup' in v;\nconst isItemRef = (v: unknown): v is ItemRef =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && '$item' in v;\n\nconst collectLookups = (m: ResolvedMutation): LookupValue['$lookup'][] => {\n const out: LookupValue['$lookup'][] = [];\n const scan = (cols: Record<string, unknown> | undefined): void => {\n for (const v of Object.values(cols ?? {})) if (isLookup(v)) out.push(v.$lookup);\n };\n if (m.op === 'insert' || m.op === 'insertEach') {\n scan(m.values);\n scan(m.onConflict?.set);\n }\n if (m.op === 'update') scan(m.set);\n return out;\n};\n\n// ─── Schema validation (anti-hallucination) ────────────────────\n// The engine already introspected for reads; reject an unknown table or a\n// written column not in it. A misauthored `contats` / `naem` fails closed,\n// before any SQL runs.\nconst findEntity = (table: string, schema: DatabaseSchema) =>\n schema.entities.find((e) => e.table === table || e.name === table);\n\n// An ON CONFLICT whose target names no unique constraint never arrests\n// anything — the insert would simply throw on the real constraint, or worse,\n// never conflict at all. The schema knows the unique column sets (PK +\n// introspected unique indexes), so a mismatched target is an AUTHORING error,\n// caught before any SQL runs, with the real options in the message.\nconst assertConflictTarget = (table: string, target: string[], entity: { fields: { name: string; primaryKey: boolean }[]; indexes: { fields: string[]; unique: boolean }[] }): void => {\n const uniqueSets = [\n entity.fields.filter((f) => f.primaryKey).map((f) => f.name),\n ...entity.indexes.filter((i) => i.unique).map((i) => [...i.fields]),\n ].filter((s) => s.length > 0);\n if (uniqueSets.length === 0) return; // the schema carries no uniqueness info — nothing to check against\n const want = new Set(target);\n const ok = uniqueSets.some((s) => s.length === want.size && s.every((c) => want.has(c)));\n if (!ok) {\n throw new VexError(\n 'invalid_dsl',\n `onConflict target (${target.join(', ')}) does not match a unique constraint on \"${table}\". Unique column sets: ${uniqueSets.map((s) => `(${s.join(', ')})`).join(' ')}.`,\n );\n }\n};\n\n// Every column a write's filter names — field positions, and value positions\n// shaped like a column (the same rule the read compiler uses to tell a column\n// from a literal). A field position is collected whatever it looks like, so a\n// string that is not a column is refused by the check below instead of being\n// compiled.\nconst filterColumns = (filter: Filter): string[] => {\n const out: string[] = [];\n const value = (v: unknown): void => {\n if (isFieldPathShape(v)) out.push(v);\n };\n const walk = (f: Filter): void => {\n if ('and' in f) return f.and.forEach(walk);\n if ('or' in f) return f.or.forEach(walk);\n if ('not' in f) return walk(f.not);\n if ('eq' in f) return f.eq.forEach(value);\n if ('neq' in f) return f.neq.forEach(value);\n if ('gt' in f) return f.gt.forEach(value);\n if ('gte' in f) return f.gte.forEach(value);\n if ('lt' in f) return f.lt.forEach(value);\n if ('lte' in f) return f.lte.forEach(value);\n if ('in' in f || 'notIn' in f) {\n const [field, target] = 'in' in f ? f.in : f.notIn;\n out.push(field);\n if (Array.isArray(target)) target.forEach(value);\n return;\n }\n if ('like' in f || 'ilike' in f) {\n const [field, pattern] = 'like' in f ? f.like : f.ilike;\n out.push(field);\n return value(pattern);\n }\n if ('isNull' in f) return void out.push(f.isNull);\n if ('isNotNull' in f) return void out.push(f.isNotNull);\n if ('semantic' in f) return void out.push(f.semantic.field);\n if ('fuzzy' in f) return void out.push(f.fuzzy.field);\n // `exists` and `optional` have no single-table meaning in a write; the\n // compiler refuses both loudly.\n };\n walk(filter);\n return out;\n};\n\n// A write's filter reads ONE table — the one it writes, or the one a `$lookup`\n// reads — and every column it names must be that table's. This is what makes\n// the compiler's identity mapping below safe: nothing reaches it that the\n// schema does not have.\nconst assertFilterColumns = (filter: Filter, table: string, schema: DatabaseSchema, where: string): void => {\n const entity = findEntity(table, schema);\n if (entity === undefined) throw new VexError('invalid_dsl', `Unknown table \"${table}\" in ${where}.`);\n for (const path of filterColumns(filter)) {\n const dot = path.indexOf('.');\n const owner = path.slice(0, dot);\n const column = path.slice(dot + 1);\n if (!isFieldPathShape(path) || owner !== table || !entity.fields.some((f) => f.name === column)) {\n throw new VexError('invalid_dsl', `\"${path}\" in ${where} is not a column of \"${table}\".`);\n }\n }\n};\n\nconst assertWritableColumns = (m: ResolvedMutation, schema: DatabaseSchema): void => {\n const entity = findEntity(m.table, schema);\n if (entity === undefined) throw new VexError('invalid_dsl', `Unknown table \"${m.table}\".`);\n if (m.op === 'update' || m.op === 'delete') assertFilterColumns(m.where, m.table, schema, 'the WHERE');\n const known = new Set(entity.fields.map((f) => f.name));\n const cols = m.op === 'insert' || m.op === 'insertEach' ? Object.keys(m.values) : m.op === 'update' ? Object.keys(m.set) : [];\n for (const c of cols) {\n if (!known.has(c)) throw new VexError('invalid_dsl', `Unknown column \"${m.table}.${c}\".`);\n }\n // A lookup reads a real table and column, or fails closed like any other\n // misauthored name.\n for (const l of collectLookups(m)) {\n const le = findEntity(l.from, schema);\n if (le === undefined) throw new VexError('invalid_dsl', `Unknown table \"${l.from}\" in $lookup.`);\n if (!le.fields.some((f) => f.name === l.field)) throw new VexError('invalid_dsl', `Unknown column \"${l.from}.${l.field}\" in $lookup.`);\n assertFilterColumns(l.where, l.from, schema, 'a $lookup');\n }\n if ((m.op === 'insert' || m.op === 'insertEach') && m.onConflict !== undefined) {\n for (const c of [...m.onConflict.target, ...Object.keys(m.onConflict.set ?? {})]) {\n if (!known.has(c)) throw new VexError('invalid_dsl', `Unknown column \"${m.table}.${c}\" in onConflict.`);\n }\n assertConflictTarget(m.table, m.onConflict.target, entity);\n if (m.onConflict.where !== undefined) assertFilterColumns(m.onConflict.where, m.table, schema, 'onConflict');\n }\n};\n\n// ─── Scope — applied by the ENGINE, never authored in the DSL ──\n// The same `ScopePolicy` reads use, its write-phase rules applied AFTER the\n// entry is parsed — so identity/tenant binding can't be touched by a stored\n// or injected mutation. `write` is the UMBRELLA phase (grants + rules for\n// insert/update/delete); the specific phases refine it — an op is allowed\n// iff its specific phase or `write` exists, and its rules are the umbrella's\n// plus the specific's. Mechanics: a `set` writes its column from scope on\n// each column-writing op (insert values, update set) — delete writes no\n// columns, so it is structurally exempt, not special-cased. A `match` pins\n// its column on insert and ANDs a filter into update/delete WHERE (the RLS\n// boundary). No applicable phase (or unlisted table) falls to `default`:\n// deny throws, allow leaves the mutation ungoverned.\n// A `$lookup` READS its table, so the read-phase rules of THAT table apply —\n// a mutation entry is never a read-scope bypass. Match rules AND into the\n// lookup's WHERE; a table the principal cannot read refuses the whole write.\nconst readMatchesFor = (table: string, policy: ScopePolicy): ScopeMatch[] => {\n const rule = policy.entities[table];\n if (rule === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `A $lookup reads \"${table}\", which is not allowed by scope policy (default: deny).`);\n return [];\n }\n if ('public' in rule) return [];\n if ('deny' in rule) throw new VexScopeError(table, `A $lookup reads \"${table}\", which is denied by scope policy.`);\n if (rule.read === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `A $lookup reads \"${table}\", which this principal has no read grant for.`);\n return [];\n }\n return rule.read;\n};\n\n// ONE SPELLING of the RLS boundary, for every place a match rule becomes a\n// WHERE — a `$lookup`'s filter, an ON CONFLICT DO UPDATE, an UPDATE and a\n// DELETE. Four copies of `{ eq: [...] }` is four places a new match shape has\n// to be remembered, and the one that was forgotten would be the hole.\nconst boundaryOf = (table: string, r: ScopeMatch): Filter =>\n isSetMatch(r) ? { in: [`${table}.${r.match}`, { $scope: r.in }] } : { eq: [`${table}.${r.match}`, { $scope: r.to }] };\n\nconst scopeLookups = <V extends MutationValue | ItemRef>(cols: Record<string, V>, policy: ScopePolicy): Record<string, V> => {\n const out: Record<string, V> = {};\n for (const [k, v] of Object.entries(cols)) {\n if (!isLookup(v)) {\n out[k] = v;\n continue;\n }\n let where: Filter = v.$lookup.where;\n for (const r of readMatchesFor(v.$lookup.from, policy)) {\n where = { and: [where, boundaryOf(v.$lookup.from, r)] };\n }\n // A scoped lookup is still a lookup — the transform is type-preserving.\n out[k] = { $lookup: { ...v.$lookup, where } } as V;\n }\n return out;\n};\n\n// The gate every write passes: throws when denied, returns `undefined` when\n// the table is ungoverned (public / default allow), else the entity rule and\n// the applicable phase rules (umbrella + specific).\ntype WriteGate = { rule: Extract<ScopePolicy['entities'][string], { read?: unknown }>; rules: readonly ScopeRule[] };\n\nconst writeGate = (table: string, op: 'insert' | 'update' | 'delete', policy: ScopePolicy): WriteGate | undefined => {\n const rule = policy.entities[table];\n if (rule === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `Writes to \"${table}\" are not allowed by scope policy (default: deny).`);\n return undefined;\n }\n if ('public' in rule) return undefined;\n if ('deny' in rule) throw new VexScopeError(table, `Writes to \"${table}\" are denied by scope policy.`);\n const specific = op === 'insert' ? rule.insert : op === 'update' ? rule.update : rule.delete;\n if (rule.write === undefined && specific === undefined) {\n if (policy.default === 'deny') throw new VexScopeError(table, `\"${op}\" on \"${table}\" is not allowed by scope policy (default: deny).`);\n return undefined;\n }\n return { rule, rules: [...(rule.write ?? []), ...(specific ?? [])] };\n};\n\n// The shared insert-shaped half: lookups scoped, insert rules applied to the\n// values, and the ON CONFLICT half gated and governed as the UPDATE it is.\n// `set` rules stamp identity into the DO UPDATE SET; `match` rules whose\n// column the conflict target already pins are inherently satisfied (the\n// inserted, scope-pinned value must equal the existing row's for a conflict\n// to arise at all); any other `match` becomes a WHERE on the DO UPDATE half —\n// the RLS boundary again.\nconst scopeInsertParts = <V extends MutationValue | ItemRef>(\n table: string,\n rawValues: Record<string, V>,\n rawConflict: ResolvedOnConflict | undefined,\n policy: ScopePolicy,\n): { values: Record<string, V | { $scope: string }>; conflict: ResolvedOnConflict | undefined } => {\n let values: Record<string, V | { $scope: string }> = scopeLookups(rawValues, policy);\n let conflict: ResolvedOnConflict | undefined =\n rawConflict === undefined || rawConflict.set === undefined ? rawConflict : { ...rawConflict, set: scopeLookups(rawConflict.set, policy) };\n\n const gate = writeGate(table, 'insert', policy);\n if (gate === undefined) return { values, conflict };\n\n for (const r of gate.rules) {\n // A WRITE'S SUBJECT IS ONE VALUE, AND THIS IS WHERE THAT IS ENFORCED.\n //\n // A `match` on an INSERT does not filter — there is no row yet — it WRITES\n // the column, which is what makes \"insert outside your boundary\"\n // unsayable rather than merely refused. A set has no single value to\n // write, so there is no honest thing to do with one here.\n //\n // Throwing rather than picking, ignoring, or compiling a guard: a reach\n // that covers several rows for READING must not silently become a reach\n // that lets a caller CHOOSE which of them to write as. A write's subject\n // comes from scope (one value) or through a `$lookup` whose own read\n // rules the engine applies — never from a set the caller indexes into.\n if ('match' in r && isSetMatch(r)) {\n throw new VexScopeError(\n table,\n `Scope rule for \"${table}\" is set-valued (\"${r.match}\" in \"${r.in}\") and cannot pin an INSERT — a write's subject must be a single value. Use a scalar match, or carry the subject in a $lookup whose own read rules bound it.`,\n );\n }\n // A `set` writes identity; a scalar `match` pins the RLS boundary — on an\n // INSERT both land in the values.\n values = { ...values, ['set' in r ? r.set : r.match]: { $scope: r.to } };\n }\n\n if (conflict?.set !== undefined) {\n if (gate.rule.write === undefined && gate.rule.update === undefined) {\n throw new VexScopeError(table, `onConflict on \"${table}\" declares DO UPDATE, but this principal has no update grant.`);\n }\n for (const r of [...(gate.rule.write ?? []), ...(gate.rule.update ?? [])]) {\n if ('set' in r) {\n conflict = { ...conflict, set: { ...(conflict.set ?? {}), [r.set]: { $scope: r.to } } };\n } else if (!conflict.target.includes(r.match)) {\n const boundary = boundaryOf(table, r);\n conflict = { ...conflict, where: conflict.where === undefined ? boundary : { and: [conflict.where, boundary] } };\n }\n }\n }\n\n return { values, conflict };\n};\n\nconst scopeMutation = (m: CoreMutation, policy: ScopePolicy): ResolvedMutation => {\n if (m.op === 'insert') {\n const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);\n return { op: 'insert', table: m.table, values, ...(conflict === undefined ? {} : { onConflict: conflict }) };\n }\n if (m.op === 'insertEach') {\n const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);\n return { op: 'insertEach', table: m.table, items: m.items, values, ...(conflict === undefined ? {} : { onConflict: conflict }) };\n }\n if (m.op === 'update') {\n let set: Record<string, MutationValue> = scopeLookups(m.set, policy);\n let where: Filter = m.where;\n const gate = writeGate(m.table, 'update', policy);\n if (gate !== undefined) {\n for (const r of gate.rules) {\n // The column is written from scope on insert AND update alike.\n if ('set' in r) set = { ...set, [r.set]: { $scope: r.to } };\n // RLS boundary on update — AND the scope filter into WHERE. A set is\n // safe HERE, unlike on insert: the rows already exist and this only\n // narrows which of them may be touched.\n else where = { and: [where, boundaryOf(m.table, r)] };\n }\n }\n return { op: 'update', table: m.table, set, where };\n }\n // delete — writes no columns, so `set` rules are structurally exempt.\n let where: Filter = m.where;\n const gate = writeGate(m.table, 'delete', policy);\n if (gate !== undefined) {\n for (const r of gate.rules) {\n if ('match' in r) where = { and: [where, boundaryOf(m.table, r)] };\n }\n }\n return { op: 'delete', table: m.table, where };\n};\n\n// ─── Compile (reuses the read pipeline's SQL + param machinery) ─\n// Only the INSERT/UPDATE/DELETE skeleton is assembled here; vex's\n// `compileFieldOrValue` / `compileFilter` fill the fragments and accumulate\n// the param slots, which `resolveParams` then binds. One catch: for a\n// comparison, vex quotes an unmapped `entity.field` as a STRING LITERAL (it\n// can't know it's a column). A single-table write has no resolver to build\n// the alias map, so we seed it ourselves — identity-mapping each `where`\n// field path to itself, which a single-table UPDATE/DELETE qualifies fine.\ntype Compiled = { sql: string; slots: ParamSlot[] };\n\nconst newCtx = (): CompilationContext => ({\n resolvedPaths: new Map(),\n aliasMap: new Map(),\n paramSlots: [],\n paramCounter: { value: 0 },\n});\n\n// Every column the filter names maps to itself — a single-table statement\n// qualifies `table.column` fine. Only ever called on a filter\n// `assertFilterColumns` has already held to the table's real columns.\nconst indexFilterFields = (filter: Filter, aliasMap: Map<string, string>): void => {\n for (const path of filterColumns(filter)) aliasMap.set(path, path);\n};\n\n// A value that may be a `$lookup` compiles to a scalar subquery INLINE, into\n// the parent's own parameter counter and slot list — the same no-renumbering\n// rule EXISTS follows on the read side.\nconst compileValue = (v: MutationValue, ctx: CompilationContext): string => {\n if (isLookup(v)) {\n indexFilterFields(v.$lookup.where, ctx.aliasMap);\n const where = compileFilter(v.$lookup.where, ctx);\n return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;\n }\n return compileFieldOrValue(v, ctx);\n};\n\n// A value written into a json/jsonb column: the slot its context value binds\n// through is marked, so the array or object goes over the wire as JSON text.\nconst compileColumnValue = (table: string, column: string, v: MutationValue, ctx: CompilationContext, schema: DatabaseSchema): string => {\n const before = ctx.paramSlots.length;\n const sql = compileValue(v, ctx);\n const json = findEntity(table, schema)?.fields.find((f) => f.name === column)?.normalizedType === 'json';\n if (json && typeof v === 'object' && v !== null && '$context' in v) {\n const slot = ctx.paramSlots[before];\n if (slot !== undefined) ctx.paramSlots[before] = { ...slot, encode: 'json' };\n }\n return sql;\n};\n\nconst compileConflict = (m: { table: string; onConflict?: ResolvedOnConflict }, ctx: CompilationContext, schema: DatabaseSchema): string => {\n const c = m.onConflict;\n if (c === undefined) return '';\n if (c.set === undefined) return ` ON CONFLICT (${c.target.join(', ')}) DO NOTHING`;\n const sets = Object.entries(c.set).map(([col, v]) => `${col} = ${compileColumnValue(m.table, col, v, ctx, schema)}`);\n let where = '';\n if (c.where !== undefined) {\n indexFilterFields(c.where, ctx.aliasMap);\n where = ` WHERE ${compileFilter(c.where, ctx)}`;\n }\n return ` ON CONFLICT (${c.target.join(', ')}) DO UPDATE SET ${sets.join(', ')}${where}`;\n};\n\n// jsonb `->>` yields text; the cast restores the column's type so the INSERT\n// binds like any other. `json` columns keep `->` (stays jsonb, no cast).\nconst ITEM_CAST: Record<string, string> = {\n number: 'numeric',\n boolean: 'boolean',\n date: 'date',\n timestamp: 'timestamptz',\n uuid: 'uuid',\n};\n\n\nconst compileMutation = (m: ResolvedMutation, schema: DatabaseSchema): Compiled => {\n const ctx = newCtx();\n if (m.op === 'insert') {\n const entries = Object.entries(m.values);\n const cols = entries.map(([c]) => c);\n const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));\n return { sql: `INSERT INTO ${m.table} (${cols.join(', ')}) VALUES (${vals.join(', ')})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots };\n }\n if (m.op === 'insertEach') {\n const entity = findEntity(m.table, schema);\n const entries = Object.entries(m.values);\n const cols = entries.map(([c]) => c);\n const exprs = entries.map(([col, v]) => {\n if (isItemRef(v)) {\n const nt = entity?.fields.find((f) => f.name === col)?.normalizedType ?? 'string';\n if (nt === 'json') return `(item.value->${quoteLiteral(v.$item)})`;\n const cast = ITEM_CAST[nt];\n const raw = `(item.value->>${quoteLiteral(v.$item)})`;\n return cast === undefined ? raw : `${raw}::${cast}`;\n }\n return compileValue(v, ctx);\n });\n ctx.paramCounter.value += 1;\n ctx.paramSlots.push({ key: m.items.$context, kind: 'context', type: 'json' });\n const source = `jsonb_array_elements($${ctx.paramCounter.value}::jsonb) AS item`;\n return {\n sql: `INSERT INTO ${m.table} (${cols.join(', ')}) SELECT ${exprs.join(', ')} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,\n slots: ctx.paramSlots,\n };\n }\n if (m.op === 'update') {\n const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);\n indexFilterFields(m.where, ctx.aliasMap);\n const where = compileFilter(m.where, ctx);\n return { sql: `UPDATE ${m.table} SET ${sets.join(', ')} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };\n }\n indexFilterFields(m.where, ctx.aliasMap);\n const where = compileFilter(m.where, ctx);\n return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };\n};\n\n// ─── Desugar (sugar → core) ────────────────────────────────────\n// Rewrite each sugar op to a core insert/update/delete BEFORE context/scope/\n// validate/compile, so those stages only ever see the three primitives.\nconst SUGAR: { [K in Mutation['op']]?: (m: Extract<Mutation, { op: K }>, context: Record<string, unknown>) => CoreMutation } = {\n upsert: (m, context) => {\n const keyed = context[m.key] !== undefined && context[m.key] !== '';\n return keyed\n ? { op: 'update', table: m.table, set: m.columns, where: { eq: [`${m.table}.${m.key}`, { $context: m.key }] } }\n : { op: 'insert', table: m.table, values: { ...m.columns, ...m.insert } };\n },\n};\n\nconst desugarMutation = (m: Mutation, context: Record<string, unknown>): CoreMutation => {\n const rewrite = SUGAR[m.op] as ((m: Mutation, c: Record<string, unknown>) => CoreMutation) | undefined;\n return rewrite === undefined ? (m as CoreMutation) : rewrite(m, context);\n};\n\n// ─── Execute ───────────────────────────────────────────────────\nexport type MutationContext = {\n context: Record<string, unknown>; // dynamic values for `$context` refs (the caller's data)\n scope: ScopeValues; // server-injected values for `$scope` refs (identity / tenant)\n policy: ScopePolicy;\n schema: DatabaseSchema;\n};\n\n// One executed statement, named by what it did: the table, the op that\n// actually ran (post-desugar — an upsert reports the branch it took, an\n// insertEach reports 'insert' because that is what it is), and the rows the\n// database returned. This is the grain a write observer needs: a two-\n// statement mutation is two writes, each with its own rows.\nexport type WriteResult = { table: string; op: 'insert' | 'update' | 'delete'; rows: Row[] };\n\nexport const executeWrites = async (client: MutationClient, def: MutationDefinition, mctx: MutationContext): Promise<WriteResult[]> => {\n const parsed = MutationDefinitionSchema.parse(def);\n const entries = Array.isArray(parsed) ? parsed : [parsed];\n const compiled = entries.map((entry) => {\n const core = desugarMutation(entry, mctx.context);\n // A write never executes with holes: every `$context` the (desugared)\n // statement binds must be present. The error teaches the WHOLE contract.\n const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === undefined);\n if (missing.length > 0) {\n throw new VexError('missing_context', `Mutation is missing context: ${missing.join(', ')}.`, {\n expected: collectMutationContext(parsed, mctx.schema),\n });\n }\n const m = scopeMutation(core, mctx.policy);\n assertWritableColumns(m, mctx.schema);\n const statement = compileMutation(m, mctx.schema);\n // A `set` rule with no value would STAMP NULL — an insert owned by nobody,\n // written anyway. Every scope slot is filled or nothing runs.\n requireScope({ paramSlots: statement.slots }, mctx.scope);\n return { ...statement, table: m.table, op: (m.op === 'insertEach' ? 'insert' : m.op) as WriteResult['op'] };\n });\n\n const runAll = async (q: MutationTx): Promise<WriteResult[]> => {\n const results: WriteResult[] = [];\n for (const c of compiled) {\n const params = await resolveParams(c.slots, mctx.context, mctx.scope);\n // A `json` slot (insertEach items) is bound as a JSON string — drivers\n // would otherwise turn a JS array into a postgres ARRAY literal, which\n // `::jsonb` refuses. Anything but an array fails loudly here.\n const bound = params.map((value, i) => {\n if (c.slots[i]?.encode === 'json') return value !== null && typeof value === 'object' ? JSON.stringify(value) : value;\n if (c.slots[i]?.type !== 'json') return value;\n if (!Array.isArray(value)) {\n throw new VexError('invalid_request', `\"${c.slots[i]?.key ?? ''}\" must be an array of objects (one inserted row per element).`);\n }\n return JSON.stringify(value);\n });\n const res = await q.query(c.sql, bound as unknown[]);\n results.push({ table: c.table, op: c.op, rows: res.rows as Row[] });\n }\n return results;\n };\n\n // A batch runs atomically; a single write needs no transaction.\n if (compiled.length === 1) return runAll(client);\n if (client.transaction === undefined) {\n throw new VexError('execution_error', 'Batch mutations require a transactional client.');\n }\n return client.transaction((tx) => runAll(tx));\n};\n\n// The rows alone, statement order preserved — the shape every existing\n// caller wants when it does not care which statement returned what.\nexport const executeMutation = async (client: MutationClient, def: MutationDefinition, mctx: MutationContext): Promise<Row[]> =>\n (await executeWrites(client, def, mctx)).flatMap((w) => w.rows);\n","import { z } from 'zod';\nimport type { QueryEngine } from './types.js';\nimport type { ScopePolicy, ScopeValues } from './scope/scope.types.js';\nimport type { DatabaseSchema, EntitySchema } from './schemas/database.schema.js';\nimport { QueryRequestSchema } from './schemas/request.schema.js';\nimport { QuerySchema } from './schemas/query.schema.js';\nimport { isEntryFresh, isTouchDue, fireAndForget } from './cache/util.js';\nimport { computeSchemaFingerprint } from './cache/hash.js';\nimport { executeWrites } from './mutations/engine.js';\nimport type { MutationClient, WriteResult } from './mutations/engine.js';\nimport { collectMutationContext, collectQueryContext, mutationEffect } from './mutations/signature.js';\nimport type { ContextSignature, MutationEffect } from './mutations/signature.js';\nimport type { CacheEntry } from './cache/cache.types.js';\nimport type { QueryResponse } from './schemas/request.schema.js';\nimport type { Query } from './schemas/query.schema.js';\nimport { VexError } from './errors.js';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { canReadTable } from './scope/apply.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Types\n// ═══════════════════════════════════════════════════════════════\n\nexport type VexHandlerConfig = {\n engine: QueryEngine;\n entities?: string[];\n // Replay-only posture (production): requests needing generation fail\n // with 'locked'; fingerprint management (PATCH/DELETE) is refused too.\n // Mutation replay is unaffected — writes are ALWAYS replay-only.\n locked?: boolean;\n // Per-request read policy — overrides the engine default for reads on\n // this request (the read-side twin of `mutations.policy`). A host that\n // resolves a policy per principal passes the SAME policy here and in\n // `mutations.policy`, so reads and writes enforce one principal's phases.\n scopePolicy?: ScopePolicy;\n // Compiles the SAME principal's policy at a named reach, for entries that\n // declare one (`OkCacheEntry.reach`). Vex holds neither grants nor behaviors,\n // so it cannot build this itself — the host does, and returning `undefined`\n // refuses the read rather than serving it at the caller's own, wider reach.\n policyForReach?: (reach: string) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;\n // Enables replay of `kind: 'mutation'` cache entries. The client is\n // structural (PGlite, a pg wrapper, a test double); the policy is the\n // same ScopePolicy reads use, its `write` rules applied by the engine.\n mutations?: {\n client: MutationClient;\n policy: ScopePolicy;\n // The write observer. Fired once per successful mutation replay, AFTER\n // the commit — per-statement writes with the rows the database returned,\n // plus the scope the request could not forge. Vex is the choke point\n // every write passes through, so this is where a host learns about all\n // of them; what the host does with the news (mint facts, wake shells)\n // is not the engine's business. A listener that throws cannot unwrite\n // a committed write, so its error is contained, never the request's.\n onWrite?: (event: WriteEvent) => void;\n };\n // The execution observer — the read/write twin of `mutations.onWrite`, and\n // vex's whole telemetry surface. Fired once per `handleQuery`, AFTER the\n // outcome is known, with vex-vocabulary facts (fingerprint, reach, cache,\n // rows, status, timing) and the unforgeable scope. Vex knows nothing of spans\n // or OTLP; a host maps this record to whatever it emits. Absent → not even the\n // record is built (see `handleQuery`), so an unobserved endpoint pays nothing.\n // A listener that throws is contained, never the request's.\n onExecute?: (record: ExecuteRecord) => void;\n};\n\nexport type WriteEvent = { fingerprint: string; writes: WriteResult[]; scope: ScopeValues };\n\n// A CALLER THAT FOLLOWS THE ANSWER. In-process only: an HTTP request cannot\n// carry a callback, so a host that runs its own clients next to the handler\n// (moss's server shells) passes one here, and a reactive entry keeps\n// answering through it until `signal` aborts. See `refresh` on an entry.\nexport type VexLive = {\n signal: AbortSignal;\n onChange: (response: QueryResponse) => void;\n};\n\n// WHICH TABLES A WRITE CHANGED. The statements' own tables, plus — for a\n// delete — every table that references one of them, transitively: an\n// `ON DELETE CASCADE` or `SET NULL` changes rows vex never wrote. The\n// introspected schema carries the reference but not its rule, so a delete is\n// assumed to reach every referencing table. Over-telling costs a refetch;\n// under-telling leaves a screen stale.\nexport const tablesChangedBy = (writes: readonly WriteResult[], schema: DatabaseSchema | undefined): string[] => {\n const changed = new Set<string>();\n const referencing = (table: string): string[] =>\n (schema?.entities.find((entity) => entity.name === table)?.relations ?? [])\n .filter((relation) => relation.type !== 'belongsTo')\n .map((relation) => relation.entity);\n for (const write of writes) {\n if (write.rows.length === 0) continue;\n changed.add(write.table);\n if (write.op !== 'delete') continue;\n const pending = [write.table];\n for (let next = pending.pop(); next !== undefined; next = pending.pop()) {\n for (const table of referencing(next)) {\n if (changed.has(table)) continue;\n changed.add(table);\n pending.push(table);\n }\n }\n }\n return [...changed];\n};\n\n// What one execution DID, in vex's own vocabulary — the record `onExecute`\n// hands a host. Not a span: vex holds no telemetry model, so a host maps these\n// facts to whatever it emits. `startUnixNano`/`endUnixNano` are epoch nanos at\n// millisecond anchoring with a sub-millisecond monotonic span between them —\n// exact enough for durations, coarse in the low bits — copied through verbatim.\nexport type ExecuteRecord = {\n kind: 'query' | 'mutation';\n status: 'ok' | 'error' | 'refused';\n fingerprint?: string;\n reach?: string;\n // Reads: whether the entry was already compiled. Mutations always replay.\n cacheHit?: boolean;\n // Rows returned (reads) or written (mutations).\n rows?: number;\n startUnixNano: number;\n endUnixNano: number;\n // The scope the request could not forge, passed exactly as `onWrite` passes\n // it — for a host to read principal PRESENCE from, never a value into a span.\n scope: ScopeValues;\n};\n\n// The mutable half of the record, filled by `runQuery` as it goes and read once\n// by `handleQuery`. Built only when an observer is attached.\ntype ExecuteProbe = {\n kind: 'query' | 'mutation';\n fingerprint?: string;\n reach?: string;\n cacheHit?: boolean;\n rows?: number;\n};\n\nexport type DiscoveryFingerprint = {\n fingerprint: string;\n kind: 'query' | 'mutation';\n protected: boolean;\n schemaFresh: boolean;\n intent?: string;\n createdAt: number;\n lastUsedAt?: number;\n // The derived input contract: every `$context` key the stored def binds,\n // typed from the schema by its position. Computed, never authored.\n context?: ContextSignature;\n // Reads: the stored result shape. Mutations: what the write changes.\n shape?: unknown;\n effect?: MutationEffect[];\n};\n\nexport type DiscoveryResponse = {\n vex: string;\n description: string;\n entities: DiscoveryEntity[];\n // Governance summary + the endpoint's known queries — self-description\n // an agent (or a management UI) can read before generating anything.\n protection: 'all' | 'some' | 'none';\n locked: boolean;\n fingerprints: DiscoveryFingerprint[];\n query: {\n method: string;\n accepts: string;\n body: Record<string, DiscoveryField>;\n };\n dsl: object;\n};\n\ntype DiscoveryEntity = {\n name: string;\n fields: Array<{\n name: string;\n type: string;\n nullable: boolean;\n primaryKey: boolean;\n }>;\n relations: Array<{\n entity: string;\n type: string;\n via: string[];\n }>;\n rowCount?: number;\n};\n\ntype DiscoveryField = {\n type: string;\n required: boolean;\n description: string;\n};\n// (queryParams are gone — the request body carries all cache semantics.)\n\n// ═══════════════════════════════════════════════════════════════\n// Discovery\n// ═══════════════════════════════════════════════════════════════\n\nconst filterSchema = (schema: DatabaseSchema | undefined, entities?: string[]): EntitySchema[] => {\n if (schema === undefined) return [];\n if (entities === undefined || entities.length === 0) return schema.entities;\n return schema.entities.filter(e => entities.includes(e.name));\n};\n\n// ─── Visibility under a policy — discovery advertises only what the\n// policy can touch. These mirror the ENFORCEMENT semantics (applyScope /\n// scopeMutation) as pure predicates: a phase exists, is public, or falls\n// to the default. Enforcement still runs on every request; this only\n// keeps the catalog honest per principal. ───────────────────────\nconst canWriteTable = (policy: ScopePolicy, table: string, op: string): boolean => {\n const rule = policy.entities[table];\n if (rule === undefined) return policy.default === 'allow';\n if ('public' in rule) return true;\n if ('deny' in rule) return false;\n if (rule.write !== undefined || policy.default === 'allow') return true;\n // insertEach is an insert that happens N times — same phase.\n if (op === 'insert' || op === 'insertEach') return rule.insert !== undefined;\n if (op === 'update') return rule.update !== undefined;\n if (op === 'delete') return rule.delete !== undefined;\n // upsert desugars to insert or update per call — advertise if either exists\n if (op === 'upsert') return rule.insert !== undefined || rule.update !== undefined;\n return false;\n};\n\n// Every table a read touches — string sources, recursing into subquery\n// sources (`{ as, query }`).\nconst collectTables = (dsl: Query): string[] => {\n const out: string[] = [];\n const walk = (q: Query): void => {\n for (const src of q.from) {\n if (typeof src === 'string') out.push(src);\n else walk(src.query);\n }\n };\n walk(dsl);\n return out;\n};\n\nconst entryVisible = (policy: ScopePolicy, entry: CacheEntry): boolean => {\n if (entry.kind === 'ok') return collectTables(entry.dsl).every((t) => canReadTable(policy, t));\n if (entry.kind === 'mutation') return mutationEffect(entry.mutation).every((e) => canWriteTable(policy, e.table, e.op));\n return false;\n};\n\nconst listFingerprints = async (engine: QueryEngine, policy?: ScopePolicy): Promise<DiscoveryFingerprint[]> => {\n if (engine.cache.entries === undefined) return [];\n const schema = engine.getSchema();\n const current = schema !== undefined ? computeSchemaFingerprint(schema) : undefined;\n const rows = await engine.cache.entries();\n return rows\n .filter(({ key, entry }) => (entry.kind === 'ok' || entry.kind === 'mutation') && !key.startsWith('neg:'))\n .filter(({ entry }) => policy === undefined || entryVisible(policy, entry))\n .map(({ key, entry }) => ({\n fingerprint: key,\n kind: entry.kind === 'mutation' ? ('mutation' as const) : ('query' as const),\n protected: entry.protected === true,\n schemaFresh: isEntryFresh(entry, current),\n ...(entry.intent !== undefined ? { intent: entry.intent } : {}),\n createdAt: entry.createdAt,\n ...(entry.lastUsedAt !== undefined ? { lastUsedAt: entry.lastUsedAt } : {}),\n // The derived contract — what to pass, straight from the stored def.\n ...(entry.kind === 'ok'\n ? {\n context: collectQueryContext(entry.dsl, schema),\n ...(entry.shape !== undefined ? { shape: entry.shape } : {}),\n }\n : entry.kind === 'mutation'\n ? {\n context: collectMutationContext(entry.mutation, schema),\n effect: mutationEffect(entry.mutation),\n }\n : {}),\n }));\n};\n\nexport const handleDiscovery = async (config: VexHandlerConfig): Promise<DiscoveryResponse> => {\n const { engine, entities: entityFilter, scopePolicy } = config;\n // Under a scopePolicy, discovery is per-principal: entities and entries\n // the policy cannot touch are not advertised (what you can't reach\n // doesn't exist for you — deny by absence, in the catalog too).\n const filtered = filterSchema(engine.getSchema(), entityFilter).filter(\n (e) => scopePolicy === undefined || canReadTable(scopePolicy, e.name),\n );\n const fingerprints = await listFingerprints(engine, scopePolicy);\n const protectedCount = fingerprints.filter((f) => f.protected).length;\n\n return {\n protection: protectedCount === 0 ? 'none' : protectedCount === fingerprints.length ? 'all' : 'some',\n locked: config.locked === true,\n fingerprints,\n vex: '1.0',\n description: 'Query this resource using natural language or structured DSL',\n entities: filtered.map(e => ({\n name: e.name,\n fields: e.fields.map(f => ({\n name: f.name,\n type: f.normalizedType,\n nullable: f.nullable,\n primaryKey: f.primaryKey,\n })),\n relations: e.relations.map(r => ({\n entity: r.entity,\n type: r.type,\n via: r.localFields,\n })),\n rowCount: e.rowCount,\n })),\n query: {\n method: 'POST',\n accepts: 'application/json',\n body: {\n fingerprint: {\n type: 'string',\n required: false,\n description:\n 'Cache identity. Alone → replay a known query (no generation). With intent+shape → a named slot: ' +\n 'matching request hits, differing request regenerates and replaces (409 when protected). ' +\n 'Omitted → generate fresh; the minted fingerprint returns in meta.cache.fingerprint.',\n },\n intent: {\n type: 'string',\n required: false,\n description: 'Natural language description of what data you need',\n },\n shape: {\n type: 'any',\n required: false,\n description: 'Example of the response structure — use empty strings, zeros, booleans as type indicators. Required unless replaying by fingerprint.',\n },\n context: {\n type: 'Record<string, unknown>',\n required: false,\n description: 'Runtime parameters referenced in filters as { $context: \"key\" }',\n },\n },\n },\n dsl: z.toJSONSchema(QuerySchema, { target: 'draft-7', reused: 'ref' }),\n };\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Query execution\n// ═══════════════════════════════════════════════════════════════\n\nexport type QueryResult = {\n status: number;\n body: unknown;\n};\n\n// Rows an execution touched, for the observer's `rows` — an array's length, a\n// single object as one, nothing as zero. Never inspects the values.\nconst rowsOf = (result: unknown): number =>\n Array.isArray(result) ? result.length : result === null || result === undefined ? 0 : 1;\n\nexport const handleQuery = async (\n config: VexHandlerConfig,\n body: unknown,\n scope: ScopeValues,\n live?: VexLive,\n): Promise<QueryResult> => {\n // Unobserved: the fast path builds no probe, takes no timestamps, allocates\n // no record. An endpoint with no telemetry pays exactly nothing.\n if (config.onExecute === undefined) return runQuery(config, body, scope, undefined, live);\n\n const startUnixNano = Date.now() * 1e6;\n const t0 = elapsedClock();\n const probe: ExecuteProbe = { kind: 'query' };\n const result = await runQuery(config, body, scope, probe, live);\n const record: ExecuteRecord = {\n kind: probe.kind,\n // 200 succeeded; 403 is a policy/reach refusal (a normal outcome, not a\n // fault); everything else is an error.\n status: result.status === 200 ? 'ok' : result.status === 403 ? 'refused' : 'error',\n startUnixNano,\n endUnixNano: startUnixNano + (elapsedClock() - t0) * 1e6,\n scope,\n ...(probe.fingerprint !== undefined ? { fingerprint: probe.fingerprint } : {}),\n ...(probe.reach !== undefined ? { reach: probe.reach } : {}),\n ...(probe.cacheHit !== undefined ? { cacheHit: probe.cacheHit } : {}),\n ...(probe.rows !== undefined ? { rows: probe.rows } : {}),\n };\n try {\n config.onExecute(record);\n } catch (err) {\n console.error('[vex:onExecute]', err);\n }\n return result;\n};\n\n// Sub-millisecond monotonic reading in milliseconds. `performance` is present\n// on every runtime vex targets; the wall clock is the fallback that keeps the\n// duration honest (0) rather than throwing where it is not.\nconst elapsedClock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nconst runQuery = async (\n config: VexHandlerConfig,\n body: unknown,\n scope: ScopeValues,\n probe: ExecuteProbe | undefined,\n live: VexLive | undefined,\n): Promise<QueryResult> => {\n const { engine } = config;\n\n // Before the schema: a deep enough body overflows it (strata depth.ts).\n if (exceedsDepth(body)) return { status: 400, body: { error: 'invalid_request', message: depthRefusal() } };\n const parsed = QueryRequestSchema.safeParse(body);\n if (!parsed.success) {\n return {\n status: 400,\n body: {\n error: 'invalid_request',\n message: parsed.error.message,\n },\n };\n }\n\n const hasShape = parsed.data.shape !== undefined && parsed.data.shape !== null;\n if (!hasShape && parsed.data.fingerprint === undefined) {\n return {\n status: 400,\n body: {\n error: 'invalid_request',\n message: 'Pass a fingerprint (replay) or intent + shape (generate) — or both (named slot).',\n },\n };\n }\n\n // Recorded before anything can refuse, so a refusal span still carries the\n // fingerprint it refused. A read that mints one overwrites this from meta.\n if (probe !== undefined && parsed.data.fingerprint !== undefined) probe.fingerprint = parsed.data.fingerprint;\n\n try {\n // ONE wire shape: `{ fingerprint, context }`. The entry's kind decides\n // the pipeline — a mutation fingerprint replays the write path; anything\n // else is the read path (which owns misses, generation, and locked).\n let entryReach: string | undefined;\n if (parsed.data.fingerprint !== undefined) {\n const entry = await engine.cache.get(parsed.data.fingerprint);\n if (entry !== undefined && entry.kind === 'ok') entryReach = entry.reach;\n if (probe !== undefined && entryReach !== undefined) probe.reach = entryReach;\n if (entry !== undefined && entry.kind === 'mutation') {\n if (probe !== undefined) {\n probe.kind = 'mutation';\n if (entry.reach !== undefined) probe.reach = entry.reach;\n }\n if (config.mutations === undefined) {\n return {\n status: 500,\n body: { error: 'execution_error', message: 'This endpoint serves no mutations — handler has no mutation client configured.' },\n };\n }\n const schema = engine.getSchema();\n if (schema === undefined) {\n return { status: 500, body: { error: 'execution_error', message: 'Vex schema not introspected.' } };\n }\n // A WRITE MAY DEMAND A NARROWER REACH TOO, and the stakes are higher\n // than for a read: too wide here changes somebody else's row rather\n // than merely showing it.\n let writePolicy = config.mutations.policy;\n if (entry.reach !== undefined) {\n if (config.policyForReach === undefined) {\n return {\n status: 500,\n body: {\n error: 'execution_error',\n message: `Entry \"${parsed.data.fingerprint ?? ''}\" requires reach \"${entry.reach}\" and this handler has no policyForReach.`,\n },\n };\n }\n const narrowed = await config.policyForReach(entry.reach);\n if (narrowed === undefined) {\n return {\n status: 403,\n body: { error: 'scope_denied', message: `Reach \"${entry.reach}\" is not available to this principal.` },\n };\n }\n writePolicy = narrowed;\n }\n\n const writes = await executeWrites(config.mutations.client, entry.mutation, {\n context: parsed.data.context,\n scope,\n policy: writePolicy,\n schema,\n });\n const rows = writes.flatMap((w) => w.rows);\n // Every reactive read over these tables is now stale. Here, not in\n // any host's observer: this is the one door every vex write passes —\n // a request, a server function's `executeAs`, a reflex's effect — and\n // a read that heard about only some of them would be live only\n // sometimes, which is worse than a snapshot that says what it is.\n engine.invalidate(tablesChangedBy(writes, schema));\n // The commit happened; the observer hears about it now, and its\n // failure is its own — the response must tell the truth about a\n // write that already landed.\n if (config.mutations.onWrite !== undefined) {\n try {\n config.mutations.onWrite({ fingerprint: parsed.data.fingerprint, writes, scope });\n } catch (err) {\n console.error('[vex:onWrite]', err);\n }\n }\n // Lifetime = usage, for writes exactly as for reads: stamp\n // lastUsedAt (off the hot path, at most once per TOUCH_EVERY_MS) so\n // the GC sweep sees replays.\n const now = Date.now();\n if (isTouchDue(entry, now)) fireAndForget(engine.cache.set(parsed.data.fingerprint, { ...entry, lastUsedAt: now }));\n if (probe !== undefined) probe.rows = rows.length;\n // A single statement returns its one affected row; a batch returns\n // the array — the same `{ result }` envelope a query reply uses.\n return { status: 200, body: { result: rows.length === 1 ? rows[0] : rows } };\n }\n }\n\n // AN ENTRY MAY REQUIRE A NARROWER REACH THAN ITS CALLER HAS.\n //\n // \"The classes you have booked\" means the caller's own, and a principal\n // holding two roles reaches as wide as either grants. So the entry names\n // the profile it must be served at and the host recompiles the same grants\n // under it — narrowing rows, never widening verbs.\n //\n // Fail closed: a declared reach the host cannot compile refuses the read.\n // Serving it at the caller's own reach is the exact failure the field\n // exists to prevent, and it would be invisible.\n let readPolicy = config.scopePolicy;\n if (entryReach !== undefined) {\n if (config.policyForReach === undefined) {\n return {\n status: 500,\n body: {\n error: 'execution_error',\n message: `Entry \"${parsed.data.fingerprint ?? ''}\" requires reach \"${entryReach}\" and this handler has no policyForReach.`,\n },\n };\n }\n readPolicy = await config.policyForReach(entryReach);\n if (readPolicy === undefined) {\n return {\n status: 403,\n body: { error: 'scope_denied', message: `Reach \"${entryReach}\" is not available to this principal.` },\n };\n }\n }\n\n const response = await engine.execute(parsed.data, {\n scope,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n ...(readPolicy !== undefined ? { scopePolicy: readPolicy } : {}),\n ...(live !== undefined ? { signal: live.signal, onChange: live.onChange } : {}),\n });\n if (probe !== undefined) {\n probe.cacheHit = response.meta.cache.hit;\n // The identity actually served — the caller's replay key, or the one just\n // minted for a miss.\n if (response.meta.cache.fingerprint !== undefined) probe.fingerprint = response.meta.cache.fingerprint;\n probe.rows = rowsOf(response.result);\n }\n return { status: 200, body: response };\n } catch (err) {\n // The host did not say who is asking. That is the server's fault, not the\n // request's, and the names of the missing keys are the host's business —\n // they go to the log, not over the wire.\n if (err instanceof VexError && err.code === 'missing_scope') {\n console.error('[vex] refused a statement the host did not scope:', err.message);\n return { status: 500, body: { error: 'missing_scope', message: 'The server did not supply the scope this request needs.' } };\n }\n if (err instanceof VexError) {\n const status = err.code === 'fingerprint_protected' ? 409 : err.code === 'cache_miss' ? 404 : 400;\n return {\n status,\n body: {\n error: err.code,\n message: err.message,\n details: err.details,\n },\n };\n }\n console.error('[vex] unhandled error:', err);\n const errObj = err as Record<string, unknown> | null;\n const message = err instanceof Error\n ? err.message\n : (typeof errObj?.message === 'string' ? errObj.message : 'Unknown error');\n const code = typeof errObj?.code === 'string' ? errObj.code : 'execution_error';\n return {\n status: 500,\n body: { error: code, message },\n };\n }\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Fingerprint management — protect (PATCH) and evict (DELETE).\n// The ONLY writers of the `protected` bit besides the seed path.\n// ═══════════════════════════════════════════════════════════════\n\nexport const handleFingerprintPatch = async (\n config: VexHandlerConfig,\n fingerprint: string,\n patch: { protected?: boolean },\n): Promise<QueryResult> => {\n if (config.locked === true) {\n return { status: 403, body: { error: 'locked', message: 'This endpoint is locked — fingerprints cannot be managed here.' } };\n }\n const entry = await config.engine.cache.get(fingerprint);\n if (entry === undefined || (entry.kind !== 'ok' && entry.kind !== 'mutation')) {\n return { status: 404, body: { error: 'cache_miss', message: `Unknown fingerprint \"${fingerprint}\"` } };\n }\n if (typeof patch.protected !== 'boolean') {\n return { status: 400, body: { error: 'invalid_request', message: 'Body must be { protected: boolean }' } };\n }\n await config.engine.cache.set(fingerprint, { ...entry, protected: patch.protected });\n return { status: 200, body: { fingerprint, protected: patch.protected } };\n};\n\nexport const handleFingerprintDelete = async (\n config: VexHandlerConfig,\n fingerprint: string,\n): Promise<QueryResult> => {\n if (config.locked === true) {\n return { status: 403, body: { error: 'locked', message: 'This endpoint is locked — fingerprints cannot be managed here.' } };\n }\n const entry = await config.engine.cache.get(fingerprint);\n if (entry === undefined) {\n return { status: 404, body: { error: 'cache_miss', message: `Unknown fingerprint \"${fingerprint}\"` } };\n }\n if ((entry.kind === 'ok' || entry.kind === 'mutation') && entry.protected === true) {\n return { status: 409, body: { error: 'fingerprint_protected', message: `\"${fingerprint}\" is protected — unprotect it first.` } };\n }\n await config.engine.cache.delete(fingerprint);\n return { status: 200, body: { fingerprint, deleted: true } };\n};\n","import type { QueryEngine } from '../../types.js';\nimport type { ScopeValues } from '../../scope/scope.types.js';\nimport type { VexHandlerConfig } from '../../handler.js';\nimport { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../handler.js';\n\n// Minimal structural types — Express.Request/Response satisfy these\n// without requiring express as a runtime dependency.\n\nexport type VexExpressRequest = {\n method: string;\n body: unknown;\n query: Record<string, unknown>;\n};\n\nexport type VexExpressResponse = {\n json(body: unknown): unknown;\n status(code: number): VexExpressResponse;\n};\n\nexport type VexExpressConfig<TReq extends VexExpressRequest = VexExpressRequest> = {\n engine: QueryEngine;\n entities?: string[];\n // Replay-only posture: no generation, no fingerprint management.\n // (Writes are unaffected — mutation replay is always replay-only.)\n locked?: boolean;\n getScope?: (req: TReq) => Promise<ScopeValues> | ScopeValues;\n // Enables replay of `kind: 'mutation'` cache entries on this endpoint.\n mutations?: VexHandlerConfig['mutations'];\n};\n\n// Fingerprints may contain '/' (named slots like \"deals/table\"), so\n// management rides the request BODY, not the path.\nconst fingerprintFromBody = (body: unknown): string | undefined => {\n if (body === null || typeof body !== 'object') return undefined;\n const fp = (body as Record<string, unknown>)['fingerprint'];\n return typeof fp === 'string' && fp.length > 0 ? fp : undefined;\n};\n\nexport const vex = <TReq extends VexExpressRequest = VexExpressRequest>(\n config: VexExpressConfig<TReq>,\n): ((req: TReq, res: VexExpressResponse) => Promise<void>) => {\n const handlerConfig = {\n engine: config.engine,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n ...(config.mutations !== undefined ? { mutations: config.mutations } : {}),\n };\n\n return async (req: TReq, res: VexExpressResponse): Promise<void> => {\n if (req.method === 'GET') {\n res.json(await handleDiscovery(handlerConfig));\n return;\n }\n\n if (req.method === 'POST') {\n const scope = config.getScope ? await config.getScope(req) : {};\n const result = await handleQuery(handlerConfig, req.body, scope);\n res.status(result.status).json(result.body);\n return;\n }\n\n if (req.method === 'PATCH') {\n const fingerprint = fingerprintFromBody(req.body);\n if (fingerprint === undefined) {\n res.status(400).json({ error: 'invalid_request', message: 'Body must include { fingerprint }' });\n return;\n }\n const wanted = (req.body as Record<string, unknown>)['protected'];\n const result = await handleFingerprintPatch(handlerConfig, fingerprint, {\n ...(typeof wanted === 'boolean' ? { protected: wanted } : {}),\n });\n res.status(result.status).json(result.body);\n return;\n }\n\n if (req.method === 'DELETE') {\n const fingerprint = fingerprintFromBody(req.body);\n if (fingerprint === undefined) {\n res.status(400).json({ error: 'invalid_request', message: 'Body must include { fingerprint }' });\n return;\n }\n const result = await handleFingerprintDelete(handlerConfig, fingerprint);\n res.status(result.status).json(result.body);\n return;\n }\n\n res.status(405).json({\n error: 'method_not_allowed',\n message: 'GET discovery · POST query · PATCH/DELETE fingerprint management',\n });\n };\n};\n"]}