latticesql 3.3.5 → 3.4.1

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.
package/dist/index.d.cts CHANGED
@@ -44,130 +44,6 @@ declare function manifestPath(outputDir: string): string;
44
44
  declare function readManifest(outputDir: string): LatticeManifest | null;
45
45
  declare function writeManifest(outputDir: string, manifest: LatticeManifest): void;
46
46
 
47
- /**
48
- * Adapter dialect identifier. Used by callers that need to issue
49
- * dialect-specific SQL (e.g. the migration runner's `pg_advisory_xact_lock`
50
- * on Postgres). Lattice itself uses this only for cross-dialect concerns
51
- * the dialect-translation layer can't paper over — most application code
52
- * should never need to branch on it.
53
- */
54
- type AdapterDialect = 'sqlite' | 'postgres';
55
- /** Pluggable storage backend interface */
56
- interface StorageAdapter {
57
- /** Adapter dialect. Drives the few cross-dialect branches in lattice core. */
58
- readonly dialect: AdapterDialect;
59
- /** Execute a statement with no return value */
60
- run(sql: string, params?: unknown[]): void;
61
- /** Execute a statement and return one row or undefined */
62
- get(sql: string, params?: unknown[]): Row | undefined;
63
- /** Execute a statement and return all rows */
64
- all(sql: string, params?: unknown[]): Row[];
65
- /** Prepare and cache a statement for repeated execution */
66
- prepare(sql: string): PreparedStatement;
67
- /** Open the connection */
68
- open(): void;
69
- /** Close the connection */
70
- close(): void;
71
- /**
72
- * Return the column names of a table. Used by the schema layer to detect
73
- * missing columns and to drive entity-context queries. Implementations
74
- * dispatch on their own dialect (SQLite uses `PRAGMA table_info`, Postgres
75
- * uses `information_schema.columns`).
76
- */
77
- introspectColumns(table: string): string[];
78
- /**
79
- * Add a column to an existing table. Implementations handle dialect quirks:
80
- * SQLite cannot use non-constant defaults in `ALTER TABLE ADD COLUMN` and
81
- * must backfill them; Postgres handles `DEFAULT NOW()`/`DEFAULT random()`
82
- * natively.
83
- */
84
- addColumn(table: string, column: string, typeSpec: string): void;
85
- /** Async equivalent of run(). Returns when the statement has completed. */
86
- runAsync?(sql: string, params?: unknown[]): Promise<void>;
87
- /** Async equivalent of get(). */
88
- getAsync?(sql: string, params?: unknown[]): Promise<Row | undefined>;
89
- /** Async equivalent of all(). */
90
- allAsync?(sql: string, params?: unknown[]): Promise<Row[]>;
91
- /** Async equivalent of introspectColumns(). Used by the boot-path schema apply. */
92
- introspectColumnsAsync?(table: string): Promise<string[]>;
93
- /** Async equivalent of addColumn(). Used by the boot-path schema apply. */
94
- addColumnAsync?(table: string, column: string, typeSpec: string): Promise<void>;
95
- /**
96
- * Async equivalent of prepare().
97
- *
98
- * Note: in Postgres under transaction-mode pooling (pgbouncer port 6543),
99
- * server-side prepared statements cannot persist across calls because the
100
- * upstream connection is returned to the pool at COMMIT. The PostgresAdapter
101
- * implementation therefore stores SQL + binding shape and re-executes per
102
- * call — semantically a prepared statement, but without SQLite-style
103
- * binding cost amortization. SQLite's implementation keeps real prepared
104
- * statements via better-sqlite3.
105
- *
106
- * Inside `withClient(fn)`, prefer the `tx.run`/`tx.get`/`tx.all` methods
107
- * directly rather than `prepareAsync` — they share the same checked-out
108
- * client for the transaction lifetime and avoid the per-call setup.
109
- */
110
- prepareAsync?(sql: string): PreparedStatementAsync;
111
- /**
112
- * Run `fn` against a single connection-scoped client, wrapped in BEGIN/COMMIT.
113
- * `fn` receives a `TxClient` whose `run`/`get`/`all` calls are guaranteed to
114
- * land on the same upstream connection for the lifetime of the transaction.
115
- * Throws inside `fn` cause an automatic ROLLBACK; otherwise the transaction
116
- * commits when `fn` resolves.
117
- *
118
- * Replacement for raw `adapter.run('BEGIN')` / `adapter.run('COMMIT')`
119
- * sequences. With `pg.Pool`-backed adapters, raw BEGIN/COMMIT calls can
120
- * land on different upstream connections and break atomicity silently;
121
- * `withClient(fn)` is the only way to hold a single connection across the
122
- * entire transaction.
123
- *
124
- * SQLite implementations may execute `fn` inside `db.transaction(fn)` (or
125
- * the equivalent `BEGIN`/`COMMIT` sequence) since better-sqlite3 has no
126
- * pool to reason about — every operation runs against the single open
127
- * connection. The TxClient surface is intentionally identical across
128
- * dialects so callers don't need to branch on adapter type.
129
- */
130
- withClient?<T>(fn: (tx: TxClient) => Promise<T>): Promise<T>;
131
- }
132
- interface PreparedStatement {
133
- run(...params: unknown[]): {
134
- changes: number;
135
- lastInsertRowid: number | bigint;
136
- };
137
- get(...params: unknown[]): Row | undefined;
138
- all(...params: unknown[]): Row[];
139
- }
140
- /** Async equivalent of {@link PreparedStatement}. */
141
- interface PreparedStatementAsync {
142
- run(...params: unknown[]): Promise<{
143
- changes: number;
144
- lastInsertRowid: number | bigint;
145
- }>;
146
- get(...params: unknown[]): Promise<Row | undefined>;
147
- all(...params: unknown[]): Promise<Row[]>;
148
- }
149
- /**
150
- * Connection-scoped client passed to `StorageAdapter.withClient(fn)`. All
151
- * `run`/`get`/`all` calls made against the same `TxClient` instance are
152
- * guaranteed to land on the same upstream connection for the transaction's
153
- * lifetime — that's the whole point of withClient. This makes raw BEGIN/COMMIT
154
- * call-site migrations to withClient mechanical: rename `this._adapter.run(sql, params)`
155
- * to `await tx.run(sql, params)`, drop the manual BEGIN/COMMIT/ROLLBACK lines.
156
- *
157
- * `run` returns `{ changes }` so callers that count affected rows (e.g.
158
- * INSERT-OR-IGNORE patterns) can do so without an extra SELECT roundtrip.
159
- * SQLite reports `db.prepare(...).run(...).changes`; Postgres reports
160
- * `pg.QueryResult.rowCount` (zero when the driver doesn't surface a count
161
- * for the query type, matching the SQLite contract).
162
- */
163
- interface TxClient {
164
- run(sql: string, params?: unknown[]): Promise<{
165
- changes: number;
166
- }>;
167
- get(sql: string, params?: unknown[]): Promise<Row | undefined>;
168
- all(sql: string, params?: unknown[]): Promise<Row[]>;
169
- }
170
-
171
47
  /**
172
48
  * Optional query refinements shared by `hasMany`, `manyToMany`, and
173
49
  * `belongsTo` sources. All fields are additive — omitting them preserves
@@ -1685,6 +1561,154 @@ interface ReconcileResult extends RenderResult {
1685
1561
  reverseSeedRequired: ReverseSeedDetection[];
1686
1562
  }
1687
1563
 
1564
+ /**
1565
+ * Adapter dialect identifier. Used by callers that need to issue
1566
+ * dialect-specific SQL (e.g. the migration runner's `pg_advisory_xact_lock`
1567
+ * on Postgres). Lattice itself uses this only for cross-dialect concerns
1568
+ * the dialect-translation layer can't paper over — most application code
1569
+ * should never need to branch on it.
1570
+ */
1571
+ type AdapterDialect = 'sqlite' | 'postgres';
1572
+ /** Pluggable storage backend interface */
1573
+ interface StorageAdapter {
1574
+ /** Adapter dialect. Drives the few cross-dialect branches in lattice core. */
1575
+ readonly dialect: AdapterDialect;
1576
+ /** Execute a statement with no return value */
1577
+ run(sql: string, params?: unknown[]): void;
1578
+ /** Execute a statement and return one row or undefined */
1579
+ get(sql: string, params?: unknown[]): Row | undefined;
1580
+ /** Execute a statement and return all rows */
1581
+ all(sql: string, params?: unknown[]): Row[];
1582
+ /** Prepare and cache a statement for repeated execution */
1583
+ prepare(sql: string): PreparedStatement;
1584
+ /** Open the connection */
1585
+ open(): void;
1586
+ /** Close the connection */
1587
+ close(): void;
1588
+ /**
1589
+ * Return the column names of a table. Used by the schema layer to detect
1590
+ * missing columns and to drive entity-context queries. Implementations
1591
+ * dispatch on their own dialect (SQLite uses `PRAGMA table_info`, Postgres
1592
+ * uses `information_schema.columns`).
1593
+ */
1594
+ introspectColumns(table: string): string[];
1595
+ /**
1596
+ * Add a column to an existing table. Implementations handle dialect quirks:
1597
+ * SQLite cannot use non-constant defaults in `ALTER TABLE ADD COLUMN` and
1598
+ * must backfill them; Postgres handles `DEFAULT NOW()`/`DEFAULT random()`
1599
+ * natively.
1600
+ */
1601
+ addColumn(table: string, column: string, typeSpec: string): void;
1602
+ /** Async equivalent of run(). Returns when the statement has completed. */
1603
+ runAsync?(sql: string, params?: unknown[]): Promise<void>;
1604
+ /** Async equivalent of get(). */
1605
+ getAsync?(sql: string, params?: unknown[]): Promise<Row | undefined>;
1606
+ /** Async equivalent of all(). */
1607
+ allAsync?(sql: string, params?: unknown[]): Promise<Row[]>;
1608
+ /** Async equivalent of introspectColumns(). Used by the boot-path schema apply. */
1609
+ introspectColumnsAsync?(table: string): Promise<string[]>;
1610
+ /** Async equivalent of addColumn(). Used by the boot-path schema apply. */
1611
+ addColumnAsync?(table: string, column: string, typeSpec: string): Promise<void>;
1612
+ /**
1613
+ * Async equivalent of prepare().
1614
+ *
1615
+ * Note: in Postgres under transaction-mode pooling (pgbouncer port 6543),
1616
+ * server-side prepared statements cannot persist across calls because the
1617
+ * upstream connection is returned to the pool at COMMIT. The PostgresAdapter
1618
+ * implementation therefore stores SQL + binding shape and re-executes per
1619
+ * call — semantically a prepared statement, but without SQLite-style
1620
+ * binding cost amortization. SQLite's implementation keeps real prepared
1621
+ * statements via better-sqlite3.
1622
+ *
1623
+ * Inside `withClient(fn)`, prefer the `tx.run`/`tx.get`/`tx.all` methods
1624
+ * directly rather than `prepareAsync` — they share the same checked-out
1625
+ * client for the transaction lifetime and avoid the per-call setup.
1626
+ */
1627
+ prepareAsync?(sql: string): PreparedStatementAsync;
1628
+ /**
1629
+ * Run `fn` against a single connection-scoped client, wrapped in BEGIN/COMMIT.
1630
+ * `fn` receives a `TxClient` whose `run`/`get`/`all` calls are guaranteed to
1631
+ * land on the same upstream connection for the lifetime of the transaction.
1632
+ * Throws inside `fn` cause an automatic ROLLBACK; otherwise the transaction
1633
+ * commits when `fn` resolves.
1634
+ *
1635
+ * Replacement for raw `adapter.run('BEGIN')` / `adapter.run('COMMIT')`
1636
+ * sequences. With `pg.Pool`-backed adapters, raw BEGIN/COMMIT calls can
1637
+ * land on different upstream connections and break atomicity silently;
1638
+ * `withClient(fn)` is the only way to hold a single connection across the
1639
+ * entire transaction.
1640
+ *
1641
+ * SQLite implementations may execute `fn` inside `db.transaction(fn)` (or
1642
+ * the equivalent `BEGIN`/`COMMIT` sequence) since better-sqlite3 has no
1643
+ * pool to reason about — every operation runs against the single open
1644
+ * connection. The TxClient surface is intentionally identical across
1645
+ * dialects so callers don't need to branch on adapter type.
1646
+ */
1647
+ withClient?<T>(fn: (tx: TxClient) => Promise<T>): Promise<T>;
1648
+ }
1649
+ interface PreparedStatement {
1650
+ run(...params: unknown[]): {
1651
+ changes: number;
1652
+ lastInsertRowid: number | bigint;
1653
+ };
1654
+ get(...params: unknown[]): Row | undefined;
1655
+ all(...params: unknown[]): Row[];
1656
+ }
1657
+ /** Async equivalent of {@link PreparedStatement}. */
1658
+ interface PreparedStatementAsync {
1659
+ run(...params: unknown[]): Promise<{
1660
+ changes: number;
1661
+ lastInsertRowid: number | bigint;
1662
+ }>;
1663
+ get(...params: unknown[]): Promise<Row | undefined>;
1664
+ all(...params: unknown[]): Promise<Row[]>;
1665
+ }
1666
+ /**
1667
+ * Connection-scoped client passed to `StorageAdapter.withClient(fn)`. All
1668
+ * `run`/`get`/`all` calls made against the same `TxClient` instance are
1669
+ * guaranteed to land on the same upstream connection for the transaction's
1670
+ * lifetime — that's the whole point of withClient. This makes raw BEGIN/COMMIT
1671
+ * call-site migrations to withClient mechanical: rename `this._adapter.run(sql, params)`
1672
+ * to `await tx.run(sql, params)`, drop the manual BEGIN/COMMIT/ROLLBACK lines.
1673
+ *
1674
+ * `run` returns `{ changes }` so callers that count affected rows (e.g.
1675
+ * INSERT-OR-IGNORE patterns) can do so without an extra SELECT roundtrip.
1676
+ * SQLite reports `db.prepare(...).run(...).changes`; Postgres reports
1677
+ * `pg.QueryResult.rowCount` (zero when the driver doesn't surface a count
1678
+ * for the query type, matching the SQLite contract).
1679
+ */
1680
+ interface TxClient {
1681
+ run(sql: string, params?: unknown[]): Promise<{
1682
+ changes: number;
1683
+ }>;
1684
+ get(sql: string, params?: unknown[]): Promise<Row | undefined>;
1685
+ all(sql: string, params?: unknown[]): Promise<Row[]>;
1686
+ }
1687
+
1688
+ /**
1689
+ * Options for {@link ReverseSyncEngine.process}.
1690
+ *
1691
+ * With no options the engine keeps its original behavior: only files with a
1692
+ * hand-written `reverseSync` are processed, and updates are applied via raw SQL.
1693
+ * The GUI file-loopback passes `apply` (to route writes through the changelog
1694
+ * path so a file edit is version-controlled exactly like a GUI edit) and
1695
+ * `useDefault` (to round-trip frontmatter + body `key: value` fields for files
1696
+ * that have no hand-written `reverseSync`).
1697
+ */
1698
+ interface ReverseSyncProcessOptions {
1699
+ /** Apply each update through a changelog-aware path instead of raw SQL. */
1700
+ apply?: (update: ReverseSyncUpdate) => Promise<void>;
1701
+ /** Derive updates for files lacking a hand-written `reverseSync`. */
1702
+ useDefault?: boolean;
1703
+ /** Called when a changed file produced no importable update (free-form/custom render). */
1704
+ onSkip?: (info: {
1705
+ table: string;
1706
+ slug: string;
1707
+ filename: string;
1708
+ filePath: string;
1709
+ }) => void;
1710
+ }
1711
+
1688
1712
  /**
1689
1713
  * Cryptographic erasure ("crypto-shred") for sources flagged sensitive.
1690
1714
  *
@@ -1792,6 +1816,16 @@ type RenderProgressCallback = (event: RenderProgress) => void;
1792
1816
  interface RenderOptions {
1793
1817
  onProgress?: RenderProgressCallback;
1794
1818
  signal?: AbortSignal;
1819
+ /**
1820
+ * Incremental render scope. When set, ONLY the entity-context tables affected
1821
+ * by a change to one of these tables are re-rendered — the changed table itself
1822
+ * plus any entity context that SOURCES from it (cross-table dependents) — and
1823
+ * every other table's manifest entry + rendered files are left untouched. Used
1824
+ * by the auto-render that fires on a single write or a single remote (cloud)
1825
+ * change, so a one-row edit re-renders one entity instead of the whole tree.
1826
+ * Omitted → a full render of everything (initial open, explicit `render()`).
1827
+ */
1828
+ changedTables?: ReadonlySet<string>;
1795
1829
  }
