@pgxsinkit/contracts 0.2.4 → 0.2.6

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,5 +1,8 @@
1
- import { canonicalizeRegistry, fingerprintRegistry, type CanonicalTable } from "./fingerprint";
2
- import type { SyncTableRegistry } from "./registry";
1
+ import { z } from "zod";
2
+
3
+ import type { EventStreamEntry } from "./event-stream";
4
+ import { canonicalizeRegistry, fingerprintRegistry, hashString, type CanonicalTable } from "./fingerprint";
5
+ import { getSyncRegistryStreams, type SyncTableEntry, type SyncTableRegistry } from "./registry";
3
6
 
4
7
  /**
5
8
  * The registry-diff gate (ADR-0006): classify a registry change as
@@ -14,6 +17,8 @@ import type { SyncTableRegistry } from "./registry";
14
17
 
15
18
  export type RegistryChangeSeverity = "compatible" | "risky" | "breaking";
16
19
 
20
+ const asString = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
21
+
17
22
  export interface RegistryChange {
18
23
  severity: RegistryChangeSeverity;
19
24
  table: string;
@@ -29,6 +34,120 @@ export interface RegistryDiff {
29
34
  export interface RegistryLock {
30
35
  version: string;
31
36
  tables: CanonicalTable[];
37
+ /**
38
+ * Each entry's row classification (ADR-0052), keyed by registry key; `null` = unclassified. A SIBLING of
39
+ * `tables`, deliberately not a field of {@link CanonicalTable}: the canonical table shape is what
40
+ * `fingerprintRegistry` hashes, and that hash is PERSISTED as the local store's cache key — so folding
41
+ * classification into it would make merely classifying a table wipe every store's read cache. The lock
42
+ * still records it, so an un-enrolment (a class removed or changed) is a reviewable diff.
43
+ *
44
+ * Optional because a committed lock is JSON on disk: one written before this field existed simply has no
45
+ * `rowClasses`, and the diff then reads the whole baseline as unclassified — so adopting classification
46
+ * against an old lock is a set of `compatible` declarations, never spurious risk. {@link buildRegistryLock}
47
+ * always populates it.
48
+ */
49
+ rowClasses?: RegistryRowClasses;
50
+ /**
51
+ * Each registered Event stream (ADR-0053 decision 1), keyed by Event-stream name → a canonical hash of its
52
+ * payload schema AND its identity declaration. A SIBLING of `tables` for the same reason `rowClasses` is:
53
+ * the canonical table shape is what `fingerprintRegistry` hashes and that hash is the local store's
54
+ * PERSISTED cache key, so folding an Event stream into it would make registering one wipe every store's read
55
+ * cache — for a lane that touches no synced table, no local schema and no apply function.
56
+ *
57
+ * Optional because a committed lock is JSON on disk: one written before this field existed simply has no
58
+ * `streams`, and the diff then reads the whole baseline as having none — so adopting the Event lane against
59
+ * an old lock is a set of `compatible` additions, never spurious risk. {@link buildRegistryLock} always
60
+ * populates it.
61
+ */
62
+ streams?: RegistryEventStreams;
63
+ }
64
+
65
+ /** Registry key → row class (`null` = unclassified). See {@link RegistryLock.rowClasses}. */
66
+ export type RegistryRowClasses = Record<string, string | null>;
67
+
68
+ /** Event-stream name → canonical contract hash. See {@link RegistryLock.streams}. */
69
+ export type RegistryEventStreams = Record<string, string>;
70
+
71
+ /** The row classification of every entry, with sorted keys so a serialized lock is stable. */
72
+ export function registryRowClasses(registry: SyncTableRegistry): RegistryRowClasses {
73
+ const classes: RegistryRowClasses = {};
74
+ for (const key of Object.keys(registry).sort()) {
75
+ classes[key] = (registry[key] as SyncTableEntry | undefined)?.rowClass ?? null;
76
+ }
77
+ return classes;
78
+ }
79
+
80
+ /**
81
+ * A stable JSON serialization with recursively SORTED object keys, so two structurally equal values
82
+ * serialize identically regardless of key insertion order (`z.toJSONSchema`'s property order follows the
83
+ * schema's declaration order, which an author may reshuffle without changing the contract).
84
+ */
85
+ function stableStringify(value: unknown): string {
86
+ if (Array.isArray(value)) {
87
+ return `[${value.map(stableStringify).join(",")}]`;
88
+ }
89
+ if (value !== null && typeof value === "object") {
90
+ const entries = Object.entries(value as Record<string, unknown>)
91
+ .filter(([, item]) => item !== undefined)
92
+ .sort(([a], [b]) => asString(a, b))
93
+ .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`);
94
+ return `{${entries.join(",")}}`;
95
+ }
96
+ return JSON.stringify(value) ?? "null";
97
+ }
98
+
99
+ /**
100
+ * The canonical string of ONE Event stream's contract: its payload schema (as a JSON Schema, stably
101
+ * stringified), its identity declaration (field name → claim path, sorted), and its author-supplied
102
+ * `revision`.
103
+ *
104
+ * The payload is converted with `io: "input"` because the schema is a PARSE contract (what a client may
105
+ * append), and with `unrepresentable: "any"` so a schema using a type JSON Schema cannot express degrades to
106
+ * a coarser canonical form instead of throwing at lock time — a lock build must never fail on a legal
107
+ * registry. The cost of that choice is under-detection for such a type, which the next two paragraphs bound.
108
+ *
109
+ * **The blind spot is real and named.** JSON Schema cannot express a zod refinement or transform, so
110
+ * `z.string().refine(v => v.length >= 3)` and the incompatible `>= 10` version canonicalize identically —
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
113
+ * on any acceptance-logic change the JSON Schema cannot carry, and the stream's hash shifts.
114
+ *
115
+ * The hash exists to DETECT change, not to VALIDATE compatibility. ADR-0053 decision 1 binds a stream's
116
+ * payload schema to backward-compatible evolution (events written offline under the old schema are still in
117
+ * flight) and requires a NEW Event-stream name for an incompatible change — a rule no hash can check. All the
118
+ * lock can do is force the change to be seen and reviewed, which is what the `risky` verdict is for.
119
+ */
120
+ function canonicalEventStreamString(entry: EventStreamEntry): string {
121
+ let payload: string;
122
+ try {
123
+ payload = stableStringify(z.toJSONSchema(entry.payload, { io: "input", unrepresentable: "any" }));
124
+ } catch {
125
+ // Defensive: an exotic schema `toJSONSchema` still refuses. A constant canonical form under-detects
126
+ // change for that one stream rather than breaking every consumer's lock build.
127
+ payload = '"<unrepresentable>"';
128
+ }
129
+ const identity = Object.keys(entry.identity ?? {})
130
+ .sort(asString)
131
+ .map((field) => [field, [...(entry.identity[field]?.claimPath ?? [])]]);
132
+ // Absent === 0, so adopting `revision` on an unchanged stream by declaring `revision: 1` IS a change (as it
133
+ // should be: an author only reaches for it because the invisible logic moved).
134
+ return stableStringify({ payload, identity, revision: entry.revision ?? 0 });
135
+ }
136
+
137
+ /** The canonical contract hash of every registered Event stream, with sorted keys so a lock is stable. */
138
+ export function registryEventStreams(registry: SyncTableRegistry): RegistryEventStreams {
139
+ const streams = getSyncRegistryStreams(registry);
140
+ const hashes: RegistryEventStreams = {};
141
+ if (!streams) {
142
+ return hashes;
143
+ }
144
+ for (const name of Object.keys(streams).sort(asString)) {
145
+ const entry = streams[name];
146
+ if (entry) {
147
+ hashes[name] = hashString(canonicalEventStreamString(entry));
148
+ }
149
+ }
150
+ return hashes;
32
151
  }
33
152
 
34
153
  const SEVERITY_RANK: Record<RegistryChangeSeverity, number> = { compatible: 0, risky: 1, breaking: 2 };
@@ -40,9 +159,17 @@ function maxSeverity(changes: readonly RegistryChange[]): RegistryChangeSeverity
40
159
  );
41
160
  }
42
161
 
43
- /** Build the committed lock (fingerprint + canonical shape) for a registry. */
162
+ /**
163
+ * Build the committed lock (fingerprint + canonical shape + row classification + Event streams) for a
164
+ * registry.
165
+ */
44
166
  export function buildRegistryLock(registry: SyncTableRegistry): RegistryLock {
45
- return { version: fingerprintRegistry(registry), tables: canonicalizeRegistry(registry) };
167
+ return {
168
+ version: fingerprintRegistry(registry),
169
+ tables: canonicalizeRegistry(registry),
170
+ rowClasses: registryRowClasses(registry),
171
+ streams: registryEventStreams(registry),
172
+ };
46
173
  }
47
174
 
48
175
  function diffTable(table: string, previous: CanonicalTable, next: CanonicalTable, changes: RegistryChange[]): void {
@@ -156,14 +283,102 @@ function diffShape(
156
283
  }
157
284
  }
158
285
 
159
- /** Classify the change from one canonical registry shape to another. */
286
+ /**
287
+ * Row-classification changes (ADR-0052). Classification is authoring metadata, invisible to the runtime and
288
+ * to the fingerprint — but it decides which registry invariants an entry is ENROLLED in, so a change to it
289
+ * is exactly the kind of quiet authoring drift the gate exists to surface.
290
+ *
291
+ * - class → different class: `risky` (the entry left one invariant's coverage and joined another's).
292
+ * - unclassified → classified: `compatible` (pure adoption; nothing loses coverage).
293
+ * - classified → unclassified: `risky` (the entry un-enrols from every invariant bound to that class).
294
+ */
295
+ function diffRowClass(table: string, previous: string | null, next: string | null, changes: RegistryChange[]): void {
296
+ if (previous === next) {
297
+ return;
298
+ }
299
+ if (previous == null) {
300
+ changes.push({ severity: "compatible", table, detail: `row class declared: ${next}` });
301
+ return;
302
+ }
303
+ if (next == null) {
304
+ changes.push({
305
+ severity: "risky",
306
+ table,
307
+ detail: `row class removed: ${previous} (un-enrols from registry invariants)`,
308
+ });
309
+ return;
310
+ }
311
+ changes.push({
312
+ severity: "risky",
313
+ table,
314
+ detail: `row class changed: ${previous} -> ${next} (review invariant enrollment)`,
315
+ });
316
+ }
317
+
318
+ /**
319
+ * Event-stream changes (ADR-0053 decision 1). The Event lane is invisible to the fingerprint, so the lock is
320
+ * the ONLY place a change to it can surface.
321
+ *
322
+ * - added → `compatible` (a new Event stream takes nothing away; a client that does not know it appends
323
+ * nothing to it).
324
+ * - removed → `breaking`. Events for it are already durable in some clients' Outboxes, and a server that no
325
+ * longer knows the stream can only park them (`deferred`, retried forever) or refuse them — the removal is
326
+ * a deliberate release decision, exactly what the gate exists to force.
327
+ * - payload/identity hash changed → `risky`. The hash cannot judge compatibility (see
328
+ * {@link canonicalEventStreamString}); the rule it enforces socially is the ADR's: evolve only
329
+ * backward-compatibly, and take a NEW Event-stream name for anything else.
330
+ */
331
+ function diffEventStreams(previous: RegistryEventStreams, next: RegistryEventStreams, changes: RegistryChange[]): void {
332
+ for (const name of Object.keys(previous).sort(asString)) {
333
+ const nextHash = next[name];
334
+ if (nextHash === undefined) {
335
+ changes.push({
336
+ severity: "breaking",
337
+ table: name,
338
+ detail: `event stream removed: ${name} (in-flight client events will be deferred/refused)`,
339
+ });
340
+ continue;
341
+ }
342
+ if (previous[name] !== nextHash) {
343
+ changes.push({
344
+ severity: "risky",
345
+ table: name,
346
+ detail:
347
+ `event stream ${name} payload/identity changed (must remain backward-compatible; ` +
348
+ `incompatible change requires a new Event-stream name)`,
349
+ });
350
+ }
351
+ }
352
+
353
+ for (const name of Object.keys(next).sort(asString)) {
354
+ if (!(name in previous)) {
355
+ changes.push({ severity: "compatible", table: name, detail: `event stream added: ${name}` });
356
+ }
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Classify the change from one canonical registry shape to another. `rowClasses` carries each side's row
362
+ * classification (ADR-0052) and `streams` each side's Event-stream contract hashes (ADR-0053) — both siblings
363
+ * of the canonical tables, never fields of them (see {@link RegistryLock.rowClasses} /
364
+ * {@link RegistryLock.streams}). An omitted side reads as entirely unclassified / streamless, which is how a
365
+ * lock predating either field diffs as adoption rather than as spurious risk.
366
+ *
367
+ * `RegistryChange.table` names the SUBJECT of the change, which for an Event-stream change is the
368
+ * Event-stream name rather than a registry table key; each such `detail` says "event stream …" so the
369
+ * summary line stays unambiguous.
370
+ */
160
371
  export function diffCanonicalRegistries(
161
372
  previous: readonly CanonicalTable[],
162
373
  next: readonly CanonicalTable[],
374
+ rowClasses?: { previous?: RegistryRowClasses | undefined; next?: RegistryRowClasses | undefined },
375
+ streams?: { previous?: RegistryEventStreams | undefined; next?: RegistryEventStreams | undefined },
163
376
  ): RegistryDiff {
164
377
  const changes: RegistryChange[] = [];
165
378
  const prevByKey = new Map(previous.map((table) => [table.key, table]));
166
379
  const nextByKey = new Map(next.map((table) => [table.key, table]));
380
+ const prevClasses = rowClasses?.previous ?? {};
381
+ const nextClasses = rowClasses?.next ?? {};
167
382
 
168
383
  for (const [key, prevTable] of prevByKey) {
169
384
  const nextTable = nextByKey.get(key);
@@ -172,6 +387,7 @@ export function diffCanonicalRegistries(
172
387
  continue;
173
388
  }
174
389
  diffTable(key, prevTable, nextTable, changes);
390
+ diffRowClass(key, prevClasses[key] ?? null, nextClasses[key] ?? null, changes);
175
391
  }
176
392
 
177
393
  for (const key of nextByKey.keys()) {
@@ -180,17 +396,29 @@ export function diffCanonicalRegistries(
180
396
  }
181
397
  }
182
398
 
399
+ diffEventStreams(streams?.previous ?? {}, streams?.next ?? {}, changes);
400
+
183
401
  return { changes, severity: maxSeverity(changes) };
184
402
  }
185
403
 
186
404
  /** Classify the change between two registries. */
187
405
  export function compareRegistries(previous: SyncTableRegistry, next: SyncTableRegistry): RegistryDiff {
188
- return diffCanonicalRegistries(canonicalizeRegistry(previous), canonicalizeRegistry(next));
406
+ return diffCanonicalRegistries(
407
+ canonicalizeRegistry(previous),
408
+ canonicalizeRegistry(next),
409
+ { previous: registryRowClasses(previous), next: registryRowClasses(next) },
410
+ { previous: registryEventStreams(previous), next: registryEventStreams(next) },
411
+ );
189
412
  }
190
413
 
191
414
  /** Classify a registry against a committed lock baseline. */
192
415
  export function diffRegistryAgainstLock(registry: SyncTableRegistry, lock: RegistryLock): RegistryDiff {
193
- return diffCanonicalRegistries(lock.tables, canonicalizeRegistry(registry));
416
+ return diffCanonicalRegistries(
417
+ lock.tables,
418
+ canonicalizeRegistry(registry),
419
+ { previous: lock.rowClasses, next: registryRowClasses(registry) },
420
+ { previous: lock.streams, next: registryEventStreams(registry) },
421
+ );
194
422
  }
195
423
 
196
424
  /**
@@ -0,0 +1,218 @@
1
+ import type { SQL } from "drizzle-orm";
2
+ import { getTableConfig, PgDialect } from "drizzle-orm/pg-core";
3
+
4
+ import { buildRowFilterShape, type JwtClaims, type RowFilterShape } from "./config";
5
+ import { getSyncRegistryRowClasses, type SyncTableEntry, type SyncTableRegistry } from "./registry";
6
+
7
+ /**
8
+ * Registry invariants (ADR-0052): assert a claim about the RENDERED authorization artifacts of every entry
9
+ * a classification binds, evaluated against named claims personas — the whole-registry counterpart to
10
+ * `assertReadContractPreserved`'s per-table read-contract check.
11
+ *
12
+ * It exists because a privacy/visibility invariant spanning many entries drifts in two structural ways that
13
+ * per-entry review cannot catch:
14
+ *
15
+ * 1. **Read/write asymmetry** — the Electric row filter and the Postgres RLS policies are two engines, so one
16
+ * can be tightened (or loosened) without the other. The assertion audits BOTH surfaces of every bound
17
+ * entry in one predicate, so "readable but unwritable" (or the reverse) is a test failure, not a bug report.
18
+ * 2. **Under-enumeration** — an invariant expressed over a hand-maintained list of tables silently stops
19
+ * covering the registry the moment someone adds an entry. Binding by {@link SyncTableEntry.rowClass}
20
+ * inverts that: with a declared `rowClasses` vocabulary, a new entry cannot even be registered without
21
+ * being classified, so it joins its class's invariants by construction.
22
+ *
23
+ * It audits RENDERED output, so it sees things the fingerprint structurally cannot (the `customWhere` BODY
24
+ * is a closure — only its presence and `RowFilterSpec.revision` are hashed). The trade: it sees exactly the
25
+ * claims fixtures you give it, and nothing else.
26
+ */
27
+
28
+ /** One rendered write policy on a bound entry's Postgres table, as the invariant predicate sees it. */
29
+ export interface RenderedPolicy {
30
+ /** The policy name as declared (e.g. `widgets_select_owner_or_admin`). */
31
+ name: string;
32
+ /** The command the policy governs: `select` | `insert` | `update` | `delete`, or `all` when undeclared. */
33
+ command: string;
34
+ /** The `USING` predicate rendered to inline SQL text, or `null` when the policy declares none. */
35
+ using: string | null;
36
+ /** The `WITH CHECK` predicate rendered to inline SQL text, or `null` when the policy declares none. */
37
+ withCheck: string | null;
38
+ }
39
+
40
+ /** One (entry × claims fixture) cell handed to a {@link RegistryInvariantSpec.holds} predicate. */
41
+ export interface RegistryInvariantCell {
42
+ /** The entry's key in the registry. */
43
+ key: string;
44
+ entry: SyncTableEntry;
45
+ /** The entry's classification, or `undefined` when it carries none (possible only for a `appliesTo` predicate). */
46
+ rowClass: string | undefined;
47
+ /** The fixture's name, as declared in {@link RegistryInvariantSpec.claimsFixtures}. */
48
+ fixtureName: string;
49
+ claims: JwtClaims;
50
+ /**
51
+ * The read filter this entry sends to Electric FOR THESE CLAIMS — the real read pipeline's output
52
+ * (`buildRowFilterShape`, exactly what the proxy calls per shape request).
53
+ *
54
+ * `null` means **unfiltered**, and covers both ways that arises: the entry declares no shape/`rowFilter`
55
+ * at all, or its `customWhere` returned `null` for these claims (the documented "bypass filtering, every
56
+ * row is visible" answer — e.g. an admin persona). Both are the same statement about what the client
57
+ * receives, which is what an invariant reasons about; distinguish them via `entry.shape?.rowFilter` if a
58
+ * predicate genuinely needs to.
59
+ */
60
+ renderedWhere: RowFilterShape | null;
61
+ /** Every RLS policy attached to the entry's Postgres table, rendered to inline SQL text. */
62
+ renderedPolicies: RenderedPolicy[];
63
+ }
64
+
65
+ export interface RegistryInvariantSpec {
66
+ /** Human name for the invariant, used as the error header (e.g. "private rows never leave their owner"). */
67
+ name: string;
68
+ /**
69
+ * Which entries the invariant binds: a list of {@link SyncTableEntry.rowClass} values (the normal form —
70
+ * coverage then grows with the registry), or a predicate over the entry for the rare case a class cannot
71
+ * express. When the registry declares its `rowClasses`, a class named here that is not in that vocabulary
72
+ * throws immediately — a typo would otherwise bind nothing and pass vacuously.
73
+ */
74
+ appliesTo: readonly string[] | ((entry: SyncTableEntry, key: string) => boolean);
75
+ /**
76
+ * The claims personas the invariant is evaluated against, by name (`{ anonymous: {}, owner: {...} }`). Every
77
+ * bound entry is checked against every fixture; the names appear in the failure report.
78
+ */
79
+ claimsFixtures: Record<string, JwtClaims>;
80
+ /**
81
+ * The invariant itself, over ONE (entry × fixture) cell's rendered artifacts. Return `true` when it holds,
82
+ * `false` or a reason string when it does not — a reason string is reproduced verbatim in the error, so
83
+ * prefer it.
84
+ */
85
+ holds: (cell: RegistryInvariantCell) => boolean | string;
86
+ }
87
+
88
+ // Policy predicates are rendered with values INLINED, matching how `CREATE POLICY` DDL carries them (and how
89
+ // supabase-rls.ts's own text builders render): a `$n` bind would be meaningless to compare against.
90
+ const policyDialect = new PgDialect();
91
+
92
+ function renderPolicyPredicate(fragment: SQL | undefined): string | null {
93
+ return fragment == null ? null : policyDialect.sqlToQuery(fragment.inlineParams()).sql;
94
+ }
95
+
96
+ /**
97
+ * The write policies attached to an entry's Postgres table, rendered to inline SQL text. Read straight off
98
+ * drizzle's own table config, so it sees exactly what the migration will emit — including policies passed
99
+ * through `defineSyncTable`'s `policies:`/`extras:` options, which are merged into the `pgTable` extras.
100
+ *
101
+ * A read PROJECTION's `table` IS its owner's, so a projection reports the OWNER's policies. That is correct:
102
+ * a projection owns no table and adds no DDL, so the owner's policies are the ones governing its rows.
103
+ */
104
+ function renderPolicies(entry: SyncTableEntry): RenderedPolicy[] {
105
+ return getTableConfig(entry.table).policies.map((policy) => ({
106
+ name: policy.name,
107
+ // drizzle leaves `for` undefined when the policy does not narrow the command, which is Postgres's `ALL`.
108
+ command: policy.for ?? "all",
109
+ using: renderPolicyPredicate(policy.using),
110
+ withCheck: renderPolicyPredicate(policy.withCheck),
111
+ }));
112
+ }
113
+
114
+ /** The read filter for these claims, through the real pipeline the proxy uses. */
115
+ function renderWhere(entry: SyncTableEntry, claims: JwtClaims): RowFilterShape | null {
116
+ const rowFilter = entry.shape?.rowFilter;
117
+ return rowFilter == null ? null : buildRowFilterShape(rowFilter, claims);
118
+ }
119
+
120
+ function boundEntries(
121
+ registry: SyncTableRegistry,
122
+ appliesTo: RegistryInvariantSpec["appliesTo"],
123
+ ): Array<[string, SyncTableEntry]> {
124
+ const entries = Object.entries(registry) as Array<[string, SyncTableEntry]>;
125
+ if (typeof appliesTo === "function") {
126
+ return entries.filter(([key, entry]) => appliesTo(entry, key));
127
+ }
128
+ const classes = new Set(appliesTo);
129
+ return entries.filter(([, entry]) => entry.rowClass != null && classes.has(entry.rowClass));
130
+ }
131
+
132
+ /**
133
+ * Assert a {@link RegistryInvariantSpec} over a registry: for every entry the invariant binds, and every
134
+ * claims fixture, evaluate `holds` against the entry's RENDERED read filter and write policies. Pure audit —
135
+ * it renders through the production code paths but changes no runtime behaviour.
136
+ *
137
+ * Call it at module eval beside the registry (or in a test), the same way {@link assertReadContractPreserved}
138
+ * is called, so a violation fails closed rather than shipping.
139
+ *
140
+ * ```ts
141
+ * assertRegistryInvariant(registry, {
142
+ * name: "private rows are never visible to an anonymous caller",
143
+ * appliesTo: ["private"],
144
+ * claimsFixtures: { anonymous: {}, member: { sub: "u-1" } },
145
+ * holds: ({ fixtureName, renderedWhere }) =>
146
+ * fixtureName !== "anonymous" || renderedWhere?.where === "false" || "anonymous read is not denied",
147
+ * });
148
+ * ```
149
+ *
150
+ * Two deliberate fail-closed behaviours:
151
+ * - An `appliesTo` class the registry's declared vocabulary does not contain throws immediately (a typo must
152
+ * not pass as "nothing to check").
153
+ * - An invariant that binds ZERO entries throws. A spec that checks nothing is a bug in the spec — nearly
154
+ * always a wrong class name or an invariant left behind after its class was renamed — and silently passing
155
+ * is the exact failure mode this whole mechanism exists to remove.
156
+ *
157
+ * Every failing cell is collected and reported together: the header names the invariant, then one
158
+ * `entry (fixture): reason` line per violation. Never first-failure-only — you fix a classification-wide
159
+ * problem in one pass, not one re-run per entry.
160
+ */
161
+ export function assertRegistryInvariant(registry: SyncTableRegistry, spec: RegistryInvariantSpec): void {
162
+ const declaredClasses = getSyncRegistryRowClasses(registry);
163
+ if (Array.isArray(spec.appliesTo) && declaredClasses != null) {
164
+ const unknown = spec.appliesTo.filter((rowClass) => !declaredClasses.includes(rowClass));
165
+ if (unknown.length > 0) {
166
+ throw new Error(
167
+ `registry invariant "${spec.name}" applies to unknown row class(es): ${unknown.join(", ")}. This ` +
168
+ `registry declares [${declaredClasses.join(", ")}] — a misspelled class would bind no entries and ` +
169
+ `pass vacuously, so it is rejected here.`,
170
+ );
171
+ }
172
+ }
173
+
174
+ const bound = boundEntries(registry, spec.appliesTo);
175
+ if (bound.length === 0) {
176
+ const binding = Array.isArray(spec.appliesTo) ? `row class(es) ${spec.appliesTo.join(", ")}` : "its predicate";
177
+ throw new Error(
178
+ `registry invariant "${spec.name}" binds no entries (${binding}). An invariant that checks nothing ` +
179
+ `passes vacuously, which defeats the point — check the class name(s) against the entries' rowClass, ` +
180
+ `or drop the invariant if its rows are gone.`,
181
+ );
182
+ }
183
+
184
+ const fixtures = Object.entries(spec.claimsFixtures);
185
+ if (fixtures.length === 0) {
186
+ throw new Error(
187
+ `registry invariant "${spec.name}" declares no claims fixtures: the invariant is evaluated per persona, ` +
188
+ `so with none it checks nothing. Declare at least one (e.g. { anonymous: {} }).`,
189
+ );
190
+ }
191
+
192
+ const violations: string[] = [];
193
+ for (const [key, entry] of bound) {
194
+ const renderedPolicies = renderPolicies(entry);
195
+ for (const [fixtureName, claims] of fixtures) {
196
+ const verdict = spec.holds({
197
+ key,
198
+ entry,
199
+ rowClass: entry.rowClass,
200
+ fixtureName,
201
+ claims,
202
+ renderedWhere: renderWhere(entry, claims),
203
+ renderedPolicies,
204
+ });
205
+ if (verdict === true) {
206
+ continue;
207
+ }
208
+ violations.push(`${key} (${fixtureName}): ${typeof verdict === "string" ? verdict : "invariant does not hold"}`);
209
+ }
210
+ }
211
+
212
+ if (violations.length > 0) {
213
+ throw new Error(
214
+ `registry invariant "${spec.name}" is violated by ${violations.length} of ${bound.length * fixtures.length} ` +
215
+ `checked cells:\n ${violations.join("\n ")}`,
216
+ );
217
+ }
218
+ }