@pgxsinkit/contracts 0.2.7 → 0.5.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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/dist/apply-strategy.d.ts +13 -1
  3. package/dist/apply-strategy.d.ts.map +1 -1
  4. package/dist/config.d.ts +256 -87
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +2 -2
  7. package/dist/convergence-model.d.ts.map +1 -1
  8. package/dist/event-stream.d.ts +1 -1
  9. package/dist/fingerprint.d.ts +31 -11
  10. package/dist/fingerprint.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +480 -202
  14. package/dist/index.js.map +16 -14
  15. package/dist/predicate.d.ts +162 -0
  16. package/dist/predicate.d.ts.map +1 -0
  17. package/dist/projection.d.ts +2 -2
  18. package/dist/projection.d.ts.map +1 -1
  19. package/dist/registry-diff.d.ts.map +1 -1
  20. package/dist/registry-invariant.d.ts +26 -14
  21. package/dist/registry-invariant.d.ts.map +1 -1
  22. package/dist/registry.d.ts +74 -48
  23. package/dist/registry.d.ts.map +1 -1
  24. package/dist/sql-role-guard.d.ts +1 -1
  25. package/dist/stream-envelope.d.ts +84 -0
  26. package/dist/stream-envelope.d.ts.map +1 -0
  27. package/dist/supabase-rls.d.ts +32 -36
  28. package/dist/supabase-rls.d.ts.map +1 -1
  29. package/package.json +3 -2
  30. package/skills/registry-authoring/SKILL.md +185 -185
  31. package/skills/registry-authoring/references/storage-engine-and-build.md +29 -0
  32. package/src/apply-strategy.ts +23 -4
  33. package/src/config.ts +340 -116
  34. package/src/convergence-model.ts +2 -2
  35. package/src/event-stream.ts +1 -1
  36. package/src/fingerprint.ts +76 -14
  37. package/src/index.ts +2 -0
  38. package/src/predicate.ts +274 -0
  39. package/src/projection.ts +6 -2
  40. package/src/registry-diff.ts +15 -4
  41. package/src/registry-invariant.ts +34 -19
  42. package/src/registry.ts +324 -78
  43. package/src/sql-role-guard.ts +1 -1
  44. package/src/stream-envelope.ts +91 -0
  45. package/src/supabase-rls.ts +76 -74
@@ -169,11 +169,11 @@ export const CONVERGENCE_EVENTS = [
169
169
  "journal row → acked, server_updated_at_us stamped; entity shows acked_unobserved until the echo catches up",
170
170
  },
171
171
  {
172
- event: "Electric insert/update observed",
172
+ event: "synced upsert observed",
173
173
  effect: "synced row applied; the barrier predicate runs; resolved entities clear overlay + acked journal",
174
174
  },
175
175
  {
176
- event: "Electric delete observed",
176
+ event: "synced delete observed",
177
177
  effect: "resolved by synced-row absence (deletes carry no Server version — ADR-0010)",
178
178
  },
179
179
  { event: "resolution", effect: "clear overlay/journal only through the shared barrier predicate (decision 4)" },
