@niscorp/vex 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/DESIGN.md +30 -14
  3. package/DOCS.md +65 -13
  4. package/dist/adapters/express/index.cjs +7 -25
  5. package/dist/adapters/express/index.cjs.map +1 -1
  6. package/dist/adapters/express/index.d.cts +3 -2
  7. package/dist/adapters/express/index.d.ts +3 -2
  8. package/dist/adapters/express/index.js +3 -2
  9. package/dist/adapters/express/index.js.map +1 -1
  10. package/dist/adapters/hono/index.cjs +7 -25
  11. package/dist/adapters/hono/index.cjs.map +1 -1
  12. package/dist/adapters/hono/index.d.cts +3 -2
  13. package/dist/adapters/hono/index.d.ts +3 -2
  14. package/dist/adapters/hono/index.js +3 -2
  15. package/dist/adapters/hono/index.js.map +1 -1
  16. package/dist/adapters/pglite/index.cjs.map +1 -1
  17. package/dist/adapters/pglite/index.js.map +1 -1
  18. package/dist/agent/index.cjs +9 -14
  19. package/dist/agent/index.cjs.map +1 -1
  20. package/dist/agent/index.d.cts +3 -2
  21. package/dist/agent/index.d.ts +3 -2
  22. package/dist/agent/index.js +8 -9
  23. package/dist/agent/index.js.map +1 -1
  24. package/dist/{chunk-IQM4SQE2.js → chunk-7F2OH4IP.js} +8 -22
  25. package/dist/chunk-7F2OH4IP.js.map +1 -0
  26. package/dist/chunk-F7RDSWYF.js +7 -0
  27. package/dist/chunk-F7RDSWYF.js.map +1 -0
  28. package/dist/{chunk-H4BHW76Q.js → chunk-UPQMKAAX.js} +6 -24
  29. package/dist/chunk-UPQMKAAX.js.map +1 -0
  30. package/dist/chunk-XTOK7YOR.js +18 -0
  31. package/dist/chunk-XTOK7YOR.js.map +1 -0
  32. package/dist/{handler-BGCL6_Si.d.ts → handler-Bw7xVmBM.d.ts} +2 -1
  33. package/dist/{handler-CMrjTXNx.d.cts → handler-Cy0gNM6K.d.cts} +2 -1
  34. package/dist/index.cjs +44 -90
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +17 -63
  37. package/dist/index.d.ts +17 -63
  38. package/dist/index.js +46 -74
  39. package/dist/index.js.map +1 -1
  40. package/dist/migrations/index.cjs +173 -0
  41. package/dist/migrations/index.cjs.map +1 -0
  42. package/dist/migrations/index.d.cts +20 -0
  43. package/dist/migrations/index.d.ts +20 -0
  44. package/dist/migrations/index.js +23 -0
  45. package/dist/migrations/index.js.map +1 -0
  46. package/dist/query.schema-B-LVNfyX.d.cts +461 -0
  47. package/dist/query.schema-B-LVNfyX.d.ts +461 -0
  48. package/dist/{types-Bi-Lg86b.d.cts → types-Bs_9VM9p.d.ts} +16 -583
  49. package/dist/{types-Bi-Lg86b.d.ts → types-DO-rYZci.d.cts} +16 -583
  50. package/package.json +17 -7
  51. package/dist/chunk-H4BHW76Q.js.map +0 -1
  52. package/dist/chunk-IQM4SQE2.js.map +0 -1
