latticesql 1.2.6 → 1.3.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.ts CHANGED
@@ -812,6 +812,90 @@ interface TableDefinition {
812
812
  * ```
813
813
  */
814
814
  relations?: Record<string, Relation>;
815
+ /**
816
+ * Enable semantic search for this table via embeddings.
817
+ *
818
+ * When configured, Lattice computes and stores vector embeddings for
819
+ * the specified text fields. Use `lattice.search(table, query, opts)`
820
+ * to retrieve rows by semantic similarity.
821
+ *
822
+ * The `embed` function is called to generate vectors — bring your own
823
+ * embedding model (OpenAI, local model, etc.).
824
+ *
825
+ * @example
826
+ * ```ts
827
+ * embeddings: {
828
+ * fields: ['title', 'body'],
829
+ * embed: async (text) => openai.embeddings.create({ input: text, model: 'text-embedding-3-small' }).then(r => r.data[0].embedding),
830
+ * }
831
+ * ```
832
+ */
833
+ embeddings?: EmbeddingsConfig;
834
+ /**
835
+ * Enable reward tracking for this table. When `true`, Lattice
836
+ * auto-adds `_reward_total REAL DEFAULT 0` and `_reward_count INTEGER
837
+ * DEFAULT 0` columns. Rows are sorted by `_reward_total DESC` before
838
+ * rendering (unless overridden by `prioritizeBy`).
839
+ *
840
+ * Use `lattice.reward(table, id, scores)` to update reward values.
841
+ */
842
+ rewardTracking?: boolean;
843
+ /**
844
+ * When `rewardTracking` is enabled, automatically soft-delete rows
845
+ * whose `_reward_total` falls below this threshold during rendering.
846
+ * Requires a `deleted_at` column on the table. Default: no pruning.
847
+ */
848
+ pruneBelow?: number;
849
+ /**
850
+ * Pipeline of enrichment functions applied to rows after query and
851
+ * filtering but before rendering. Each function receives the row
852
+ * array and returns a (possibly transformed) row array.
853
+ *
854
+ * Use enrichment hooks to cluster, annotate, summarize, or
855
+ * cross-reference rows without modifying the underlying data.
856
+ *
857
+ * @example
858
+ * ```ts
859
+ * enrich: [
860
+ * (rows) => rows.map(r => ({ ...r, _age: Date.now() - new Date(r.created_at as string).getTime() })),
861
+ * (rows) => rows.length > 50 ? [{ summary: `${rows.length} items` }] : rows,
862
+ * ]
863
+ * ```
864
+ */
865
+ enrich?: ((rows: Row[]) => Row[])[];
866
+ /**
867
+ * Dynamic filter that scores rows against the current task context
868
+ * (set via `lattice.setTaskContext()`). Called before `filter` and
869
+ * before rendering. Only rows for which the function returns `true`
870
+ * are included.
871
+ *
872
+ * The second argument is the current task-context string (empty string
873
+ * when none has been set).
874
+ *
875
+ * @example
876
+ * ```ts
877
+ * relevanceFilter: (row, ctx) =>
878
+ * ctx ? String(row.body).toLowerCase().includes(ctx.toLowerCase()) : true
879
+ * ```
880
+ */
881
+ relevanceFilter?: (row: Row, taskContext: string) => boolean;
882
+ /**
883
+ * Maximum estimated token count for the rendered output.
884
+ * When the rendered content exceeds this budget, rows are pruned
885
+ * (lowest-priority first) and re-rendered with a truncation notice.
886
+ *
887
+ * Token count is estimated at ~4 characters per token.
888
+ */
889
+ tokenBudget?: number;
890
+ /**
891
+ * Controls row priority when `tokenBudget` forces pruning.
892
+ *
893
+ * - `string` — column name to sort by descending (highest value = highest priority).
894
+ * - `(a, b) => number` — custom comparator (positive = a has higher priority).
895
+ *
896
+ * When omitted, rows at the end of the query result are pruned first.
897
+ */
898
+ prioritizeBy?: string | ((a: Row, b: Row) => number);
815
899
  }
816
900
  interface MultiTableDefinition {
817
901
  /** Returns the "anchor" entities — one output file is produced per anchor */
@@ -823,6 +907,58 @@ interface MultiTableDefinition {
823
907
  /** Additional table names to query and pass into render */
824
908
  tables?: string[];
825
909
  }
910
+ /**
911
+ * Configuration for embedding-based semantic search on a table.
912
+ */
913
+ interface EmbeddingsConfig {
914
+ /** Column names whose values are concatenated and embedded. */
915
+ fields: string[];
916
+ /**
917
+ * Function that converts text into a numeric vector.
918
+ * Bring your own model — Lattice does not bundle an embedding provider.
919
+ */
920
+ embed: (text: string) => Promise<number[]>;
921
+ }
922
+ /**
923
+ * Options for `Lattice.search()`.
924
+ */
925
+ interface SearchOptions {
926
+ /** Maximum number of results to return. Default: 10. */
927
+ topK?: number;
928
+ /**
929
+ * Minimum cosine similarity threshold (0–1). Results below this
930
+ * score are excluded. Default: 0.
931
+ */
932
+ minScore?: number;
933
+ }
934
+ /**
935
+ * A single search result returned by `Lattice.search()`.
936
+ */
937
+ interface SearchResult {
938
+ /** The matched row from the source table. */
939
+ row: Row;
940
+ /** Cosine similarity score (0–1). */
941
+ score: number;
942
+ }
943
+ /**
944
+ * Dimension scores passed to `Lattice.reward()`.
945
+ * Values should be between 0 and 1. The total reward is the average
946
+ * of all provided dimension scores, accumulated over multiple calls.
947
+ */
948
+ interface RewardScores {
949
+ [dimension: string]: number;
950
+ }
951
+ /**
952
+ * Result of a writeback validation check.
953
+ */
954
+ interface WritebackValidationResult {
955
+ /** Whether the entry passed validation. */
956
+ pass: boolean;
957
+ /** Overall quality score (0–1). */
958
+ score: number;
959
+ /** Human-readable reason when validation fails. */
960
+ reason?: string;
961
+ }
826
962
  interface WritebackDefinition {
827
963
  /** Path or glob to agent-written files */
828
964
  file: string;
@@ -843,6 +979,25 @@ interface WritebackDefinition {
843
979
  stateStore?: WritebackStateStore;
844
980
  /** Called after entries are processed for a file. Useful for archival. */
845
981
  onArchive?: (filePath: string) => void;
982
+ /**
983
+ * Optional validation hook. Called before `persist` for each entry.
984
+ * Return `{ pass: true, score }` to allow the write, or
985
+ * `{ pass: false, score, reason }` to reject it.
986
+ *
987
+ * When omitted, all parsed entries are persisted without validation.
988
+ */
989
+ validate?: (entry: unknown) => WritebackValidationResult | Promise<WritebackValidationResult>;
990
+ /**
991
+ * Minimum score threshold. Entries with `score < rejectBelow` are
992
+ * automatically rejected even if `validate` returns `pass: true`.
993
+ * Only meaningful when `validate` is set. Default: 0 (no threshold).
994
+ */
995
+ rejectBelow?: number;
996
+ /**
997
+ * Called for each entry that fails validation.
998
+ * Useful for logging or auditing rejected writes.
999
+ */
1000
+ onReject?: (entry: unknown, result: WritebackValidationResult) => void;
846
1001
  }
847
1002
  interface QueryOptions {
848
1003
  /**
@@ -1154,6 +1309,8 @@ declare class Lattice {
1154
1309
  private readonly _encryptedTableColumns;
1155
1310
  /** Raw encryption key passphrase from constructor options. */
1156
1311
  private readonly _encryptionKeyRaw?;
1312
+ /** Current task context string for relevance filtering. */
1313
+ private _taskContext;
1157
1314
  private readonly _auditHandlers;
1158
1315
  private readonly _renderHandlers;
1159
1316
  private readonly _writebackHandlers;
@@ -1178,6 +1335,13 @@ declare class Lattice {
1178
1335
  */
1179
1336
  migrate(migrations: Migration[]): Promise<void>;
1180
1337
  close(): void;
1338
+ /**
1339
+ * Set the current task context string. Tables with a `relevanceFilter`
1340
+ * will use this value to filter rows before rendering.
1341
+ */
1342
+ setTaskContext(context: string): this;
1343
+ /** Return the current task context string. */
1344
+ getTaskContext(): string;
1181
1345
  private _setupEncryption;
1182
1346
  /** Encrypt applicable columns in a row before writing. Returns a new row. */
1183
1347
  private _encryptRow;
@@ -1258,6 +1422,22 @@ declare class Lattice {
1258
1422
  buildReport(config: ReportConfig): Promise<ReportResult>;
1259
1423
  /** Parse duration shorthand ('8h', '24h', '7d') into ISO timestamp. */
1260
1424
  private _resolveSince;
1425
+ /**
1426
+ * Update reward scores for a row. The total reward is recalculated as
1427
+ * the running average across all reward calls. Requires `rewardTracking`
1428
+ * on the table definition.
1429
+ */
1430
+ reward(table: string, id: PkLookup, scores: RewardScores): Promise<void>;
1431
+ /**
1432
+ * Search for rows by semantic similarity. Requires `embeddings` config
1433
+ * on the table definition.
1434
+ *
1435
+ * @param table - Table to search
1436
+ * @param query - Natural-language query text
1437
+ * @param opts - Search options (topK, minScore)
1438
+ * @returns Matching rows with similarity scores, sorted best-first.
1439
+ */
1440
+ search(table: string, query: string, opts?: SearchOptions): Promise<SearchResult[]>;
1261
1441
  query(table: string, opts?: QueryOptions): Promise<Row[]>;
1262
1442
  count(table: string, opts?: CountOptions): Promise<number>;
1263
1443
  render(outputDir: string): Promise<RenderResult>;
@@ -1297,6 +1477,11 @@ declare class Lattice {
1297
1477
  private _buildFilters;
1298
1478
  /** Returns a rejected Promise if not initialized; null if ready. */
1299
1479
  private _fireWriteHooks;
1480
+ /**
1481
+ * Update or remove the embedding for a row.
1482
+ * No-op if the table doesn't have `embeddings` configured.
1483
+ */
1484
+ private _syncEmbedding;
1300
1485
  private _notInitError;
1301
1486
  /**
1302
1487
  * Returns a rejected Promise if any of the given column names are not present
@@ -1512,6 +1697,25 @@ declare function parseConfigString(yamlContent: string, configDir: string): Pars
1512
1697
 
1513
1698
  declare function contentHash(content: string): string;
1514
1699
 
1700
+ /**
1701
+ * Estimate the number of tokens in a string using a fast heuristic.
1702
+ * Uses ~4 characters per token, a reasonable approximation for English
1703
+ * text with typical LLM tokenizers (BPE/ByteBPE).
1704
+ *
1705
+ * Users who need exact counts should pre-process with their own tokenizer
1706
+ * and use the `filter` hook to manually limit rows.
1707
+ */
1708
+ declare function estimateTokens(text: string): number;
1709
+ /**
1710
+ * Apply a token budget to rendered output.
1711
+ * If the full render exceeds the budget, rows are sorted by priority,
1712
+ * pruned via binary search, and re-rendered. A truncation footer is
1713
+ * appended so the consuming agent knows context was limited.
1714
+ *
1715
+ * @returns Final content string, possibly with truncation footer.
1716
+ */
1717
+ declare function applyTokenBudget(rows: Row[], renderFn: (rows: Row[]) => string, budget: number, prioritizeBy?: string | ((a: Row, b: Row) => number)): string;
1718
+
1515
1719
  /**
1516
1720
  * Fix legacy schema conflicts before Lattice init().
1517
1721
  *
@@ -1827,4 +2031,4 @@ declare function autoUpdate(opts?: {
1827
2031
  quiet?: boolean;
1828
2032
  }): Promise<AutoUpdateResult>;
1829
2033
 
1830
- export { type ApplyWriteResult, type AuditEvent, type AutoUpdateResult, type BelongsToRelation, type BelongsToSource, type BuiltinTemplateName, type CleanupOptions, type CleanupResult, type CountOptions, type CustomSource, DEFAULT_ENTRY_TYPES, DEFAULT_TYPE_ALIASES, 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 Filter, type FilterOp, type HasManyRelation, type HasManySource, InMemoryStateStore, type InitOptions, Lattice, type LatticeConfig, type LatticeConfigInput, type LatticeEntityDef, type LatticeEntityRenderSpec, type LatticeFieldDef, type LatticeFieldType, type LatticeManifest, type LatticeOptions, type LinkOptions, type ManyToManySource, type MarkdownTableColumn, type Migration, type MultiTableDefinition, type OrderBySpec, type ParseError, type ParseResult, type ParsedConfig, type PkLookup, type PrimaryKey, type QueryOptions, READ_ONLY_HEADER, type ReadOnlyHeaderOptions, type ReconcileOptions, type ReconcileResult, type Relation, type RenderHooks, type RenderResult, type RenderSpec, type ReportConfig, type ReportResult, type ReportSection, type ReportSectionResult, type ReverseSyncError, type ReverseSyncResult, type ReverseSyncUpdate, type Row, type SecurityOptions, type SeedConfig, type SeedLinkSpec, type SeedResult, type SelfSource, type SessionEntry, type SessionParseOptions, type SessionWriteEntry, type SessionWriteOp, type SessionWriteParseResult, type SourceQueryOptions, type StopFn, type SyncResult, type TableDefinition, type TemplateRenderSpec, type UpsertByNaturalKeyOptions, type WatchOptions, type WriteHook, type WriteHookContext, type WritebackDefinition, type WritebackStateStore, applyWriteEntry, autoUpdate, contentHash, createReadOnlyHeader, createSQLiteStateStore, decrypt, deriveKey, encrypt, entityFileNames, fixSchemaConflicts, frontmatter, generateEntryId, generateWriteEntryId, isEncrypted, isV1EntityFiles, manifestPath, markdownTable, normalizeEntityFiles, parseConfigFile, parseConfigString, parseMarkdownEntries, parseSessionMD, parseSessionWrites, readManifest, slugify, truncate, validateEntryId, writeManifest };
2034
+ export { type ApplyWriteResult, type AuditEvent, type AutoUpdateResult, type BelongsToRelation, type BelongsToSource, type BuiltinTemplateName, type CleanupOptions, type CleanupResult, type CountOptions, type CustomSource, DEFAULT_ENTRY_TYPES, DEFAULT_TYPE_ALIASES, type EmbeddingsConfig, 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 Filter, type FilterOp, type HasManyRelation, type HasManySource, InMemoryStateStore, type InitOptions, Lattice, type LatticeConfig, type LatticeConfigInput, type LatticeEntityDef, type LatticeEntityRenderSpec, type LatticeFieldDef, type LatticeFieldType, type LatticeManifest, type LatticeOptions, type LinkOptions, type ManyToManySource, type MarkdownTableColumn, type Migration, type MultiTableDefinition, type OrderBySpec, type ParseError, type ParseResult, type ParsedConfig, type PkLookup, type PrimaryKey, type QueryOptions, READ_ONLY_HEADER, type ReadOnlyHeaderOptions, type ReconcileOptions, type ReconcileResult, type Relation, type RenderHooks, type RenderResult, type RenderSpec, type ReportConfig, type ReportResult, type ReportSection, type ReportSectionResult, type ReverseSyncError, type ReverseSyncResult, type ReverseSyncUpdate, type RewardScores, type Row, type SearchOptions, type SearchResult, type SecurityOptions, type SeedConfig, type SeedLinkSpec, type SeedResult, type SelfSource, type SessionEntry, type SessionParseOptions, type SessionWriteEntry, type SessionWriteOp, type SessionWriteParseResult, type SourceQueryOptions, type StopFn, type SyncResult, type TableDefinition, type TemplateRenderSpec, type UpsertByNaturalKeyOptions, type WatchOptions, type WriteHook, type WriteHookContext, type WritebackDefinition, type WritebackStateStore, type WritebackValidationResult, applyTokenBudget, applyWriteEntry, autoUpdate, contentHash, createReadOnlyHeader, createSQLiteStateStore, decrypt, deriveKey, encrypt, entityFileNames, estimateTokens, fixSchemaConflicts, frontmatter, generateEntryId, generateWriteEntryId, isEncrypted, isV1EntityFiles, manifestPath, markdownTable, normalizeEntityFiles, parseConfigFile, parseConfigString, parseMarkdownEntries, parseSessionMD, parseSessionWrites, readManifest, slugify, truncate, validateEntryId, writeManifest };