1796
1830
  /**
1797
1831
  * Coalesces high-frequency `table-progress` events down to ≤ ~5/sec per table,
@@ -1879,6 +1913,16 @@ declare class Lattice {
1879
1913
  private _autoRenderPending;
1880
1914
  private _autoRenderInFlight;
1881
1915
  private _autoRenderDebounceMs;
1916
+ /**
1917
+ * Incremental auto-render scope, accumulated between debounced renders. A write
1918
+ * or a remote (cloud) change records the AFFECTED table here, so the next
1919
+ * auto-render re-renders only that entity (+ its cross-table dependents) instead
1920
+ * of the whole tree. `_pendingRenderAll` forces a full render (the initial
1921
+ * render, or a change with no known table). Captured + reset when a render
1922
+ * starts, so changes during a render re-accumulate and re-trigger.
1923
+ */
1924
+ private _pendingRenderTables;
1925
+ private _pendingRenderAll;
1882
1926
  /** Cache of actual table columns (from PRAGMA), populated after init(). */
1883
1927
  private readonly _columnCache;
1884
1928
  /** Derived encryption key (from options.encryptionKey via scrypt). */
@@ -2276,6 +2320,55 @@ declare class Lattice {
2276
2320
  * not swallowed here.
2277
2321
  */
2278
2322
  renderInBackground(outputDir: string, opts?: RenderOptions): Promise<RenderResult>;
2323
+ /**
2324
+ * Install a per-viewer read-relation resolver for ALL renders (initial,
2325
+ * background, and the debounced auto-render that fires after every write).
2326
+ * A cloud member open passes `(t) => maskedReadViews.get(t) ?? t` so the
2327
+ * rendered context tree is read THROUGH the member's RLS connection + masking
2328
+ * views — making the on-disk tree the viewer's own scoped projection. Owner /
2329
+ * local SQLite leave it unset → identity → unchanged behavior. Set on the
2330
+ * engine (not per-render-call) so the opts-less auto-render path masks too.
2331
+ */
2332
+ setRenderReadRelation(fn: (table: string) => string): void;
2333
+ /**
2334
+ * Turn on the per-viewer enrichment fold for ALL renders. A cloud member open
2335
+ * calls this so the rendered context overlays the member-visible DERIVED
2336
+ * observations onto each ground row ({@link foldRenderRows}). Owner / local
2337
+ * SQLite leave it off → ground truth renders unchanged.
2338
+ */
2339
+ enableRenderFold(): void;
2340
+ /**
2341
+ * Request a debounced re-render (the same coalesced, pending-requeue path that
2342
+ * a local write triggers). Used to eagerly refresh a cloud member's rendered
2343
+ * tree when a REMOTE change arrives — notably an owner re-sharing or un-sharing
2344
+ * a row, after which the member's per-viewer projection must be recompiled. A
2345
+ * no-op when auto-render isn't enabled.
2346
+ *
2347
+ * Pass the CHANGED table so only that entity (+ its cross-table dependents) is
2348
+ * re-rendered instead of the whole tree; omit it to force a full render.
2349
+ */
2350
+ requestRender(table?: string): void;
2351
+ /**
2352
+ * True while a render is actively writing the context tree + manifest (auto-
2353
+ * render OR a guarded background render). The file-loopback watcher checks this
2354
+ * to avoid reverse-syncing mid-render — a pass then would read half-written
2355
+ * output whose manifest hash hasn't caught up yet and re-ingest the render's
2356
+ * OWN writes as spurious "file-edit" changes.
2357
+ */
2358
+ isRendering(): boolean;
2359
+ /**
2360
+ * Fold the viewer-visible DERIVED observations onto a table's ground rows in one
2361
+ * batched changelog read — the render-time, whole-table analogue of
2362
+ * {@link foldForViewer} (which is per-row). Read THROUGH this connection: on a
2363
+ * cloud member connection the changelog RLS (`lattice_changelog_sel`) already
2364
+ * drops any derived observation whose sources the member can't all reach AND
2365
+ * hides every owner-only ground-truth/audit entry — so what returns is exactly
2366
+ * the member-visible derived set, and overlaying it is leak-free by construction
2367
+ * (the database, not this code, is the enforcement point). One read per table,
2368
+ * never per row (the per-row `history()` fan-out would be an unbounded hot-path
2369
+ * cost). A no-op when the changelog substrate is absent or nothing is derived.
2370
+ */
2371
+ foldRenderRows(table: string, rows: Row[]): Promise<Row[]>;
2279
2372
  sync(outputDir: string): Promise<SyncResult>;
2280
2373
  /**
2281
2374
  * Recover rows from rendered files into empty database tables.
@@ -2291,6 +2384,28 @@ declare class Lattice {
2291
2384
  */
2292
2385
  reverseSeed(outputDir: string): Promise<ReverseSeedResult>;
2293
2386
  reconcile(outputDir: string, options?: ReconcileOptions): Promise<ReconcileResult>;
2387
+ /** Build/refresh the full-text index for every `fts`-configured table (idempotent;
2388
+ * `ensureFtsIndex` creates the index, triggers, and backfills existing rows). */
2389
+ private _buildFtsIndexes;
2390
+ /**
2391
+ * Rebuild the full-text search indexes for all `fts`-configured tables and
2392
+ * backfill existing rows. `init()` runs this on an empty DB; this public entry
2393
+ * point re-runs it AFTER rows are present — notably after a migrate-to-cloud row
2394
+ * copy, which otherwise leaves the cloud with data but no `__lattice_fts_*`
2395
+ * tables (so search/the assistant find nothing). Idempotent.
2396
+ */
2397
+ rebuildFtsIndexes(): Promise<void>;
2398
+ /**
2399
+ * Run reverse-sync against the rendered tree at `outputDir` and return what was
2400
+ * applied. Unlike {@link reconcile} (which runs reverse-sync with raw SQL as a
2401
+ * pre-render step), this is the changelog-aware entry point the GUI file-loopback
2402
+ * uses: pass `apply` to route each update through a versioned write (so a file
2403
+ * edit is recorded exactly like a GUI edit) and `useDefault` to round-trip
2404
+ * frontmatter + body `key: value` fields for files lacking a hand-written
2405
+ * `reverseSync`. Compares file hashes against the current manifest, so a
2406
+ * render-written file is recognized as an echo and skipped.
2407
+ */
2408
+ reverseSyncFromFiles(outputDir: string, opts?: ReverseSyncProcessOptions): Promise<ReverseSyncResult>;
2294
2409
  watch(outputDir: string, opts?: WatchOptions): Promise<StopFn>;
2295
2410
  on(event: 'audit', handler: EventHandler<AuditEvent>): this;
2296
2411
  on(event: 'render', handler: EventHandler<RenderResult>): this;
@@ -2391,6 +2506,10 @@ declare class Lattice {
2391
2506
  /** Turn off automatic rendering and cancel any pending render. */
2392
2507
  disableAutoRender(): this;
2393
2508
  private _scheduleAutoRender;
2509
+ /** Arm the debounce timer if not already armed. Does NOT change the render
2510
+ * scope — used both by `_scheduleAutoRender` and the post-render re-arm so a
2511
+ * re-arm never escalates a pending incremental render to a full one. */
2512
+ private _armAutoRenderTimer;
2394
2513
  /**
2395
2514
  * Shared single-flight render path used by {@link renderInBackground}.
2396
2515
  *
@@ -4148,14 +4267,6 @@ declare function provisionMemberRole(db: Lattice, role: string, password: string
4148
4267
  * its columns joined by TAB, matching Lattice's serialization.
4149
4268
  */
4150
4269
  declare function setRowVisibility(db: Lattice, table: string, pk: string, visibility: string): Promise<void>;
4151
- /**
4152
- * Per-card audience override: grant (or revoke) one member access to ONE masked
4153
- * cell — a specific (table, pk, column) — without changing the column's
4154
- * schema-level audience. Owner-only (the SQL function raises for a non-owner).
4155
- * `pk` is the row's canonical primary-key string.
4156
- */
4157
- declare function grantCell(db: Lattice, table: string, pk: string, column: string, grantee: string): Promise<void>;
4158
- declare function revokeCell(db: Lattice, table: string, pk: string, column: string, grantee: string): Promise<void>;
4159
4270
  /**
4160
4271
  * Remove a member: clear its privileges and drop the role. NOTE: rows the member
4161
4272
  * owned remain in their tables but become unreachable (their `owner_role` no
@@ -4191,6 +4302,22 @@ interface DiscoveredTable {
4191
4302
  */
4192
4303
  declare function discoverCloudTables(db: Lattice): Promise<DiscoveredTable[]>;
4193
4304
 
4305
+ /**
4306
+ * Per-column audience → a generated cell-masking view (Stage 2 of the per-viewer
4307
+ * enrichment model). Postgres RLS is whole-row; column-level masking is layered
4308
+ * on with one generated view per entity: every column passes through, except a
4309
+ * column with a non-default `audience`, which becomes
4310
+ * `CASE WHEN <audience-predicate> THEN col END` — masked cells read as NULL, so
4311
+ * `SELECT *` keeps working and the column stays a real column (no side tables).
4312
+ *
4313
+ * The `owner` predicate calls the `session_user`-keyed `SECURITY DEFINER` helper
4314
+ * `lattice_is_owner` from the RLS bootstrap, so the mask binds to the real member
4315
+ * even though the view executes with its owner's rights. That identity choice is
4316
+ * what lets an owner-defined view filter per-viewer without re-broadening.
4317
+ *
4318
+ * The view is a rendered artifact, generated from schema metadata, never
4319
+ * hand-edited. Postgres-only; SQLite (single-user, local) needs no masking.
4320
+ */
4194
4321
  /** Row context the `owner` clause needs (the table literal + pk SQL expression). */
4195
4322
  interface AudienceRowCtx {
4196
4323
  tableLit: string;
@@ -4199,9 +4326,9 @@ interface AudienceRowCtx {
4199
4326
  /** True when this audience means "no mask" (visible to whoever can see the row). */
4200
4327
  declare function isRowAudience(audience: string | undefined): boolean;
4201
4328
  /**
4202
- * Compile a column `audience` spec into a boolean SQL predicate over the helper
4203
- * functions. Returns `'true'` for the row-audience / everyone case. Throws on an
4204
- * unknown or malformed clause.
4329
+ * Compile a column `audience` spec into a boolean SQL predicate. Returns `'true'`
4330
+ * for the row-audience / everyone case, `lattice_is_owner(...)` for the owner
4331
+ * (secret-column) case. Throws on anything else — fail closed.
4205
4332
  */
4206
4333
  declare function audiencePredicate(audience: string, ctx?: AudienceRowCtx): string;
4207
4334
  /** Whether a table needs a masking view at all (any column has a real audience). */
@@ -4382,7 +4509,7 @@ declare function secureCloud(db: Lattice): Promise<void>;
4382
4509
  * **app-mediated** (hidden from the UI + every API response), NOT cryptographic
4383
4510
  * — a member CAN read the value from their own session if they go looking.
4384
4511
  * - `lattice_set_cloud_setting(key, value)` — owner-only (RAISEs unless the
4385
- * caller can create roles, the same gate as `lattice_assign_role`).
4512
+ * caller can create roles, the cloud-owner gate).
4386
4513
  *
4387
4514
  * Postgres-only: a local SQLite workspace is single-user, so there is nothing to
4388
4515
  * keep secret and these are all no-ops / null there.
@@ -4767,6 +4894,15 @@ interface StartGuiServerOptions {
4767
4894
  * Omitted ⇒ the broker's default (20s). 0 disables it.
4768
4895
  */
4769
4896
  realtimeWatchdogMs?: number;
4897
+ /**
4898
+ * Run the in-process auto-update poll: while the GUI is open, check npm for a
4899
+ * newer version and, when one lands on an installable copy, install it and
4900
+ * exit with the supervisor's restart code so it relaunches on the new version.
4901
+ * Set ONLY for a supervised child (`LATTICE_GUI_SUPERVISED=1`) — exiting to
4902
+ * apply an update is safe only when a supervisor is there to respawn it.
4903
+ * `GET /api/version` + `GET /api/update/status` are served regardless.
4904
+ */
4905
+ selfUpdate?: boolean;
4770
4906
  }
4771
4907
  interface GuiServerHandle {
4772
4908
  server: Server;
@@ -4840,4 +4976,4 @@ declare class FileSourceKeyStore implements SourceKeyStore {
4840
4976
  private encodeFile;
4841
4977
  }
4842
4978
 
4843
- export { type AddWorkspaceOptions, type AdoptNativeOptions, type AdoptResult, type ApplyWriteResult, type AudienceRowCtx, type AuditEvent, type AutoUpdateResult, type BelongsToRelation, type BelongsToSource, type BlobMetadata, type BuiltinTemplateName, CLOUD_SETTING_SYSTEM_PROMPT, CLOUD_SETTING_WORKSPACE_LOGO, CLOUD_SETTING_WORKSPACE_LOGO_ETAG, CONFIG_SUBDIR, type CatalogEntity, type CatalogRecord, type ChangeEntry, type ChangelogOptions, type ClassifyMatch, type CleanupOptions, type CleanupResult, type CloudProbeResult, type CountOptions, type CrawlOptions, type CrawlResult, type CustomSource, DEFAULT_ENTRY_TYPES, DEFAULT_TYPE_ALIASES, type DiscoveredTable, type EmbeddingsConfig, type EnrichOptions, type EnrichResult, type EnrichedSource, type EnrichmentLookup, type EntityContextDefinition, type EntityContextManifestEntry, type EntityFileManifestInfo, type EntityFileSource, type EntityFileSpec, type EntityProfileField, type EntityProfileSection, type EntityProfileTemplate, type EntityRenderSpec, type EntityRenderTemplate, type EntitySectionPerRow, type EntitySectionsTemplate, type EntityTableColumn, type EntityTableTemplate, type ExtractedObject, FileSourceKeyStore, type FileSourceKeyStoreOptions, type FilesRow, type Filter, type FilterOp, FoldCache, type FtsConfig, type FtsGroup, type FtsHit, type FtsOptions, type FtsResult, type GuiServerHandle, type HasManyRelation, type HasManySource, InMemorySourceKeyStore, InMemoryStateStore, type InitOptions, LOCAL_DB_RELPATH, Lattice, type LatticeConfig, type LatticeConfigInput, type LatticeEntityDef, type LatticeEntityRenderSpec, type LatticeFieldDef, type LatticeFieldType, type LatticeManifest, type LatticeOptions, type LinkOptions, type LlmClient, type LlmMessage, MEMBER_GROUP, type ManyToManySource, type MarkdownTableColumn, type MigrateResult, type Migration, type MigrationOptions, type MigrationProgress, type MigrationResult, type MultiTableDefinition, NATIVE_ENTITY_DEFS, NATIVE_ENTITY_NAMES, NATIVE_REGISTRY_TABLE, type Observation, type OrderBySpec, type OrganizeOptions, type OrganizeResult, type OrganizedCreation, type OrganizedLink, type ParseError, type ParseResult, type ParsedConfig, type PdfOptions, type PdfSenderInput, type PkLookup, PostgresAdapter, type PostgresAdapterOptions, type PreparedStatement, type PrimaryKey, ProgressThrottle, type QueryOptions, READ_ONLY_HEADER, ROOT_DIRNAME, type ReadOnlyHeaderOptions, type ReconcileOptions, type ReconcileResult, type RefKind, type RefProvider, type ReferenceMetadata, ReferenceUnavailableError, type Relation, type RemoteBlobStore, type RenderHooks, type RenderOptions, type RenderProgress, type RenderProgressCallback, type RenderProgressKind, type RenderResult, type RenderSpec, type ReportConfig, type ReportResult, type ReportSection, type ReportSectionResult, type ResolveOptions, type ReverseSeedDetection, type ReverseSeedResult, type ReverseSeedTableResult, type ReverseSyncError, type ReverseSyncResult, type ReverseSyncUpdate, type RewardScores, type Row, type RowVisibilityDefault, type S3Config, type S3StoreConfig, S3UnavailableError, SQLiteAdapter, type SchemaEntity, type SearchOptions, type SearchResult, type SecurityOptions, type SeedConfig, type SeedLinkSpec, SeedReconciliationError, type SeedResult, type SelfSource, type SessionEntry, type SessionParseOptions, type SessionWriteEntry, type SessionWriteOp, type SessionWriteParseResult, type SourceHandle, type SourceKeyStore, type SourceMetadata, type SourceQueryOptions, SourceShreddedError, type StartGuiServerOptions, type StopFn, type StorageAdapter, type SyncResult, type TableDefinition, type TablePolicy, type TemplateRenderSpec, type TurnParams, type TurnResult, type UnresolvedLink, type UpsertByNaturalKeyOptions, type UserIdentity, type UserPreferences, type Viewer, type VisionOptions, type VisionSenderInput, WORKSPACES_SUBDIR, type WatchOptions, type WorkspacePaths, type WorkspaceRecord, type WorkspaceRegistry, type WriteHook, type WriteHookContext, type WritebackDefinition, type WritebackStateStore, type WritebackValidationResult, activeWorkspaceLabel, addWorkspace, adoptNativeEntities, analyticsEnabled, applyTokenBudget, applyWriteEntry, archiveLocalSqlite, assertSafeUrl, attachBlob, audiencePredicate, audienceViewSql, autoFtsColumns, autoUpdate, backfillOwnership, canManageRoles, classifyLinks, cloudRlsInstalled, configDir, contentHash, crawlUrl, createReadOnlyHeader, createS3Store, createSQLiteStateStore, decrypt, defaultWorkspaceYaml, deleteDbCredential, deleteToken, deriveCanonicalContexts, deriveKey, describeImage, describePdf, discoverCloudTables, enableAudienceView, enableChangelogRls, enableRlsForTable, encrypt, enrichKnowledge, ensureFtsIndex, ensureLatticeRoot, entityFileNames, estimateTokens, extractObjects, findLatticeRoot, fixSchemaConflicts, foldEntity, frontmatter, ftsTableName, fullTextSearch, generateEntryId, generateMemberPassword, generateWriteEntryId, getActiveWorkspace, getCloudSetting, getDbCredential, getOrCreateMasterKey, getTablePolicy, getWorkspace, grantCell, hasFtsIndex, hashFile, importLegacyUserConfig, installCloudRls, installCloudSettings, isEncrypted, isNativeEntity, isPostgresUrl, isPrivateIp, isRowAudience, isV1EntityFiles, listDbCredentials, listNativeBindings, listTokens, listWorkspaces, loadColumnPolicy, manifestPath, markdownTable, memberRoleName, migrateLatticeData, normalizeEntityFiles, observationVisible, observationsFromChange, openTargetLatticeForMigration, openUnderSource, organizeSource, parseConfigFile, parseConfigString, parseMarkdownEntries, parseMatches, parseObjects, parseSessionMD, parseSessionWrites, probeCloud, providerForUrl, provisionMemberRole, readIdentity, readManifest, readPreferences, readRegistry, readToken, referenceLocalFile, referenceUrl, regenerateAudienceViewFromDb, registerNativeEntities, registryPath, resolveActiveS3Config, resolveLatticeRoot, resolveSource, resolveWorkspacePaths, revokeCell, revokeMemberRole, rootConfigDir, s3Key, saveDbCredential, saveDbCredentialForTeam, sealUnderSource, secureCloud, seedColumnPolicyFromYaml, setActiveWorkspace, setCloudSetting, setColumnAudience, setRowVisibility, setTableDefaultVisibility, setTableNeverShare, shredSource, slugify, startGuiServer, summarizeText, tableNeedsAudienceView, toSafeDirName, truncate, validateEntryId, workspaceBlobsDir, workspaceConfigPath, workspaceContextDir, workspaceDataDir, workspaceDbPath, workspaceDir, workspacesDir, writeIdentity, writeManifest, writePreferences, writeRegistry, writeToken };
4979
+ export { type AddWorkspaceOptions, type AdoptNativeOptions, type AdoptResult, type ApplyWriteResult, type AudienceRowCtx, type AuditEvent, type AutoUpdateResult, type BelongsToRelation, type BelongsToSource, type BlobMetadata, type BuiltinTemplateName, CLOUD_SETTING_SYSTEM_PROMPT, CLOUD_SETTING_WORKSPACE_LOGO, CLOUD_SETTING_WORKSPACE_LOGO_ETAG, CONFIG_SUBDIR, type CatalogEntity, type CatalogRecord, type ChangeEntry, type ChangelogOptions, type ClassifyMatch, type CleanupOptions, type CleanupResult, type CloudProbeResult, type CountOptions, type CrawlOptions, type CrawlResult, type CustomSource, DEFAULT_ENTRY_TYPES, DEFAULT_TYPE_ALIASES, type DiscoveredTable, type EmbeddingsConfig, type EnrichOptions, type EnrichResult, type EnrichedSource, type EnrichmentLookup, type EntityContextDefinition, type EntityContextManifestEntry, type EntityFileManifestInfo, type EntityFileSource, type EntityFileSpec, type EntityProfileField, type EntityProfileSection, type EntityProfileTemplate, type EntityRenderSpec, type EntityRenderTemplate, type EntitySectionPerRow, type EntitySectionsTemplate, type EntityTableColumn, type EntityTableTemplate, type ExtractedObject, FileSourceKeyStore, type FileSourceKeyStoreOptions, type FilesRow, type Filter, type FilterOp, FoldCache, type FtsConfig, type FtsGroup, type FtsHit, type FtsOptions, type FtsResult, type GuiServerHandle, type HasManyRelation, type HasManySource, InMemorySourceKeyStore, InMemoryStateStore, type InitOptions, LOCAL_DB_RELPATH, Lattice, type LatticeConfig, type LatticeConfigInput, type LatticeEntityDef, type LatticeEntityRenderSpec, type LatticeFieldDef, type LatticeFieldType, type LatticeManifest, type LatticeOptions, type LinkOptions, type LlmClient, type LlmMessage, MEMBER_GROUP, type ManyToManySource, type MarkdownTableColumn, type MigrateResult, type Migration, type MigrationOptions, type MigrationProgress, type MigrationResult, type MultiTableDefinition, NATIVE_ENTITY_DEFS, NATIVE_ENTITY_NAMES, NATIVE_REGISTRY_TABLE, type Observation, type OrderBySpec, type OrganizeOptions, type OrganizeResult, type OrganizedCreation, type OrganizedLink, type ParseError, type ParseResult, type ParsedConfig, type PdfOptions, type PdfSenderInput, type PkLookup, PostgresAdapter, type PostgresAdapterOptions, type PreparedStatement, type PrimaryKey, ProgressThrottle, type QueryOptions, READ_ONLY_HEADER, ROOT_DIRNAME, type ReadOnlyHeaderOptions, type ReconcileOptions, type ReconcileResult, type RefKind, type RefProvider, type ReferenceMetadata, ReferenceUnavailableError, type Relation, type RemoteBlobStore, type RenderHooks, type RenderOptions, type RenderProgress, type RenderProgressCallback, type RenderProgressKind, type RenderResult, type RenderSpec, type ReportConfig, type ReportResult, type ReportSection, type ReportSectionResult, type ResolveOptions, type ReverseSeedDetection, type ReverseSeedResult, type ReverseSeedTableResult, type ReverseSyncError, type ReverseSyncResult, type ReverseSyncUpdate, type RewardScores, type Row, type RowVisibilityDefault, type S3Config, type S3StoreConfig, S3UnavailableError, SQLiteAdapter, type SchemaEntity, type SearchOptions, type SearchResult, type SecurityOptions, type SeedConfig, type SeedLinkSpec, SeedReconciliationError, type SeedResult, type SelfSource, type SessionEntry, type SessionParseOptions, type SessionWriteEntry, type SessionWriteOp, type SessionWriteParseResult, type SourceHandle, type SourceKeyStore, type SourceMetadata, type SourceQueryOptions, SourceShreddedError, type StartGuiServerOptions, type StopFn, type StorageAdapter, type SyncResult, type TableDefinition, type TablePolicy, type TemplateRenderSpec, type TurnParams, type TurnResult, type UnresolvedLink, type UpsertByNaturalKeyOptions, type UserIdentity, type UserPreferences, type Viewer, type VisionOptions, type VisionSenderInput, WORKSPACES_SUBDIR, type WatchOptions, type WorkspacePaths, type WorkspaceRecord, type WorkspaceRegistry, type WriteHook, type WriteHookContext, type WritebackDefinition, type WritebackStateStore, type WritebackValidationResult, activeWorkspaceLabel, addWorkspace, adoptNativeEntities, analyticsEnabled, applyTokenBudget, applyWriteEntry, archiveLocalSqlite, assertSafeUrl, attachBlob, audiencePredicate, audienceViewSql, autoFtsColumns, autoUpdate, backfillOwnership, canManageRoles, classifyLinks, cloudRlsInstalled, configDir, contentHash, crawlUrl, createReadOnlyHeader, createS3Store, createSQLiteStateStore, decrypt, defaultWorkspaceYaml, deleteDbCredential, deleteToken, deriveCanonicalContexts, deriveKey, describeImage, describePdf, discoverCloudTables, enableAudienceView, enableChangelogRls, enableRlsForTable, encrypt, enrichKnowledge, ensureFtsIndex, ensureLatticeRoot, entityFileNames, estimateTokens, extractObjects, findLatticeRoot, fixSchemaConflicts, foldEntity, frontmatter, ftsTableName, fullTextSearch, generateEntryId, generateMemberPassword, generateWriteEntryId, getActiveWorkspace, getCloudSetting, getDbCredential, getOrCreateMasterKey, getTablePolicy, getWorkspace, hasFtsIndex, hashFile, importLegacyUserConfig, installCloudRls, installCloudSettings, isEncrypted, isNativeEntity, isPostgresUrl, isPrivateIp, isRowAudience, isV1EntityFiles, listDbCredentials, listNativeBindings, listTokens, listWorkspaces, loadColumnPolicy, manifestPath, markdownTable, memberRoleName, migrateLatticeData, normalizeEntityFiles, observationVisible, observationsFromChange, openTargetLatticeForMigration, openUnderSource, organizeSource, parseConfigFile, parseConfigString, parseMarkdownEntries, parseMatches, parseObjects, parseSessionMD, parseSessionWrites, probeCloud, providerForUrl, provisionMemberRole, readIdentity, readManifest, readPreferences, readRegistry, readToken, referenceLocalFile, referenceUrl, regenerateAudienceViewFromDb, registerNativeEntities, registryPath, resolveActiveS3Config, resolveLatticeRoot, resolveSource, resolveWorkspacePaths, revokeMemberRole, rootConfigDir, s3Key, saveDbCredential, saveDbCredentialForTeam, sealUnderSource, secureCloud, seedColumnPolicyFromYaml, setActiveWorkspace, setCloudSetting, setColumnAudience, setRowVisibility, setTableDefaultVisibility, setTableNeverShare, shredSource, slugify, startGuiServer, summarizeText, tableNeedsAudienceView, toSafeDirName, truncate, validateEntryId, workspaceBlobsDir, workspaceConfigPath, workspaceContextDir, workspaceDataDir, workspaceDbPath, workspaceDir, workspacesDir, writeIdentity, writeManifest, writePreferences, writeRegistry, writeToken };