@@ -72,7 +72,7 @@ export interface EventStreamEntry<TPayload extends z.ZodType = z.ZodType> {
72
72
  identity: Record<string, EventStreamIdentityField>;
73
73
  /**
74
74
  * An opaque version counter for the part of this payload contract the lock's hash cannot see — the same
75
- * role `RowFilterSpec.revision` plays for a `customWhere` closure. The lock hashes the payload schema as
75
+ * role `RowFilterSpec.revision` plays for a `customPredicate` closure. The lock hashes the payload schema as
76
76
  * a **JSON Schema**, and refinements/transforms are simply not representable there: a reviewer
77
77
  * demonstrated that `z.string().refine(v => v.length >= 3)` and the INCOMPATIBLE `>= 10` version produce
78
78
  * the identical stream hash, so the `risky` diff the ADR relies on never fires.
@@ -1,6 +1,14 @@
1
1
  import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
2
2
 
3
3
  import type { RowFilterSpec } from "./config";
4
+ import {
5
+ isAndPredicate,
6
+ isInSubqueryPredicate,
7
+ isIsNullPredicate,
8
+ isNotPredicate,
9
+ isOrPredicate,
10
+ type Predicate,
11
+ } from "./predicate";
4
12
  import type { SyncTableEntry, SyncTableRegistry } from "./registry";
5
13
 
6
14
  /**
@@ -9,10 +17,10 @@ import type { SyncTableEntry, SyncTableRegistry } from "./registry";
9
17
  *
10
18
  * This is the single source of "has the shape changed" — consumed as the local-DB
11
19
  * version key and as the basis of the registry-diff gate (ADR-0006). Function *bodies*
12
- * (`rowTransform`, `customWhere`) cannot be fingerprinted and are excluded — but their
20
+ * (`rowTransform`, `customPredicate`) cannot be fingerprinted and are excluded — but their
13
21
  * *presence* and the surrounding **static** filter structure (the projected columns)
14
22
  * participate. For the invisible *logic* itself, a consumer-bumped `rowFilter.revision` is
15
- * folded in: changing it is how a `customWhere` authorization change is forced to shift the
23
+ * folded in: changing it is how a `customPredicate` authorization change is forced to shift the
16
24
  * fingerprint (and so rebuild the cache + reset the subscription).
17
25
  */
18
26
 
@@ -39,8 +47,18 @@ export interface CanonicalTable {
39
47
  shape: {
40
48
  tableName: string;
41
49
  shapeKey: string;
42
- electricTable: string | null;
50
+ physicalTable: string | null;
43
51
  rowFilter: CanonicalRowFilter | null;
52
+ /** Shared-tier scope columns, in declaration order — the order parameterizes the family. */
53
+ scope: string[] | null;
54
+ /**
55
+ * The native static predicate, canonicalized in full.
56
+ *
57
+ * Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only
58
+ * ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing
59
+ * a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.
60
+ */
61
+ where: string | null;
44
62
  } | null;
45
63
  managedFields: Array<{ field: string; strategy: string; applyOn: string[] }>;
46
64
  /**
@@ -61,16 +79,16 @@ export interface CanonicalTable {
61
79
 
62
80
  /**
63
81
  * The static, fingerprint-able structure of a row filter. A changed projection shifts the
64
- * fingerprint, so the local store rebuilds and the diff gate flags it. `customWhere`'s body is
65
- * invisible — only its presence (`hasCustomWhere`) is recorded — so a `customWhere` *logic* change
82
+ * fingerprint, so the local store rebuilds and the diff gate flags it. `customPredicate`'s body is
83
+ * invisible — only its presence (`hasCustomPredicate`) is recorded — so a `customPredicate` *logic* change
66
84
  * is surfaced only by bumping `revision`.
67
85
  */
68
86
  export interface CanonicalRowFilter {
69
- hasCustomWhere: boolean;
87
+ hasCustomPredicate: boolean;
70
88
  columns: string[] | null;
71
89
  /**
72
- * The consumer-supplied version tag for the non-fingerprintable filter logic (the `customWhere`
73
- * body). Changing it shifts the fingerprint, which is the only way a `customWhere` *logic* change
90
+ * The consumer-supplied version tag for the non-fingerprintable filter logic (the `customPredicate`
91
+ * body). Changing it shifts the fingerprint, which is the only way a `customPredicate` *logic* change
74
92
  * forces a cache + subscription reset.
75
93
  */
76
94
  revision: string | null;
@@ -108,12 +126,42 @@ function canonicalizeManagedFields(entry: SyncTableEntry): CanonicalTable["manag
108
126
  .sort((a, b) => asString(a.field, b.field));
109
127
  }
110
128
 
129
+ /**
130
+ * A stable string form of a native predicate.
131
+ *
132
+ * Keys are emitted in a fixed order rather than serialized as authored, so two predicates that
133
+ * differ only in how their object literals were written fingerprint identically — otherwise a
134
+ * cosmetic edit would force every client to rebuild its local cache.
135
+ */
136
+ function canonicalizePredicate(node: Predicate | undefined): string | null {
137
+ if (node === undefined) return null;
138
+ const render = (current: Predicate): unknown => {
139
+ if (isAndPredicate(current)) return { and: current.and.map(render) };
140
+ if (isOrPredicate(current)) return { or: current.or.map(render) };
141
+ if (isNotPredicate(current)) return { not: render(current.not) };
142
+ if (isInSubqueryPredicate(current)) {
143
+ return {
144
+ col: current.col,
145
+ in: {
146
+ table: current.in.table,
147
+ project: current.in.project,
148
+ where: current.in.where ? render(current.in.where) : null,
149
+ },
150
+ negated: current.negated === true,
151
+ };
152
+ }
153
+ if (isIsNullPredicate(current)) return { col: current.col, isNull: current.isNull };
154
+ return { col: current.col, op: current.op, value: current.value };
155
+ };
156
+ return JSON.stringify(render(node));
157
+ }
158
+
111
159
  function canonicalizeRowFilter(filter: RowFilterSpec | undefined): CanonicalRowFilter | null {
112
160
  if (!filter) {
113
161
  return null;
114
162
  }
115
163
  return {
116
- hasCustomWhere: filter.customWhere != null,
164
+ hasCustomPredicate: filter.customPredicate != null,
117
165
  columns: filter.columns ? [...filter.columns].sort(asString) : null,
118
166
  revision: filter.revision != null ? String(filter.revision) : null,
119
167
  };
@@ -133,8 +181,10 @@ function canonicalizeTable(key: string, entry: SyncTableEntry): CanonicalTable {
133
181
  ? {
134
182
  tableName: entry.shape.tableName,
135
183
  shapeKey: entry.shape.shapeKey,
136
- electricTable: entry.shape.electricTable ?? null,
184
+ physicalTable: entry.shape.physicalTable ?? null,
137
185
  rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
186
+ scope: entry.shape.scope ? [...entry.shape.scope] : null,
187
+ where: canonicalizePredicate(entry.shape.where),
138
188
  }
139
189
  : null;
140
190
 
@@ -198,7 +248,7 @@ export function fingerprintRegistry(registry: SyncTableRegistry): string {
198
248
  /**
199
249
  * The **read contract** of a single sync table: the subset of its canonical shape that decides what
200
250
  * data streams down and how a row is identified and filtered — synced-table name, columns, primary key
201
- * (and any local-PK override), column omission, and the shape (electric table + row filter). It is the
251
+ * (and any local-PK override), column omission, and the shape (physical table + row filter). It is the
202
252
  * stable identity a writable entry shares with its {@link asReadonly} projection.
203
253
  *
204
254
  * Deliberately EXCLUDES the two axes a per-client projection may legitimately differ on:
@@ -209,7 +259,7 @@ export function fingerprintRegistry(registry: SyncTableRegistry): string {
209
259
  *
210
260
  * What it pins is the data itself: two registries that present "the same" logical table to different
211
261
  * clients must agree here, or those clients are silently seeing different rows/columns. As with the
212
- * full registry fingerprint, the `customWhere` *body* is invisible — only its presence and the
262
+ * full registry fingerprint, the `customPredicate` *body* is invisible — only its presence and the
213
263
  * consumer-bumped {@link RowFilterSpec.revision} participate, so bump `revision` to force a divergence
214
264
  * a logic-only change would otherwise hide.
215
265
  */
@@ -222,8 +272,18 @@ export interface CanonicalReadContract {
222
272
  shape: {
223
273
  tableName: string;
224
274
  shapeKey: string;
225
- electricTable: string | null;
275
+ physicalTable: string | null;
226
276
  rowFilter: CanonicalRowFilter | null;
277
+ /** Shared-tier scope columns, in declaration order — the order parameterizes the family. */
278
+ scope: string[] | null;
279
+ /**
280
+ * The native static predicate, canonicalized in full.
281
+ *
282
+ * Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only
283
+ * ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing
284
+ * a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.
285
+ */
286
+ where: string | null;
227
287
  } | null;
228
288
  }
229
289
 
@@ -233,8 +293,10 @@ export function canonicalizeReadContract(entry: SyncTableEntry): CanonicalReadCo
233
293
  ? {
234
294
  tableName: entry.shape.tableName,
235
295
  shapeKey: entry.shape.shapeKey,
236
- electricTable: entry.shape.electricTable ?? null,
296
+ physicalTable: entry.shape.physicalTable ?? null,
237
297
  rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
298
+ scope: entry.shape.scope ? [...entry.shape.scope] : null,
299
+ where: canonicalizePredicate(entry.shape.where),
238
300
  }
239
301
  : null;
240
302
 
package/src/index.ts CHANGED
@@ -9,9 +9,11 @@ export * from "./registry";
9
9
  export * from "./registry-diff";
10
10
  export * from "./registry-invariant";
11
11
  export * from "./mutation";
12
+ export * from "./predicate";
12
13
  export * from "./projection";
13
14
  export * from "./runtime";
14
15
  export * from "./sql-defaults";
16
+ export * from "./stream-envelope";
15
17
  export * from "./sql-identifier";
16
18
  export * from "./sql-role-guard";
17
19
  export * from "./supabase-rls";
@@ -0,0 +1,274 @@
1
+ import { getColumnTable, getTableName, type AnyColumn } from "drizzle-orm";
2
+
3
+ /**
4
+ * The **native predicate AST** — the wire form a shape's `where` takes on the Circuits-native read
5
+ * path (ADR-0055), replacing the Electric path's SQL `where` **text**.
6
+ *
7
+ * This matters beyond serialization. The Electric path compiled a Drizzle `SQL` fragment down to a
8
+ * string that the engine then re-lexed (`where_sql.rs`); the native path never produces text at all,
9
+ * so there is no lexer on our path and no grammar to keep two implementations agreeing on. It is
10
+ * also what makes the repo's SQL-tier rule reachable at tier ① here: authoring is real column
11
+ * objects and typed values end to end, with no string to escape and nothing to interpolate.
12
+ *
13
+ * These types mirror `@electric-circuits/protocol`'s `Predicate` union exactly. They are restated
14
+ * rather than imported: this is the wire contract pgxsinkit commits to, the protocol package is
15
+ * alpha, and a published library should not put an alpha peer in its public types. Any divergence
16
+ * is a bug here — the engine's serde definitions are authoritative.
17
+ */
18
+ export type PredicateValue = string | number | boolean | null;
19
+
20
+ /**
21
+ * Comparison operators for a leaf predicate.
22
+ *
23
+ * `like` is SQL `LIKE`: case-sensitive, `%` = any sequence, `_` = any single char. There is no
24
+ * `notLike` op — the engine models it as `Not(Like)`, which is what {@link p.notLike} builds.
25
+ */
26
+ export type PredicateLeafOp = "eq" | "neq" | "lt" | "lte" | "gt" | "gte" | "like";
27
+
28
+ /** `col <op> value`. Three-valued: never TRUE on a NULL cell — use {@link IsNullPredicate} for that. */
29
+ export interface LeafPredicate {
30
+ col: string;
31
+ op: PredicateLeafOp;
32
+ value: PredicateValue;
33
+ }
34
+
35
+ /**
36
+ * `col IS NULL` / `col IS NOT NULL`. A separate leaf because it is the one test that is TRUE on a
37
+ * NULL cell, and the only two-valued one — so it is also the only leaf that composes soundly under
38
+ * {@link NotPredicate}.
39
+ */
40
+ export interface IsNullPredicate {
41
+ col: string;
42
+ isNull: boolean;
43
+ }
44
+
45
+ export interface AndPredicate {
46
+ and: Predicate[];
47
+ }
48
+
49
+ export interface OrPredicate {
50
+ or: Predicate[];
51
+ }
52
+
53
+ export interface NotPredicate {
54
+ not: Predicate;
55
+ }
56
+
57
+ /**
58
+ * The inner half of an `IN` test: the set of `project` values over `table`'s rows matching `where`.
59
+ * `where` may itself contain subquery leaves. Single column only — the engine has no composite
60
+ * `(a, b) IN (…)`. Subqueries must stay **uncorrelated**: the inner `where` references the inner
61
+ * table's columns only, never the outer row's.
62
+ */
63
+ export interface SubqueryRef<TValue extends PredicateValue = PredicateValue> {
64
+ table: string;
65
+ project: string;
66
+ where?: Predicate;
67
+ /**
68
+ * Phantom: the projected column's value type, carried so {@link p.in} can require the OUTER column
69
+ * to be comparable with what the subquery actually projects. Never serialized — it is a type-level
70
+ * marker only, which is why it is optional and never read.
71
+ */
72
+ readonly __value?: TValue;
73
+ }
74
+
75
+ /**
76
+ * `outer.col IN (SELECT project FROM table WHERE …)`, or `NOT IN` when `negated`. The engine
77
+ * maintains the inner set incrementally and shares it across every shape referencing the same
78
+ * subquery, which is why an entitlement-shaped subquery costs one index rather than one per shape.
79
+ */
80
+ export interface InSubqueryPredicate {
81
+ col: string;
82
+ in: SubqueryRef;
83
+ negated?: boolean;
84
+ }
85
+
86
+ /** A restricted boolean predicate over one table's columns, plus single-column `IN`/`NOT IN`. */
87
+ export type Predicate =
88
+ | LeafPredicate
89
+ | IsNullPredicate
90
+ | AndPredicate
91
+ | OrPredicate
92
+ | NotPredicate
93
+ | InSubqueryPredicate;
94
+
95
+ export function isLeafPredicate(node: Predicate): node is LeafPredicate {
96
+ return "col" in node && "op" in node;
97
+ }
98
+ export function isIsNullPredicate(node: Predicate): node is IsNullPredicate {
99
+ return "col" in node && "isNull" in node;
100
+ }
101
+ export function isAndPredicate(node: Predicate): node is AndPredicate {
102
+ return "and" in node;
103
+ }
104
+ export function isOrPredicate(node: Predicate): node is OrPredicate {
105
+ return "or" in node;
106
+ }
107
+ export function isNotPredicate(node: Predicate): node is NotPredicate {
108
+ return "not" in node;
109
+ }
110
+ export function isInSubqueryPredicate(node: Predicate): node is InSubqueryPredicate {
111
+ return "in" in node && "col" in node;
112
+ }
113
+
114
+ /**
115
+ * Values reach the engine as JSON scalars, so a Drizzle column whose TS type is richer than the
116
+ * four Circuits column types (`int`/`text`/`bool`/`float`) has no automatic rendering here.
117
+ *
118
+ * `Date` is the case that actually turns up, and it is deliberately **not** coerced: a timestamp
119
+ * column syncs as `text`, and JS's ISO rendering is not Postgres's, so a silent `toISOString()`
120
+ * would produce a predicate that compares unequal to every row it was meant to match. Render it the
121
+ * way the column does and pass the string.
122
+ */
123
+ function assertPredicateValue(column: AnyColumn, value: unknown): asserts value is PredicateValue {
124
+ if (value === null) return;
125
+ const kind = typeof value;
126
+ if (kind === "string" || kind === "number" || kind === "boolean") return;
127
+
128
+ const shown = value instanceof Date ? "Date" : kind === "object" ? "object" : kind;
129
+ throw new Error(
130
+ `[pgxsinkit] predicate on "${column.name}": ${shown} is not a predicate value — the wire form ` +
131
+ `carries JSON scalars (string | number | boolean | null). Render it to the text form the ` +
132
+ `column itself stores and pass that, rather than relying on a coercion that may not match.`,
133
+ );
134
+ }
135
+
136
+ /**
137
+ * What a builder accepts, versus {@link PredicateValue} (what goes on the wire).
138
+ *
139
+ * `bigint` is admitted because the toolkit's own timestamp convention is a **microsecond BIGINT**, so
140
+ * comparing against one is ordinary rather than exotic. It is narrowed to a number by `toWireValue`
141
+ * rather than widening the wire type: Postgres `bigint` is `ColumnType::Int` to the engine, which reads
142
+ * the JSON scalar as an `i64` — a decimal *string* would be rejected against an int column.
143
+ */
144
+ export type PredicateValueInput = PredicateValue | bigint;
145
+
146
+ /** A column's TypeScript value type, as Drizzle carries it on the column object. */
147
+ type ColumnData<TCol extends AnyColumn> = TCol["_"]["data"];
148
+
149
+ type IsAny<T> = 0 extends 1 & T ? true : false;
150
+ /**
151
+ * Whether a column's value type is statically unknowable — `any`, or the `unknown` that Drizzle's
152
+ * erased column paths (`getColumns`, `PgBuildExtraConfigColumns`) yield. Those must stay PERMISSIVE:
153
+ * narrowing an unknowable type through `Extract` collapses it to `never`, which would refuse every
154
+ * comparison on a column the author cannot re-type.
155
+ */
156
+ type IsUnknownData<T> = IsAny<T> extends true ? true : unknown extends T ? true : false;
157
+
158
+ /**
159
+ * What may be compared against `TCol` — the column's OWN value type, narrowed to what this wire can
160
+ * carry, plus `null` when the column is nullable.
161
+ *
162
+ * `Extract` is what refuses a column whose values have no scalar form at all: a `jsonb` column typed
163
+ * as an object, or a `timestamp` column typed as `Date`, resolves to `never` here, so the comparison
164
+ * is a compile error rather than the runtime throw it used to be. And because a `pgEnum` column's
165
+ * data type is the literal union of its labels, a mistyped label is caught too — something the SQL
166
+ * text form could never see.
167
+ */
168
+ export type ColumnValue<TCol extends AnyColumn> =
169
+ IsUnknownData<ColumnData<TCol>> extends true
170
+ ? PredicateValueInput
171
+ : Extract<ColumnData<TCol>, PredicateValueInput> | (TCol["_"]["notNull"] extends true ? never : null);
172
+
173
+ /**
174
+ * Narrow a builder input to its wire form, refusing the one conversion that would be silently wrong.
175
+ *
176
+ * A `bigint` past `Number.MAX_SAFE_INTEGER` cannot survive the trip: JSON's only integer carrier here
177
+ * is a JS `number` (an IEEE double), so serializing it would round to a nearby value and the predicate
178
+ * would compare unequal to the row it was written for. Microsecond timestamps sit comfortably inside
179
+ * the safe range, so this throws only for a value that genuinely cannot be expressed.
180
+ */
181
+ function toWireValue(column: AnyColumn, value: PredicateValueInput): PredicateValue {
182
+ if (typeof value !== "bigint") {
183
+ assertPredicateValue(column, value);
184
+ return value;
185
+ }
186
+
187
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
188
+ throw new Error(
189
+ `[pgxsinkit] predicate on "${column.name}": ${value}n is outside the exactly-representable ` +
190
+ `integer range, so serializing it would silently round to a different value. Compare against ` +
191
+ `a value inside the safe-integer range, or split the test.`,
192
+ );
193
+ }
194
+ return Number(value);
195
+ }
196
+
197
+ function leaf<TCol extends AnyColumn>(column: TCol, op: PredicateLeafOp, value: ColumnValue<TCol>): LeafPredicate {
198
+ return { col: column.name, op, value: toWireValue(column, value as PredicateValueInput) };
199
+ }
200
+
201
+ /**
202
+ * The predicate builder — the tier-① authoring surface for a native `where`.
203
+ *
204
+ * Deliberately namespaced rather than exported as bare `eq`/`and`/`or`/`not`, which would collide
205
+ * with `drizzle-orm`'s operators of the same names in exactly the files that use both (a registry
206
+ * authoring RLS policies with Drizzle's `eq` and a shape `where` with this one). The shapes are
207
+ * intentionally the same so the two read alike; only the AST-versus-`SQL` return type differs.
208
+ *
209
+ * ```ts
210
+ * where: (c) => p.and(p.eq(c.published, true), p.isNotNull(c.releasedAt))
211
+ * ```
212
+ */
213
+ export const p = {
214
+ eq: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "eq", value),
215
+ ne: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "neq", value),
216
+ lt: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "lt", value),
217
+ lte: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "lte", value),
218
+ gt: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "gt", value),
219
+ gte: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "gte", value),
220
+
221
+ /** SQL `LIKE` (case-sensitive; `%` = any sequence, `_` = any single char). Text columns only. */
222
+ like: <TCol extends AnyColumn<{ data: string }>>(column: TCol, pattern: string): LeafPredicate =>
223
+ leaf(column, "like", pattern as ColumnValue<TCol>),
224
+ /** SQL `NOT LIKE`. The engine has no negated-like op; it models it as `Not(Like)`, so this does too. */
225
+ notLike: <TCol extends AnyColumn<{ data: string }>>(column: TCol, pattern: string): NotPredicate => ({
226
+ not: leaf(column, "like", pattern as ColumnValue<TCol>),
227
+ }),
228
+
229
+ isNull: (column: AnyColumn): IsNullPredicate => ({ col: column.name, isNull: true }),
230
+ isNotNull: (column: AnyColumn): IsNullPredicate => ({ col: column.name, isNull: false }),
231
+
232
+ and: (...nodes: Predicate[]): AndPredicate => ({ and: nodes }),
233
+ or: (...nodes: Predicate[]): OrPredicate => ({ or: nodes }),
234
+ not: (node: Predicate): NotPredicate => ({ not: node }),
235
+
236
+ /**
237
+ * The inner set for an `IN` test, named by the column it projects — the table is read off that
238
+ * column, so there is no table name to get wrong and no way to project a column the named table
239
+ * does not have.
240
+ */
241
+ subquery: <TCol extends AnyColumn>(
242
+ projected: TCol,
243
+ where?: Predicate,
244
+ ): SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>> => ({
245
+ table: getTableName(getColumnTable(projected)),
246
+ project: projected.name,
247
+ ...(where !== undefined ? { where } : {}),
248
+ }),
249
+
250
+ in: <TCol extends AnyColumn>(
251
+ column: TCol,
252
+ ref: SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>>,
253
+ ): InSubqueryPredicate => ({ col: column.name, in: ref }),
254
+ notIn: <TCol extends AnyColumn>(
255
+ column: TCol,
256
+ ref: SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>>,
257
+ ): InSubqueryPredicate => ({
258
+ col: column.name,
259
+ in: ref,
260
+ negated: true,
261
+ }),
262
+ } as const;
263
+
264
+ /**
265
+ * Conjoin, dropping absent branches and collapsing the trivial cases. `undefined` when nothing is
266
+ * left, which is the AST's own spelling of "all rows" (an omitted `where`) — so a caller never has
267
+ * to invent an always-true leaf to stand in for one.
268
+ */
269
+ export function conjoinPredicates(...nodes: (Predicate | undefined)[]): Predicate | undefined {
270
+ const present = nodes.filter((node): node is Predicate => node !== undefined);
271
+ if (present.length === 0) return undefined;
272
+ if (present.length === 1) return present[0];
273
+ return { and: present };
274
+ }
package/src/projection.ts CHANGED
@@ -43,6 +43,10 @@ export function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgT
43
43
  ...(clientProjection.syncedTable != null ? { syncedTable: clientProjection.syncedTable } : {}),
