latticesql 3.0.0 → 3.1.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.
package/dist/index.d.cts CHANGED
@@ -1731,6 +1731,89 @@ declare function openUnderSource(ciphertext: string, sourceId: string, store: So
1731
1731
  */
1732
1732
  declare function shredSource(sourceId: string, store: SourceKeyStore): void;
1733
1733
 
1734
+ /**
1735
+ * Progress reporting for the render engine.
1736
+ *
1737
+ * A render walks every table and every per-entity context file; for a large
1738
+ * database this can take a while. These types let a caller observe progress
1739
+ * (per-table %, which table is in flight) and cancel a render in progress via
1740
+ * an `AbortSignal`. All of it is optional: a render with no `onProgress` and no
1741
+ * `signal` behaves exactly as it did before — zero overhead, identical output.
1742
+ */
1743
+ /** The kind of progress event the render engine emits. */
1744
+ type RenderProgressKind = 'table-start' | 'table-progress' | 'table-done' | 'done' | 'error';
1745
+ /**
1746
+ * A single progress event. Fields beyond `kind` describe the table currently
1747
+ * being rendered (`table`, `tableIndex`, `tableCount`) and how far along it is
1748
+ * (`entitiesRendered`, `entitiesTotal`, `pct`). `durationMs` is set on the
1749
+ * terminal `done` event; `message` carries human-readable detail (e.g. the
1750
+ * error text on an `error` event).
1751
+ */
1752
+ interface RenderProgress {
1753
+ /** Discriminator: what stage of the render this event reports. */
1754
+ kind: RenderProgressKind;
1755
+ /** The table being rendered, or null for non-table events (`done`/`error`). */
1756
+ table: string | null;
1757
+ /** Entities rendered so far within `table` (per-table running count). */
1758
+ entitiesRendered: number;
1759
+ /** Total entities in `table` — the denominator for the per-table %. */
1760
+ entitiesTotal: number;
1761
+ /** Zero-based index of `table` among the entity-context tables. */
1762
+ tableIndex: number;
1763
+ /** Total number of entity-context tables in this render. */
1764
+ tableCount: number;
1765
+ /** Per-table completion percentage, 0–100, exact (`rendered/total`). */
1766
+ pct: number;
1767
+ /** Wall-clock duration of the whole render, set on the `done` event. */
1768
+ durationMs?: number;
1769
+ /** Human-readable detail; the error text on an `error` event. */
1770
+ message?: string;
1771
+ }
1772
+ /** Sink the render engine pushes {@link RenderProgress} events into. */
1773
+ type RenderProgressCallback = (event: RenderProgress) => void;
1774
+ /**
1775
+ * Optional knobs for a render. Both are opt-in:
1776
+ * - `onProgress` — observe per-table render progress.
1777
+ * - `signal` — cancel a render in flight; the engine bails between entities and
1778
+ * returns the partial manifest (which the caller is expected to discard).
1779
+ */
1780
+ interface RenderOptions {
1781
+ onProgress?: RenderProgressCallback;
1782
+ signal?: AbortSignal;
1783
+ }
1784
+ /**
1785
+ * Coalesces high-frequency `table-progress` events down to ≤ ~5/sec per table,
1786
+ * while always passing through the lifecycle events (`table-start`,
1787
+ * `table-done`, `done`, `error`) immediately.
1788
+ *
1789
+ * A render over a 6,760-row table would otherwise emit thousands of
1790
+ * `table-progress` events; this caps it at a few dozen. The throttle lives in
1791
+ * the engine so every consumer benefits and no per-entity object crosses the
1792
+ * progress boundary more than ~5×/sec.
1793
+ *
1794
+ * The 200 ms window is reset on every `table-start` (via {@link force}), so each
1795
+ * table gets its own fresh budget and the first progress tick of a new table is
1796
+ * not suppressed by the previous table's last tick.
1797
+ */
1798
+ declare class ProgressThrottle {
1799
+ private readonly cb;
1800
+ private readonly windowMs;
1801
+ private lastEmit;
1802
+ constructor(cb: RenderProgressCallback | undefined, windowMs?: number);
1803
+ /**
1804
+ * Emit a `table-progress` event, but only if the window since the last
1805
+ * passthrough has elapsed. Dropped events are simply not delivered — the next
1806
+ * one that survives carries the latest running count.
1807
+ */
1808
+ tick(event: RenderProgress): void;
1809
+ /**
1810
+ * Emit a lifecycle event immediately and reset the throttle window. Use for
1811
+ * `table-start`, `table-done`, `done`, and `error` — none of which should
1812
+ * ever be dropped. Resetting on `table-start` gives each table a clean budget.
1813
+ */
1814
+ force(event: RenderProgress): void;
1815
+ }
1816
+
1734
1817
  /**
1735
1818
  * Initialise Lattice from a YAML config file instead of an explicit path.
1736
1819
  *
@@ -1994,6 +2077,34 @@ declare class Lattice {
1994
2077
  */
1995
2078
  private _assertIdent;
1996
2079
  insert(table: string, row: Row, provenance?: ChangeProvenance): Promise<string>;
2080
+ /**
2081
+ * Insert a row while atomically forcing its cloud row-visibility, regardless of
2082
+ * the table's `default_row_visibility`. The per-table insert trigger reads a
2083
+ * transaction-local GUC (`lattice.force_row_visibility`); we set it and run the
2084
+ * INSERT inside a single transaction, so the row is stamped at `visibility` the
2085
+ * instant it exists — it is never momentarily visible at the table default, and
2086
+ * the change-feed `NOTIFY` (delivered only at COMMIT) fires when the row already
2087
+ * carries this visibility. This closes the create-then-demote window that a
2088
+ * plain `insert()` + `setRowVisibility()` would leave open.
2089
+ *
2090
+ * Postgres-only: SQLite is single-user (no cross-viewer leak) and has no trigger
2091
+ * to read the GUC, so it degrades to a plain {@link insert}. A `never_share`
2092
+ * table still wins — its rows are forced private even if `visibility` is
2093
+ * `'everyone'` (the trigger enforces that precedence).
2094
+ *
2095
+ * @since 3.1.0
2096
+ */
2097
+ insertForcingVisibility(table: string, row: Row, visibility: 'private' | 'everyone', provenance?: ChangeProvenance): Promise<string>;
2098
+ /**
2099
+ * Build the INSERT statement + canonical pk for a row (sanitize → schema-filter →
2100
+ * auto-pk → encrypt). Shared by {@link insert} and {@link insertForcingVisibility}
2101
+ * so both produce byte-identical writes; the latter only differs in running it
2102
+ * inside a GUC-scoped transaction.
2103
+ */
2104
+ private _prepareInsert;
2105
+ /** Post-insert side effects (changelog, audit, write hooks, embedding sync),
2106
+ * identical for the plain and force-visibility insert paths. */
2107
+ private _afterInsert;
1997
2108
  /**
1998
2109
  * Insert a row and return the full inserted row (including auto-generated
1999
2110
  * fields and defaults). Equivalent to `insert()` followed by `get()`.
@@ -2120,7 +2231,22 @@ declare class Lattice {
2120
2231
  search(table: string, query: string, opts?: SearchOptions): Promise<SearchResult[]>;
2121
2232
  query(table: string, opts?: QueryOptions): Promise<Row[]>;
2122
2233
  count(table: string, opts?: CountOptions): Promise<number>;
2123
- render(outputDir: string): Promise<RenderResult>;
2234
+ render(outputDir: string, opts?: RenderOptions): Promise<RenderResult>;
2235
+ /**
2236
+ * Render into `outputDir` through the shared single-flight guard, intended to
2237
+ * be called fire-and-forget (e.g. the GUI's instant-open background render).
2238
+ *
2239
+ * The guard ({@link _renderGuarded}) holds {@link _autoRenderInFlight} for the
2240
+ * render's duration, so a data mutation that lands while this render is in
2241
+ * flight is deferred by {@link _runAutoRender} and coalesced — when this
2242
+ * render settles, `finally` clears the flag and re-arms exactly one follow-up
2243
+ * render via {@link _rearmAutoRenderIfPending}. Net invariant: at most one
2244
+ * render to a given dir at a time.
2245
+ *
2246
+ * Errors propagate to the caller (the GUI surfaces them, never silently swallowed); they are
2247
+ * not swallowed here.
2248
+ */
2249
+ renderInBackground(outputDir: string, opts?: RenderOptions): Promise<RenderResult>;
2124
2250
  sync(outputDir: string): Promise<SyncResult>;
2125
2251
  /**
2126
2252
  * Recover rows from rendered files into empty database tables.
@@ -2236,6 +2362,17 @@ declare class Lattice {
2236
2362
  /** Turn off automatic rendering and cancel any pending render. */
2237
2363
  disableAutoRender(): this;
2238
2364
  private _scheduleAutoRender;
2365
+ /**
2366
+ * Shared single-flight render path used by {@link renderInBackground}.
2367
+ *
2368
+ * Holds {@link _autoRenderInFlight} for the render's duration so the
2369
+ * mutation-driven {@link _runAutoRender} defers while this render runs (it
2370
+ * sees the flag and marks itself pending instead of starting a second,
2371
+ * overlapping render). On settle, `finally` clears the flag and re-arms a
2372
+ * single coalesced follow-up render if any mutation arrived mid-flight.
2373
+ * Errors propagate to the caller; the flag is always cleared.
2374
+ */
2375
+ private _renderGuarded;
2239
2376
  private _runAutoRender;
2240
2377
  private _rearmAutoRenderIfPending;
2241
2378
  /**
@@ -3904,10 +4041,10 @@ declare function isPostgresUrl(url: string): boolean;
3904
4041
  * `CREATE OR REPLACE FUNCTION`). Multi-statement — Postgres-only, so it never hits
3905
4042
  * the single-statement SQLite migration path.
3906
4043
  *
3907
- * NOTE (follow-up): the `SECURITY DEFINER` helpers below should pin `search_path`
3908
- * to the cloud schema to fully close the definer-search_path class of issue. Today
3909
- * members are `NOSUPERUSER` without CREATE on the schema, so they cannot plant a
3910
- * shadowing object; the pin is hardening, tracked for the schema-awareness pass.
4044
+ * Every `SECURITY DEFINER` helper below gets `search_path` pinned at install time
4045
+ * via {@link pinDefinerSearchPath} (see its doc for the threat it closes). The pin
4046
+ * is applied in {@link installCloudRls}, not baked into the literal here, because
4047
+ * the cloud's schema name is only known at runtime (`current_schema()`).
3911
4048
  */
3912
4049
  /**
3913
4050
  * Group role every cloud member inherits. Table privileges are granted to the
@@ -3923,14 +4060,31 @@ declare function installCloudRls(db: Lattice): Promise<void>;
3923
4060
  * only what they're allowed to: a DERIVED observation only when it can reach
3924
4061
  * EVERY source it was derived from (so a hidden enrichment never reaches the
3925
4062
  * member — existence-hiding is structural), and a ground-truth / audit entry
3926
- * only for a row that is itself visible to the member. Both predicates route
3927
- * through the `session_user`-keyed SECURITY DEFINER helpers, so they bind to the
3928
- * real member. `FORCE ROW LEVEL SECURITY` applies the policy even to the table
3929
- * owner. No-op on SQLite (single-user; no cross-viewer leak to guard). Run after
3930
- * the change-log table exists (`Lattice.ensureObservationSubstrate`).
4063
+ * only when the member OWNS the row it records. Both predicates route through the
4064
+ * `session_user`-keyed SECURITY DEFINER helpers, so they bind to the real member.
4065
+ * `FORCE ROW LEVEL SECURITY` applies the policy even to the table owner. No-op on
4066
+ * SQLite (single-user; no cross-viewer leak to guard). Run after the change-log
4067
+ * table exists (`Lattice.ensureObservationSubstrate`).
4068
+ *
4069
+ * Ground-truth entries are OWNER-ONLY (v2), not merely "row is visible". A
4070
+ * changelog row carries the full `changes`/`previous` JSON of the underlying row —
4071
+ * EVERY column in cleartext, including ones the `<table>_v` mask hides from a
4072
+ * non-owner (an `owner`-audience secret column, a role-gated column). If a member
4073
+ * who was merely granted the row could read its history, those masked columns
4074
+ * would leak in cleartext, bypassing column masking. The row's full mutation
4075
+ * history is an owner/audit artifact; a non-owner sees the row only through the
4076
+ * masked view, never its raw history. (The derived-observation branch is the
4077
+ * per-viewer enrichment path and is unaffected — it carries enrichment, not the
4078
+ * base row's masked columns.)
3931
4079
  */
3932
4080
  declare function enableChangelogRls(db: Lattice): Promise<void>;
3933
- /** Enable RLS on one shared table. No-op on SQLite. Idempotent via a per-table version key. */
4081
+ /**
4082
+ * Enable RLS on one shared table. No-op on SQLite. Idempotent via a per-table
4083
+ * version key. v3 bumps the key so existing clouds re-install the policy-aware
4084
+ * insert trigger (which now stamps the per-table `default_row_visibility` / forces
4085
+ * private under `never_share`) and pick up the `search_path` pin on the trigger
4086
+ * function — neither of which a v2-stamped clone would otherwise get.
4087
+ */
3934
4088
  declare function enableRlsForTable(db: Lattice, table: string, pkCols: readonly string[]): Promise<void>;
3935
4089
  /**
3936
4090
  * Stamp the current role as owner of every row that already exists in a table —
@@ -4008,6 +4162,11 @@ interface DiscoveredTable {
4008
4162
  */
4009
4163
  declare function discoverCloudTables(db: Lattice): Promise<DiscoveredTable[]>;
4010
4164
 
4165
+ /** Row context the `owner` clause needs (the table literal + pk SQL expression). */
4166
+ interface AudienceRowCtx {
4167
+ tableLit: string;
4168
+ pkExpr: string;
4169
+ }
4011
4170
  /** True when this audience means "no mask" (visible to whoever can see the row). */
4012
4171
  declare function isRowAudience(audience: string | undefined): boolean;
4013
4172
  /**
@@ -4015,7 +4174,7 @@ declare function isRowAudience(audience: string | undefined): boolean;
4015
4174
  * functions. Returns `'true'` for the row-audience / everyone case. Throws on an
4016
4175
  * unknown or malformed clause.
4017
4176
  */
4018
- declare function audiencePredicate(audience: string): string;
4177
+ declare function audiencePredicate(audience: string, ctx?: AudienceRowCtx): string;
4019
4178
  /** Whether a table needs a masking view at all (any column has a real audience). */
4020
4179
  declare function tableNeedsAudienceView(columnAudience: Record<string, string>): boolean;
4021
4180
  /**
@@ -4047,6 +4206,54 @@ declare function audienceViewSql(table: string, columns: readonly string[], pkCo
4047
4206
  * visibility helper and revokes the base SELECT that enableRlsForTable granted).
4048
4207
  */
4049
4208
  declare function enableAudienceView(db: Lattice, table: string, columns: readonly string[], pkCols: readonly string[], columnAudience: Record<string, string>): Promise<void>;
4209
+ /** Read a table's canonical column->audience map from __lattice_column_policy. */
4210
+ declare function loadColumnPolicy(db: Lattice, table: string): Promise<Record<string, string>>;
4211
+ /** Seed a table's YAML-declared audiences into __lattice_column_policy — ONE TIME
4212
+ * per table, the migration from the legacy on-disk spec to the DB-canonical store.
4213
+ * A marker in __lattice_migrations gates it: after the first run we never seed from
4214
+ * YAML again, because a later secureCloud would otherwise re-insert a policy row
4215
+ * for a column the owner has since CLEARED through the DB (a cleared column has no
4216
+ * row, so ON CONFLICT DO NOTHING would NOT protect it) — silently re-masking a
4217
+ * column the owner deliberately un-masked. Once seeded, the DB is canonical and
4218
+ * the only path to change a column's audience is setColumnAudience. */
4219
+ declare function seedColumnPolicyFromYaml(db: Lattice, table: string, yamlAudience: Record<string, string>): Promise<void>;
4220
+ /** Regenerate a table's cell-masking view FROM the DB column-policy (not YAML). If
4221
+ * the table now has no audience columns, drop the view and restore base SELECT to
4222
+ * members; otherwise (re)create the masked view and revoke base SELECT. Runs the
4223
+ * DDL directly (not via db.migrate) so it always reflects the current spec. */
4224
+ declare function regenerateAudienceViewFromDb(db: Lattice, table: string, columns: readonly string[], pkCols: readonly string[]): Promise<void>;
4225
+ /** Owner-only: set (or clear, with an empty spec) a column's audience in the DB and
4226
+ * regenerate the table's mask view from the DB. The owner gate is enforced inside
4227
+ * lattice_set_column_audience (raises for a non-owner). */
4228
+ declare function setColumnAudience(db: Lattice, table: string, column: string, audience: string, columns: readonly string[], pkCols: readonly string[]): Promise<void>;
4229
+
4230
+ /**
4231
+ * Per-table cloud policy (owner-controlled, Postgres-stored + enforced):
4232
+ * - `defaultRowVisibility` — the visibility NEW rows in this table are stamped
4233
+ * with (the per-table insert trigger reads `__lattice_table_policy`); default
4234
+ * `private` ⇒ unchanged behavior.
4235
+ * - `neverShare` — a hard exclusion (Secrets/Messages-class): the share/grant
4236
+ * SECURITY DEFINER functions raise for the table and the trigger forces its rows
4237
+ * private. Set at the data-model level, so a direct `psql` connection obeys it.
4238
+ *
4239
+ * These are thin wrappers over the owner-gated SQL functions in the RLS bootstrap
4240
+ * (`lattice_set_table_default_visibility` / `lattice_set_table_never_share`), which
4241
+ * raise unless the caller can create roles. No-op / safe defaults on SQLite.
4242
+ */
4243
+ type RowVisibilityDefault = 'private' | 'everyone';
4244
+ interface TablePolicy {
4245
+ defaultRowVisibility: RowVisibilityDefault;
4246
+ neverShare: boolean;
4247
+ }
4248
+ /** Read a table's policy. Returns the safe default (private, shareable) on SQLite
4249
+ * or when no policy row exists. */
4250
+ declare function getTablePolicy(db: Lattice, table: string): Promise<TablePolicy>;
4251
+ /** Owner-only: set the visibility NEW rows in `table` are created with. Raises (via
4252
+ * the SQL function) for a non-owner or for `everyone` on a never-share table. */
4253
+ declare function setTableDefaultVisibility(db: Lattice, table: string, visibility: RowVisibilityDefault): Promise<void>;
4254
+ /** Owner-only: mark (or unmark) a table never-shareable. When on, the share/grant
4255
+ * functions refuse it and its new rows are forced private. */
4256
+ declare function setTableNeverShare(db: Lattice, table: string, on: boolean): Promise<void>;
4050
4257
 
4051
4258
  /**
4052
4259
  * The per-viewer fold (the "local compile" of the per-viewer enrichment model).
@@ -4476,4 +4683,4 @@ interface PdfOptions {
4476
4683
  */
4477
4684
  declare function describePdf(auth: ClaudeAuth, path: string, opts?: PdfOptions): Promise<string>;
4478
4685
 
4479
- export { type AddWorkspaceOptions, type AdoptNativeOptions, type AdoptResult, type ApplyWriteResult, type AuditEvent, type AutoUpdateResult, type BelongsToRelation, type BelongsToSource, type BlobMetadata, type BuiltinTemplateName, CLOUD_SETTING_SYSTEM_PROMPT, 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, type FilesRow, type Filter, type FilterOp, FoldCache, type FtsConfig, type FtsGroup, type FtsHit, type FtsOptions, type FtsResult, 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, 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 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 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 StopFn, type StorageAdapter, type SyncResult, type TableDefinition, 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, getWorkspace, grantCell, hasFtsIndex, hashFile, importLegacyUserConfig, installCloudRls, installCloudSettings, isEncrypted, isNativeEntity, isPostgresUrl, isPrivateIp, isRowAudience, isV1EntityFiles, listDbCredentials, listNativeBindings, listTokens, listWorkspaces, 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, registerNativeEntities, registryPath, resolveActiveS3Config, resolveLatticeRoot, resolveSource, resolveWorkspacePaths, revokeCell, revokeMemberRole, rootConfigDir, s3Key, saveDbCredential, saveDbCredentialForTeam, sealUnderSource, secureCloud, setActiveWorkspace, setCloudSetting, setRowVisibility, shredSource, slugify, summarizeText, tableNeedsAudienceView, toSafeDirName, truncate, validateEntryId, workspaceBlobsDir, workspaceConfigPath, workspaceContextDir, workspaceDataDir, workspaceDbPath, workspaceDir, workspacesDir, writeIdentity, writeManifest, writePreferences, writeRegistry, writeToken };
4686
+ 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, 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, type FilesRow, type Filter, type FilterOp, FoldCache, type FtsConfig, type FtsGroup, type FtsHit, type FtsOptions, type FtsResult, 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 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, summarizeText, tableNeedsAudienceView, toSafeDirName, truncate, validateEntryId, workspaceBlobsDir, workspaceConfigPath, workspaceContextDir, workspaceDataDir, workspaceDbPath, workspaceDir, workspacesDir, writeIdentity, writeManifest, writePreferences, writeRegistry, writeToken };
package/dist/index.d.ts CHANGED
@@ -1731,6 +1731,89 @@ declare function openUnderSource(ciphertext: string, sourceId: string, store: So
1731
1731
  */
1732
1732
  declare function shredSource(sourceId: string, store: SourceKeyStore): void;
1733
1733
 
1734
+ /**
1735
+ * Progress reporting for the render engine.
1736
+ *
1737
+ * A render walks every table and every per-entity context file; for a large
1738
+ * database this can take a while. These types let a caller observe progress
1739
+ * (per-table %, which table is in flight) and cancel a render in progress via
1740
+ * an `AbortSignal`. All of it is optional: a render with no `onProgress` and no
1741
+ * `signal` behaves exactly as it did before — zero overhead, identical output.
1742
+ */
1743
+ /** The kind of progress event the render engine emits. */
1744
+ type RenderProgressKind = 'table-start' | 'table-progress' | 'table-done' | 'done' | 'error';
1745
+ /**
1746
+ * A single progress event. Fields beyond `kind` describe the table currently
1747
+ * being rendered (`table`, `tableIndex`, `tableCount`) and how far along it is
1748
+ * (`entitiesRendered`, `entitiesTotal`, `pct`). `durationMs` is set on the
1749
+ * terminal `done` event; `message` carries human-readable detail (e.g. the
1750
+ * error text on an `error` event).
1751
+ */
1752
+ interface RenderProgress {
1753
+ /** Discriminator: what stage of the render this event reports. */
1754
+ kind: RenderProgressKind;
1755
+ /** The table being rendered, or null for non-table events (`done`/`error`). */
1756
+ table: string | null;
1757
+ /** Entities rendered so far within `table` (per-table running count). */
1758
+ entitiesRendered: number;
1759
+ /** Total entities in `table` — the denominator for the per-table %. */
1760
+ entitiesTotal: number;
1761
+ /** Zero-based index of `table` among the entity-context tables. */
1762
+ tableIndex: number;
1763
+ /** Total number of entity-context tables in this render. */
1764
+ tableCount: number;
1765
+ /** Per-table completion percentage, 0–100, exact (`rendered/total`). */
1766
+ pct: number;
1767
+ /** Wall-clock duration of the whole render, set on the `done` event. */
1768
+ durationMs?: number;
1769
+ /** Human-readable detail; the error text on an `error` event. */
1770
+ message?: string;
1771
+ }
1772
+ /** Sink the render engine pushes {@link RenderProgress} events into. */
1773
+ type RenderProgressCallback = (event: RenderProgress) => void;
1774
+ /**
1775
+ * Optional knobs for a render. Both are opt-in:
1776
+ * - `onProgress` — observe per-table render progress.
1777
+ * - `signal` — cancel a render in flight; the engine bails between entities and
1778
+ * returns the partial manifest (which the caller is expected to discard).
1779
+ */
1780
+ interface RenderOptions {
1781
+ onProgress?: RenderProgressCallback;
1782
+ signal?: AbortSignal;
1783
+ }
1784
+ /**
1785
+ * Coalesces high-frequency `table-progress` events down to ≤ ~5/sec per table,
1786
+ * while always passing through the lifecycle events (`table-start`,
1787
+ * `table-done`, `done`, `error`) immediately.
1788
+ *
1789
+ * A render over a 6,760-row table would otherwise emit thousands of
1790
+ * `table-progress` events; this caps it at a few dozen. The throttle lives in
1791
+ * the engine so every consumer benefits and no per-entity object crosses the
1792
+ * progress boundary more than ~5×/sec.
1793
+ *
1794
+ * The 200 ms window is reset on every `table-start` (via {@link force}), so each
1795
+ * table gets its own fresh budget and the first progress tick of a new table is
1796
+ * not suppressed by the previous table's last tick.
1797
+ */
1798
+ declare class ProgressThrottle {
1799
+ private readonly cb;
1800
+ private readonly windowMs;
1801
+ private lastEmit;
1802
+ constructor(cb: RenderProgressCallback | undefined, windowMs?: number);
1803
+ /**
1804
+ * Emit a `table-progress` event, but only if the window since the last
1805
+ * passthrough has elapsed. Dropped events are simply not delivered — the next
1806
+ * one that survives carries the latest running count.
1807
+ */
1808
+ tick(event: RenderProgress): void;
1809
+ /**
1810
+ * Emit a lifecycle event immediately and reset the throttle window. Use for
1811
+ * `table-start`, `table-done`, `done`, and `error` — none of which should
1812
+ * ever be dropped. Resetting on `table-start` gives each table a clean budget.
1813
+ */
1814
+ force(event: RenderProgress): void;
1815
+ }
1816
+
1734
1817
  /**
1735
1818
  * Initialise Lattice from a YAML config file instead of an explicit path.
1736
1819
  *
@@ -1994,6 +2077,34 @@ declare class Lattice {
1994
2077
  */
1995
2078
  private _assertIdent;
1996
2079
  insert(table: string, row: Row, provenance?: ChangeProvenance): Promise<string>;
2080
+ /**
2081
+ * Insert a row while atomically forcing its cloud row-visibility, regardless of
2082
+ * the table's `default_row_visibility`. The per-table insert trigger reads a
2083
+ * transaction-local GUC (`lattice.force_row_visibility`); we set it and run the
2084
+ * INSERT inside a single transaction, so the row is stamped at `visibility` the
2085
+ * instant it exists — it is never momentarily visible at the table default, and
2086
+ * the change-feed `NOTIFY` (delivered only at COMMIT) fires when the row already
2087
+ * carries this visibility. This closes the create-then-demote window that a
2088
+ * plain `insert()` + `setRowVisibility()` would leave open.
2089
+ *
2090
+ * Postgres-only: SQLite is single-user (no cross-viewer leak) and has no trigger
2091
+ * to read the GUC, so it degrades to a plain {@link insert}. A `never_share`
2092
+ * table still wins — its rows are forced private even if `visibility` is
2093
+ * `'everyone'` (the trigger enforces that precedence).
2094
+ *
2095
+ * @since 3.1.0
2096
+ */
2097
+ insertForcingVisibility(table: string, row: Row, visibility: 'private' | 'everyone', provenance?: ChangeProvenance): Promise<string>;
2098
+ /**
2099
+ * Build the INSERT statement + canonical pk for a row (sanitize → schema-filter →
2100
+ * auto-pk → encrypt). Shared by {@link insert} and {@link insertForcingVisibility}
2101
+ * so both produce byte-identical writes; the latter only differs in running it
2102
+ * inside a GUC-scoped transaction.
2103
+ */
2104
+ private _prepareInsert;
2105
+ /** Post-insert side effects (changelog, audit, write hooks, embedding sync),
2106
+ * identical for the plain and force-visibility insert paths. */
2107
+ private _afterInsert;
1997
2108
  /**
1998
2109
  * Insert a row and return the full inserted row (including auto-generated
1999
2110
  * fields and defaults). Equivalent to `insert()` followed by `get()`.
@@ -2120,7 +2231,22 @@ declare class Lattice {
2120
2231
  search(table: string, query: string, opts?: SearchOptions): Promise<SearchResult[]>;
2121
2232
  query(table: string, opts?: QueryOptions): Promise<Row[]>;
2122
2233
  count(table: string, opts?: CountOptions): Promise<number>;
2123
- render(outputDir: string): Promise<RenderResult>;
2234
+ render(outputDir: string, opts?: RenderOptions): Promise<RenderResult>;
2235
+ /**
2236
+ * Render into `outputDir` through the shared single-flight guard, intended to
2237
+ * be called fire-and-forget (e.g. the GUI's instant-open background render).
2238
+ *
2239
+ * The guard ({@link _renderGuarded}) holds {@link _autoRenderInFlight} for the
2240
+ * render's duration, so a data mutation that lands while this render is in
2241
+ * flight is deferred by {@link _runAutoRender} and coalesced — when this
2242
+ * render settles, `finally` clears the flag and re-arms exactly one follow-up
2243
+ * render via {@link _rearmAutoRenderIfPending}. Net invariant: at most one
2244
+ * render to a given dir at a time.
2245
+ *
2246
+ * Errors propagate to the caller (the GUI surfaces them, never silently swallowed); they are
2247
+ * not swallowed here.
2248
+ */
2249
+ renderInBackground(outputDir: string, opts?: RenderOptions): Promise<RenderResult>;
2124
2250
  sync(outputDir: string): Promise<SyncResult>;
2125
2251
  /**
2126
2252
  * Recover rows from rendered files into empty database tables.
@@ -2236,6 +2362,17 @@ declare class Lattice {
2236
2362
  /** Turn off automatic rendering and cancel any pending render. */
2237
2363
  disableAutoRender(): this;
2238
2364
  private _scheduleAutoRender;
2365
+ /**
2366
+ * Shared single-flight render path used by {@link renderInBackground}.
2367
+ *
2368
+ * Holds {@link _autoRenderInFlight} for the render's duration so the
2369
+ * mutation-driven {@link _runAutoRender} defers while this render runs (it
2370
+ * sees the flag and marks itself pending instead of starting a second,
2371
+ * overlapping render). On settle, `finally` clears the flag and re-arms a
2372
+ * single coalesced follow-up render if any mutation arrived mid-flight.
2373
+ * Errors propagate to the caller; the flag is always cleared.
2374
+ */
2375
+ private _renderGuarded;
2239
2376
  private _runAutoRender;
2240
2377
  private _rearmAutoRenderIfPending;
2241
2378
  /**
@@ -3904,10 +4041,10 @@ declare function isPostgresUrl(url: string): boolean;
3904
4041
  * `CREATE OR REPLACE FUNCTION`). Multi-statement — Postgres-only, so it never hits
3905
4042
  * the single-statement SQLite migration path.
3906
4043
  *
3907
- * NOTE (follow-up): the `SECURITY DEFINER` helpers below should pin `search_path`
3908
- * to the cloud schema to fully close the definer-search_path class of issue. Today
3909
- * members are `NOSUPERUSER` without CREATE on the schema, so they cannot plant a
3910
- * shadowing object; the pin is hardening, tracked for the schema-awareness pass.
4044
+ * Every `SECURITY DEFINER` helper below gets `search_path` pinned at install time
4045
+ * via {@link pinDefinerSearchPath} (see its doc for the threat it closes). The pin
4046
+ * is applied in {@link installCloudRls}, not baked into the literal here, because
4047
+ * the cloud's schema name is only known at runtime (`current_schema()`).
3911
4048
  */
3912
4049
  /**
3913
4050
  * Group role every cloud member inherits. Table privileges are granted to the
@@ -3923,14 +4060,31 @@ declare function installCloudRls(db: Lattice): Promise<void>;
3923
4060
  * only what they're allowed to: a DERIVED observation only when it can reach
3924
4061
  * EVERY source it was derived from (so a hidden enrichment never reaches the
3925
4062
  * member — existence-hiding is structural), and a ground-truth / audit entry
3926
- * only for a row that is itself visible to the member. Both predicates route
3927
- * through the `session_user`-keyed SECURITY DEFINER helpers, so they bind to the
3928
- * real member. `FORCE ROW LEVEL SECURITY` applies the policy even to the table
3929
- * owner. No-op on SQLite (single-user; no cross-viewer leak to guard). Run after
3930
- * the change-log table exists (`Lattice.ensureObservationSubstrate`).
4063
+ * only when the member OWNS the row it records. Both predicates route through the
4064
+ * `session_user`-keyed SECURITY DEFINER helpers, so they bind to the real member.
4065
+ * `FORCE ROW LEVEL SECURITY` applies the policy even to the table owner. No-op on
4066
+ * SQLite (single-user; no cross-viewer leak to guard). Run after the change-log
4067
+ * table exists (`Lattice.ensureObservationSubstrate`).
4068
+ *
4069
+ * Ground-truth entries are OWNER-ONLY (v2), not merely "row is visible". A
4070
+ * changelog row carries the full `changes`/`previous` JSON of the underlying row —
4071
+ * EVERY column in cleartext, including ones the `<table>_v` mask hides from a
4072
+ * non-owner (an `owner`-audience secret column, a role-gated column). If a member
4073
+ * who was merely granted the row could read its history, those masked columns
4074
+ * would leak in cleartext, bypassing column masking. The row's full mutation
4075
+ * history is an owner/audit artifact; a non-owner sees the row only through the
4076
+ * masked view, never its raw history. (The derived-observation branch is the
4077
+ * per-viewer enrichment path and is unaffected — it carries enrichment, not the
4078
+ * base row's masked columns.)
3931
4079
  */
3932
4080
  declare function enableChangelogRls(db: Lattice): Promise<void>;
3933
- /** Enable RLS on one shared table. No-op on SQLite. Idempotent via a per-table version key. */
4081
+ /**
4082
+ * Enable RLS on one shared table. No-op on SQLite. Idempotent via a per-table
4083
+ * version key. v3 bumps the key so existing clouds re-install the policy-aware
4084
+ * insert trigger (which now stamps the per-table `default_row_visibility` / forces
4085
+ * private under `never_share`) and pick up the `search_path` pin on the trigger
4086
+ * function — neither of which a v2-stamped clone would otherwise get.
4087
+ */
3934
4088
  declare function enableRlsForTable(db: Lattice, table: string, pkCols: readonly string[]): Promise<void>;
3935
4089
  /**
3936
4090
  * Stamp the current role as owner of every row that already exists in a table —
@@ -4008,6 +4162,11 @@ interface DiscoveredTable {
4008
4162
  */
4009
4163
  declare function discoverCloudTables(db: Lattice): Promise<DiscoveredTable[]>;
4010
4164
 
4165
+ /** Row context the `owner` clause needs (the table literal + pk SQL expression). */
4166
+ interface AudienceRowCtx {
4167
+ tableLit: string;
4168
+ pkExpr: string;
4169
+ }
4011
4170
  /** True when this audience means "no mask" (visible to whoever can see the row). */
4012
4171
  declare function isRowAudience(audience: string | undefined): boolean;
4013
4172
  /**
@@ -4015,7 +4174,7 @@ declare function isRowAudience(audience: string | undefined): boolean;
4015
4174
  * functions. Returns `'true'` for the row-audience / everyone case. Throws on an
4016
4175
  * unknown or malformed clause.
4017
4176
  */
4018
- declare function audiencePredicate(audience: string): string;
4177
+ declare function audiencePredicate(audience: string, ctx?: AudienceRowCtx): string;
4019
4178
  /** Whether a table needs a masking view at all (any column has a real audience). */
4020
4179
  declare function tableNeedsAudienceView(columnAudience: Record<string, string>): boolean;
4021
4180
  /**
@@ -4047,6 +4206,54 @@ declare function audienceViewSql(table: string, columns: readonly string[], pkCo
4047
4206
  * visibility helper and revokes the base SELECT that enableRlsForTable granted).
4048
4207
  */
4049
4208
  declare function enableAudienceView(db: Lattice, table: string, columns: readonly string[], pkCols: readonly string[], columnAudience: Record<string, string>): Promise<void>;
4209
+ /** Read a table's canonical column->audience map from __lattice_column_policy. */
4210
+ declare function loadColumnPolicy(db: Lattice, table: string): Promise<Record<string, string>>;
4211
+ /** Seed a table's YAML-declared audiences into __lattice_column_policy — ONE TIME
4212
+ * per table, the migration from the legacy on-disk spec to the DB-canonical store.
4213
+ * A marker in __lattice_migrations gates it: after the first run we never seed from
4214
+ * YAML again, because a later secureCloud would otherwise re-insert a policy row
4215
+ * for a column the owner has since CLEARED through the DB (a cleared column has no
4216
+ * row, so ON CONFLICT DO NOTHING would NOT protect it) — silently re-masking a
4217
+ * column the owner deliberately un-masked. Once seeded, the DB is canonical and
4218
+ * the only path to change a column's audience is setColumnAudience. */
4219
+ declare function seedColumnPolicyFromYaml(db: Lattice, table: string, yamlAudience: Record<string, string>): Promise<void>;
4220
+ /** Regenerate a table's cell-masking view FROM the DB column-policy (not YAML). If
4221
+ * the table now has no audience columns, drop the view and restore base SELECT to
4222
+ * members; otherwise (re)create the masked view and revoke base SELECT. Runs the
4223
+ * DDL directly (not via db.migrate) so it always reflects the current spec. */
4224
+ declare function regenerateAudienceViewFromDb(db: Lattice, table: string, columns: readonly string[], pkCols: readonly string[]): Promise<void>;
4225
+ /** Owner-only: set (or clear, with an empty spec) a column's audience in the DB and
4226
+ * regenerate the table's mask view from the DB. The owner gate is enforced inside
4227
+ * lattice_set_column_audience (raises for a non-owner). */
4228
+ declare function setColumnAudience(db: Lattice, table: string, column: string, audience: string, columns: readonly string[], pkCols: readonly string[]): Promise<void>;
4229
+
4230
+ /**
4231
+ * Per-table cloud policy (owner-controlled, Postgres-stored + enforced):
4232
+ * - `defaultRowVisibility` — the visibility NEW rows in this table are stamped
4233
+ * with (the per-table insert trigger reads `__lattice_table_policy`); default
4234
+ * `private` ⇒ unchanged behavior.
4235
+ * - `neverShare` — a hard exclusion (Secrets/Messages-class): the share/grant
4236
+ * SECURITY DEFINER functions raise for the table and the trigger forces its rows
4237
+ * private. Set at the data-model level, so a direct `psql` connection obeys it.
4238
+ *
4239
+ * These are thin wrappers over the owner-gated SQL functions in the RLS bootstrap
4240
+ * (`lattice_set_table_default_visibility` / `lattice_set_table_never_share`), which
4241
+ * raise unless the caller can create roles. No-op / safe defaults on SQLite.
4242
+ */
4243
+ type RowVisibilityDefault = 'private' | 'everyone';
4244
+ interface TablePolicy {
4245
+ defaultRowVisibility: RowVisibilityDefault;
4246
+ neverShare: boolean;
4247
+ }
4248
+ /** Read a table's policy. Returns the safe default (private, shareable) on SQLite
4249
+ * or when no policy row exists. */
4250
+ declare function getTablePolicy(db: Lattice, table: string): Promise<TablePolicy>;
4251
+ /** Owner-only: set the visibility NEW rows in `table` are created with. Raises (via
4252
+ * the SQL function) for a non-owner or for `everyone` on a never-share table. */
4253
+ declare function setTableDefaultVisibility(db: Lattice, table: string, visibility: RowVisibilityDefault): Promise<void>;
4254
+ /** Owner-only: mark (or unmark) a table never-shareable. When on, the share/grant
4255
+ * functions refuse it and its new rows are forced private. */
4256
+ declare function setTableNeverShare(db: Lattice, table: string, on: boolean): Promise<void>;
4050
4257
 
4051
4258
  /**
4052
4259
  * The per-viewer fold (the "local compile" of the per-viewer enrichment model).
@@ -4476,4 +4683,4 @@ interface PdfOptions {
4476
4683
  */
4477
4684
  declare function describePdf(auth: ClaudeAuth, path: string, opts?: PdfOptions): Promise<string>;
4478
4685
 
4479
- export { type AddWorkspaceOptions, type AdoptNativeOptions, type AdoptResult, type ApplyWriteResult, type AuditEvent, type AutoUpdateResult, type BelongsToRelation, type BelongsToSource, type BlobMetadata, type BuiltinTemplateName, CLOUD_SETTING_SYSTEM_PROMPT, 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, type FilesRow, type Filter, type FilterOp, FoldCache, type FtsConfig, type FtsGroup, type FtsHit, type FtsOptions, type FtsResult, 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, 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 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 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 StopFn, type StorageAdapter, type SyncResult, type TableDefinition, 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, getWorkspace, grantCell, hasFtsIndex, hashFile, importLegacyUserConfig, installCloudRls, installCloudSettings, isEncrypted, isNativeEntity, isPostgresUrl, isPrivateIp, isRowAudience, isV1EntityFiles, listDbCredentials, listNativeBindings, listTokens, listWorkspaces, 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, registerNativeEntities, registryPath, resolveActiveS3Config, resolveLatticeRoot, resolveSource, resolveWorkspacePaths, revokeCell, revokeMemberRole, rootConfigDir, s3Key, saveDbCredential, saveDbCredentialForTeam, sealUnderSource, secureCloud, setActiveWorkspace, setCloudSetting, setRowVisibility, shredSource, slugify, summarizeText, tableNeedsAudienceView, toSafeDirName, truncate, validateEntryId, workspaceBlobsDir, workspaceConfigPath, workspaceContextDir, workspaceDataDir, workspaceDbPath, workspaceDir, workspacesDir, writeIdentity, writeManifest, writePreferences, writeRegistry, writeToken };
4686
+ 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, 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, type FilesRow, type Filter, type FilterOp, FoldCache, type FtsConfig, type FtsGroup, type FtsHit, type FtsOptions, type FtsResult, 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 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, summarizeText, tableNeedsAudienceView, toSafeDirName, truncate, validateEntryId, workspaceBlobsDir, workspaceConfigPath, workspaceContextDir, workspaceDataDir, workspaceDbPath, workspaceDir, workspacesDir, writeIdentity, writeManifest, writePreferences, writeRegistry, writeToken };