@@ -0,0 +1,18 @@
1
+ // src/errors.ts
2
+ var VEX_ERROR = /* @__PURE__ */ Symbol.for("@niscorp/vex:VexError");
3
+ var VexError = class extends Error {
4
+ code;
5
+ details;
6
+ constructor(code, message, details) {
7
+ super(message);
8
+ this.name = "VexError";
9
+ this.code = code;
10
+ this.details = details;
11
+ }
12
+ };
13
+ Object.defineProperty(VexError.prototype, VEX_ERROR, { value: true });
14
+ var isVexError = (err) => err instanceof VexError || err instanceof Error && Reflect.get(err, VEX_ERROR) === true;
15
+
16
+ export { VexError, isVexError };
17
+ //# sourceMappingURL=chunk-XTOK7YOR.js.map
18
+ //# sourceMappingURL=chunk-XTOK7YOR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AAKA,IAAM,SAAA,mBAAY,MAAA,CAAO,GAAA,CAAI,uBAAuB,CAAA;AAE7C,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EACzB,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAsB,OAAA,EAAiB,OAAA,EAAmC;AACpF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF;AAEA,MAAA,CAAO,eAAe,QAAA,CAAS,SAAA,EAAW,WAAW,EAAE,KAAA,EAAO,MAAM,CAAA;AAE7D,IAAM,UAAA,GAAa,CAAC,GAAA,KACzB,GAAA,YAAe,QAAA,IAAa,GAAA,YAAe,KAAA,IAAS,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,SAAS,CAAA,KAAM","file":"chunk-XTOK7YOR.js","sourcesContent":["import type { QueryErrorCode } from './schemas/request.schema.js';\n\n// The CommonJS build gives each entry point its own copy of this class, and an\n// app can load the ESM and CommonJS builds side by side, so `instanceof` fails\n// across copies. Every copy marks its prototype under this process-wide key.\nconst VEX_ERROR = Symbol.for('@niscorp/vex:VexError');\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\nObject.defineProperty(VexError.prototype, VEX_ERROR, { value: true });\n\nexport const isVexError = (err: unknown): err is VexError =>\n err instanceof VexError || (err instanceof Error && Reflect.get(err, VEX_ERROR) === true);\n"]}
@@ -1,4 +1,5 @@
1
- import { al as ScopeValues, S as ScopePolicy, D as DatabaseSchema, f as Row, M as MutationDefinition, N as Mutation, b as Query, u as CoreMutation, a as QueryEngine, a0 as QueryResponse } from './types-Bi-Lg86b.js';
1
+ import { aa as ScopeValues, S as ScopePolicy, D as DatabaseSchema, e as Row, M as MutationDefinition, u as Mutation, m as CoreMutation, a as QueryEngine, T as QueryResponse } from './types-Bs_9VM9p.js';
2
+ import { Q as Query } from './query.schema-B-LVNfyX.js';
2
3
 