44
44
  ...(clientProjection.omitColumns != null ? { omitColumns: clientProjection.omitColumns } : {}),
45
45
  ...(clientProjection.localPrimaryKey != null ? { localPrimaryKey: clientProjection.localPrimaryKey } : {}),
46
+ // Read-relevant: a local index serves the CLIENT's reads, and a readonly client reads the same
47
+ // rows through the same columns. Dropping it would leave the projected store scanning where the
48
+ // authoritative one seeks — silently, since nothing else would differ.
49
+ ...(clientProjection.localIndexes != null ? { localIndexes: clientProjection.localIndexes } : {}),
46
50
  }
47
51
  : undefined;
48
52
 
@@ -74,7 +78,7 @@ export function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgT
74
78
 
75
79
  /**
76
80
  * Project an entry onto a different **retention** (ADR-0021) — the per-table local-persistence axis:
77
- * `persistent` (the durable PGlite/OPFS backend) | `ephemeral` (the table's whole local cluster — read
81
+ * `persistent` (the durable pgwasm/OPFS backend) | `ephemeral` (the table's whole local cluster — read
78
82
  * cache, overlay, journal, sequence, views, reconcile function — emitted as `TEMP`/`pg_temp`, leaving no
79
83
  * durable trace). Returns a copy of `entry` with `retention` overridden and **everything else preserved
80
84
  * verbatim** (table, columns, mode, write contract, shape/row filter, the other lifecycle axes).
@@ -126,7 +130,7 @@ export function asEphemeral<TEntry extends SyncTableEntry>(entry: TEntry): TEntr
126
130
  *
127
131
  * Throws, naming the divergent tables, on any mismatch. Call it where the client registries are assembled
128
132
  * (module-eval or a test) so a drifted projection fails closed instead of silently serving different rows
129
- * to different clients. The `customWhere` body is invisible to the fingerprint — bump
133
+ * to different clients. The `customPredicate` body is invisible to the fingerprint — bump
130
134
  * {@link RowFilterSpec.revision} so a logic-only divergence is caught.
131
135
  */
132
136
  export function assertReadContractPreserved(
@@ -109,7 +109,7 @@ function stableStringify(value: unknown): string {
109
109
  * **The blind spot is real and named.** JSON Schema cannot express a zod refinement or transform, so
110
110
  * `z.string().refine(v => v.length >= 3)` and the incompatible `>= 10` version canonicalize identically —
111
111
  * the hash sees no change and the review gate never fires. {@link EventStreamEntry.revision} is the fix and
112
- * it is the AUTHOR's obligation, exactly as `RowFilterSpec.revision` is for a `customWhere` closure: bump it
112
+ * it is the AUTHOR's obligation, exactly as `RowFilterSpec.revision` is for a `customPredicate` closure: bump it
113
113
  * on any acceptance-logic change the JSON Schema cannot carry, and the stream's hash shifts.
114
114
  *
115
115
  * The hash exists to DETECT change, not to VALIDATE compatibility. ADR-0053 decision 1 binds a stream's
@@ -261,9 +261,9 @@ function diffProjection(
261
261
  }
262
262
 
263
263
  /**
264
- * Shape changes. The Electric target (table/shapeKey/electricTable) and the row filter both
264
+ * Shape changes. The shape target (table/shapeKey/physicalTable) and the row filter both
265
265
  * govern which rows stream; a change to either needs a re-sync so the local cache is not left
266
- * holding rows selected under the old definition (risky). The row filter's `customWhere` body
266
+ * holding rows selected under the old definition (risky). The row filter's `customPredicate` body
267
267
  * is invisible to the fingerprint, so a change confined to it is not detectable here.
268
268
  */
269
269
  function diffShape(
@@ -273,7 +273,7 @@ function diffShape(
273
273
  changes: RegistryChange[],
274
274
  ): void {
275
275
  const target = (shape: CanonicalTable["shape"]): string | null =>
276
- shape ? `${shape.tableName}|${shape.shapeKey}|${shape.electricTable ?? ""}` : null;
276
+ shape ? `${shape.tableName}|${shape.shapeKey}|${shape.physicalTable ?? ""}` : null;
277
277
 
278
278
  if (target(previous) !== target(next)) {
279
279
  changes.push({ severity: "risky", table, detail: "shape target changed (re-sync required)" });
@@ -281,6 +281,17 @@ function diffShape(
281
281
  if (JSON.stringify(previous?.rowFilter ?? null) !== JSON.stringify(next?.rowFilter ?? null)) {
282
282
  changes.push({ severity: "risky", table, detail: "row filter changed (re-sync required)" });
283
283
  }
284
+
285
+ // A change of scope columns re-partitions the whole family: rows that were in one shape land in
286
+ // another, and a client holding the old partition cannot reconcile itself to the new one.
287
+ if (JSON.stringify(previous?.scope ?? null) !== JSON.stringify(next?.scope ?? null)) {
288
+ changes.push({ severity: "risky", table, detail: "shape scope changed (re-sync required)" });
289
+ }
290
+ // Unlike `customPredicate`, this one IS visible — so a change confined to the static predicate is
291
+ // caught here rather than needing a consumer to remember to bump a revision.
292
+ if ((previous?.where ?? null) !== (next?.where ?? null)) {
293
+ changes.push({ severity: "risky", table, detail: "shape predicate changed (re-sync required)" });
294
+ }
284
295
  }
285
296
 
286
297
  /**