3
4
  type MutationTx = {
4
5
  query: (sql: string, params?: unknown[]) => Promise<{
@@ -1,4 +1,5 @@
1
- import { al as ScopeValues, S as ScopePolicy, D as DatabaseSchema, f as Row, M as MutationDefinition, N as Mutation, b as Query, u as CoreMutation, a as QueryEngine, a0 as QueryResponse } from './types-Bi-Lg86b.cjs';
1
+ import { aa as ScopeValues, S as ScopePolicy, D as DatabaseSchema, e as Row, M as MutationDefinition, u as Mutation, m as CoreMutation, a as QueryEngine, T as QueryResponse } from './types-DO-rYZci.cjs';
2
+ import { Q as Query } from './query.schema-B-LVNfyX.cjs';
2
3
 
3
4
  type MutationTx = {
4
5
  query: (sql: string, params?: unknown[]) => Promise<{
package/dist/index.cjs CHANGED
@@ -14,11 +14,6 @@ var ContextSchema = zod.z.object({
14
14
  '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.'
15
15
  );
16
16
  var QueryRequestSchema = zod.z.object({
17
- // The ONE cache identity. Server-minted (`fp_…`) when absent — returned in
18
- // meta.cache.fingerprint, an immutable pin. Caller-chosen strings are
19
- // mutable named slots: the name is yours, its content follows your request.
20
- // Alone → replay-or-error. With intent/shape → hit when the stored request
21
- // matches, regenerate-and-replace when it differs (409 when protected).
22
17
  fingerprint: zod.z.string().min(1).optional(),
23
18
  intent: zod.z.string().optional(),
24
19
  shape: zod.z.unknown().optional(),
@@ -94,12 +89,9 @@ var FilterSchema = zod.z.lazy(
94
89
  zod.z.object({
95
90
  optional: zod.z.object({
96
91
  key: zod.z.union([zod.z.string().min(1), zod.z.array(zod.z.string().min(1)).min(1)]).describe("The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both \u2014 gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply."),
97
- // BARE, never `.describe()`d. That call CLONES the schema, and zod
98
- // detects a recursive reference by instance identity — a clone is a
99
- // different instance, so `to-json-schema` stops seeing the cycle and
100
- // expands the filter union into itself until the stack goes. Every
101
- // other recursive slot here (`not`, `and`, `or`) uses it bare for the
102
- // same reason; the description belongs on the wrapper below.
92
+ // Bare, never `.describe()`d: that call clones the schema, and zod's
93
+ // to-json-schema detects recursion by instance identity, so a clone
94
+ // expands the filter union into itself until the stack overflows.
103
95
  then: FilterSchema
104
96
  }).strict()
105
97
  }).strict().describe(
@@ -1507,13 +1499,9 @@ var computeSchemaFingerprint = (schema) => {
1507
1499
  primaryKey: f.primaryKey,
1508
1500
  ...f.vectorDimensions !== void 0 ? { vectorDimensions: f.vectorDimensions } : {}
1509
1501
  })),
1510
- // Column order within a relation is the key's own order, so it is
1511
- // preserved; relations are sorted by target and columns. This shape
1512
- // changed when keys became composite, so every entry cached before
1513
- // revalidates once on the next boot — the drift eviction, by design.
1502
+ // Column order within a relation is the key's own order, so it is not sorted.
1514
1503
  relations: [...e.relations].sort((a, b) => `${a.entity}.${a.localFields.join(",")}`.localeCompare(`${b.entity}.${b.localFields.join(",")}`)).map((r) => ({ type: r.type, entity: r.entity, localFields: r.localFields, foreignFields: r.foreignFields })),
1515
- // Index field order is significant (composite indexes) and stable
1516
- // from introspection, so it is preserved; indexes are sorted by name.
1504
+ // Index field order is significant (composite indexes) and stable from introspection.
1517
1505
  indexes: [...e.indexes].sort(byName).map((i) => ({
1518
1506
  name: i.name,
1519
1507
  fields: i.fields,
@@ -1892,12 +1880,12 @@ var createQueryEngine = (engineConfig) => {
1892
1880
  const now = Date.now();
1893
1881
  if (isTouchDue(entry, now)) fireAndForget(cache.set(key, { ...entry, lastUsedAt: now }));
1894
1882
  };
1895
- const resolveFingerprint = async (validRequest, hasRequest, requestHash) => {
1883
+ const resolveFingerprint = async (validRequest, hasRequest, requestHash, scope) => {
1896
1884
  const fp = validRequest.fingerprint;
1897
1885
  if (fp === void 0) {
1898
1886
  return { fingerprint: mintFingerprint(), hit: false, replaced: false };
1899
1887
  }
1900
- const entry = await cache.get(fp);
1888
+ const entry = await cache.get(fp, scope);
1901
1889
  if (entry?.kind === "mutation") {
1902
1890
  throw new VexError(
1903
1891
  "invalid_request",
@@ -2001,6 +1989,7 @@ var createQueryEngine = (engineConfig) => {
2001
1989
  let result = rows;
2002
1990
  let mappingMs;
2003
1991
  let mappedIr = cachedIr;
1992
+ let mappedConfig;
2004
1993
  if (validRequest.shape !== void 0) {
2005
1994
  if (cachedIr !== void 0) {
2006
1995
  const mapStart = Date.now();
@@ -2012,10 +2001,11 @@ var createQueryEngine = (engineConfig) => {
2012
2001
  mappingMs = Date.now() - mapStart;
2013
2002
  result = mapped.transformed;
2014
2003
  mappedIr = mapped.ir;
2004
+ mappedConfig = mapped.config;
2015
2005
  }
2016
2006
  if (mappingMs !== void 0) emit({ type: "query.mapped", mappingMs });
2017
2007
  }
2018
- return { result, rowCount: rows.length, executionMs, mappingMs, mappedIr };
2008
+ return { result, rowCount: rows.length, executionMs, mappingMs, mappedIr, ...mappedConfig !== void 0 ? { mappedConfig } : {} };
2019
2009
  };
2020
2010
  const execute = async (request, options) => {
2021
2011
  if (strata.exceedsDepth(request)) throw new VexError("invalid_request", `Invalid request: ${strata.depthRefusal()}`);
@@ -2041,7 +2031,7 @@ var createQueryEngine = (engineConfig) => {
2041
2031
  fingerprint: validRequest.fingerprint,
2042
2032
  entities: options?.entities
2043
2033
  });
2044
- const cached = await resolveFingerprint(validRequest, hasRequest, requestHash);
2034
+ const cached = await resolveFingerprint(validRequest, hasRequest, requestHash, scope);
2045
2035
  emit({ type: "query.cache", hit: cached.hit, fingerprint: cached.fingerprint, replaced: cached.replaced });
2046
2036
  let dsl = cached.dsl;
2047
2037
  let agentMs;
@@ -2128,7 +2118,7 @@ var createQueryEngine = (engineConfig) => {
2128
2118
  emit({ type: "query.done", totalMs: Date.now() - t0 });
2129
2119
  return { result: result2, meta: { ...metaOf(rows.length), timing: { executionMs: executionMs2 } } };
2130
2120
  }
2131
- const { result, rowCount, executionMs, mappingMs, mappedIr } = await executeAndMap(
2121
+ const { result, rowCount, executionMs, mappingMs, mappedIr, mappedConfig } = await executeAndMap(
2132
2122
  compiled,
2133
2123
  effectiveRequest,
2134
2124
  cached.cachedIr,
@@ -2143,6 +2133,7 @@ var createQueryEngine = (engineConfig) => {
2143
2133
  kind: "ok",
2144
2134
  dsl,
2145
2135
  ...mappedIr !== void 0 ? { prismIr: mappedIr } : {},
2136
+ ...mappedConfig !== void 0 ? { mapping: mappedConfig } : {},
2146
2137
  createdAt: now,
2147
2138
  lastUsedAt: now,
2148
2139
  ...requestHash !== void 0 ? { requestHash } : {},
@@ -2538,8 +2529,7 @@ var compileFilter = (filter, ctx) => {
2538
2529
  const inner = {
2539
2530
  ...ctx,
2540
2531
  resolvedPaths: resolved.filter?.resolvedPaths ?? ctx.resolvedPaths,
2541
- // The inner map LAYERS OVER the outer one, so an inner path resolves to
2542
- // the inner alias and an outer path — the correlation — still resolves.
2532
+ // Inner over outer: an outer path, the correlation, still resolves.
2543
2533
  aliasMap: new Map([...ctx.aliasMap, ...resolved.aliasMap])
2544
2534
  };
2545
2535
  const parts = ["SELECT 1"];
@@ -2726,7 +2716,14 @@ var compileAggregate = (expr, ctx) => {
2726
2716
  // src/adapters/postgres/compile.ts
2727
2717
  var compileQuery = (resolved) => {
2728
2718
  const paramSlots = [];
2729
- const paramCounter = { value: 0 };
2719
+ const sql = compileLevel(resolved, paramSlots, { value: 0 });
2720
+ const contextContract = {};
2721
+ for (const slot of paramSlots) {
2722
+ contextContract[slot.key] = { type: slot.type, kind: slot.kind };
2723
+ }
2724
+ return { sql, paramSlots, contextContract };
2725
+ };
2726
+ var compileLevel = (resolved, paramSlots, paramCounter) => {
2730
2727
  const ctx = {
2731
2728
  resolvedPaths: resolved.filter?.resolvedPaths ?? /* @__PURE__ */ new Map(),
2732
2729
  aliasMap: resolved.aliasMap,
@@ -2750,15 +2747,7 @@ var compileQuery = (resolved) => {
2750
2747
  const expr = compileAggregate(a.expression, ctx);
2751
2748
  return `${expr} AS ${quoteIdent(a.name)}`;
2752
2749
  });
2753
- const semanticColumns = [];
2754
- if (resolved.semantic !== void 0) {
2755
- const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
2756
- const semanticParamIndex = findSemanticParamIndex(paramSlots);
2757
- if (semanticParamIndex !== void 0) {
2758
- semanticColumns.push(`1 - (${col} <=> $${semanticParamIndex}) AS "$score"`);
2759
- }
2760
- }
2761
- const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns, ...semanticColumns];
2750
+ const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns];
2762
2751
  if (selectParts.length > 0) {
2763
2752
  sqlParts.push(`SELECT ${selectParts.join(" ")} ${allColumns.join(", ")}`);
2764
2753
  } else {
@@ -2767,9 +2756,7 @@ var compileQuery = (resolved) => {
2767
2756
  const firstSource = resolved.sources[0];
2768
2757
  if (firstSource !== void 0) {
2769
2758
  if (firstSource.subquery !== void 0) {
2770
- const subSql = compileQuery(firstSource.subquery);
2771
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
2772
- sqlParts.push(`FROM (${subSql.sql}) AS ${firstSource.alias}`);
2759
+ sqlParts.push(`FROM (${compileLevel(firstSource.subquery, paramSlots, paramCounter)}) AS ${firstSource.alias}`);
2773
2760
  } else if (firstSource.table !== void 0) {
2774
2761
  sqlParts.push(`FROM ${firstSource.table} AS ${firstSource.alias}`);
2775
2762
  }
@@ -2784,9 +2771,7 @@ var compileQuery = (resolved) => {
2784
2771
  ];
2785
2772
  const on = conditions.join(" AND ");
2786
2773
  if (joinSource.subquery !== void 0) {
2787
- const subSql = compileQuery(joinSource.subquery);
2788
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
2789
- sqlParts.push(`${keyword} (${subSql.sql}) AS ${join.toAlias} ON ${on}`);
2774
+ sqlParts.push(`${keyword} (${compileLevel(joinSource.subquery, paramSlots, paramCounter)}) AS ${join.toAlias} ON ${on}`);
2790
2775
  } else {
2791
2776
  sqlParts.push(`${keyword} ${join.toTable} AS ${join.toAlias} ON ${on}`);
2792
2777
  }
@@ -2796,9 +2781,7 @@ var compileQuery = (resolved) => {
2796
2781
  for (const source of resolved.sources) {
2797
2782
  if (source.alias === firstSource?.alias || joinedAliases.has(source.alias)) continue;
2798
2783
  if (source.subquery !== void 0) {
2799
- const subSql = compileQuery(source.subquery);
2800
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
2801
- sqlParts.push(`CROSS JOIN (${subSql.sql}) AS ${source.alias}`);
2784
+ sqlParts.push(`CROSS JOIN (${compileLevel(source.subquery, paramSlots, paramCounter)}) AS ${source.alias}`);
2802
2785
  } else if (source.table !== void 0) {
2803
2786
  sqlParts.push(`CROSS JOIN ${source.table} AS ${source.alias}`);
2804
2787
  }
@@ -2820,11 +2803,9 @@ var compileQuery = (resolved) => {
2820
2803
  });
2821
2804
  sqlParts.push(`ORDER BY ${orderByParts.join(", ")}`);
2822
2805
  } else if (resolved.semantic !== void 0) {
2823
- const semanticIdx = findSemanticParamIndex(paramSlots);
2824
- if (semanticIdx !== void 0) {
2825
- const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
2826
- sqlParts.push(`ORDER BY ${col} <=> $${semanticIdx} ASC`);
2827
- }
2806
+ const { field, contextPath } = resolved.semantic;
2807
+ const position = paramSlots.findIndex((slot) => slot.kind === "semantic" && slot.key === contextPath) + 1;
2808
+ if (position > 0) sqlParts.push(`ORDER BY ${field.alias}.${field.column} <=> $${position} ASC`);
2828
2809
  }
2829
2810
  if (resolved.limit !== void 0) {
2830
2811
  if (!Number.isInteger(resolved.limit) || resolved.limit < 1) {
@@ -2832,30 +2813,7 @@ var compileQuery = (resolved) => {
2832
2813
  }
2833
2814
  sqlParts.push(`LIMIT ${resolved.limit}`);
2834
2815
  }
2835
- const contextContract = {};
2836
- for (const slot of paramSlots) {
2837
- contextContract[slot.key] = { type: slot.type, kind: slot.kind };
2838
- }
2839
- return {
2840
- sql: sqlParts.join(" "),
2841
- paramSlots,
2842
- contextContract
2843
- };
2844
- };
2845
- var findSemanticParamIndex = (slots) => {
2846
- for (let i = 0; i < slots.length; i++) {
2847
- const slot = slots[i];
2848
- if (slot !== void 0 && slot.kind === "semantic") {
2849
- return i + 1;
2850
- }
2851
- }
2852
- return void 0;
2853
- };
2854
- var mergeSubqueryParams = (subCompiled, parentSlots, parentCounter) => {
2855
- for (const slot of subCompiled.paramSlots) {
2856
- parentCounter.value += 1;
2857
- parentSlots.push(slot);
2858
- }
2816
+ return sqlParts.join(" ");
2859
2817
  };
2860
2818
 
2861
2819
  // src/adapters/postgres/statement-timeout.ts
@@ -2905,7 +2863,7 @@ var createPostgresAdapter = (config) => {
2905
2863
  const capabilities = {
2906
2864
  vectorSearch: true,
2907
2865
  fuzzyMatch: false,
2908
- // Requires pg_trgm extension, not guaranteed
2866
+ // needs the pg_trgm extension, which may not be installed
2909
2867
  jsonFields: true,
2910
2868
  fullTextSearch: true,
2911
2869
  returningClause: true,
@@ -3013,9 +2971,7 @@ var UpsertSchema = zod.z.object({
3013
2971
  op: zod.z.literal("upsert"),
3014
2972
  table: zod.z.string(),
3015
2973
  columns: Columns,
3016
- // set on BOTH branches (update SET, and part of the insert)
3017
2974
  insert: Columns.optional(),
3018
- // extra columns set ONLY on insert — immutable-on-create (e.g. a FK)
3019
2975
  key: zod.z.string()
3020
2976
  }).strict().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).');
3021
2977
  var MutationSchema = zod.z.discriminatedUnion("op", [InsertSchema, InsertEachSchema, UpdateSchema, DeleteSchema, UpsertSchema]);
@@ -3064,7 +3020,7 @@ var quoteIdent2 = (name, label) => {
3064
3020
  }
3065
3021
  return `"${name}"`;
3066
3022
  };
3067
- var SELECT_COLS = "key, kind, intent, shape, dsl, prism_ir, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh";
3023
+ var SELECT_COLS = "key, kind, intent, shape, dsl, prism_ir, mapping, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh";
3068
3024
  var rowToEntry = (row) => {
3069
3025
  const createdAt = row["created_at"].getTime();
3070
3026
  const expiresAtRaw = row["expires_at"];
@@ -3095,13 +3051,8 @@ var rowToEntry = (row) => {
3095
3051
  kind: "ok",
3096
3052
  dsl: row["dsl"],
3097
3053
  ...row["prism_ir"] != null ? { prismIr: row["prism_ir"] } : {},
3098
- // A DECLARED REACH IS PART OF THE ENTRY, so it has to survive the round
3099
- // trip. Dropping it here would not fail loudly — the read would simply be
3100
- // served at the caller's own, wider reach, which is the exact thing the
3101
- // field exists to prevent.
3054
+ ...row["mapping"] != null ? { mapping: row["mapping"] } : {},
3102
3055
  ...row["reach"] != null ? { reach: row["reach"] } : {},
3103
- // So must the refresh mode: dropped, a reactive read would quietly answer
3104
- // once and never again.
3105
3056
  ...isRefresh(row["refresh"]) ? { refresh: row["refresh"] } : {},
3106
3057
  ...meta
3107
3058
  };
@@ -3146,6 +3097,10 @@ var createPostgresCache = (config) => {
3146
3097
  { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS reach text` },
3147
3098
  { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS refresh text` }
3148
3099
  ]
3100
+ },
3101
+ {
3102
+ description: "The prism config a mapping was compiled from",
3103
+ steps: [{ kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS mapping jsonb` }]
3149
3104
  }
3150
3105
  ]
3151
3106
  };
@@ -3189,6 +3144,7 @@ var createPostgresCache = (config) => {
3189
3144
  const isOk = entry.kind === "ok";
3190
3145
  const dsl = isOk ? JSON.stringify(entry.dsl) : entry.kind === "mutation" ? JSON.stringify(entry.mutation) : null;
3191
3146
  const prismIr = isOk && entry.prismIr !== void 0 ? JSON.stringify(entry.prismIr) : null;
3147
+ const mapping = isOk && entry.mapping !== void 0 ? JSON.stringify(entry.mapping) : null;
3192
3148
  const reason = entry.kind === "unsatisfiable" ? entry.reason : null;
3193
3149
  const intent = entry.intent ?? null;
3194
3150
  const shape = entry.shape !== void 0 ? JSON.stringify(entry.shape) : null;
@@ -3201,8 +3157,8 @@ var createPostgresCache = (config) => {
3201
3157
  const reach = entry.kind === "unsatisfiable" ? null : entry.reach ?? null;
3202
3158
  const refresh = entry.kind === "ok" ? entry.refresh ?? null : null;
3203
3159
  await pool.query(
3204
- `INSERT INTO ${qualified} (key, kind, intent, shape, dsl, prism_ir, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh)
3205
- VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7, $8, $9, $10, $11, $12, $13, $14, $15)
3160
+ `INSERT INTO ${qualified} (key, kind, intent, shape, dsl, prism_ir, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh, mapping)
3161
+ VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb)
3206
3162
  ON CONFLICT (key) DO UPDATE SET
3207
3163
  kind = EXCLUDED.kind,
3208
3164
  intent = EXCLUDED.intent,
@@ -3217,8 +3173,9 @@ var createPostgresCache = (config) => {
3217
3173
  protected = EXCLUDED.protected,
3218
3174
  last_used_at = EXCLUDED.last_used_at,
3219
3175
  request_hash = EXCLUDED.request_hash,
3220
- refresh = EXCLUDED.refresh`,
3221
- [key, entry.kind, intent, shape, dsl, prismIr, reach, reason, createdAt, expiresAt, fingerprint, isProtected, lastUsedAt, requestHash, refresh]
3176
+ refresh = EXCLUDED.refresh,
3177
+ mapping = EXCLUDED.mapping`,
3178
+ [key, entry.kind, intent, shape, dsl, prismIr, reach, reason, createdAt, expiresAt, fingerprint, isProtected, lastUsedAt, requestHash, refresh, mapping]
3222
3179
  );
3223
3180
  };
3224
3181
  const del = async (key) => {
@@ -4010,7 +3967,6 @@ var listFingerprints = async (engine, policy) => {
4010
3967
  ...entry.intent !== void 0 ? { intent: entry.intent } : {},
4011
3968
  createdAt: entry.createdAt,
4012
3969
  ...entry.lastUsedAt !== void 0 ? { lastUsedAt: entry.lastUsedAt } : {},
4013
- // The derived contract — what to pass, straight from the stored def.
4014
3970
  ...entry.kind === "ok" ? {
4015
3971
  context: collectQueryContext(entry.dsl, schema),
4016
3972
  ...entry.shape !== void 0 ? { shape: entry.shape } : {}
@@ -4086,8 +4042,6 @@ var handleQuery = async (config, body, scope, live) => {
4086
4042
  const result = await runQuery(config, body, scope, probe, live);
4087
4043
  const record = {
4088
4044
  kind: probe.kind,
4089
- // 200 succeeded; 403 is a policy/reach refusal (a normal outcome, not a
4090
- // fault); everything else is an error.
4091
4045
  status: result.status === 200 ? "ok" : result.status === 403 ? "refused" : "error",
4092
4046
  startUnixNano,
4093
4047
  endUnixNano: startUnixNano + (elapsedClock() - t0) * 1e6,
@@ -4132,7 +4086,7 @@ var runQuery = async (config, body, scope, probe, live) => {
4132
4086
  try {
4133
4087
  let entryReach;
4134
4088
  if (parsed.data.fingerprint !== void 0) {
4135
- const entry = await engine.cache.get(parsed.data.fingerprint);
4089
+ const entry = await engine.cache.get(parsed.data.fingerprint, scope);
4136
4090
  if (entry !== void 0 && entry.kind === "ok") entryReach = entry.reach;
4137
4091
  if (probe !== void 0 && entryReach !== void 0) probe.reach = entryReach;
4138
4092
  if (entry !== void 0 && entry.kind === "mutation") {