@fortemi/core 2026.9.5 → 2026.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.ts +1705 -1508
  3. package/dist/index.js +2633 -675
  4. package/dist/index.js.map +1 -1
  5. package/package.json +5 -1
  6. package/schemas/lifecycle-purge/contract.receipt.json +15 -0
  7. package/schemas/lifecycle-purge/v1.conformance.json +73 -0
  8. package/schemas/metadata-search/candidate/1.0.0/README.md +36 -0
  9. package/schemas/metadata-search/candidate/1.0.0/contract.receipt.json +38 -0
  10. package/schemas/metadata-search/candidate/1.0.0/evidence-locator.schema.json +50 -0
  11. package/schemas/metadata-search/candidate/1.0.0/evidence-resolution-vectors.json +355 -0
  12. package/schemas/metadata-search/candidate/1.0.0/evidence-resolution.schema.json +25 -0
  13. package/schemas/metadata-search/candidate/1.0.0/evidence-set-vectors.json +6095 -0
  14. package/schemas/metadata-search/candidate/1.0.0/evidence-set.schema.json +21 -0
  15. package/schemas/metadata-search/candidate/1.0.0/evidence-vectors.json +1603 -0
  16. package/schemas/metadata-search/candidate/1.0.0/predicate-vectors.json +919 -0
  17. package/schemas/metadata-search/candidate/1.0.0/predicates.schema.json +287 -0
  18. package/schemas/metadata-search/candidate/1.0.0/resolution.receipt.json +44 -0
  19. package/schemas/metadata-search/candidate/1.0.0/rest.receipt.json +51 -0
  20. package/schemas/metadata-search/candidate/1.0.0/search-rest-vectors.json +28 -0
  21. package/schemas/metadata-search/candidate/1.0.0/search-rest.schema.json +318 -0
  22. package/schemas/metadata-search/candidate/1.0.0/source.receipt.json +46 -0
  23. package/schemas/metadata-search/candidate/1.0.0/sql-scope-vectors.json +894 -0
package/dist/index.d.ts CHANGED
@@ -1177,6 +1177,58 @@ declare class RemoteBackendError extends Error {
1177
1177
  readonly name = "RemoteBackendError";
1178
1178
  constructor(kind: RemoteBackendErrorKind, status?: number | undefined, problemCode?: string | undefined, requestId?: string | undefined, retryAfterSeconds?: number | undefined);
1179
1179
  }
1180
+ interface EvidenceTextUnit {
1181
+ readonly kind: 'attachment' | 'current' | 'embedding' | 'title';
1182
+ readonly id: string;
1183
+ readonly index: number;
1184
+ }
1185
+ interface EvidenceSourceIdentity {
1186
+ readonly namespace: string;
1187
+ readonly external_id_hash: string;
1188
+ readonly import_run_id: string;
1189
+ readonly schema_version: string;
1190
+ }
1191
+ interface SearchEvidenceLocator {
1192
+ readonly version: '1.0.0';
1193
+ readonly note_id: string;
1194
+ readonly unit: EvidenceTextUnit;
1195
+ readonly content_digest: string;
1196
+ readonly span: {
1197
+ readonly end: number;
1198
+ readonly start: number;
1199
+ readonly unit: 'utf8-bytes';
1200
+ };
1201
+ readonly source?: EvidenceSourceIdentity;
1202
+ }
1203
+ /** The caller supplies already-authorized text, not an access grant from this type. */
1204
+ interface EvidenceTextSnapshot {
1205
+ readonly note_id: string;
1206
+ readonly unit: EvidenceTextUnit;
1207
+ readonly content: string;
1208
+ readonly source?: EvidenceSourceIdentity;
1209
+ }
1210
+ /** Parse an untrusted wire value, taking an immutable validated copy. */
1211
+ declare function parseSearchEvidenceLocator(value: unknown): SearchEvidenceLocator;
1212
+ /** Bind exact raw text. No Unicode normalization, trimming or HTML processing. */
1213
+ declare function bindSearchEvidence(text: EvidenceTextSnapshot, start: number, end: number): SearchEvidenceLocator;
1214
+ /** Pure binding check over already-authorized text; never performs database I/O. */
1215
+ declare function resolveSearchEvidence(value: unknown, text: EvidenceTextSnapshot | null): string;
1216
+ declare const EVIDENCE_OMISSIONS: readonly [
1217
+ "unavailable-unit",
1218
+ "locator-limit"
1219
+ ];
1220
+ type SearchEvidenceOmission = typeof EVIDENCE_OMISSIONS[number];
1221
+ interface SearchEvidenceSet {
1222
+ readonly version: '1.0.0';
1223
+ readonly locators: readonly SearchEvidenceLocator[];
1224
+ readonly omissions: readonly SearchEvidenceOmission[];
1225
+ }
1226
+ /** Validate canonical ordering and the enclosing hit's native note identity. */
1227
+ declare function parseSearchEvidenceSet(value: unknown, noteId: string): SearchEvidenceSet;
1228
+ /** Bound and deduplicate already-projected locators; never fetch or invent text. */
1229
+ declare function createSearchEvidenceSet(noteId: string, values: readonly unknown[], omissions?: readonly SearchEvidenceOmission[]): SearchEvidenceSet;
1230
+ /** Merge one hit's retrieval legs, retaining partial/unavailable provenance. */
1231
+ declare function mergeSearchEvidenceSets(noteId: string, sets: readonly SearchEvidenceSet[]): SearchEvidenceSet;
1180
1232
  /**
1181
1233
  * Type-safe client for the PGlite Worker.
1182
1234
  *
@@ -1644,1565 +1696,1628 @@ interface ShardReader {
1644
1696
  * reader than this build throws (the host should fall back to `importShard`).
1645
1697
  */
1646
1698
  declare function openShard(source: ShardReaderSource, options?: OpenShardOptions): Promise<ShardReader>;
1647
- /**
1648
- * Backend seam (#191) — a uniform tool-intent operation interface that lets the
1649
- * PGlite database backend (#187) and the static-file shard backend (#189) be
1650
- * selected and dispatched against the same way, plus a capability-negotiation
1651
- * API so a caller asks for the operations it needs and gets the lightest backend
1652
- * that provides them.
1653
- *
1654
- * The seam sits one level above SQL: every adapter exposes the same read
1655
- * operations (and optional relationship, write, semantic, and full-content ops)
1656
- * regardless of whether the data lives in a queryable PGlite instance, a set of
1657
- * static shard files fetched over HTTP, or the Fortemi server tier.
1658
- */
1659
- /**
1660
- * Semantic-search tier a backend offers, in increasing capability:
1661
- * - `none` — no vector search (text / facets only)
1662
- * - `cosine-small` — brute-force cosine over a small static vector set (#189)
1663
- * - `ann-full` — prebuilt/queryable approximate-nearest-neighbour over the full
1664
- * corpus (PGlite + pgvector, or a prebuilt ANN snapshot)
1665
- * - `server` — delegated to the remote Fortemi server backend
1666
- */
1667
- type BackendSemanticTier = 'ann-full' | 'cosine-small' | 'none' | 'server';
1668
- /** Relative startup cost of bringing a backend online. */
1669
- type BackendStartupCost = 'index-build' | 'instant' | 'network';
1670
- /** What a backend can do — the unit of capability negotiation. */
1671
- interface BackendCapabilities {
1672
- /** Can answer list / get / search read operations. */
1673
- read: boolean;
1674
- /** Can mutate notes (manageNote). */
1675
- write: boolean;
1676
- /** Can merge external shards into its store. */
1677
- merge: boolean;
1678
- /** Coordinates concurrent multi-user writes. */
1679
- multiUser: boolean;
1680
- /** Highest semantic-search tier available. */
1681
- semantic: BackendSemanticTier;
1682
- /** Relative cost to bring the backend online. */
1683
- startupCost: BackendStartupCost;
1699
+ type JsonObject = Record<string, unknown>;
1700
+ interface NativeEmbeddingConfig {
1701
+ id: string;
1702
+ name: string;
1703
+ description: null | string;
1704
+ model: string;
1705
+ dimension: number;
1706
+ chunk_size: number;
1707
+ chunk_overlap: number;
1708
+ hnsw_m: null | number;
1709
+ hnsw_ef_construction: null | number;
1710
+ ivfflat_lists: null | number;
1711
+ is_default: boolean | null;
1712
+ supports_mrl: boolean | null;
1713
+ matryoshka_dims: null | number[];
1714
+ default_truncate_dim: null | number;
1715
+ provider: null | string;
1716
+ provider_config: JsonObject | null;
1717
+ content_types: null | string[];
1718
+ strengths: null | string[];
1719
+ limitations: null | string[];
1720
+ recommended_for: null | string[];
1721
+ benchmark_scores: JsonObject | null;
1722
+ is_available: boolean | null;
1723
+ document_composition: JsonObject;
1724
+ created_at: string;
1725
+ updated_at: string;
1726
+ }
1727
+ interface NativeEmbeddingSet {
1728
+ id: string;
1729
+ name: string;
1730
+ slug: null | string;
1731
+ description: null | string;
1732
+ purpose: null | string;
1733
+ usage_hints: null | string;
1734
+ keywords: null | string[];
1735
+ set_type: 'filter' | 'full';
1736
+ mode: 'auto' | 'manual' | 'mixed' | null;
1737
+ criteria: JsonObject | null;
1738
+ embedding_config_id: null | string;
1739
+ truncate_dim: null | number;
1740
+ auto_embed_rules: JsonObject | null;
1741
+ index_status: string;
1742
+ index_type: null | string;
1743
+ last_indexed_at: null | string;
1744
+ document_count: null | number;
1745
+ embedding_count: null | number;
1746
+ embeddings_current: boolean | null;
1747
+ index_size_bytes: null | number;
1748
+ is_system: boolean | null;
1749
+ is_active: boolean | null;
1750
+ auto_refresh: boolean | null;
1751
+ refresh_interval: null | string;
1752
+ last_refresh_at: null | string;
1753
+ agent_metadata: JsonObject | null;
1754
+ created_at: string;
1755
+ updated_at: string;
1756
+ created_by: null | string;
1757
+ }
1758
+ interface NativeEmbeddingMember {
1759
+ embedding_set_id: string;
1760
+ note_id: string;
1761
+ membership_type: null | string;
1762
+ added_at: null | string;
1763
+ added_by: null | string;
1684
1764
  }
1685
1765
  /**
1686
- * Backend-neutral note record. `source`/`starred`/`archived` are optional
1687
- * because lean read paths (PGlite full-text search) do not return them; list,
1688
- * get, and every shard path populate all fields.
1766
+ * EmbeddingSetsRepository - named, filter, and virtual embedding set API.
1689
1767
  */
1690
- interface BackendNote {
1691
- id: string;
1692
- title: null | string;
1693
- tags: string[];
1694
- createdAt: string;
1695
- updatedAt: string;
1696
- source?: string;
1697
- starred?: boolean;
1698
- archived?: boolean;
1768
+ type EmbeddingSetKind = 'filter' | 'physical' | 'virtual';
1769
+ type EmbeddingSetMode = 'auto' | 'manual' | 'mixed';
1770
+ interface EmbeddingSetCriteria {
1771
+ query?: string;
1772
+ tags?: string[];
1773
+ collectionIds?: string[];
1774
+ conceptIds?: string[];
1775
+ noteIds?: string[];
1776
+ sources?: string[];
1777
+ formats?: string[];
1778
+ visibilities?: string[];
1779
+ isStarred?: boolean;
1780
+ isArchived?: boolean;
1781
+ hasTitle?: boolean;
1782
+ hasEmbedding?: boolean;
1783
+ isUserEdited?: boolean;
1784
+ hasAiMetadata?: boolean;
1785
+ hasRevisions?: boolean;
1786
+ minGenerationCount?: number;
1787
+ maxGenerationCount?: number;
1788
+ updatedAfter?: string;
1789
+ updatedBefore?: string;
1699
1790
  }
1700
- /** A note plus its current rendered content. */
1701
- interface BackendNoteFull extends BackendNote {
1702
- content: string;
1703
- /** Native note metadata, separate from inference metadata where supported. */
1704
- metadata?: unknown;
1705
- links?: BackendLink[];
1706
- concepts?: BackendConcept[];
1707
- provenance?: BackendProvenanceEdge[];
1708
- /** Server revision/activity graph; not interchangeable with local provenance edges. */
1709
- provenanceGraph?: RemoteProvenanceGraph;
1791
+ interface EmbeddingSetFreshness {
1792
+ status: 'fresh' | 'stale' | 'unknown';
1793
+ sourceHash?: string;
1794
+ checkedAt?: string;
1795
+ reason?: string;
1710
1796
  }
1711
- interface BackendLink {
1712
- id: string;
1713
- fromNoteId: string;
1714
- toNoteId: null | string;
1715
- toUrl?: null | string;
1716
- kind: string;
1717
- score: null | number;
1718
- createdAt: string;
1719
- metadata?: Record<string, unknown>;
1720
- /** Exact server JSON metadata, including non-object values and null. */
1721
- remoteMetadata?: unknown;
1722
- /** Relative to the requested note; remote self-links can appear in both directions. */
1723
- direction?: 'incoming' | 'outgoing';
1724
- snippet?: null | string;
1797
+ interface EmbeddingCompatibilityPolicy {
1798
+ model: 'allow-compatible-family' | 'require-same';
1799
+ dimension: 'allow-truncation' | 'require-same';
1800
+ duplicateVectors: 'error' | 'prefer-latest' | 'prefer-set-order';
1801
+ missingVectors: 'error' | 'include-unembedded-note' | 'omit';
1725
1802
  }
1726
- interface BackendConcept {
1727
- id: string;
1728
- schemeId: string;
1729
- prefLabel: string;
1730
- altLabels: string[];
1731
- definition: null | string;
1732
- createdAt: string;
1733
- updatedAt: string;
1734
- /** Placeholder values for these fields are unavailable, not evidence of absence. */
1735
- unavailableFields?: Array<'altLabels' | 'definition'>;
1736
- assignment?: {
1737
- confidence?: number;
1738
- createdAt: string;
1739
- createdBy?: string;
1740
- isPrimary: boolean;
1741
- noteId: string;
1742
- relevanceScore: number;
1743
- source: string;
1744
- };
1803
+ interface VirtualMaterializationPolicy {
1804
+ allowed: boolean;
1805
+ includeResolvedMembers?: boolean;
1806
+ includeResolvedEdges?: boolean;
1807
+ freshness: 'fresh' | 'stale' | 'unknown';
1808
+ inputHash?: string;
1809
+ generatedAt?: string;
1810
+ resolvedMemberCount?: number;
1745
1811
  }
1746
- interface BackendProvenanceEdge {
1747
- id: string;
1748
- entityType: string;
1749
- entityId: string;
1750
- activity: string;
1751
- agent: null | string;
1752
- startedAt: string;
1753
- endedAt: null | string;
1754
- attributes: unknown;
1812
+ interface CriteriaVirtualSource {
1813
+ type: 'criteria';
1814
+ baseSetId: string;
1815
+ criteria: EmbeddingSetCriteria;
1755
1816
  }
1756
- /** One search hit — note plus optional rank/snippet when the backend ranks. */
1757
- interface BackendSearchHit {
1758
- note: BackendNote;
1759
- rank?: number;
1760
- snippet?: string;
1761
- /** Original remote search metadata; detail enrichment is a separate read. */
1762
- remoteSearch?: RemoteSearchMetadata;
1817
+ interface SetOperationVirtualSource {
1818
+ type: 'set-operation';
1819
+ operation: 'difference' | 'intersection' | 'union';
1820
+ setIds: string[];
1763
1821
  }
1764
- /** Search response with optional facet counts. */
1765
- interface BackendSearchResult {
1766
- hits: BackendSearchHit[];
1767
- total: number;
1768
- facets?: {
1769
- source?: Record<string, number>;
1770
- tags: Record<string, number>;
1771
- };
1822
+ interface FallbackVirtualSource {
1823
+ type: 'fallback';
1824
+ preferredSetIds: string[];
1772
1825
  }
1773
- interface BackendListOptions {
1774
- offset?: number;
1775
- limit?: number;
1826
+ interface LatestCompatibleVirtualSource {
1827
+ type: 'latest-compatible';
1828
+ candidateSetIds: string[];
1829
+ model?: string;
1830
+ dimension?: number;
1776
1831
  }
1777
- interface BackendSearchQueryOptions extends BackendListOptions {
1778
- /** AND-filter: note must carry every listed tag. */
1779
- tags?: string[];
1780
- /** OR-filter on note source. */
1781
- source?: string[];
1832
+ interface SnapshotVirtualSource {
1833
+ type: 'snapshot';
1834
+ snapshotId: string;
1835
+ sourceDefinitionId: string;
1836
+ generatedAt: string;
1837
+ inputHash: string;
1782
1838
  }
1783
- /**
1784
- * Uniform tool-intent operation interface. Every backend implements the read
1785
- * core; `getNoteFull`, `semantic`, and `manageNote` are optional and present
1786
- * only on backends whose capabilities advertise them.
1787
- */
1788
- interface DataBackend {
1789
- readonly id: string;
1790
- readonly capabilities: BackendCapabilities;
1791
- listNotes(options?: BackendListOptions): Promise<{
1792
- items: BackendNote[];
1793
- total: number;
1794
- }>;
1795
- getNote(id: string): Promise<BackendNote | null>;
1796
- search(query: string, options?: BackendSearchQueryOptions): Promise<BackendSearchResult>;
1797
- /** Lazy full content (present when capabilities.read). */
1798
- getNoteFull?(id: string): Promise<BackendNoteFull | null>;
1799
- /** Note links (present when capabilities.read). */
1800
- linksOf?(id: string): Promise<BackendLink[]>;
1801
- /** SKOS concepts assigned to a note (present when capabilities.read). */
1802
- conceptsOf?(id: string): Promise<BackendConcept[]>;
1803
- /** W3C PROV edges for a note (present when capabilities.read). */
1804
- provenanceOf?(id: string): Promise<BackendProvenanceEdge[]>;
1805
- /** Remote revision/activity graph, preserving the server model and field names. */
1806
- provenanceGraphOf?(id: string): Promise<RemoteProvenanceGraph>;
1807
- /** Vector search (present when capabilities.semantic !== 'none'). */
1808
- semantic?(query: string, k?: number): Promise<BackendSearchHit[]>;
1809
- /** Write op (present when capabilities.write). */
1810
- manageNote?(input: unknown): Promise<unknown>;
1811
- }
1812
- /** What a caller needs. Booleans require `true`; `semantic` is a minimum tier. */
1813
- interface BackendRequest {
1814
- read?: boolean;
1815
- write?: boolean;
1816
- merge?: boolean;
1817
- multiUser?: boolean;
1818
- /** Minimum acceptable semantic tier (a higher tier satisfies a lower request). */
1819
- semantic?: BackendSemanticTier;
1839
+ type VirtualEmbeddingSetSource = CriteriaVirtualSource | FallbackVirtualSource | LatestCompatibleVirtualSource | SetOperationVirtualSource | SnapshotVirtualSource;
1840
+ interface VirtualEmbeddingSetDefinition {
1841
+ id: string;
1842
+ name: string;
1843
+ purpose?: null | string;
1844
+ source: VirtualEmbeddingSetSource;
1845
+ compatibility: EmbeddingCompatibilityPolicy;
1846
+ materialization?: VirtualMaterializationPolicy;
1847
+ createdAt?: string;
1848
+ updatedAt?: string;
1820
1849
  }
1821
- interface BackendCandidate {
1822
- backend: DataBackend;
1823
- /** Requested capabilities this backend cannot satisfy ([] = fully satisfies). */
1824
- missing: string[];
1850
+ interface EmbeddingSetSelector {
1851
+ kind: 'default' | 'embedding-set' | 'virtual-definition';
1852
+ embeddingSetId?: string;
1853
+ definition?: VirtualEmbeddingSetDefinition;
1825
1854
  }
1826
- interface BackendSelection {
1827
- /** Chosen backend — fully-satisfying-and-lightest, else fewest-missing. Null only when no backends are available. */
1828
- backend: DataBackend | null;
1829
- capabilities: BackendCapabilities | null;
1830
- /** Requested capabilities the chosen backend cannot satisfy. */
1831
- missing: string[];
1832
- /** Every candidate with its own missing set, ordered as evaluated. */
1833
- candidates: BackendCandidate[];
1855
+ interface EmbeddingSetDescriptor {
1856
+ id: string;
1857
+ name: string;
1858
+ purpose?: null | string;
1859
+ kind: EmbeddingSetKind;
1860
+ mode?: EmbeddingSetMode;
1861
+ model?: string;
1862
+ dimension?: number;
1863
+ truncateDimension?: null | number;
1864
+ criteria?: EmbeddingSetCriteria | null;
1865
+ createdAt?: string;
1866
+ updatedAt?: string;
1867
+ freshness?: EmbeddingSetFreshness;
1834
1868
  }
1835
- /**
1836
- * Pick the backend that best satisfies `request` from `available`. Prefers a
1837
- * fully-satisfying backend with the lightest startup cost; if none fully
1838
- * satisfy, returns the one missing the fewest capabilities (lightest on ties) so
1839
- * the caller can degrade with eyes open via `selection.missing`.
1840
- */
1841
- declare function selectBackend(request: BackendRequest, available: DataBackend[]): BackendSelection;
1842
- interface PGliteBackendOptions {
1843
- id?: string;
1844
- /** Whether embeddings exist so search can use the semantic path. */
1845
- semanticAvailable?: boolean;
1869
+ type VirtualEmbeddingSetValidationError = {
1870
+ code: 'duplicate-vector';
1871
+ noteId: string;
1872
+ setIds: string[];
1873
+ } | {
1874
+ code: 'missing-vector';
1875
+ noteId: string;
1876
+ setId: string;
1877
+ } | {
1878
+ code: 'mixed-dimensions';
1879
+ setIds: string[];
1880
+ } | {
1881
+ code: 'mixed-models';
1882
+ setIds: string[];
1883
+ } | {
1884
+ code: 'stale-snapshot';
1885
+ snapshotId: string;
1886
+ } | {
1887
+ code: 'unsupported-criteria';
1888
+ field: string;
1889
+ };
1890
+ interface ResolvedEmbeddingRow {
1891
+ note_id: string;
1892
+ embedding_set_id: string;
1893
+ embedding_id: string;
1894
+ vector: string;
1895
+ created_at: Date | null;
1846
1896
  }
1847
- /**
1848
- * Wrap a PGlite-backed `DatabaseClient` as a `DataBackend`. Read ops delegate to
1849
- * the repositories; writes go through the `manageNote` tool. Advertises full
1850
- * read+write+merge with `ann-full` semantic when embeddings are present.
1851
- */
1852
- declare function createPGliteBackend(db: DatabaseClient, options?: PGliteBackendOptions): DataBackend;
1853
- interface RemoteBackendPaths {
1854
- notes: string;
1855
- note: string;
1856
- search: string;
1857
- links: string;
1858
- concepts: string;
1859
- provenance: string;
1860
- restore: string;
1861
- /** @deprecated Tool-intent path overrides cannot adapt the REST contract and are rejected. */
1862
- manageNote?: string;
1863
- /** @deprecated Semantic search uses the search path and mode parameter. Overrides are rejected. */
1864
- semantic?: string;
1897
+ interface ResolvedEmbeddingSet {
1898
+ selector: EmbeddingSetSelector;
1899
+ rows: ResolvedEmbeddingRow[];
1900
+ noteIds: string[];
1901
+ embeddingIds: string[];
1902
+ errors: VirtualEmbeddingSetValidationError[];
1903
+ freshness: EmbeddingSetFreshness;
1904
+ resolutionSource: 'live' | 'materialized';
1865
1905
  }
1866
- interface RemoteSearchOptions extends BackendSearchQueryOptions {
1867
- mode?: RemoteSearchMode;
1906
+ interface EmbeddingConfigRow extends Omit<NativeEmbeddingConfig, 'created_at' | 'updated_at'> {
1907
+ created_at: Date;
1908
+ updated_at: Date;
1868
1909
  }
1869
- interface RemoteSearchResult extends BackendSearchResult {
1870
- /** The server total counts returned hits, not the corpus or a pagination estimate. */
1871
- totalKind: 'returned-hits';
1872
- requestedMode: RemoteSearchMode;
1873
- effectiveMode: RemoteSearchMode;
1874
- degraded: boolean;
1875
- degradation?: RemoteSearchDegradation;
1910
+ interface EmbeddingMemberRow extends Omit<NativeEmbeddingMember, 'added_at'> {
1911
+ embedding_id: null | string;
1912
+ added_at: Date | null;
1876
1913
  }
1877
- interface RemoteManageNoteResult {
1878
- action: 'archive' | 'create' | 'delete' | 'restore' | 'star' | 'unarchive' | 'unstar' | 'update';
1879
- note_id: string;
1880
- /** Present only when the mutation itself returns a note envelope. */
1881
- note?: BackendNoteFull;
1914
+ interface EmbeddingRow {
1915
+ id: string;
1916
+ note_id: null | string;
1917
+ embedding_set_id: null | string;
1918
+ chunk_index: number;
1919
+ text: string;
1920
+ vector: null | string;
1921
+ model: null | string;
1922
+ contract_fingerprint: null | string;
1923
+ shard_contract_fingerprint_present: boolean;
1924
+ created_at: Date | null;
1882
1925
  }
1883
- interface RemoteDataBackend extends DataBackend {
1884
- search(query: string, options?: RemoteSearchOptions): Promise<RemoteSearchResult>;
1885
- semanticWithReport(query: string, k?: number): Promise<RemoteSearchResult>;
1886
- manageNote(input: unknown): Promise<RemoteManageNoteResult>;
1926
+ interface EmbeddingSetRow extends Partial<Omit<NativeEmbeddingSet, 'created_at' | 'criteria' | 'keywords' | 'mode' | 'set_type' | 'truncate_dim' | 'updated_at'>> {
1927
+ id: string;
1928
+ name: string;
1929
+ purpose: null | string;
1930
+ model_name: string;
1931
+ dimensions: number;
1932
+ kind: EmbeddingSetKind;
1933
+ mode: EmbeddingSetMode | null;
1934
+ truncate_dimension: null | number;
1935
+ criteria_json: null | unknown;
1936
+ source_json: null | unknown;
1937
+ compatibility_json: null | unknown;
1938
+ materialization_json: null | unknown;
1939
+ freshness_json: null | unknown;
1940
+ created_at: Date;
1941
+ updated_at: Date;
1887
1942
  }
1888
- interface RemoteBackendConfig {
1889
- baseUrl: string;
1943
+ interface EmbeddingSetCreateInput {
1890
1944
  id?: string;
1891
- fetchImpl?: typeof fetch;
1892
- headers?: (() => HeadersInit | Promise<HeadersInit>) | HeadersInit;
1893
- authToken?: string;
1894
- paths?: Partial<RemoteBackendPaths>;
1945
+ name: string;
1946
+ slug?: null | string;
1947
+ purpose?: null | string;
1948
+ model_name?: string;
1949
+ dimensions?: number;
1950
+ kind?: EmbeddingSetKind;
1951
+ mode?: EmbeddingSetMode | null;
1952
+ truncate_dimension?: null | number;
1953
+ criteria?: EmbeddingSetCriteria | null;
1895
1954
  }
1896
- declare function createRemoteBackend(config: RemoteBackendConfig): RemoteDataBackend;
1897
- interface ShardBackendOptions {
1955
+ interface EmbeddingSetEmbeddingInput {
1898
1956
  id?: string;
1899
- /** Declared semantic tier this shard provides (default `none`). Set to `cosine-small` when the reader has a vector provider. */
1900
- semantic?: BackendSemanticTier;
1957
+ note_id: string;
1958
+ embedding_set_id: string;
1959
+ vector: number[];
1901
1960
  }
1902
- /**
1903
- * Wrap a `ShardReader` (#189) as a read-only `DataBackend`. Startup is instant
1904
- * (no index build) and the semantic tier is whatever the reader's provider
1905
- * offers — `none` for text/facets-only shards, `cosine-small` when a vector
1906
- * provider is attached.
1907
- */
1908
- declare function createShardBackend(reader: ShardReader, options?: ShardBackendOptions): DataBackend;
1909
- declare const provenanceGraph: z.ZodObject<{
1910
- all_activities: z.ZodArray<z.ZodObject<{
1911
- activity_type: z.ZodString;
1912
- ended_at: z.ZodNullable<z.ZodString>;
1913
- id: z.ZodEffects<z.ZodString, string, string>;
1914
- metadata: z.ZodEffects<z.ZodUnknown, {} | null, unknown>;
1915
- model_name: z.ZodNullable<z.ZodString>;
1916
- note_id: z.ZodEffects<z.ZodString, string, string>;
1917
- revision_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
1918
- started_at: z.ZodString;
1919
- }, "strip", z.ZodTypeAny, {
1920
- activity_type: string;
1921
- ended_at: null | string;
1961
+ declare class EmbeddingSetsRepository {
1962
+ private db;
1963
+ constructor(db: QueryExecutor);
1964
+ getConfig(id: string): Promise<EmbeddingConfigRow>;
1965
+ listConfigs(): Promise<EmbeddingConfigRow[]>;
1966
+ listMembers(setId: string): Promise<EmbeddingMemberRow[]>;
1967
+ /** Includes metadata-only records and every chunk, unlike a resolved graph selector. */
1968
+ listEmbeddings(setId: string): Promise<EmbeddingRow[]>;
1969
+ create(input: EmbeddingSetCreateInput): Promise<EmbeddingSetRow>;
1970
+ createVirtualDefinition(input: VirtualEmbeddingSetDefinition): Promise<EmbeddingSetRow>;
1971
+ ensureDefault(): Promise<EmbeddingSetRow>;
1972
+ get(id: string): Promise<EmbeddingSetRow>;
1973
+ list(): Promise<EmbeddingSetRow[]>;
1974
+ listDescriptors(): Promise<EmbeddingSetDescriptor[]>;
1975
+ toDescriptor(row: EmbeddingSetRow): EmbeddingSetDescriptor;
1976
+ putEmbedding(input: EmbeddingSetEmbeddingInput): Promise<{
1922
1977
  id: string;
1923
- metadata: {} | null;
1924
- model_name: null | string;
1925
- note_id: string;
1926
- revision_id: null | string;
1927
- started_at: string;
1928
- }, {
1929
- activity_type: string;
1930
- ended_at: null | string;
1931
- id: string;
1932
- metadata?: unknown;
1933
- model_name: null | string;
1934
- note_id: string;
1935
- revision_id: null | string;
1936
- started_at: string;
1937
- }>, "many">;
1938
- all_edges: z.ZodArray<z.ZodObject<{
1939
- created_at_utc: z.ZodString;
1940
- id: z.ZodEffects<z.ZodString, string, string>;
1941
- relation: z.ZodString;
1942
- revision_id: z.ZodEffects<z.ZodString, string, string>;
1943
- source_note_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
1944
- source_url: z.ZodNullable<z.ZodString>;
1945
- }, "strip", z.ZodTypeAny, {
1946
- created_at_utc: string;
1947
- id: string;
1948
- relation: string;
1949
- revision_id: string;
1950
- source_note_id: null | string;
1951
- source_url: null | string;
1952
- }, {
1953
- created_at_utc: string;
1954
- id: string;
1955
- relation: string;
1956
- revision_id: string;
1957
- source_note_id: null | string;
1958
- source_url: null | string;
1959
- }>, "many">;
1960
- current_chain: z.ZodNullable<z.ZodObject<{
1961
- activity: z.ZodNullable<z.ZodObject<{
1962
- activity_type: z.ZodString;
1963
- ended_at: z.ZodNullable<z.ZodString>;
1964
- id: z.ZodEffects<z.ZodString, string, string>;
1965
- metadata: z.ZodEffects<z.ZodUnknown, {} | null, unknown>;
1966
- model_name: z.ZodNullable<z.ZodString>;
1967
- note_id: z.ZodEffects<z.ZodString, string, string>;
1968
- revision_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
1969
- started_at: z.ZodString;
1970
- }, "strip", z.ZodTypeAny, {
1971
- activity_type: string;
1972
- ended_at: null | string;
1973
- id: string;
1974
- metadata: {} | null;
1975
- model_name: null | string;
1976
- note_id: string;
1977
- revision_id: null | string;
1978
- started_at: string;
1979
- }, {
1980
- activity_type: string;
1981
- ended_at: null | string;
1982
- id: string;
1983
- metadata?: unknown;
1984
- model_name: null | string;
1985
- note_id: string;
1986
- revision_id: null | string;
1987
- started_at: string;
1988
- }>>;
1989
- edges: z.ZodArray<z.ZodObject<{
1990
- created_at_utc: z.ZodString;
1991
- id: z.ZodEffects<z.ZodString, string, string>;
1992
- relation: z.ZodString;
1993
- revision_id: z.ZodEffects<z.ZodString, string, string>;
1994
- source_note_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
1995
- source_url: z.ZodNullable<z.ZodString>;
1996
- }, "strip", z.ZodTypeAny, {
1997
- created_at_utc: string;
1998
- id: string;
1999
- relation: string;
2000
- revision_id: string;
2001
- source_note_id: null | string;
2002
- source_url: null | string;
2003
- }, {
2004
- created_at_utc: string;
2005
- id: string;
2006
- relation: string;
2007
- revision_id: string;
2008
- source_note_id: null | string;
2009
- source_url: null | string;
2010
- }>, "many">;
2011
- note_id: z.ZodEffects<z.ZodString, string, string>;
2012
- revision_id: z.ZodEffects<z.ZodString, string, string>;
2013
- }, "strip", z.ZodTypeAny, {
2014
- activity: {
2015
- activity_type: string;
2016
- ended_at: null | string;
2017
- id: string;
2018
- metadata: {} | null;
2019
- model_name: null | string;
2020
- note_id: string;
2021
- revision_id: null | string;
2022
- started_at: string;
2023
- } | null;
2024
- edges: {
2025
- created_at_utc: string;
2026
- id: string;
2027
- relation: string;
2028
- revision_id: string;
2029
- source_note_id: null | string;
2030
- source_url: null | string;
2031
- }[];
2032
- note_id: string;
2033
- revision_id: string;
2034
- }, {
2035
- activity: {
2036
- activity_type: string;
2037
- ended_at: null | string;
2038
- id: string;
2039
- metadata?: unknown;
2040
- model_name: null | string;
2041
- note_id: string;
2042
- revision_id: null | string;
2043
- started_at: string;
2044
- } | null;
2045
- edges: {
2046
- created_at_utc: string;
2047
- id: string;
2048
- relation: string;
2049
- revision_id: string;
2050
- source_note_id: null | string;
2051
- source_url: null | string;
2052
- }[];
2053
- note_id: string;
2054
- revision_id: string;
2055
- }>>;
2056
- derived_count: z.ZodNumber;
2057
- derived_notes: z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">;
2058
- note_id: z.ZodEffects<z.ZodString, string, string>;
2059
- }, "strip", z.ZodTypeAny, {
2060
- all_activities: {
2061
- activity_type: string;
2062
- ended_at: null | string;
2063
- id: string;
2064
- metadata: {} | null;
2065
- model_name: null | string;
2066
- note_id: string;
2067
- revision_id: null | string;
2068
- started_at: string;
2069
- }[];
2070
- all_edges: {
2071
- created_at_utc: string;
2072
- id: string;
2073
- relation: string;
2074
- revision_id: string;
2075
- source_note_id: null | string;
2076
- source_url: null | string;
2077
- }[];
2078
- current_chain: {
2079
- activity: {
2080
- activity_type: string;
2081
- ended_at: null | string;
2082
- id: string;
2083
- metadata: {} | null;
2084
- model_name: null | string;
2085
- note_id: string;
2086
- revision_id: null | string;
2087
- started_at: string;
2088
- } | null;
2089
- edges: {
2090
- created_at_utc: string;
2091
- id: string;
2092
- relation: string;
2093
- revision_id: string;
2094
- source_note_id: null | string;
2095
- source_url: null | string;
2096
- }[];
2097
- note_id: string;
2098
- revision_id: string;
2099
- } | null;
2100
- derived_count: number;
2101
- derived_notes: string[];
2102
- note_id: string;
2103
- }, {
2104
- all_activities: {
2105
- activity_type: string;
2106
- ended_at: null | string;
2107
- id: string;
2108
- metadata?: unknown;
2109
- model_name: null | string;
2110
- note_id: string;
2111
- revision_id: null | string;
2112
- started_at: string;
1978
+ }>;
1979
+ resolveSelector(selector: EmbeddingSetSelector): Promise<ResolvedEmbeddingSet>;
1980
+ refreshMaterializedVirtualSet(setId: string): Promise<ResolvedEmbeddingSet>;
1981
+ markVirtualSetStale(setId: string, reason: string): Promise<void>;
1982
+ /** @internal The repository and mutation must use the same caller-owned transaction. */
1983
+ withMaterializationInvalidation<T>(mutate: () => Promise<T>): Promise<T>;
1984
+ private liveResolutionHash;
1985
+ private resolveDefinition;
1986
+ private resolvePhysicalSet;
1987
+ private resolvePhysicalRows;
1988
+ private resolveMaterializedRows;
1989
+ private resolveCriteriaSource;
1990
+ private resolveSetOperationSource;
1991
+ private resolveFallbackSource;
1992
+ private resolveLatestCompatibleSource;
1993
+ private validateCompatibility;
1994
+ private resolveDuplicateRows;
1995
+ private finalizeResolution;
1996
+ private resolutionInputHash;
1997
+ private definitionFromRow;
1998
+ private inferDefinitionModel;
1999
+ private inferDefinitionDimension;
2000
+ }
2001
+ /**
2002
+ * Shared types for repository layer.
2003
+ * All repository methods use these types as inputs and outputs.
2004
+ */
2005
+ interface NoteSummary {
2006
+ id: string;
2007
+ title: null | string;
2008
+ format: string;
2009
+ source: string;
2010
+ visibility: string;
2011
+ is_starred: boolean;
2012
+ is_pinned: boolean;
2013
+ is_archived: boolean;
2014
+ created_at: Date;
2015
+ updated_at: Date;
2016
+ deleted_at: Date | null;
2017
+ tags: string[];
2018
+ }
2019
+ interface NoteFull extends NoteSummary {
2020
+ /** Note metadata is independent of the current revision's AI metadata. */
2021
+ metadata?: unknown;
2022
+ archive_id: null | string;
2023
+ revision_mode: string;
2024
+ original: {
2025
+ content_hash: string;
2026
+ content: string;
2027
+ created_at: Date;
2028
+ id: null | string;
2029
+ user_created_at?: null | string;
2030
+ user_last_edited_at?: null | string;
2031
+ version_number?: number;
2032
+ };
2033
+ current: {
2034
+ ai_metadata: null | unknown;
2035
+ content: string;
2036
+ generation_count: number;
2037
+ is_user_edited: boolean;
2038
+ last_revision_id?: null | string;
2039
+ model: null | string;
2040
+ updated_at: Date;
2041
+ };
2042
+ }
2043
+ interface NoteCreateInput {
2044
+ metadata?: unknown;
2045
+ content: string;
2046
+ title?: string;
2047
+ format?: string;
2048
+ source?: string;
2049
+ visibility?: string;
2050
+ tags?: string[];
2051
+ archive_id?: string;
2052
+ /**
2053
+ * Explicit primary key. When omitted a UUIDv7 is minted (the default). Supply
2054
+ * this only for deterministic seeding or cross-instance identity — e.g. two
2055
+ * in-browser databases that must agree on a shared note's id so a shard swap
2056
+ * can dedupe it under the `skip` conflict strategy.
2057
+ */
2058
+ id?: string;
2059
+ }
2060
+ interface NoteUpdateInput {
2061
+ metadata?: unknown;
2062
+ title?: string;
2063
+ content?: string;
2064
+ format?: string;
2065
+ visibility?: string;
2066
+ }
2067
+ interface NoteListOptions {
2068
+ limit?: number;
2069
+ offset?: number;
2070
+ sort?: 'created_at' | 'title' | 'updated_at';
2071
+ order?: 'asc' | 'desc';
2072
+ is_starred?: boolean;
2073
+ is_pinned?: boolean;
2074
+ is_archived?: boolean;
2075
+ include_deleted?: boolean;
2076
+ include_archived?: boolean;
2077
+ collection_id?: string;
2078
+ tags?: string[];
2079
+ }
2080
+ interface PaginatedResult<T> {
2081
+ items: T[];
2082
+ total: number;
2083
+ limit: number;
2084
+ offset: number;
2085
+ }
2086
+ interface SearchResult {
2087
+ id: string;
2088
+ title: null | string;
2089
+ snippet: string;
2090
+ rank: number;
2091
+ created_at: Date;
2092
+ updated_at: Date;
2093
+ tags: string[];
2094
+ has_embedding?: boolean;
2095
+ locators?: EvidenceLocator[];
2096
+ /** Candidate matched-unit citations, separate from legacy source projections. */
2097
+ evidence?: SearchEvidenceSet;
2098
+ }
2099
+ interface SearchFacets {
2100
+ tags: {
2101
+ count: number;
2102
+ tag: string;
2113
2103
  }[];
2114
- all_edges: {
2115
- created_at_utc: string;
2104
+ collections: {
2105
+ count: number;
2116
2106
  id: string;
2117
- relation: string;
2118
- revision_id: string;
2119
- source_note_id: null | string;
2120
- source_url: null | string;
2107
+ name: string;
2121
2108
  }[];
2122
- current_chain: {
2123
- activity: {
2124
- activity_type: string;
2125
- ended_at: null | string;
2126
- id: string;
2127
- metadata?: unknown;
2128
- model_name: null | string;
2129
- note_id: string;
2130
- revision_id: null | string;
2131
- started_at: string;
2132
- } | null;
2133
- edges: {
2134
- created_at_utc: string;
2135
- id: string;
2136
- relation: string;
2137
- revision_id: string;
2138
- source_note_id: null | string;
2139
- source_url: null | string;
2140
- }[];
2141
- note_id: string;
2142
- revision_id: string;
2143
- } | null;
2144
- derived_count: number;
2145
- derived_notes: string[];
2146
- note_id: string;
2147
- }>;
2148
- /** Producer field names intentionally distinguish this graph from local PGlite PROV edges. */
2149
- type RemoteProvenanceGraph = z.infer<typeof provenanceGraph>;
2150
- declare const searchMode: z.ZodEnum<[
2151
- "fts",
2152
- "semantic",
2153
- "hybrid"
2154
- ]>;
2155
- type RemoteSearchMode = z.infer<typeof searchMode>;
2156
- declare const searchHit: z.ZodObject<{
2157
- chain_info: z.ZodOptional<z.ZodObject<{
2158
- best_chunk_sequence: z.ZodNumber;
2159
- chain_id: z.ZodEffects<z.ZodString, string, string>;
2160
- chunks_matched: z.ZodNumber;
2161
- original_title: z.ZodString;
2162
- total_chunks: z.ZodNumber;
2163
- }, "strip", z.ZodTypeAny, {
2164
- best_chunk_sequence: number;
2165
- chain_id: string;
2166
- chunks_matched: number;
2167
- original_title: string;
2168
- total_chunks: number;
2169
- }, {
2170
- best_chunk_sequence: number;
2171
- chain_id: string;
2172
- chunks_matched: number;
2173
- original_title: string;
2174
- total_chunks: number;
2175
- }>>;
2176
- embedding_status: z.ZodOptional<z.ZodEnum<[
2177
- "ready",
2178
- "pending",
2179
- "failed",
2180
- "none"
2181
- ]>>;
2182
- note_id: z.ZodEffects<z.ZodString, string, string>;
2183
- score: z.ZodNumber;
2184
- snippet: z.ZodNullable<z.ZodString>;
2185
- tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
2186
- title: z.ZodOptional<z.ZodString>;
2187
- }, "strip", z.ZodTypeAny, {
2188
- chain_info?: {
2189
- best_chunk_sequence: number;
2190
- chain_id: string;
2191
- chunks_matched: number;
2192
- original_title: string;
2193
- total_chunks: number;
2194
- } | undefined;
2195
- embedding_status?: "failed" | "none" | "pending" | "ready" | undefined;
2109
+ }
2110
+ interface SearchResponse {
2111
+ results: SearchResult[];
2112
+ total: number;
2113
+ query: string;
2114
+ mode: 'hybrid' | 'semantic' | 'text';
2115
+ semantic_available: boolean;
2116
+ limit: number;
2117
+ offset: number;
2118
+ facets?: SearchFacets;
2119
+ }
2120
+ interface SearchOptions {
2121
+ limit?: number;
2122
+ offset?: number;
2123
+ tags?: string[];
2124
+ /** Require every tag; the existing tags option retains its ANY semantics. */
2125
+ tagsAll?: string[];
2126
+ collection_id?: string;
2127
+ date_from?: Date;
2128
+ date_to?: Date;
2129
+ is_starred?: boolean;
2130
+ is_archived?: boolean;
2131
+ format?: string;
2132
+ source?: string;
2133
+ /** Match any listed source before ranking. */
2134
+ sources?: string[];
2135
+ visibility?: string;
2136
+ tenant_id?: string;
2137
+ archive_id?: null | string;
2138
+ metadataPredicates?: readonly MetadataPredicate[];
2139
+ include_facets?: boolean;
2140
+ mode?: 'auto' | 'hybrid' | 'semantic' | 'text';
2141
+ embeddingSetId?: string;
2142
+ embeddingSetSelector?: EmbeddingSetSelector;
2143
+ }
2144
+ interface NoteRevision {
2145
+ id: string;
2196
2146
  note_id: string;
2197
- score: number;
2198
- snippet: null | string;
2199
- tags?: string[] | undefined;
2200
- title?: string | undefined;
2201
- }, {
2202
- chain_info?: {
2203
- best_chunk_sequence: number;
2204
- chain_id: string;
2205
- chunks_matched: number;
2206
- original_title: string;
2207
- total_chunks: number;
2208
- } | undefined;
2209
- embedding_status?: "failed" | "none" | "pending" | "ready" | undefined;
2147
+ revision_number: number;
2148
+ type: string;
2149
+ content: string;
2150
+ ai_metadata: null | unknown;
2151
+ model: null | string;
2152
+ created_at: Date;
2153
+ parent_revision_id?: null | string;
2154
+ summary?: null | string;
2155
+ rationale?: null | string;
2156
+ created_at_utc?: null | string;
2157
+ ai_generated_at?: null | string;
2158
+ user_last_edited_at?: null | string;
2159
+ is_user_edited?: boolean;
2160
+ generation_count?: number;
2161
+ }
2162
+ interface OriginalContentRevision {
2163
+ id: string;
2210
2164
  note_id: string;
2211
- score: number;
2212
- snippet: null | string;
2213
- tags?: string[] | undefined;
2214
- title?: string | undefined;
2215
- }>;
2216
- declare const searchDegradation: z.ZodObject<{
2217
- code: z.ZodString;
2218
- effective_mode: z.ZodEnum<[
2219
- "fts",
2220
- "semantic",
2221
- "hybrid"
2222
- ]>;
2223
- }, "strip", z.ZodTypeAny, {
2224
- code: string;
2225
- effective_mode: "fts" | "hybrid" | "semantic";
2226
- }, {
2227
- code: string;
2228
- effective_mode: "fts" | "hybrid" | "semantic";
2229
- }>;
2230
- type RemoteSearchDegradation = z.infer<typeof searchDegradation>;
2231
- type RemoteSearchMetadata = Pick<z.infer<typeof searchHit>, 'chain_info' | 'embedding_status' | 'tags' | 'title'>;
2232
- declare const manageInput: z.ZodUnion<[
2233
- z.ZodObject<{
2234
- action: z.ZodLiteral<"create">;
2235
- content: z.ZodString;
2236
- source: z.ZodOptional<z.ZodString>;
2237
- tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
2238
- title: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2239
- }, "strict", z.ZodTypeAny, {
2240
- action: "create";
2241
- content: string;
2242
- source?: string | undefined;
2243
- tags?: string[] | undefined;
2244
- title?: null | string | undefined;
2245
- }, {
2246
- action: "create";
2247
- content: string;
2248
- source?: string | undefined;
2249
- tags?: string[] | undefined;
2250
- title?: null | string | undefined;
2251
- }>,
2252
- z.ZodEffects<z.ZodObject<{
2253
- action: z.ZodLiteral<"update">;
2254
- content: z.ZodOptional<z.ZodString>;
2255
- note_id: z.ZodEffects<z.ZodString, string, string>;
2256
- tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
2257
- }, "strict", z.ZodTypeAny, {
2258
- action: "update";
2259
- content?: string | undefined;
2260
- note_id: string;
2261
- tags?: string[] | undefined;
2262
- }, {
2263
- action: "update";
2264
- content?: string | undefined;
2265
- note_id: string;
2266
- tags?: string[] | undefined;
2267
- }>, {
2268
- action: "update";
2269
- content?: string | undefined;
2270
- note_id: string;
2271
- tags?: string[] | undefined;
2272
- }, {
2273
- action: "update";
2274
- content?: string | undefined;
2275
- note_id: string;
2276
- tags?: string[] | undefined;
2277
- }>,
2278
- z.ZodObject<{
2279
- action: z.ZodEnum<[
2280
- "delete",
2281
- "restore",
2282
- "archive",
2283
- "unarchive",
2284
- "star",
2285
- "unstar"
2286
- ]>;
2287
- note_id: z.ZodEffects<z.ZodString, string, string>;
2288
- }, "strict", z.ZodTypeAny, {
2289
- action: "archive" | "delete" | "restore" | "star" | "unarchive" | "unstar";
2290
- note_id: string;
2291
- }, {
2292
- action: "archive" | "delete" | "restore" | "star" | "unarchive" | "unstar";
2293
- note_id: string;
2294
- }>
2295
- ]>;
2296
- type RemoteManageNoteInput = z.infer<typeof manageInput>;
2165
+ version_number: number;
2166
+ content: string;
2167
+ hash: string;
2168
+ created_at_utc: string;
2169
+ created_by: string;
2170
+ }
2171
+ declare const REGISTERED_METADATA_PATHS: readonly [
2172
+ "provider",
2173
+ "model",
2174
+ "role",
2175
+ "event_kind",
2176
+ "sensitivity",
2177
+ "import_run_id"
2178
+ ];
2179
+ type RegisteredMetadataPath = typeof REGISTERED_METADATA_PATHS[number];
2180
+ type MetadataPredicate = {
2181
+ gte?: number | string;
2182
+ lte?: number | string;
2183
+ op: 'range';
2184
+ path: RegisteredMetadataPath;
2185
+ } | {
2186
+ op: 'eq';
2187
+ path: RegisteredMetadataPath;
2188
+ value: boolean | null | number | string;
2189
+ } | {
2190
+ op: 'exists';
2191
+ path: RegisteredMetadataPath;
2192
+ value?: boolean;
2193
+ } | {
2194
+ op: 'in';
2195
+ path: RegisteredMetadataPath;
2196
+ value: readonly (boolean | null | number | string)[];
2197
+ };
2198
+ interface EvidenceLocator {
2199
+ note_id: string;
2200
+ chunk?: {
2201
+ index: number;
2202
+ kind: 'attachment' | 'current' | 'title';
2203
+ };
2204
+ span?: {
2205
+ end: number;
2206
+ start: number;
2207
+ };
2208
+ source?: {
2209
+ external_id_hash: string;
2210
+ import_run_id: string;
2211
+ namespace: string;
2212
+ schema_version: string;
2213
+ };
2214
+ metadata_paths: RegisteredMetadataPath[];
2215
+ }
2216
+ interface MetadataPredicateConditionResult {
2217
+ conditions: string[];
2218
+ joins: string[];
2219
+ params: unknown[];
2220
+ nextIdx: number;
2221
+ }
2222
+ type ScopeOptions = Pick<SearchOptions, 'archive_id' | 'metadataPredicates' | 'tenant_id'>;
2223
+ declare function buildMetadataPredicateConditions(options: ScopeOptions, startIdx: number): MetadataPredicateConditionResult;
2224
+ interface RemoteEvidenceResolutionOptions {
2225
+ metadataPredicates?: readonly MetadataPredicate[];
2226
+ includeArchived?: boolean;
2227
+ /** Cancels header lookup, transport and response reading; a 30-second ceiling also applies. */
2228
+ signal?: AbortSignal;
2229
+ }
2297
2230
  /**
2298
- * Capability module system (ADR-002).
2299
- * Tracks opt-in WASM module states. No WASM loaded by default (CAP-001).
2231
+ * Backend seam (#191) — a uniform tool-intent operation interface that lets the
2232
+ * PGlite database backend (#187) and the static-file shard backend (#189) be
2233
+ * selected and dispatched against the same way, plus a capability-negotiation
2234
+ * API so a caller asks for the operations it needs and gets the lightest backend
2235
+ * that provides them.
2300
2236
  *
2301
- * State machine (valid transitions):
2302
- * unloaded -> loading (via enable)
2303
- * loading -> ready (via markReady or successful loader)
2304
- * loading -> error (via markError or failed loader)
2305
- * ready -> disabled (via disable)
2306
- * disabled -> loading (via enable, re-enable)
2307
- * error -> loading (via enable, retry)
2237
+ * The seam sits one level above SQL: every adapter exposes the same read
2238
+ * operations (and optional relationship, write, semantic, and full-content ops)
2239
+ * regardless of whether the data lives in a queryable PGlite instance, a set of
2240
+ * static shard files fetched over HTTP, or the Fortemi server tier.
2308
2241
  */
2309
- type CapabilityState = 'disabled' | 'error' | 'loading' | 'ready' | 'unloaded';
2310
- type CapabilityName = 'audio' | 'llm' | 'pdf' | 'semantic' | 'vision';
2311
- declare class CapabilityManager {
2312
- private events;
2313
- private capabilities;
2314
- private loaders;
2315
- private progressMessages;
2316
- constructor(events: TypedEventBus);
2317
- /**
2318
- * Register an async loader for a capability.
2319
- * Called by enable(); if no loader is registered the capability transitions
2320
- * directly to ready (useful for capabilities that require no async init).
2321
- */
2322
- registerLoader(name: CapabilityName, loader: () => Promise<void>): void;
2323
- getState(name: CapabilityName): CapabilityState;
2324
- isReady(name: CapabilityName): boolean;
2325
- /**
2326
- * Enable a capability.
2327
- * Valid from: unloaded, disabled, error (retry).
2328
- * Runs the registered loader if present; transitions to ready on success,
2329
- * error on failure.
2330
- */
2331
- enable(name: CapabilityName): Promise<void>;
2332
- /**
2333
- * Disable a ready capability.
2334
- * Valid from: ready only.
2335
- */
2336
- disable(name: CapabilityName): void;
2337
- /**
2338
- * Mark a loading capability as ready (external use, e.g. bridge protocol).
2339
- * Valid from: loading only.
2340
- */
2341
- markReady(name: CapabilityName): void;
2342
- /**
2343
- * Mark a loading capability as errored (external use, e.g. bridge protocol).
2344
- * Valid from: loading only.
2345
- */
2346
- markError(name: CapabilityName, error: string): void;
2347
- /**
2348
- * Report loading progress (0-100).
2349
- * Emits capability.loading with progress if the capability is currently loading.
2350
- * No-op if the capability is not in loading state.
2351
- */
2352
- reportProgress(name: CapabilityName, progress: number): void;
2353
- /** Set a human-readable progress message for a loading capability */
2354
- setProgress(name: CapabilityName, message: string): void;
2355
- /** Get the current progress message for a capability */
2356
- getProgress(name: CapabilityName): string | undefined;
2357
- getError(name: CapabilityName): string | undefined;
2358
- listAll(): Array<{
2359
- name: CapabilityName;
2360
- state: CapabilityState;
2361
- }>;
2362
- }
2363
2242
  /**
2364
- * Sequential SQL migration runner for DatabaseClient.
2365
- * Tracks applied migrations in a schema_version table.
2366
- * Each migration runs in a transaction; version updated atomically.
2243
+ * Semantic-search tier a backend offers, in increasing capability:
2244
+ * - `none` — no vector search (text / facets only)
2245
+ * - `cosine-small` brute-force cosine over a small static vector set (#189)
2246
+ * - `ann-full` — prebuilt/queryable approximate-nearest-neighbour over the full
2247
+ * corpus (PGlite + pgvector, or a prebuilt ANN snapshot)
2248
+ * - `server` — delegated to the remote Fortemi server backend
2367
2249
  */
2368
- interface Migration {
2369
- version: number;
2370
- name: string;
2371
- sql: string;
2372
- }
2373
- declare class MigrationRunner {
2374
- private db;
2375
- private events?;
2376
- constructor(db: DatabaseClient, events?: TypedEventBus | undefined);
2377
- ensureSchemaTable(): Promise<void>;
2378
- getCurrentVersion(): Promise<number>;
2379
- apply(migrations: Migration[]): Promise<number>;
2380
- getAppliedMigrations(): Promise<Array<{
2381
- name: string;
2382
- version: number;
2383
- }>>;
2250
+ type BackendSemanticTier = 'ann-full' | 'cosine-small' | 'none' | 'server';
2251
+ /** Relative startup cost of bringing a backend online. */
2252
+ type BackendStartupCost = 'index-build' | 'instant' | 'network';
2253
+ /** What a backend can do — the unit of capability negotiation. */
2254
+ interface BackendCapabilities {
2255
+ /** Local candidate-v1 indexed predicate operations, not server contract negotiation. */
2256
+ typedMetadataPredicates?: boolean;
2257
+ /** Complete reproducible citations, not merely partial source projections. */
2258
+ evidenceLocators?: boolean;
2259
+ /** Can answer list / get / search read operations. */
2260
+ read: boolean;
2261
+ /** Can mutate notes (manageNote). */
2262
+ write: boolean;
2263
+ /** Can merge external shards into its store. */
2264
+ merge: boolean;
2265
+ /** Coordinates concurrent multi-user writes. */
2266
+ multiUser: boolean;
2267
+ /** Highest semantic-search tier available. */
2268
+ semantic: BackendSemanticTier;
2269
+ /** Relative cost to bring the backend online. */
2270
+ startupCost: BackendStartupCost;
2384
2271
  }
2385
- declare const allMigrations: Migration[];
2386
2272
  /**
2387
- * Multi-archive manager for Fortemi.
2388
- * Each archive is a separate PGlite instance with its own persistence path.
2389
- * Migrations are applied automatically on open.
2273
+ * Backend-neutral note record. `source`/`starred`/`archived` are optional
2274
+ * because lean read paths (PGlite full-text search) do not return them; list,
2275
+ * get, and every shard path populate all fields.
2390
2276
  */
2391
- interface ArchiveInfo {
2392
- name: string;
2277
+ interface BackendNote {
2278
+ id: string;
2279
+ title: null | string;
2280
+ tags: string[];
2393
2281
  createdAt: string;
2282
+ updatedAt: string;
2283
+ source?: string;
2284
+ starred?: boolean;
2285
+ archived?: boolean;
2394
2286
  }
2395
- declare class ArchiveManager {
2396
- private events?;
2397
- private currentArchive;
2398
- private db;
2399
- private archives;
2400
- private persistence;
2401
- private backendFactory;
2402
- /**
2403
- * Persistence is a PLUGGABLE, opt-in backend (issue #261). Pass a
2404
- * `StorageBackendFactory` to run against any `StorageBackend`
2405
- * implementation; PGlite is merely the built-in default, selected only when
2406
- * the convenience `PersistenceMode` string form is used. Because
2407
- * `defaultStorageBackendFactory` reaches PGlite through the lazily-imported
2408
- * `createPGliteInstance` (see `db.ts`), a consumer that supplies its own
2409
- * factory — or never opens an archive at all — never pulls the PGlite WASM
2410
- * engine into its bundle.
2411
- *
2412
- * @param persistenceOrFactory `PersistenceMode` string (uses the built-in
2413
- * PGlite backend) OR a custom `StorageBackendFactory`.
2414
- * @param persistenceOverride persistence hint passed to a custom factory.
2415
- */
2416
- constructor(persistenceOrFactory: PersistenceMode | StorageBackendFactory, events?: TypedEventBus | undefined, persistenceOverride?: PersistenceMode);
2417
- getCurrentArchiveName(): string;
2418
- getDb(): null | StorageBackend;
2419
- open(archiveName?: string): Promise<StorageBackend>;
2420
- /**
2421
- * Adopt an already-created backend WITHOUT running migrations — for a backend
2422
- * whose schema is already present, e.g. a PGlite restored from a physical
2423
- * data-dir snapshot (issue #187, `restoreDbSnapshot`). Running migrations here
2424
- * would be wrong: the restored dir already carries them (and the HNSW index).
2425
- */
2426
- adopt(backend: StorageBackend, archiveName?: string): Promise<StorageBackend>;
2427
- create(archiveName: string): Promise<StorageBackend>;
2428
- switchTo(archiveName: string): Promise<StorageBackend>;
2429
- delete(archiveName: string): Promise<void>;
2430
- listArchives(): ArchiveInfo[];
2431
- close(): Promise<void>;
2287
+ /** A note plus its current rendered content. */
2288
+ interface BackendNoteFull extends BackendNote {
2289
+ content: string;
2290
+ /** Native note metadata, separate from inference metadata where supported. */
2291
+ metadata?: unknown;
2292
+ links?: BackendLink[];
2293
+ concepts?: BackendConcept[];
2294
+ provenance?: BackendProvenanceEdge[];
2295
+ /** Server revision/activity graph; not interchangeable with local provenance edges. */
2296
+ provenanceGraph?: RemoteProvenanceGraph;
2432
2297
  }
2433
- /**
2434
- * Factory function for creating a FortemiCore instance.
2435
- * All deployment modes use this entry point.
2436
- */
2437
- interface FortemiConfig {
2438
- persistence: 'idb' | 'memory' | 'opfs';
2439
- archiveName?: string;
2298
+ interface BackendLink {
2299
+ id: string;
2300
+ fromNoteId: string;
2301
+ toNoteId: null | string;
2302
+ toUrl?: null | string;
2303
+ kind: string;
2304
+ score: null | number;
2305
+ createdAt: string;
2306
+ metadata?: Record<string, unknown>;
2307
+ /** Exact server JSON metadata, including non-object values and null. */
2308
+ remoteMetadata?: unknown;
2309
+ /** Relative to the requested note; remote self-links can appear in both directions. */
2310
+ direction?: 'incoming' | 'outgoing';
2311
+ snippet?: null | string;
2440
2312
  }
2441
- interface FortemiCore {
2442
- events: TypedEventBus;
2443
- config: FortemiConfig;
2444
- destroy(): void;
2313
+ interface BackendConcept {
2314
+ id: string;
2315
+ schemeId: string;
2316
+ prefLabel: string;
2317
+ altLabels: string[];
2318
+ definition: null | string;
2319
+ createdAt: string;
2320
+ updatedAt: string;
2321
+ /** Placeholder values for these fields are unavailable, not evidence of absence. */
2322
+ unavailableFields?: Array<'altLabels' | 'definition'>;
2323
+ assignment?: {
2324
+ confidence?: number;
2325
+ createdAt: string;
2326
+ createdBy?: string;
2327
+ isPrimary: boolean;
2328
+ noteId: string;
2329
+ relevanceScore: number;
2330
+ source: string;
2331
+ };
2332
+ }
2333
+ interface BackendProvenanceEdge {
2334
+ id: string;
2335
+ entityType: string;
2336
+ entityId: string;
2337
+ activity: string;
2338
+ agent: null | string;
2339
+ startedAt: string;
2340
+ endedAt: null | string;
2341
+ attributes: unknown;
2342
+ }
2343
+ /** One search hit — note plus optional rank/snippet when the backend ranks. */
2344
+ interface BackendSearchHit {
2345
+ note: BackendNote;
2346
+ rank?: number;
2347
+ snippet?: string;
2348
+ /** Original remote search metadata; detail enrichment is a separate read. */
2349
+ remoteSearch?: RemoteSearchMetadata;
2350
+ /** Partial local source projections; does not imply complete citation capability. */
2351
+ locators?: EvidenceLocator[];
2352
+ /** Candidate matched-unit evidence; not a negotiated complete capability. */
2353
+ evidence?: SearchEvidenceSet;
2354
+ }
2355
+ /** Search response with optional facet counts. */
2356
+ interface BackendSearchResult {
2357
+ hits: BackendSearchHit[];
2358
+ total: number;
2359
+ facets?: {
2360
+ source?: Record<string, number>;
2361
+ tags: Record<string, number>;
2362
+ };
2363
+ }
2364
+ interface BackendListOptions {
2365
+ offset?: number;
2366
+ limit?: number;
2367
+ }
2368
+ interface BackendSearchQueryOptions extends BackendListOptions {
2369
+ /** AND-filter: note must carry every listed tag. */
2370
+ tags?: string[];
2371
+ /** OR-filter on note source. */
2372
+ source?: string[];
2373
+ mode?: 'fts' | 'hybrid' | 'semantic';
2374
+ metadataPredicates?: readonly MetadataPredicate[];
2375
+ /** Local source-identity selection, never a grant of authorization. */
2376
+ tenant_id?: string;
2377
+ archive_id?: null | string;
2445
2378
  }
2446
- declare function createFortemi(config: FortemiConfig): FortemiCore;
2447
- /**
2448
- * Compute a browser-local content-identity hash (SHA-256), encoded as
2449
- * `sha256:<64-char lowercase hex>`.
2450
- *
2451
- * This is an internal identity/dedup digest used for note content, embedding
2452
- * configs, the AIWG index, and graph identity — NOT the server's attachment
2453
- * content-hash convention. Binary-attachment blobs use {@link computeBlobHash}
2454
- * (BLAKE3), which is the canonical checksum defined by the binary-attachment
2455
- * projection contract (`checksum: "blake3:<hex>"`). Keeping these two functions
2456
- * separate preserves JSON format parity for the identity hashes above while
2457
- * letting attachments match the server's `compute_content_hash`.
2458
- *
2459
- * @param data - Raw bytes to hash
2460
- * @returns `'sha256:<64-char lowercase hex>'`
2461
- */
2462
- declare function computeHash(data: Uint8Array): string;
2463
2379
  /**
2464
- * Compute the canonical attachment content hash: **BLAKE3**, encoded as
2465
- * `blake3:<64-char lowercase hex>`.
2466
- *
2467
- * Matches the fortemi server (`crates/matric-db/src/file_storage.rs`
2468
- * `compute_content_hash`) and the portable Knowledge-Shard byte-sidecar
2469
- * contract, where the sidecar tar entry name is the bare hex (the `blake3:`
2470
- * prefix stripped). SubtleCrypto has no BLAKE3, so this uses `@noble/hashes`.
2471
- *
2472
- * @param data - Raw attachment bytes to hash
2473
- * @returns `'blake3:<64-char lowercase hex>'`
2380
+ * Uniform tool-intent operation interface. Every backend implements the read
2381
+ * core; `getNoteFull`, `semantic`, and `manageNote` are optional and present
2382
+ * only on backends whose capabilities advertise them.
2474
2383
  */
2475
- declare function computeBlobHash(data: Uint8Array): string;
2476
- declare const FORTEMI_COMPATIBILITY_PATH = "/api/v1/system/compatibility";
2477
- declare const FORTEMI_SERVER_COMPATIBILITY_REVISION = "2026-07-06";
2478
- declare const FORTEMI_COMPATIBILITY_STATES: readonly [
2479
- "available",
2480
- "degraded",
2481
- "preview",
2482
- "unavailable",
2483
- "unknown"
2484
- ];
2485
- type FortemiCompatibilityState = (typeof FORTEMI_COMPATIBILITY_STATES)[number];
2486
- declare const FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES: readonly [
2487
- "core_notes",
2488
- "search",
2489
- "jobs",
2490
- "realtime_activity",
2491
- "hosted_auth",
2492
- "premium_components",
2493
- "backoffice_api",
2494
- "audit_posture",
2495
- "quota_status",
2496
- "kms_status",
2497
- "mcp_scope_gate"
2498
- ];
2499
- type FortemiRequiredCompatibilityCapability = (typeof FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES)[number];
2500
- interface FortemiCompatibilityCapability {
2501
- state: FortemiCompatibilityState;
2502
- reason_code?: string;
2384
+ interface DataBackend {
2385
+ readonly id: string;
2386
+ readonly capabilities: BackendCapabilities;
2387
+ listNotes(options?: BackendListOptions): Promise<{
2388
+ items: BackendNote[];
2389
+ total: number;
2390
+ }>;
2391
+ getNote(id: string): Promise<BackendNote | null>;
2392
+ search(query: string, options?: BackendSearchQueryOptions): Promise<BackendSearchResult>;
2393
+ /** Lazy full content (present when capabilities.read). */
2394
+ getNoteFull?(id: string): Promise<BackendNoteFull | null>;
2395
+ /** Note links (present when capabilities.read). */
2396
+ linksOf?(id: string): Promise<BackendLink[]>;
2397
+ /** SKOS concepts assigned to a note (present when capabilities.read). */
2398
+ conceptsOf?(id: string): Promise<BackendConcept[]>;
2399
+ /** W3C PROV edges for a note (present when capabilities.read). */
2400
+ provenanceOf?(id: string): Promise<BackendProvenanceEdge[]>;
2401
+ /** Remote revision/activity graph, preserving the server model and field names. */
2402
+ provenanceGraphOf?(id: string): Promise<RemoteProvenanceGraph>;
2403
+ /** Vector search (present when capabilities.semantic !== 'none'). */
2404
+ semantic?(query: string, k?: number): Promise<BackendSearchHit[]>;
2405
+ /** Write op (present when capabilities.write). */
2406
+ manageNote?(input: unknown): Promise<unknown>;
2407
+ }
2408
+ /** What a caller needs. Booleans require `true`; `semantic` is a minimum tier. */
2409
+ interface BackendRequest {
2410
+ typedMetadataPredicates?: boolean;
2411
+ evidenceLocators?: boolean;
2412
+ read?: boolean;
2413
+ write?: boolean;
2414
+ merge?: boolean;
2415
+ multiUser?: boolean;
2416
+ /** Minimum acceptable semantic tier (a higher tier satisfies a lower request). */
2417
+ semantic?: BackendSemanticTier;
2418
+ }
2419
+ interface BackendCandidate {
2420
+ backend: DataBackend;
2421
+ /** Requested capabilities this backend cannot satisfy ([] = fully satisfies). */
2422
+ missing: string[];
2423
+ }
2424
+ interface BackendSelection {
2425
+ /** Chosen backend — fully-satisfying-and-lightest, else fewest-missing. Null only when no backends are available. */
2426
+ backend: DataBackend | null;
2427
+ capabilities: BackendCapabilities | null;
2428
+ /** Requested capabilities the chosen backend cannot satisfy. */
2429
+ missing: string[];
2430
+ /** Every candidate with its own missing set, ordered as evaluated. */
2431
+ candidates: BackendCandidate[];
2503
2432
  }
2504
- interface FortemiCompatibilityResponse {
2505
- schema_version: number;
2506
- contract_revision: string;
2507
- api: {
2508
- build_date_present: boolean;
2509
- git_sha_present: boolean;
2510
- minimum_hotm_enterprise_client: string;
2511
- name: string;
2512
- version: string;
2513
- };
2514
- deployment: {
2515
- edition: string;
2516
- hosted_multi_tenant_ready: boolean;
2517
- mode: string;
2518
- };
2519
- auth: {
2520
- mode: string;
2521
- oauth_issuer_configured: boolean;
2522
- required: boolean;
2523
- tenant_context_available: boolean;
2524
- };
2525
- capabilities: Record<string, FortemiCompatibilityCapability>;
2526
- links: {
2527
- asyncapi: string;
2528
- health: string;
2529
- openapi: string;
2530
- streaming_health: string;
2531
- };
2433
+ /**
2434
+ * Pick the backend that best satisfies `request` from `available`. Prefers a
2435
+ * fully-satisfying backend with the lightest startup cost; if none fully
2436
+ * satisfy, returns the one missing the fewest capabilities (lightest on ties) so
2437
+ * the caller can degrade with eyes open via `selection.missing`.
2438
+ */
2439
+ declare function selectBackend(request: BackendRequest, available: DataBackend[]): BackendSelection;
2440
+ interface PGliteBackendOptions {
2441
+ id?: string;
2442
+ /** Whether embeddings exist so search can use the semantic path. */
2443
+ semanticAvailable?: boolean;
2444
+ /** Host-owned query embedding, required to expose semantic/hybrid operations. */
2445
+ embedQuery?: (query: string) => Promise<number[]>;
2532
2446
  }
2533
- interface FortemiCompatibilityValidationResult {
2534
- ok: boolean;
2535
- errors: string[];
2536
- warnings: string[];
2537
- response?: FortemiCompatibilityResponse;
2447
+ /**
2448
+ * Wrap a PGlite-backed `DatabaseClient` as a `DataBackend`. Read ops delegate to
2449
+ * the repositories; writes go through the `manageNote` tool. Advertises full
2450
+ * read+write+merge with `ann-full` only when vector storage and a query embedder
2451
+ * are configured. Typed predicates refer to the local unpublished candidate.
2452
+ */
2453
+ declare function createPGliteBackend(db: DatabaseClient, options?: PGliteBackendOptions): DataBackend;
2454
+ interface RemoteBackendPaths {
2455
+ notes: string;
2456
+ note: string;
2457
+ search: string;
2458
+ resolveEvidence?: string;
2459
+ links: string;
2460
+ concepts: string;
2461
+ provenance: string;
2462
+ restore: string;
2463
+ /** @deprecated Tool-intent path overrides cannot adapt the REST contract and are rejected. */
2464
+ manageNote?: string;
2465
+ /** @deprecated Semantic search uses the search path and mode parameter. Overrides are rejected. */
2466
+ semantic?: string;
2538
2467
  }
2539
- interface FetchFortemiCompatibilityOptions {
2540
- baseUrl?: string;
2468
+ interface RemoteSearchOptions extends BackendSearchQueryOptions {
2469
+ mode?: RemoteSearchMode;
2470
+ }
2471
+ interface RemoteSearchResult extends BackendSearchResult {
2472
+ /** The server total counts returned hits, not the corpus or a pagination estimate. */
2473
+ totalKind: 'returned-hits';
2474
+ requestedMode: RemoteSearchMode;
2475
+ effectiveMode: RemoteSearchMode;
2476
+ degraded: boolean;
2477
+ degradation?: RemoteSearchDegradation;
2478
+ }
2479
+ interface RemoteManageNoteResult {
2480
+ action: 'archive' | 'create' | 'delete' | 'restore' | 'star' | 'unarchive' | 'unstar' | 'update';
2481
+ note_id: string;
2482
+ /** Present only when the mutation itself returns a note envelope. */
2483
+ note?: BackendNoteFull;
2484
+ }
2485
+ interface RemoteDataBackend extends DataBackend {
2486
+ /** Candidate current-storage resolution; not a complete evidence capability advertisement. */
2487
+ resolveEvidence(locator: unknown, options?: RemoteEvidenceResolutionOptions): Promise<string>;
2488
+ search(query: string, options?: RemoteSearchOptions): Promise<RemoteSearchResult>;
2489
+ semanticWithReport(query: string, k?: number): Promise<RemoteSearchResult>;
2490
+ manageNote(input: unknown): Promise<RemoteManageNoteResult>;
2491
+ }
2492
+ interface RemoteBackendConfig {
2493
+ baseUrl: string;
2494
+ id?: string;
2541
2495
  fetchImpl?: typeof fetch;
2542
- timeoutMs?: number;
2496
+ headers?: (() => HeadersInit | Promise<HeadersInit>) | HeadersInit;
2497
+ authToken?: string;
2498
+ paths?: Partial<RemoteBackendPaths>;
2543
2499
  }
2544
- declare function fortemiCompatibilityUrl(baseUrl?: string): string;
2545
- declare function validateFortemiCompatibilityResponse(raw: unknown): FortemiCompatibilityValidationResult;
2546
- declare function formatFortemiCompatibilitySummary(response: FortemiCompatibilityResponse): string;
2547
- declare function fetchAndValidateFortemiCompatibility(options?: FetchFortemiCompatibilityOptions): Promise<FortemiCompatibilityValidationResult & {
2548
- status?: number;
2549
- url: string;
2500
+ declare function createRemoteBackend(config: RemoteBackendConfig): RemoteDataBackend;
2501
+ interface ShardBackendOptions {
2502
+ id?: string;
2503
+ /** Declared semantic tier this shard provides (default `none`). Set to `cosine-small` when the reader has a vector provider. */
2504
+ semantic?: BackendSemanticTier;
2505
+ }
2506
+ /**
2507
+ * Wrap a `ShardReader` (#189) as a read-only `DataBackend`. Startup is instant
2508
+ * (no index build) and the semantic tier is whatever the reader's provider
2509
+ * offers — `none` for text/facets-only shards, `cosine-small` when a vector
2510
+ * provider is attached.
2511
+ */
2512
+ declare function createShardBackend(reader: ShardReader, options?: ShardBackendOptions): DataBackend;
2513
+ declare const provenanceGraph: z.ZodObject<{
2514
+ all_activities: z.ZodArray<z.ZodObject<{
2515
+ activity_type: z.ZodString;
2516
+ ended_at: z.ZodNullable<z.ZodString>;
2517
+ id: z.ZodEffects<z.ZodString, string, string>;
2518
+ metadata: z.ZodEffects<z.ZodUnknown, {} | null, unknown>;
2519
+ model_name: z.ZodNullable<z.ZodString>;
2520
+ note_id: z.ZodEffects<z.ZodString, string, string>;
2521
+ revision_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
2522
+ started_at: z.ZodString;
2523
+ }, "strip", z.ZodTypeAny, {
2524
+ activity_type: string;
2525
+ ended_at: null | string;
2526
+ id: string;
2527
+ metadata: {} | null;
2528
+ model_name: null | string;
2529
+ note_id: string;
2530
+ revision_id: null | string;
2531
+ started_at: string;
2532
+ }, {
2533
+ activity_type: string;
2534
+ ended_at: null | string;
2535
+ id: string;
2536
+ metadata?: unknown;
2537
+ model_name: null | string;
2538
+ note_id: string;
2539
+ revision_id: null | string;
2540
+ started_at: string;
2541
+ }>, "many">;
2542
+ all_edges: z.ZodArray<z.ZodObject<{
2543
+ created_at_utc: z.ZodString;
2544
+ id: z.ZodEffects<z.ZodString, string, string>;
2545
+ relation: z.ZodString;
2546
+ revision_id: z.ZodEffects<z.ZodString, string, string>;
2547
+ source_note_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
2548
+ source_url: z.ZodNullable<z.ZodString>;
2549
+ }, "strip", z.ZodTypeAny, {
2550
+ created_at_utc: string;
2551
+ id: string;
2552
+ relation: string;
2553
+ revision_id: string;
2554
+ source_note_id: null | string;
2555
+ source_url: null | string;
2556
+ }, {
2557
+ created_at_utc: string;
2558
+ id: string;
2559
+ relation: string;
2560
+ revision_id: string;
2561
+ source_note_id: null | string;
2562
+ source_url: null | string;
2563
+ }>, "many">;
2564
+ current_chain: z.ZodNullable<z.ZodObject<{
2565
+ activity: z.ZodNullable<z.ZodObject<{
2566
+ activity_type: z.ZodString;
2567
+ ended_at: z.ZodNullable<z.ZodString>;
2568
+ id: z.ZodEffects<z.ZodString, string, string>;
2569
+ metadata: z.ZodEffects<z.ZodUnknown, {} | null, unknown>;
2570
+ model_name: z.ZodNullable<z.ZodString>;
2571
+ note_id: z.ZodEffects<z.ZodString, string, string>;
2572
+ revision_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
2573
+ started_at: z.ZodString;
2574
+ }, "strip", z.ZodTypeAny, {
2575
+ activity_type: string;
2576
+ ended_at: null | string;
2577
+ id: string;
2578
+ metadata: {} | null;
2579
+ model_name: null | string;
2580
+ note_id: string;
2581
+ revision_id: null | string;
2582
+ started_at: string;
2583
+ }, {
2584
+ activity_type: string;
2585
+ ended_at: null | string;
2586
+ id: string;
2587
+ metadata?: unknown;
2588
+ model_name: null | string;
2589
+ note_id: string;
2590
+ revision_id: null | string;
2591
+ started_at: string;
2592
+ }>>;
2593
+ edges: z.ZodArray<z.ZodObject<{
2594
+ created_at_utc: z.ZodString;
2595
+ id: z.ZodEffects<z.ZodString, string, string>;
2596
+ relation: z.ZodString;
2597
+ revision_id: z.ZodEffects<z.ZodString, string, string>;
2598
+ source_note_id: z.ZodNullable<z.ZodEffects<z.ZodString, string, string>>;
2599
+ source_url: z.ZodNullable<z.ZodString>;
2600
+ }, "strip", z.ZodTypeAny, {
2601
+ created_at_utc: string;
2602
+ id: string;
2603
+ relation: string;
2604
+ revision_id: string;
2605
+ source_note_id: null | string;
2606
+ source_url: null | string;
2607
+ }, {
2608
+ created_at_utc: string;
2609
+ id: string;
2610
+ relation: string;
2611
+ revision_id: string;
2612
+ source_note_id: null | string;
2613
+ source_url: null | string;
2614
+ }>, "many">;
2615
+ note_id: z.ZodEffects<z.ZodString, string, string>;
2616
+ revision_id: z.ZodEffects<z.ZodString, string, string>;
2617
+ }, "strip", z.ZodTypeAny, {
2618
+ activity: {
2619
+ activity_type: string;
2620
+ ended_at: null | string;
2621
+ id: string;
2622
+ metadata: {} | null;
2623
+ model_name: null | string;
2624
+ note_id: string;
2625
+ revision_id: null | string;
2626
+ started_at: string;
2627
+ } | null;
2628
+ edges: {
2629
+ created_at_utc: string;
2630
+ id: string;
2631
+ relation: string;
2632
+ revision_id: string;
2633
+ source_note_id: null | string;
2634
+ source_url: null | string;
2635
+ }[];
2636
+ note_id: string;
2637
+ revision_id: string;
2638
+ }, {
2639
+ activity: {
2640
+ activity_type: string;
2641
+ ended_at: null | string;
2642
+ id: string;
2643
+ metadata?: unknown;
2644
+ model_name: null | string;
2645
+ note_id: string;
2646
+ revision_id: null | string;
2647
+ started_at: string;
2648
+ } | null;
2649
+ edges: {
2650
+ created_at_utc: string;
2651
+ id: string;
2652
+ relation: string;
2653
+ revision_id: string;
2654
+ source_note_id: null | string;
2655
+ source_url: null | string;
2656
+ }[];
2657
+ note_id: string;
2658
+ revision_id: string;
2659
+ }>>;
2660
+ derived_count: z.ZodNumber;
2661
+ derived_notes: z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">;
2662
+ note_id: z.ZodEffects<z.ZodString, string, string>;
2663
+ }, "strip", z.ZodTypeAny, {
2664
+ all_activities: {
2665
+ activity_type: string;
2666
+ ended_at: null | string;
2667
+ id: string;
2668
+ metadata: {} | null;
2669
+ model_name: null | string;
2670
+ note_id: string;
2671
+ revision_id: null | string;
2672
+ started_at: string;
2673
+ }[];
2674
+ all_edges: {
2675
+ created_at_utc: string;
2676
+ id: string;
2677
+ relation: string;
2678
+ revision_id: string;
2679
+ source_note_id: null | string;
2680
+ source_url: null | string;
2681
+ }[];
2682
+ current_chain: {
2683
+ activity: {
2684
+ activity_type: string;
2685
+ ended_at: null | string;
2686
+ id: string;
2687
+ metadata: {} | null;
2688
+ model_name: null | string;
2689
+ note_id: string;
2690
+ revision_id: null | string;
2691
+ started_at: string;
2692
+ } | null;
2693
+ edges: {
2694
+ created_at_utc: string;
2695
+ id: string;
2696
+ relation: string;
2697
+ revision_id: string;
2698
+ source_note_id: null | string;
2699
+ source_url: null | string;
2700
+ }[];
2701
+ note_id: string;
2702
+ revision_id: string;
2703
+ } | null;
2704
+ derived_count: number;
2705
+ derived_notes: string[];
2706
+ note_id: string;
2707
+ }, {
2708
+ all_activities: {
2709
+ activity_type: string;
2710
+ ended_at: null | string;
2711
+ id: string;
2712
+ metadata?: unknown;
2713
+ model_name: null | string;
2714
+ note_id: string;
2715
+ revision_id: null | string;
2716
+ started_at: string;
2717
+ }[];
2718
+ all_edges: {
2719
+ created_at_utc: string;
2720
+ id: string;
2721
+ relation: string;
2722
+ revision_id: string;
2723
+ source_note_id: null | string;
2724
+ source_url: null | string;
2725
+ }[];
2726
+ current_chain: {
2727
+ activity: {
2728
+ activity_type: string;
2729
+ ended_at: null | string;
2730
+ id: string;
2731
+ metadata?: unknown;
2732
+ model_name: null | string;
2733
+ note_id: string;
2734
+ revision_id: null | string;
2735
+ started_at: string;
2736
+ } | null;
2737
+ edges: {
2738
+ created_at_utc: string;
2739
+ id: string;
2740
+ relation: string;
2741
+ revision_id: string;
2742
+ source_note_id: null | string;
2743
+ source_url: null | string;
2744
+ }[];
2745
+ note_id: string;
2746
+ revision_id: string;
2747
+ } | null;
2748
+ derived_count: number;
2749
+ derived_notes: string[];
2750
+ note_id: string;
2550
2751
  }>;
2551
- interface SWRegistrationResult {
2552
- registered: boolean;
2553
- registration?: ServiceWorkerRegistration;
2554
- error?: string;
2555
- }
2556
- declare function registerServiceWorker(swUrl?: string): Promise<SWRegistrationResult>;
2557
- /**
2558
- * REST route definitions for Service Worker.
2559
- * These are pure functions that transform HTTP Request → tool input and tool output → Response.
2560
- * The actual DB connection is injected at registration time.
2561
- *
2562
- * All routes currently return 503 Not Implemented — the DB wiring happens in a later issue.
2563
- * The URL structure and request/response shapes are the valuable contract defined here.
2564
- */
2565
- interface RouteHandler {
2566
- method: string;
2567
- pattern: RegExp;
2568
- handler: (request: Request, match: RegExpMatchArray, params: URLSearchParams) => Promise<Response>;
2569
- }
2570
- /**
2571
- * Create route handlers.
2572
- * db parameter will be injected when the SW gets access to PGlite.
2573
- * For now, returns 503 Not Implemented for all routes.
2574
- */
2575
- declare function createRoutes(): RouteHandler[];
2576
- /**
2577
- * Match a request against the registered routes and return the first matching
2578
- * handler, or null if no route matches.
2579
- */
2580
- declare function matchRoute(routes: RouteHandler[], request: Request, url: URL): null | RouteHandler;
2581
- /**
2582
- * One-shot migration of the pre-bytecask blob layout into the new store.
2583
- *
2584
- * The legacy layout (shipped through v2026.7.x) was:
2585
- * - IndexedDB: database `fortemi-<archive>-blobs`, object store `blobs`,
2586
- * values keyed by the full checksum string (`blake3:<hex>`, historically
2587
- * also `sha256:<hex>`).
2588
- * - OPFS: directory `fortemi-<archive>-blobs/<h0h1>/<h2h3>/<checksum>`.
2589
- *
2590
- * Migration re-`put()`s every payload — the new store recomputes BLAKE3, so
2591
- * legacy `sha256:`-keyed entries converge to canonical keys for free
2592
- * (ADR-012 D3). The legacy source is deleted only after every entry migrated
2593
- * without error; any failure leaves it untouched for the next attempt.
2594
- */
2595
- /** Outcome of one migration attempt (for diagnostics/logging). */
2596
- interface LegacyMigrationReport {
2597
- migrated: number;
2598
- /** Migration aborted without deleting the legacy source. */
2599
- failed: boolean;
2600
- }
2601
- /**
2602
- * Migrate any legacy blob layout for `archiveName` into `target`, then delete
2603
- * the legacy source. Failures are contained: the legacy data stays in place
2604
- * and the new store keeps whatever was already re-put (idempotent on retry).
2605
- */
2606
- declare function migrateLegacyBlobStore(archiveName: string, target: BlobStore, indexedDbFactory?: IDBFactory): Promise<LegacyMigrationReport>;
2752
+ /** Producer field names intentionally distinguish this graph from local PGlite PROV edges. */
2753
+ type RemoteProvenanceGraph = z.infer<typeof provenanceGraph>;
2754
+ declare const searchMode: z.ZodEnum<[
2755
+ "fts",
2756
+ "semantic",
2757
+ "hybrid"
2758
+ ]>;
2759
+ type RemoteSearchMode = z.infer<typeof searchMode>;
2760
+ declare const searchHit: z.ZodEffects<z.ZodObject<{
2761
+ chain_info: z.ZodOptional<z.ZodObject<{
2762
+ best_chunk_sequence: z.ZodNumber;
2763
+ chain_id: z.ZodEffects<z.ZodString, string, string>;
2764
+ chunks_matched: z.ZodNumber;
2765
+ original_title: z.ZodString;
2766
+ total_chunks: z.ZodNumber;
2767
+ }, "strip", z.ZodTypeAny, {
2768
+ best_chunk_sequence: number;
2769
+ chain_id: string;
2770
+ chunks_matched: number;
2771
+ original_title: string;
2772
+ total_chunks: number;
2773
+ }, {
2774
+ best_chunk_sequence: number;
2775
+ chain_id: string;
2776
+ chunks_matched: number;
2777
+ original_title: string;
2778
+ total_chunks: number;
2779
+ }>>;
2780
+ embedding_status: z.ZodOptional<z.ZodEnum<[
2781
+ "ready",
2782
+ "pending",
2783
+ "failed",
2784
+ "none"
2785
+ ]>>;
2786
+ evidence: z.ZodOptional<z.ZodUnknown>;
2787
+ note_id: z.ZodEffects<z.ZodString, string, string>;
2788
+ score: z.ZodNumber;
2789
+ snippet: z.ZodNullable<z.ZodString>;
2790
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
2791
+ title: z.ZodOptional<z.ZodString>;
2792
+ }, "strip", z.ZodTypeAny, {
2793
+ chain_info?: {
2794
+ best_chunk_sequence: number;
2795
+ chain_id: string;
2796
+ chunks_matched: number;
2797
+ original_title: string;
2798
+ total_chunks: number;
2799
+ } | undefined;
2800
+ embedding_status?: "failed" | "none" | "pending" | "ready" | undefined;
2801
+ evidence?: unknown;
2802
+ note_id: string;
2803
+ score: number;
2804
+ snippet: null | string;
2805
+ tags?: string[] | undefined;
2806
+ title?: string | undefined;
2807
+ }, {
2808
+ chain_info?: {
2809
+ best_chunk_sequence: number;
2810
+ chain_id: string;
2811
+ chunks_matched: number;
2812
+ original_title: string;
2813
+ total_chunks: number;
2814
+ } | undefined;
2815
+ embedding_status?: "failed" | "none" | "pending" | "ready" | undefined;
2816
+ evidence?: unknown;
2817
+ note_id: string;
2818
+ score: number;
2819
+ snippet: null | string;
2820
+ tags?: string[] | undefined;
2821
+ title?: string | undefined;
2822
+ }>, {
2823
+ chain_info?: {
2824
+ best_chunk_sequence: number;
2825
+ chain_id: string;
2826
+ chunks_matched: number;
2827
+ original_title: string;
2828
+ total_chunks: number;
2829
+ } | undefined;
2830
+ embedding_status?: "failed" | "none" | "pending" | "ready" | undefined;
2831
+ evidence?: SearchEvidenceSet | undefined;
2832
+ note_id: string;
2833
+ score: number;
2834
+ snippet: null | string;
2835
+ tags?: string[] | undefined;
2836
+ title?: string | undefined;
2837
+ }, {
2838
+ chain_info?: {
2839
+ best_chunk_sequence: number;
2840
+ chain_id: string;
2841
+ chunks_matched: number;
2842
+ original_title: string;
2843
+ total_chunks: number;
2844
+ } | undefined;
2845
+ embedding_status?: "failed" | "none" | "pending" | "ready" | undefined;
2846
+ evidence?: unknown;
2847
+ note_id: string;
2848
+ score: number;
2849
+ snippet: null | string;
2850
+ tags?: string[] | undefined;
2851
+ title?: string | undefined;
2852
+ }>;
2853
+ declare const searchDegradation: z.ZodObject<{
2854
+ code: z.ZodString;
2855
+ effective_mode: z.ZodLiteral<"fts">;
2856
+ }, "strip", z.ZodTypeAny, {
2857
+ code: string;
2858
+ effective_mode: "fts";
2859
+ }, {
2860
+ code: string;
2861
+ effective_mode: "fts";
2862
+ }>;
2863
+ type RemoteSearchDegradation = z.infer<typeof searchDegradation>;
2864
+ type RemoteSearchMetadata = Pick<z.infer<typeof searchHit>, 'chain_info' | 'embedding_status' | 'tags' | 'title'>;
2865
+ declare const manageInput: z.ZodUnion<[
2866
+ z.ZodObject<{
2867
+ action: z.ZodLiteral<"create">;
2868
+ content: z.ZodString;
2869
+ source: z.ZodOptional<z.ZodString>;
2870
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
2871
+ title: z.ZodOptional<z.ZodNullable<z.ZodString>>;
2872
+ }, "strict", z.ZodTypeAny, {
2873
+ action: "create";
2874
+ content: string;
2875
+ source?: string | undefined;
2876
+ tags?: string[] | undefined;
2877
+ title?: null | string | undefined;
2878
+ }, {
2879
+ action: "create";
2880
+ content: string;
2881
+ source?: string | undefined;
2882
+ tags?: string[] | undefined;
2883
+ title?: null | string | undefined;
2884
+ }>,
2885
+ z.ZodEffects<z.ZodObject<{
2886
+ action: z.ZodLiteral<"update">;
2887
+ content: z.ZodOptional<z.ZodString>;
2888
+ note_id: z.ZodEffects<z.ZodString, string, string>;
2889
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
2890
+ }, "strict", z.ZodTypeAny, {
2891
+ action: "update";
2892
+ content?: string | undefined;
2893
+ note_id: string;
2894
+ tags?: string[] | undefined;
2895
+ }, {
2896
+ action: "update";
2897
+ content?: string | undefined;
2898
+ note_id: string;
2899
+ tags?: string[] | undefined;
2900
+ }>, {
2901
+ action: "update";
2902
+ content?: string | undefined;
2903
+ note_id: string;
2904
+ tags?: string[] | undefined;
2905
+ }, {
2906
+ action: "update";
2907
+ content?: string | undefined;
2908
+ note_id: string;
2909
+ tags?: string[] | undefined;
2910
+ }>,
2911
+ z.ZodObject<{
2912
+ action: z.ZodEnum<[
2913
+ "delete",
2914
+ "restore",
2915
+ "archive",
2916
+ "unarchive",
2917
+ "star",
2918
+ "unstar"
2919
+ ]>;
2920
+ note_id: z.ZodEffects<z.ZodString, string, string>;
2921
+ }, "strict", z.ZodTypeAny, {
2922
+ action: "archive" | "delete" | "restore" | "star" | "unarchive" | "unstar";
2923
+ note_id: string;
2924
+ }, {
2925
+ action: "archive" | "delete" | "restore" | "star" | "unarchive" | "unstar";
2926
+ note_id: string;
2927
+ }>
2928
+ ]>;
2929
+ type RemoteManageNoteInput = z.infer<typeof manageInput>;
2607
2930
  /**
2608
- * Shared postMessage protocol types for the PGlite worker.
2609
- *
2610
- * WorkerRequest — messages sent from the client to the worker.
2611
- * WorkerResponse — messages sent from the worker back to the client.
2931
+ * Capability module system (ADR-002).
2932
+ * Tracks opt-in WASM module states. No WASM loaded by default (CAP-001).
2612
2933
  *
2613
- * Every request carries a unique `id` that the worker echoes in its response,
2614
- * allowing the client to correlate replies with pending promises.
2615
- * The READY broadcast is the only message without an `id` — it is sent once
2616
- * on startup before any requests are processed.
2934
+ * State machine (valid transitions):
2935
+ * unloaded -> loading (via enable)
2936
+ * loading -> ready (via markReady or successful loader)
2937
+ * loading -> error (via markError or failed loader)
2938
+ * ready -> disabled (via disable)
2939
+ * disabled -> loading (via enable, re-enable)
2940
+ * error -> loading (via enable, retry)
2617
2941
  */
2618
- /** Messages from client to worker */
2619
- type WorkerRequest = {
2620
- id: string;
2621
- isolationLevel?: string;
2622
- type: 'BEGIN';
2623
- } | {
2624
- id: string;
2625
- params?: unknown[];
2626
- sql: string;
2627
- txId: string;
2628
- type: 'TX_QUERY';
2629
- } | {
2630
- id: string;
2631
- params?: unknown[];
2632
- sql: string;
2633
- type: 'QUERY';
2634
- } | {
2635
- id: string;
2636
- sql: string;
2637
- txId: string;
2638
- type: 'TX_EXEC';
2639
- } | {
2640
- id: string;
2641
- sql: string;
2642
- type: 'EXEC';
2643
- } | {
2644
- id: string;
2645
- txId: string;
2646
- type: 'COMMIT';
2647
- } | {
2648
- id: string;
2649
- txId: string;
2650
- type: 'ROLLBACK';
2651
- } | {
2652
- id: string;
2653
- type: 'CLOSE';
2654
- } | {
2655
- id: string;
2656
- type: 'PING';
2657
- };
2658
- /** Messages from worker to client */
2659
- type WorkerResponse = {
2660
- affectedRows?: number;
2661
- id: string;
2662
- type: 'EXEC_DONE';
2663
- } | {
2664
- error: string;
2665
- id: string;
2666
- type: 'ERROR';
2667
- } | {
2668
- fields?: Array<{
2669
- dataTypeID: number;
2670
- name: string;
2671
- }>;
2672
- id: string;
2673
- rows: unknown[];
2674
- type: 'RESULT';
2675
- } | {
2676
- id: string;
2677
- txId: string;
2678
- type: 'TX_STARTED';
2679
- } | {
2680
- id: string;
2681
- type: 'PONG';
2682
- } | {
2683
- id: string;
2684
- type: 'TX_DONE';
2685
- } | {
2686
- type: 'READY';
2687
- };
2688
- type JsonObject = Record<string, unknown>;
2689
- interface NativeEmbeddingConfig {
2690
- id: string;
2691
- name: string;
2692
- description: null | string;
2693
- model: string;
2694
- dimension: number;
2695
- chunk_size: number;
2696
- chunk_overlap: number;
2697
- hnsw_m: null | number;
2698
- hnsw_ef_construction: null | number;
2699
- ivfflat_lists: null | number;
2700
- is_default: boolean | null;
2701
- supports_mrl: boolean | null;
2702
- matryoshka_dims: null | number[];
2703
- default_truncate_dim: null | number;
2704
- provider: null | string;
2705
- provider_config: JsonObject | null;
2706
- content_types: null | string[];
2707
- strengths: null | string[];
2708
- limitations: null | string[];
2709
- recommended_for: null | string[];
2710
- benchmark_scores: JsonObject | null;
2711
- is_available: boolean | null;
2712
- document_composition: JsonObject;
2713
- created_at: string;
2714
- updated_at: string;
2715
- }
2716
- interface NativeEmbeddingSet {
2717
- id: string;
2718
- name: string;
2719
- slug: null | string;
2720
- description: null | string;
2721
- purpose: null | string;
2722
- usage_hints: null | string;
2723
- keywords: null | string[];
2724
- set_type: 'filter' | 'full';
2725
- mode: 'auto' | 'manual' | 'mixed' | null;
2726
- criteria: JsonObject | null;
2727
- embedding_config_id: null | string;
2728
- truncate_dim: null | number;
2729
- auto_embed_rules: JsonObject | null;
2730
- index_status: string;
2731
- index_type: null | string;
2732
- last_indexed_at: null | string;
2733
- document_count: null | number;
2734
- embedding_count: null | number;
2735
- embeddings_current: boolean | null;
2736
- index_size_bytes: null | number;
2737
- is_system: boolean | null;
2738
- is_active: boolean | null;
2739
- auto_refresh: boolean | null;
2740
- refresh_interval: null | string;
2741
- last_refresh_at: null | string;
2742
- agent_metadata: JsonObject | null;
2743
- created_at: string;
2744
- updated_at: string;
2745
- created_by: null | string;
2942
+ type CapabilityState = 'disabled' | 'error' | 'loading' | 'ready' | 'unloaded';
2943
+ type CapabilityName = 'audio' | 'llm' | 'pdf' | 'semantic' | 'vision';
2944
+ declare class CapabilityManager {
2945
+ private events;
2946
+ private capabilities;
2947
+ private loaders;
2948
+ private progressMessages;
2949
+ constructor(events: TypedEventBus);
2950
+ /**
2951
+ * Register an async loader for a capability.
2952
+ * Called by enable(); if no loader is registered the capability transitions
2953
+ * directly to ready (useful for capabilities that require no async init).
2954
+ */
2955
+ registerLoader(name: CapabilityName, loader: () => Promise<void>): void;
2956
+ getState(name: CapabilityName): CapabilityState;
2957
+ isReady(name: CapabilityName): boolean;
2958
+ /**
2959
+ * Enable a capability.
2960
+ * Valid from: unloaded, disabled, error (retry).
2961
+ * Runs the registered loader if present; transitions to ready on success,
2962
+ * error on failure.
2963
+ */
2964
+ enable(name: CapabilityName): Promise<void>;
2965
+ /**
2966
+ * Disable a ready capability.
2967
+ * Valid from: ready only.
2968
+ */
2969
+ disable(name: CapabilityName): void;
2970
+ /**
2971
+ * Mark a loading capability as ready (external use, e.g. bridge protocol).
2972
+ * Valid from: loading only.
2973
+ */
2974
+ markReady(name: CapabilityName): void;
2975
+ /**
2976
+ * Mark a loading capability as errored (external use, e.g. bridge protocol).
2977
+ * Valid from: loading only.
2978
+ */
2979
+ markError(name: CapabilityName, error: string): void;
2980
+ /**
2981
+ * Report loading progress (0-100).
2982
+ * Emits capability.loading with progress if the capability is currently loading.
2983
+ * No-op if the capability is not in loading state.
2984
+ */
2985
+ reportProgress(name: CapabilityName, progress: number): void;
2986
+ /** Set a human-readable progress message for a loading capability */
2987
+ setProgress(name: CapabilityName, message: string): void;
2988
+ /** Get the current progress message for a capability */
2989
+ getProgress(name: CapabilityName): string | undefined;
2990
+ getError(name: CapabilityName): string | undefined;
2991
+ listAll(): Array<{
2992
+ name: CapabilityName;
2993
+ state: CapabilityState;
2994
+ }>;
2746
2995
  }
2747
- interface NativeEmbeddingMember {
2748
- embedding_set_id: string;
2749
- note_id: string;
2750
- membership_type: null | string;
2751
- added_at: null | string;
2752
- added_by: null | string;
2996
+ /**
2997
+ * Sequential SQL migration runner for DatabaseClient.
2998
+ * Tracks applied migrations in a schema_version table.
2999
+ * Each migration runs in a transaction; version updated atomically.
3000
+ */
3001
+ interface Migration {
3002
+ version: number;
3003
+ name: string;
3004
+ sql: string;
3005
+ }
3006
+ declare class MigrationRunner {
3007
+ private db;
3008
+ private events?;
3009
+ constructor(db: DatabaseClient, events?: TypedEventBus | undefined);
3010
+ ensureSchemaTable(): Promise<void>;
3011
+ getCurrentVersion(): Promise<number>;
3012
+ apply(migrations: Migration[]): Promise<number>;
3013
+ getAppliedMigrations(): Promise<Array<{
3014
+ name: string;
3015
+ version: number;
3016
+ }>>;
2753
3017
  }
3018
+ declare const allMigrations: Migration[];
2754
3019
  /**
2755
- * EmbeddingSetsRepository - named, filter, and virtual embedding set API.
3020
+ * Multi-archive manager for Fortemi.
3021
+ * Each archive is a separate PGlite instance with its own persistence path.
3022
+ * Migrations are applied automatically on open.
2756
3023
  */
2757
- type EmbeddingSetKind = 'filter' | 'physical' | 'virtual';
2758
- type EmbeddingSetMode = 'auto' | 'manual' | 'mixed';
2759
- interface EmbeddingSetCriteria {
2760
- query?: string;
2761
- tags?: string[];
2762
- collectionIds?: string[];
2763
- conceptIds?: string[];
2764
- noteIds?: string[];
2765
- sources?: string[];
2766
- formats?: string[];
2767
- visibilities?: string[];
2768
- isStarred?: boolean;
2769
- isArchived?: boolean;
2770
- hasTitle?: boolean;
2771
- hasEmbedding?: boolean;
2772
- isUserEdited?: boolean;
2773
- hasAiMetadata?: boolean;
2774
- hasRevisions?: boolean;
2775
- minGenerationCount?: number;
2776
- maxGenerationCount?: number;
2777
- updatedAfter?: string;
2778
- updatedBefore?: string;
3024
+ interface ArchiveInfo {
3025
+ name: string;
3026
+ createdAt: string;
2779
3027
  }
2780
- interface EmbeddingSetFreshness {
2781
- status: 'fresh' | 'stale' | 'unknown';
2782
- sourceHash?: string;
2783
- checkedAt?: string;
2784
- reason?: string;
3028
+ declare class ArchiveManager {
3029
+ private events?;
3030
+ private currentArchive;
3031
+ private db;
3032
+ private archives;
3033
+ private persistence;
3034
+ private backendFactory;
3035
+ /**
3036
+ * Persistence is a PLUGGABLE, opt-in backend (issue #261). Pass a
3037
+ * `StorageBackendFactory` to run against any `StorageBackend`
3038
+ * implementation; PGlite is merely the built-in default, selected only when
3039
+ * the convenience `PersistenceMode` string form is used. Because
3040
+ * `defaultStorageBackendFactory` reaches PGlite through the lazily-imported
3041
+ * `createPGliteInstance` (see `db.ts`), a consumer that supplies its own
3042
+ * factory — or never opens an archive at all — never pulls the PGlite WASM
3043
+ * engine into its bundle.
3044
+ *
3045
+ * @param persistenceOrFactory `PersistenceMode` string (uses the built-in
3046
+ * PGlite backend) OR a custom `StorageBackendFactory`.
3047
+ * @param persistenceOverride persistence hint passed to a custom factory.
3048
+ */
3049
+ constructor(persistenceOrFactory: PersistenceMode | StorageBackendFactory, events?: TypedEventBus | undefined, persistenceOverride?: PersistenceMode);
3050
+ getCurrentArchiveName(): string;
3051
+ getDb(): null | StorageBackend;
3052
+ open(archiveName?: string): Promise<StorageBackend>;
3053
+ /**
3054
+ * Adopt an already-created backend WITHOUT running migrations — for a backend
3055
+ * whose schema is already present, e.g. a PGlite restored from a physical
3056
+ * data-dir snapshot (issue #187, `restoreDbSnapshot`). Running migrations here
3057
+ * would be wrong: the restored dir already carries them (and the HNSW index).
3058
+ */
3059
+ adopt(backend: StorageBackend, archiveName?: string): Promise<StorageBackend>;
3060
+ create(archiveName: string): Promise<StorageBackend>;
3061
+ switchTo(archiveName: string): Promise<StorageBackend>;
3062
+ delete(archiveName: string): Promise<void>;
3063
+ listArchives(): ArchiveInfo[];
3064
+ close(): Promise<void>;
2785
3065
  }
2786
- interface EmbeddingCompatibilityPolicy {
2787
- model: 'allow-compatible-family' | 'require-same';
2788
- dimension: 'allow-truncation' | 'require-same';
2789
- duplicateVectors: 'error' | 'prefer-latest' | 'prefer-set-order';
2790
- missingVectors: 'error' | 'include-unembedded-note' | 'omit';
3066
+ /**
3067
+ * Factory function for creating a FortemiCore instance.
3068
+ * All deployment modes use this entry point.
3069
+ */
3070
+ interface FortemiConfig {
3071
+ persistence: 'idb' | 'memory' | 'opfs';
3072
+ archiveName?: string;
2791
3073
  }
2792
- interface VirtualMaterializationPolicy {
2793
- allowed: boolean;
2794
- includeResolvedMembers?: boolean;
2795
- includeResolvedEdges?: boolean;
2796
- freshness: 'fresh' | 'stale' | 'unknown';
2797
- inputHash?: string;
2798
- generatedAt?: string;
2799
- resolvedMemberCount?: number;
3074
+ interface FortemiCore {
3075
+ events: TypedEventBus;
3076
+ config: FortemiConfig;
3077
+ destroy(): void;
2800
3078
  }
2801
- interface CriteriaVirtualSource {
2802
- type: 'criteria';
2803
- baseSetId: string;
2804
- criteria: EmbeddingSetCriteria;
3079
+ declare function createFortemi(config: FortemiConfig): FortemiCore;
3080
+ /**
3081
+ * Compute a browser-local content-identity hash (SHA-256), encoded as
3082
+ * `sha256:<64-char lowercase hex>`.
3083
+ *
3084
+ * This is an internal identity/dedup digest used for note content, embedding
3085
+ * configs, the AIWG index, and graph identity — NOT the server's attachment
3086
+ * content-hash convention. Binary-attachment blobs use {@link computeBlobHash}
3087
+ * (BLAKE3), which is the canonical checksum defined by the binary-attachment
3088
+ * projection contract (`checksum: "blake3:<hex>"`). Keeping these two functions
3089
+ * separate preserves JSON format parity for the identity hashes above while
3090
+ * letting attachments match the server's `compute_content_hash`.
3091
+ *
3092
+ * @param data - Raw bytes to hash
3093
+ * @returns `'sha256:<64-char lowercase hex>'`
3094
+ */
3095
+ declare function computeHash(data: Uint8Array): string;
3096
+ /**
3097
+ * Compute the canonical attachment content hash: **BLAKE3**, encoded as
3098
+ * `blake3:<64-char lowercase hex>`.
3099
+ *
3100
+ * Matches the fortemi server (`crates/matric-db/src/file_storage.rs`
3101
+ * `compute_content_hash`) and the portable Knowledge-Shard byte-sidecar
3102
+ * contract, where the sidecar tar entry name is the bare hex (the `blake3:`
3103
+ * prefix stripped). SubtleCrypto has no BLAKE3, so this uses `@noble/hashes`.
3104
+ *
3105
+ * @param data - Raw attachment bytes to hash
3106
+ * @returns `'blake3:<64-char lowercase hex>'`
3107
+ */
3108
+ declare function computeBlobHash(data: Uint8Array): string;
3109
+ declare const FORTEMI_COMPATIBILITY_PATH = "/api/v1/system/compatibility";
3110
+ declare const FORTEMI_SERVER_COMPATIBILITY_REVISION = "2026-07-06";
3111
+ declare const FORTEMI_COMPATIBILITY_STATES: readonly [
3112
+ "available",
3113
+ "degraded",
3114
+ "preview",
3115
+ "unavailable",
3116
+ "unknown"
3117
+ ];
3118
+ type FortemiCompatibilityState = (typeof FORTEMI_COMPATIBILITY_STATES)[number];
3119
+ declare const FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES: readonly [
3120
+ "core_notes",
3121
+ "search",
3122
+ "jobs",
3123
+ "realtime_activity",
3124
+ "hosted_auth",
3125
+ "premium_components",
3126
+ "backoffice_api",
3127
+ "audit_posture",
3128
+ "quota_status",
3129
+ "kms_status",
3130
+ "mcp_scope_gate"
3131
+ ];
3132
+ type FortemiRequiredCompatibilityCapability = (typeof FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES)[number];
3133
+ interface FortemiCompatibilityCapability {
3134
+ state: FortemiCompatibilityState;
3135
+ reason_code?: string;
2805
3136
  }
2806
- interface SetOperationVirtualSource {
2807
- type: 'set-operation';
2808
- operation: 'difference' | 'intersection' | 'union';
2809
- setIds: string[];
3137
+ interface FortemiCompatibilityResponse {
3138
+ schema_version: number;
3139
+ contract_revision: string;
3140
+ api: {
3141
+ build_date_present: boolean;
3142
+ git_sha_present: boolean;
3143
+ minimum_hotm_enterprise_client: string;
3144
+ name: string;
3145
+ version: string;
3146
+ };
3147
+ deployment: {
3148
+ edition: string;
3149
+ hosted_multi_tenant_ready: boolean;
3150
+ mode: string;
3151
+ };
3152
+ auth: {
3153
+ mode: string;
3154
+ oauth_issuer_configured: boolean;
3155
+ required: boolean;
3156
+ tenant_context_available: boolean;
3157
+ };
3158
+ capabilities: Record<string, FortemiCompatibilityCapability>;
3159
+ links: {
3160
+ asyncapi: string;
3161
+ health: string;
3162
+ openapi: string;
3163
+ streaming_health: string;
3164
+ };
2810
3165
  }
2811
- interface FallbackVirtualSource {
2812
- type: 'fallback';
2813
- preferredSetIds: string[];
3166
+ interface FortemiCompatibilityValidationResult {
3167
+ ok: boolean;
3168
+ errors: string[];
3169
+ warnings: string[];
3170
+ response?: FortemiCompatibilityResponse;
2814
3171
  }
2815
- interface LatestCompatibleVirtualSource {
2816
- type: 'latest-compatible';
2817
- candidateSetIds: string[];
2818
- model?: string;
2819
- dimension?: number;
3172
+ interface FetchFortemiCompatibilityOptions {
3173
+ baseUrl?: string;
3174
+ fetchImpl?: typeof fetch;
3175
+ timeoutMs?: number;
2820
3176
  }
2821
- interface SnapshotVirtualSource {
2822
- type: 'snapshot';
2823
- snapshotId: string;
2824
- sourceDefinitionId: string;
2825
- generatedAt: string;
2826
- inputHash: string;
3177
+ declare function fortemiCompatibilityUrl(baseUrl?: string): string;
3178
+ declare function validateFortemiCompatibilityResponse(raw: unknown): FortemiCompatibilityValidationResult;
3179
+ declare function formatFortemiCompatibilitySummary(response: FortemiCompatibilityResponse): string;
3180
+ declare function fetchAndValidateFortemiCompatibility(options?: FetchFortemiCompatibilityOptions): Promise<FortemiCompatibilityValidationResult & {
3181
+ status?: number;
3182
+ url: string;
3183
+ }>;
3184
+ interface SWRegistrationResult {
3185
+ registered: boolean;
3186
+ registration?: ServiceWorkerRegistration;
3187
+ error?: string;
2827
3188
  }
2828
- type VirtualEmbeddingSetSource = CriteriaVirtualSource | FallbackVirtualSource | LatestCompatibleVirtualSource | SetOperationVirtualSource | SnapshotVirtualSource;
2829
- interface VirtualEmbeddingSetDefinition {
2830
- id: string;
2831
- name: string;
2832
- purpose?: null | string;
2833
- source: VirtualEmbeddingSetSource;
2834
- compatibility: EmbeddingCompatibilityPolicy;
2835
- materialization?: VirtualMaterializationPolicy;
2836
- createdAt?: string;
2837
- updatedAt?: string;
3189
+ declare function registerServiceWorker(swUrl?: string): Promise<SWRegistrationResult>;
3190
+ /**
3191
+ * REST route definitions for Service Worker.
3192
+ * These are pure functions that transform HTTP Request → tool input and tool output → Response.
3193
+ * The actual DB connection is injected at registration time.
3194
+ *
3195
+ * All routes currently return 503 Not Implemented — the DB wiring happens in a later issue.
3196
+ * The URL structure and request/response shapes are the valuable contract defined here.
3197
+ */
3198
+ interface RouteHandler {
3199
+ method: string;
3200
+ pattern: RegExp;
3201
+ handler: (request: Request, match: RegExpMatchArray, params: URLSearchParams) => Promise<Response>;
2838
3202
  }
2839
- interface EmbeddingSetSelector {
2840
- kind: 'default' | 'embedding-set' | 'virtual-definition';
2841
- embeddingSetId?: string;
2842
- definition?: VirtualEmbeddingSetDefinition;
3203
+ /**
3204
+ * Create route handlers.
3205
+ * db parameter will be injected when the SW gets access to PGlite.
3206
+ * For now, returns 503 Not Implemented for all routes.
3207
+ */
3208
+ declare function createRoutes(): RouteHandler[];
3209
+ /**
3210
+ * Match a request against the registered routes and return the first matching
3211
+ * handler, or null if no route matches.
3212
+ */
3213
+ declare function matchRoute(routes: RouteHandler[], request: Request, url: URL): null | RouteHandler;
3214
+ /**
3215
+ * One-shot migration of the pre-bytecask blob layout into the new store.
3216
+ *
3217
+ * The legacy layout (shipped through v2026.7.x) was:
3218
+ * - IndexedDB: database `fortemi-<archive>-blobs`, object store `blobs`,
3219
+ * values keyed by the full checksum string (`blake3:<hex>`, historically
3220
+ * also `sha256:<hex>`).
3221
+ * - OPFS: directory `fortemi-<archive>-blobs/<h0h1>/<h2h3>/<checksum>`.
3222
+ *
3223
+ * Migration re-`put()`s every payload — the new store recomputes BLAKE3, so
3224
+ * legacy `sha256:`-keyed entries converge to canonical keys for free
3225
+ * (ADR-012 D3). The legacy source is deleted only after every entry migrated
3226
+ * without error; any failure leaves it untouched for the next attempt.
3227
+ */
3228
+ /** Outcome of one migration attempt (for diagnostics/logging). */
3229
+ interface LegacyMigrationReport {
3230
+ migrated: number;
3231
+ /** Migration aborted without deleting the legacy source. */
3232
+ failed: boolean;
2843
3233
  }
2844
- interface EmbeddingSetDescriptor {
3234
+ /**
3235
+ * Migrate any legacy blob layout for `archiveName` into `target`, then delete
3236
+ * the legacy source. Failures are contained: the legacy data stays in place
3237
+ * and the new store keeps whatever was already re-put (idempotent on retry).
3238
+ */
3239
+ declare function migrateLegacyBlobStore(archiveName: string, target: BlobStore, indexedDbFactory?: IDBFactory): Promise<LegacyMigrationReport>;
3240
+ /**
3241
+ * Shared postMessage protocol types for the PGlite worker.
3242
+ *
3243
+ * WorkerRequest — messages sent from the client to the worker.
3244
+ * WorkerResponse — messages sent from the worker back to the client.
3245
+ *
3246
+ * Every request carries a unique `id` that the worker echoes in its response,
3247
+ * allowing the client to correlate replies with pending promises.
3248
+ * The READY broadcast is the only message without an `id` — it is sent once
3249
+ * on startup before any requests are processed.
3250
+ */
3251
+ /** Messages from client to worker */
3252
+ type WorkerRequest = {
2845
3253
  id: string;
2846
- name: string;
2847
- purpose?: null | string;
2848
- kind: EmbeddingSetKind;
2849
- mode?: EmbeddingSetMode;
2850
- model?: string;
2851
- dimension?: number;
2852
- truncateDimension?: null | number;
2853
- criteria?: EmbeddingSetCriteria | null;
2854
- createdAt?: string;
2855
- updatedAt?: string;
2856
- freshness?: EmbeddingSetFreshness;
2857
- }
2858
- type VirtualEmbeddingSetValidationError = {
2859
- code: 'duplicate-vector';
2860
- noteId: string;
2861
- setIds: string[];
2862
- } | {
2863
- code: 'missing-vector';
2864
- noteId: string;
2865
- setId: string;
3254
+ isolationLevel?: string;
3255
+ type: 'BEGIN';
2866
3256
  } | {
2867
- code: 'mixed-dimensions';
2868
- setIds: string[];
3257
+ id: string;
3258
+ params?: unknown[];
3259
+ sql: string;
3260
+ txId: string;
3261
+ type: 'TX_QUERY';
2869
3262
  } | {
2870
- code: 'mixed-models';
2871
- setIds: string[];
3263
+ id: string;
3264
+ params?: unknown[];
3265
+ sql: string;
3266
+ type: 'QUERY';
2872
3267
  } | {
2873
- code: 'stale-snapshot';
2874
- snapshotId: string;
3268
+ id: string;
3269
+ sql: string;
3270
+ txId: string;
3271
+ type: 'TX_EXEC';
2875
3272
  } | {
2876
- code: 'unsupported-criteria';
2877
- field: string;
2878
- };
2879
- interface ResolvedEmbeddingRow {
2880
- note_id: string;
2881
- embedding_set_id: string;
2882
- embedding_id: string;
2883
- vector: string;
2884
- created_at: Date | null;
2885
- }
2886
- interface ResolvedEmbeddingSet {
2887
- selector: EmbeddingSetSelector;
2888
- rows: ResolvedEmbeddingRow[];
2889
- noteIds: string[];
2890
- embeddingIds: string[];
2891
- errors: VirtualEmbeddingSetValidationError[];
2892
- freshness: EmbeddingSetFreshness;
2893
- resolutionSource: 'live' | 'materialized';
2894
- }
2895
- interface EmbeddingConfigRow extends Omit<NativeEmbeddingConfig, 'created_at' | 'updated_at'> {
2896
- created_at: Date;
2897
- updated_at: Date;
2898
- }
2899
- interface EmbeddingMemberRow extends Omit<NativeEmbeddingMember, 'added_at'> {
2900
- embedding_id: null | string;
2901
- added_at: Date | null;
2902
- }
2903
- interface EmbeddingRow {
2904
3273
  id: string;
2905
- note_id: null | string;
2906
- embedding_set_id: null | string;
2907
- chunk_index: number;
2908
- text: string;
2909
- vector: null | string;
2910
- model: null | string;
2911
- contract_fingerprint: null | string;
2912
- shard_contract_fingerprint_present: boolean;
2913
- created_at: Date | null;
2914
- }
2915
- interface EmbeddingSetRow extends Partial<Omit<NativeEmbeddingSet, 'created_at' | 'criteria' | 'keywords' | 'mode' | 'set_type' | 'truncate_dim' | 'updated_at'>> {
3274
+ sql: string;
3275
+ type: 'EXEC';
3276
+ } | {
2916
3277
  id: string;
2917
- name: string;
2918
- purpose: null | string;
2919
- model_name: string;
2920
- dimensions: number;
2921
- kind: EmbeddingSetKind;
2922
- mode: EmbeddingSetMode | null;
2923
- truncate_dimension: null | number;
2924
- criteria_json: null | unknown;
2925
- source_json: null | unknown;
2926
- compatibility_json: null | unknown;
2927
- materialization_json: null | unknown;
2928
- freshness_json: null | unknown;
2929
- created_at: Date;
2930
- updated_at: Date;
2931
- }
2932
- interface EmbeddingSetCreateInput {
2933
- id?: string;
2934
- name: string;
2935
- slug?: null | string;
2936
- purpose?: null | string;
2937
- model_name?: string;
2938
- dimensions?: number;
2939
- kind?: EmbeddingSetKind;
2940
- mode?: EmbeddingSetMode | null;
2941
- truncate_dimension?: null | number;
2942
- criteria?: EmbeddingSetCriteria | null;
2943
- }
2944
- interface EmbeddingSetEmbeddingInput {
2945
- id?: string;
2946
- note_id: string;
2947
- embedding_set_id: string;
2948
- vector: number[];
2949
- }
2950
- declare class EmbeddingSetsRepository {
2951
- private db;
2952
- constructor(db: QueryExecutor);
2953
- getConfig(id: string): Promise<EmbeddingConfigRow>;
2954
- listConfigs(): Promise<EmbeddingConfigRow[]>;
2955
- listMembers(setId: string): Promise<EmbeddingMemberRow[]>;
2956
- /** Includes metadata-only records and every chunk, unlike a resolved graph selector. */
2957
- listEmbeddings(setId: string): Promise<EmbeddingRow[]>;
2958
- create(input: EmbeddingSetCreateInput): Promise<EmbeddingSetRow>;
2959
- createVirtualDefinition(input: VirtualEmbeddingSetDefinition): Promise<EmbeddingSetRow>;
2960
- ensureDefault(): Promise<EmbeddingSetRow>;
2961
- get(id: string): Promise<EmbeddingSetRow>;
2962
- list(): Promise<EmbeddingSetRow[]>;
2963
- listDescriptors(): Promise<EmbeddingSetDescriptor[]>;
2964
- toDescriptor(row: EmbeddingSetRow): EmbeddingSetDescriptor;
2965
- putEmbedding(input: EmbeddingSetEmbeddingInput): Promise<{
2966
- id: string;
2967
- }>;
2968
- resolveSelector(selector: EmbeddingSetSelector): Promise<ResolvedEmbeddingSet>;
2969
- refreshMaterializedVirtualSet(setId: string): Promise<ResolvedEmbeddingSet>;
2970
- markVirtualSetStale(setId: string, reason: string): Promise<void>;
2971
- /** @internal The repository and mutation must use the same caller-owned transaction. */
2972
- withMaterializationInvalidation<T>(mutate: () => Promise<T>): Promise<T>;
2973
- private liveResolutionHash;
2974
- private resolveDefinition;
2975
- private resolvePhysicalSet;
2976
- private resolvePhysicalRows;
2977
- private resolveMaterializedRows;
2978
- private resolveCriteriaSource;
2979
- private resolveSetOperationSource;
2980
- private resolveFallbackSource;
2981
- private resolveLatestCompatibleSource;
2982
- private validateCompatibility;
2983
- private resolveDuplicateRows;
2984
- private finalizeResolution;
2985
- private resolutionInputHash;
2986
- private definitionFromRow;
2987
- private inferDefinitionModel;
2988
- private inferDefinitionDimension;
2989
- }
2990
- declare const REGISTERED_METADATA_PATHS: readonly [
2991
- "provider",
2992
- "model",
2993
- "role",
2994
- "event_kind",
2995
- "sensitivity",
2996
- "import_run_id"
2997
- ];
2998
- type RegisteredMetadataPath = typeof REGISTERED_METADATA_PATHS[number];
2999
- type MetadataPredicate = {
3000
- gte?: number | string;
3001
- lte?: number | string;
3002
- op: 'range';
3003
- path: RegisteredMetadataPath;
3278
+ txId: string;
3279
+ type: 'COMMIT';
3004
3280
  } | {
3005
- op: 'eq';
3006
- path: RegisteredMetadataPath;
3007
- value: boolean | null | number | string;
3281
+ id: string;
3282
+ txId: string;
3283
+ type: 'ROLLBACK';
3008
3284
  } | {
3009
- op: 'exists';
3010
- path: RegisteredMetadataPath;
3011
- value?: boolean;
3285
+ id: string;
3286
+ type: 'CLOSE';
3012
3287
  } | {
3013
- op: 'in';
3014
- path: RegisteredMetadataPath;
3015
- value: readonly (boolean | null | number | string)[];
3288
+ id: string;
3289
+ type: 'PING';
3016
3290
  };
3017
- interface EvidenceLocator {
3018
- note_id: string;
3019
- chunk?: {
3020
- index: number;
3021
- kind: 'attachment' | 'current' | 'title';
3022
- };
3023
- span?: {
3024
- end: number;
3025
- start: number;
3026
- };
3027
- source?: {
3028
- external_id_hash: string;
3029
- import_run_id: string;
3030
- namespace: string;
3031
- schema_version: string;
3032
- };
3033
- metadata_paths: RegisteredMetadataPath[];
3034
- }
3035
- interface MetadataPredicateConditionResult {
3036
- conditions: string[];
3037
- joins: string[];
3038
- params: unknown[];
3039
- nextIdx: number;
3040
- }
3041
- declare function buildMetadataPredicateConditions(options: Pick<SearchOptions, 'archive_id' | 'metadataPredicates' | 'tenant_id'>, startIdx: number): MetadataPredicateConditionResult;
3042
- /**
3043
- * Shared types for repository layer.
3044
- * All repository methods use these types as inputs and outputs.
3045
- */
3046
- interface NoteSummary {
3291
+ /** Messages from worker to client */
3292
+ type WorkerResponse = {
3293
+ affectedRows?: number;
3047
3294
  id: string;
3048
- title: null | string;
3049
- format: string;
3050
- source: string;
3051
- visibility: string;
3052
- is_starred: boolean;
3053
- is_pinned: boolean;
3054
- is_archived: boolean;
3055
- created_at: Date;
3056
- updated_at: Date;
3057
- deleted_at: Date | null;
3058
- tags: string[];
3059
- }
3060
- interface NoteFull extends NoteSummary {
3061
- /** Note metadata is independent of the current revision's AI metadata. */
3062
- metadata?: unknown;
3063
- archive_id: null | string;
3064
- revision_mode: string;
3065
- original: {
3066
- content_hash: string;
3067
- content: string;
3068
- created_at: Date;
3069
- id: null | string;
3070
- user_created_at?: null | string;
3071
- user_last_edited_at?: null | string;
3072
- version_number?: number;
3073
- };
3074
- current: {
3075
- ai_metadata: null | unknown;
3076
- content: string;
3077
- generation_count: number;
3078
- is_user_edited: boolean;
3079
- last_revision_id?: null | string;
3080
- model: null | string;
3081
- updated_at: Date;
3082
- };
3083
- }
3084
- interface NoteCreateInput {
3085
- metadata?: unknown;
3086
- content: string;
3087
- title?: string;
3088
- format?: string;
3089
- source?: string;
3090
- visibility?: string;
3091
- tags?: string[];
3092
- archive_id?: string;
3093
- /**
3094
- * Explicit primary key. When omitted a UUIDv7 is minted (the default). Supply
3095
- * this only for deterministic seeding or cross-instance identity — e.g. two
3096
- * in-browser databases that must agree on a shared note's id so a shard swap
3097
- * can dedupe it under the `skip` conflict strategy.
3098
- */
3099
- id?: string;
3100
- }
3101
- interface NoteUpdateInput {
3102
- metadata?: unknown;
3103
- title?: string;
3104
- content?: string;
3105
- format?: string;
3106
- visibility?: string;
3107
- }
3108
- interface NoteListOptions {
3109
- limit?: number;
3110
- offset?: number;
3111
- sort?: 'created_at' | 'title' | 'updated_at';
3112
- order?: 'asc' | 'desc';
3113
- is_starred?: boolean;
3114
- is_pinned?: boolean;
3115
- is_archived?: boolean;
3116
- include_deleted?: boolean;
3117
- include_archived?: boolean;
3118
- collection_id?: string;
3119
- tags?: string[];
3120
- }
3121
- interface PaginatedResult<T> {
3122
- items: T[];
3123
- total: number;
3124
- limit: number;
3125
- offset: number;
3126
- }
3127
- interface SearchResult {
3295
+ type: 'EXEC_DONE';
3296
+ } | {
3297
+ error: string;
3128
3298
  id: string;
3129
- title: null | string;
3130
- snippet: string;
3131
- rank: number;
3132
- created_at: Date;
3133
- updated_at: Date;
3134
- tags: string[];
3135
- has_embedding?: boolean;
3136
- locators?: EvidenceLocator[];
3137
- }
3138
- interface SearchFacets {
3139
- tags: {
3140
- count: number;
3141
- tag: string;
3142
- }[];
3143
- collections: {
3144
- count: number;
3145
- id: string;
3299
+ type: 'ERROR';
3300
+ } | {
3301
+ fields?: Array<{
3302
+ dataTypeID: number;
3146
3303
  name: string;
3147
- }[];
3148
- }
3149
- interface SearchResponse {
3150
- results: SearchResult[];
3151
- total: number;
3152
- query: string;
3153
- mode: 'hybrid' | 'semantic' | 'text';
3154
- semantic_available: boolean;
3155
- limit: number;
3156
- offset: number;
3157
- facets?: SearchFacets;
3158
- }
3159
- interface SearchOptions {
3160
- limit?: number;
3161
- offset?: number;
3162
- tags?: string[];
3163
- collection_id?: string;
3164
- date_from?: Date;
3165
- date_to?: Date;
3166
- is_starred?: boolean;
3167
- is_archived?: boolean;
3168
- format?: string;
3169
- source?: string;
3170
- visibility?: string;
3171
- tenant_id?: string;
3172
- archive_id?: null | string;
3173
- metadataPredicates?: readonly MetadataPredicate[];
3174
- include_facets?: boolean;
3175
- mode?: 'auto' | 'hybrid' | 'semantic' | 'text';
3176
- embeddingSetId?: string;
3177
- embeddingSetSelector?: EmbeddingSetSelector;
3178
- }
3179
- interface NoteRevision {
3304
+ }>;
3180
3305
  id: string;
3181
- note_id: string;
3182
- revision_number: number;
3183
- type: string;
3184
- content: string;
3185
- ai_metadata: null | unknown;
3186
- model: null | string;
3187
- created_at: Date;
3188
- parent_revision_id?: null | string;
3189
- summary?: null | string;
3190
- rationale?: null | string;
3191
- created_at_utc?: null | string;
3192
- ai_generated_at?: null | string;
3193
- user_last_edited_at?: null | string;
3194
- is_user_edited?: boolean;
3195
- generation_count?: number;
3196
- }
3197
- interface OriginalContentRevision {
3306
+ rows: unknown[];
3307
+ type: 'RESULT';
3308
+ } | {
3198
3309
  id: string;
3199
- note_id: string;
3200
- version_number: number;
3201
- content: string;
3202
- hash: string;
3203
- created_at_utc: string;
3204
- created_by: string;
3205
- }
3310
+ txId: string;
3311
+ type: 'TX_STARTED';
3312
+ } | {
3313
+ id: string;
3314
+ type: 'PONG';
3315
+ } | {
3316
+ id: string;
3317
+ type: 'TX_DONE';
3318
+ } | {
3319
+ type: 'READY';
3320
+ };
3206
3321
  /**
3207
3322
  * NotesRepository — CRUD and lifecycle operations for the note entity.
3208
3323
  *
@@ -3268,6 +3383,8 @@ declare class NotesRepository {
3268
3383
  /** User-authored original history is distinct from generated revision history. */
3269
3384
  getOriginalHistory(noteId: string): Promise<OriginalContentRevision[]>;
3270
3385
  }
3386
+ /** Local selection only. Hosted callers must supply their own authorized database context. */
3387
+ type SearchEvidenceScope = Pick<SearchOptions, 'archive_id' | 'metadataPredicates' | 'tenant_id' | 'visibility'>;
3271
3388
  /**
3272
3389
  * SearchRepository - full-text search using DatabaseClient tsvector/tsquery,
3273
3390
  * with optional semantic search (pgvector) and hybrid (BM25 + vector RRF).
@@ -3276,6 +3393,8 @@ declare class SearchRepository {
3276
3393
  private db;
3277
3394
  private semanticAvailable;
3278
3395
  constructor(db: DatabaseClient, semanticAvailable?: boolean);
3396
+ /** Candidate citation resolution with fresh local scope and content checks. */
3397
+ resolveEvidence(locator: unknown, scope?: SearchEvidenceScope): Promise<string>;
3279
3398
  private tsqueryFn;
3280
3399
  private fetchEmbeddingSet;
3281
3400
  private selectorFromOptions;
@@ -3384,6 +3503,9 @@ declare class SourceUpsertRepository {
3384
3503
  upsertRequest(request: SourceUpsertRequest, scope?: SourceUpsertScope): Promise<SourceUpsertResponse>;
3385
3504
  upsertBatch(items: readonly SourceUpsertItem[], options?: SourceUpsertOptions): Promise<SourceUpsertBatchResult>;
3386
3505
  }
3506
+ declare const LIFECYCLE_PURGE_MAX_NOTE_IDS = 500;
3507
+ declare const LIFECYCLE_PURGE_CONTRACT_VERSION: "1.0.0";
3508
+ declare const LIFECYCLE_PURGE_PREVIEW_TTL_SECONDS = 900;
3387
3509
  interface PurgeSelector {
3388
3510
  tenant_id?: string;
3389
3511
  archive_id?: null | string;
@@ -3405,33 +3527,52 @@ interface PurgeCounts {
3405
3527
  provenance_edges: number;
3406
3528
  source_identities: number;
3407
3529
  }
3530
+ interface PurgePreview {
3531
+ contract_version: typeof LIFECYCLE_PURGE_CONTRACT_VERSION;
3532
+ preview_id: string;
3533
+ counts: PurgeCounts;
3534
+ expires_at: string;
3535
+ }
3536
+ interface PurgeRequest {
3537
+ operation_id: string;
3538
+ preview_id: string;
3539
+ }
3540
+ type PurgeOutcome = 'cleanup_pending' | 'completed';
3541
+ interface PurgeReceiptPolicy {
3542
+ authority: 'Fortemi/fortemi#1092';
3543
+ mode: 'terminal_purge';
3544
+ receipt_contains_content: false;
3545
+ backup_disposition: 'beyond_use_then_reerase';
3546
+ restore_reerasure: true;
3547
+ }
3408
3548
  interface DeletionReceipt {
3409
- id: string;
3410
- operation_key: string;
3411
- tenant_id: string;
3412
- archive_id: null | string;
3413
- selector_hash: string;
3549
+ contract_version: typeof LIFECYCLE_PURGE_CONTRACT_VERSION;
3550
+ operation_id: string;
3414
3551
  outcome: 'completed';
3415
3552
  counts: PurgeCounts;
3416
3553
  completed_at: string;
3417
- policy: {
3418
- authority: 'fortemi#1092';
3419
- mode: 'terminal-purge';
3420
- receipt_contains_content: false;
3421
- };
3554
+ policy: PurgeReceiptPolicy;
3422
3555
  }
3423
- interface PurgePreview {
3424
- selector_hash: string;
3556
+ interface PurgeStatus {
3557
+ contract_version: typeof LIFECYCLE_PURGE_CONTRACT_VERSION;
3558
+ operation_id: string;
3559
+ outcome: PurgeOutcome;
3425
3560
  counts: PurgeCounts;
3561
+ blob_cleanup_pending: number;
3562
+ search_cleanup_pending: boolean;
3563
+ receipt?: DeletionReceipt;
3426
3564
  }
3427
3565
  declare class LifecyclePurgeRepository {
3428
3566
  private db;
3429
3567
  private events?;
3430
- constructor(db: DatabaseClient, events?: TypedEventBus | undefined);
3568
+ private blobStore?;
3569
+ constructor(db: DatabaseClient, events?: TypedEventBus | undefined, blobStore?: BlobStore | undefined);
3431
3570
  preview(selector: PurgeSelector): Promise<PurgePreview>;
3432
- purge(selector: PurgeSelector, operationKey: string): Promise<DeletionReceipt>;
3433
- private count;
3434
- private deleteSelected;
3571
+ begin(request: PurgeRequest): Promise<PurgeStatus>;
3572
+ status(operationId: string): Promise<null | PurgeStatus>;
3573
+ resume(operationId: string): Promise<PurgeStatus>;
3574
+ /** Compatibility convenience: create and consume a fresh preview. */
3575
+ purge(selector: PurgeSelector, operationId: string): Promise<DeletionReceipt>;
3435
3576
  }
3436
3577
  interface GraphNode {
3437
3578
  id: string;
@@ -3658,7 +3799,7 @@ interface ConditionResult {
3658
3799
  * @param startIdx - Starting parameter index ($N)
3659
3800
  * @param includeDeleted - Whether to include soft-deleted notes (default: false)
3660
3801
  */
3661
- declare function buildNoteConditions(options: Pick<SearchOptions, 'collection_id' | 'date_from' | 'date_to' | 'format' | 'is_archived' | 'is_starred' | 'source' | 'tags' | 'visibility'>, startIdx: number, includeDeleted?: boolean): ConditionResult;
3802
+ declare function buildNoteConditions(options: Pick<SearchOptions, 'collection_id' | 'date_from' | 'date_to' | 'format' | 'is_archived' | 'is_starred' | 'source' | 'sources' | 'tags' | 'tagsAll' | 'visibility'>, startIdx: number, includeDeleted?: boolean): ConditionResult;
3662
3803
  /**
3663
3804
  * Job queue worker — polls job_queue for pending jobs, dispatches to registered
3664
3805
  * handlers, manages status transitions and exponential backoff retries.
@@ -4303,13 +4444,6 @@ declare function manageNote(db: DatabaseClient, rawInput: unknown, events?: Type
4303
4444
  * Input is Zod-validated at entry.
4304
4445
  */
4305
4446
  declare function searchTool(db: DatabaseClient, rawInput: unknown): Promise<SearchResponse>;
4306
- /**
4307
- * Zod schemas for tool function inputs.
4308
- *
4309
- * These schemas are the contract between callers (e.g. host platform bridge) and
4310
- * the tool functions. All inputs are validated at the tool boundary so that
4311
- * repository methods only receive well-typed data.
4312
- */
4313
4447
  declare const CaptureKnowledgeInputSchema: z.ZodObject<{
4314
4448
  action: z.ZodEnum<[
4315
4449
  "create",
@@ -4421,6 +4555,7 @@ declare const ManageNoteInputSchema: z.ZodObject<{
4421
4555
  }>;
4422
4556
  type ManageNoteInput = z.infer<typeof ManageNoteInputSchema>;
4423
4557
  declare const SearchInputSchema: z.ZodObject<{
4558
+ archive_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
4424
4559
  collection_id: z.ZodOptional<z.ZodString>;
4425
4560
  date_from: z.ZodOptional<z.ZodDate>;
4426
4561
  date_to: z.ZodOptional<z.ZodDate>;
@@ -4434,6 +4569,7 @@ declare const SearchInputSchema: z.ZodObject<{
4434
4569
  is_archived: z.ZodOptional<z.ZodBoolean>;
4435
4570
  is_starred: z.ZodOptional<z.ZodBoolean>;
4436
4571
  limit: z.ZodDefault<z.ZodNumber>;
4572
+ metadataPredicates: z.ZodOptional<z.ZodEffects<z.ZodUnknown, readonly MetadataPredicate[], unknown>>;
4437
4573
  mode: z.ZodDefault<z.ZodEnum<[
4438
4574
  "text",
4439
4575
  "semantic",
@@ -4445,12 +4581,14 @@ declare const SearchInputSchema: z.ZodObject<{
4445
4581
  query: z.ZodString;
4446
4582
  source: z.ZodOptional<z.ZodString>;
4447
4583
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
4584
+ tenant_id: z.ZodOptional<z.ZodString>;
4448
4585
  visibility: z.ZodOptional<z.ZodEnum<[
4449
4586
  "private",
4450
4587
  "shared",
4451
4588
  "public"
4452
4589
  ]>>;
4453
4590
  }, "strip", z.ZodTypeAny, {
4591
+ archive_id?: null | string | undefined;
4454
4592
  collection_id?: string | undefined;
4455
4593
  date_from?: Date | undefined;
4456
4594
  date_to?: Date | undefined;
@@ -4460,14 +4598,17 @@ declare const SearchInputSchema: z.ZodObject<{
4460
4598
  is_archived?: boolean | undefined;
4461
4599
  is_starred?: boolean | undefined;
4462
4600
  limit: number;
4601
+ metadataPredicates?: readonly MetadataPredicate[] | undefined;
4463
4602
  mode: "auto" | "hybrid" | "semantic" | "text";
4464
4603
  offset: number;
4465
4604
  query_embedding?: number[] | undefined;
4466
4605
  query: string;
4467
4606
  source?: string | undefined;
4468
4607
  tags?: string[] | undefined;
4608
+ tenant_id?: string | undefined;
4469
4609
  visibility?: "private" | "public" | "shared" | undefined;
4470
4610
  }, {
4611
+ archive_id?: null | string | undefined;
4471
4612
  collection_id?: string | undefined;
4472
4613
  date_from?: Date | undefined;
4473
4614
  date_to?: Date | undefined;
@@ -4477,12 +4618,14 @@ declare const SearchInputSchema: z.ZodObject<{
4477
4618
  is_archived?: boolean | undefined;
4478
4619
  is_starred?: boolean | undefined;
4479
4620
  limit?: number | undefined;
4621
+ metadataPredicates?: unknown;
4480
4622
  mode?: "auto" | "hybrid" | "semantic" | "text" | undefined;
4481
4623
  offset?: number | undefined;
4482
4624
  query_embedding?: number[] | undefined;
4483
4625
  query: string;
4484
4626
  source?: string | undefined;
4485
4627
  tags?: string[] | undefined;
4628
+ tenant_id?: string | undefined;
4486
4629
  visibility?: "private" | "public" | "shared" | undefined;
4487
4630
  }>;
4488
4631
  type SearchInput = z.infer<typeof SearchInputSchema>;
@@ -6165,6 +6308,8 @@ interface AttachmentRecord extends PresenceTrackedRecord {
6165
6308
  id: string;
6166
6309
  note_id: string;
6167
6310
  blob_id: string;
6311
+ /** Optional preview bytes participate in the same shared-blob ownership rules. */
6312
+ preview_blob_id?: null | string;
6168
6313
  document_type_id: null | string;
6169
6314
  mime_type: null | string;
6170
6315
  extracted_text: null | string;
@@ -6233,15 +6378,43 @@ interface SourceImportBatchRecord extends PresenceTrackedRecord {
6233
6378
  }
6234
6379
  interface DeletionReceiptRecord extends PresenceTrackedRecord {
6235
6380
  id: string;
6236
- operation_key: string;
6237
- tenant_id: string;
6238
- archive_id: null | string;
6239
- selector_hash: string;
6240
- outcome: string;
6381
+ contract_version: string;
6382
+ operation_id: string;
6383
+ outcome: 'completed';
6241
6384
  counts: Record<string, number>;
6242
6385
  completed_at: string;
6243
6386
  policy: Record<string, unknown>;
6244
6387
  }
6388
+ interface LifecyclePurgePreviewRecord extends PresenceTrackedRecord {
6389
+ id: string;
6390
+ selector_fingerprint: string;
6391
+ selector: Record<string, unknown>;
6392
+ selected_note_ids: string[];
6393
+ counts: Record<string, number>;
6394
+ expires_at: string;
6395
+ consumed_by: null | string;
6396
+ }
6397
+ interface LifecyclePurgeOperationRecord extends PresenceTrackedRecord {
6398
+ id: string;
6399
+ preview_id: string;
6400
+ selector_fingerprint: string;
6401
+ state: 'cleanup_pending' | 'completed';
6402
+ counts: Record<string, number>;
6403
+ created_at: string;
6404
+ completed_at: null | string;
6405
+ }
6406
+ interface LifecyclePurgeErasureTargetRecord extends PresenceTrackedRecord {
6407
+ id: string;
6408
+ operation_id: string;
6409
+ note_id: string;
6410
+ }
6411
+ interface LifecyclePurgeBlobCleanupRecord extends PresenceTrackedRecord {
6412
+ id: string;
6413
+ operation_id: string;
6414
+ blob_id: string;
6415
+ content_hash: string;
6416
+ completed_at: null | string;
6417
+ }
6245
6418
  /** Collection name → record type. The store is generic over this map. */
6246
6419
  interface RecordCollections {
6247
6420
  note: NoteRecord0;
@@ -6259,6 +6432,10 @@ interface RecordCollections {
6259
6432
  source_import_run: SourceImportRunRecord;
6260
6433
  source_import_batch: SourceImportBatchRecord;
6261
6434
  deletion_receipt: DeletionReceiptRecord;
6435
+ lifecycle_purge_preview: LifecyclePurgePreviewRecord;
6436
+ lifecycle_purge_operation: LifecyclePurgeOperationRecord;
6437
+ lifecycle_purge_erasure_target: LifecyclePurgeErasureTargetRecord;
6438
+ lifecycle_purge_blob_cleanup: LifecyclePurgeBlobCleanupRecord;
6262
6439
  }
6263
6440
  type RecordCollectionName = keyof RecordCollections;
6264
6441
  declare const RECORD_COLLECTIONS: readonly RecordCollectionName[];
@@ -6292,8 +6469,10 @@ interface RecordStoreCapabilities {
6292
6469
  boundedTextScan: true;
6293
6470
  sourceAddressedUpsert?: true;
6294
6471
  deletionReceipts?: true;
6472
+ /** Purge can remove prior content-bearing journal entries atomically. */
6473
+ purgeJournalCompaction?: true;
6295
6474
  typedMetadataPredicates?: false;
6296
- evidenceLocators?: true;
6475
+ evidenceLocators?: false;
6297
6476
  fullTextSearch: false;
6298
6477
  vectorSearch: false;
6299
6478
  sqlJoins: false;
@@ -6314,6 +6493,10 @@ type RecordMutation = {
6314
6493
  id: string;
6315
6494
  op: 'delete';
6316
6495
  };
6496
+ interface RecordJournalKey {
6497
+ collection: RecordCollectionName;
6498
+ id: string;
6499
+ }
6317
6500
  /**
6318
6501
  * The writable canonical structured-record store. Implementations MUST make
6319
6502
  * each `put`/`remove` an atomic commit of the record mutation plus its
@@ -6331,6 +6514,11 @@ interface RecordStore {
6331
6514
  * An error leaves both record state and the journal unchanged.
6332
6515
  */
6333
6516
  applyBatch?(mutations: readonly RecordMutation[]): Promise<JournalEntry[]>;
6517
+ /**
6518
+ * Apply terminal-purge mutations while removing prior journal entries for
6519
+ * the supplied record identities in the same transaction.
6520
+ */
6521
+ applyPurgeBatch?(mutations: readonly RecordMutation[], scrubJournal: readonly RecordJournalKey[]): Promise<JournalEntry[]>;
6334
6522
  /** All records of a collection (insertion order not guaranteed). */
6335
6523
  list<C extends RecordCollectionName>(collection: C, opts?: RecordListOptions): Promise<RecordCollections[C][]>;
6336
6524
  /** Journal entries with `seq > sinceSeq`, ascending. */
@@ -6354,6 +6542,8 @@ declare class MemoryRecordStore implements RecordStore {
6354
6542
  put<C extends RecordCollectionName>(collection: C, record: RecordCollections[C]): Promise<JournalEntry>;
6355
6543
  remove(collection: RecordCollectionName, id: string): Promise<JournalEntry>;
6356
6544
  applyBatch(mutations: readonly RecordMutation[]): Promise<JournalEntry[]>;
6545
+ applyPurgeBatch(mutations: readonly RecordMutation[], scrubJournal: readonly RecordJournalKey[]): Promise<JournalEntry[]>;
6546
+ private commitBatch;
6357
6547
  list<C extends RecordCollectionName>(collection: C, opts?: RecordListOptions): Promise<RecordCollections[C][]>;
6358
6548
  journalSince(sinceSeq: number, limit?: number): Promise<JournalEntry[]>;
6359
6549
  headSeq(): Promise<number>;
@@ -6377,7 +6567,7 @@ declare class MemoryRecordStore implements RecordStore {
6377
6567
  * discipline.
6378
6568
  */
6379
6569
  /** Logical record-schema version stored in `meta` (independent of DB_VERSION). */
6380
- declare const RECORD_SCHEMA_VERSION = 3;
6570
+ declare const RECORD_SCHEMA_VERSION = 4;
6381
6571
  interface CreateRecordStoreOptions {
6382
6572
  /** Injectable factory for tests (fake-indexeddb). Defaults to the global. */
6383
6573
  indexedDB?: IDBFactory;
@@ -6392,6 +6582,8 @@ declare class IdbRecordStore implements RecordStore {
6392
6582
  put<C extends RecordCollectionName>(collection: C, record: RecordCollections[C]): Promise<JournalEntry>;
6393
6583
  remove(collection: RecordCollectionName, id: string): Promise<JournalEntry>;
6394
6584
  applyBatch(mutations: readonly RecordMutation[]): Promise<JournalEntry[]>;
6585
+ applyPurgeBatch(mutations: readonly RecordMutation[], scrubJournal: readonly RecordJournalKey[]): Promise<JournalEntry[]>;
6586
+ private commitBatch;
6395
6587
  list<C extends RecordCollectionName>(collection: C, opts?: RecordListOptions): Promise<RecordCollections[C][]>;
6396
6588
  journalSince(sinceSeq: number, limit?: number): Promise<JournalEntry[]>;
6397
6589
  headSeq(): Promise<number>;
@@ -6447,7 +6639,7 @@ declare class CanonicalNotesRepository {
6447
6639
  * Bounded substring scan over title + revised content (case-insensitive).
6448
6640
  * This is deliberately not ranked FTS — see `store.capabilities`.
6449
6641
  */
6450
- searchText(query: string, limit?: number): Promise<NoteRecord0[]>;
6642
+ searchText(query: string, limit?: number, accept?: (note: NoteRecord0) => boolean): Promise<NoteRecord0[]>;
6451
6643
  addTag(noteId: string, tag: string): Promise<void>;
6452
6644
  removeTag(noteId: string, tag: string): Promise<void>;
6453
6645
  notesByTag(tag: string): Promise<NoteRecord0[]>;
@@ -6657,13 +6849,18 @@ declare function exportShardFromRecords(store: RecordStore, options?: ExportOpti
6657
6849
  declare function importShardToRecords(store: RecordStore, data: ArrayBuffer | Uint8Array, options?: ImportOptions): Promise<ImportResult>;
6658
6850
  declare function upsertRecordStoreRequest(store: RecordStore, request: SourceUpsertRequest, scope?: SourceUpsertScope): Promise<SourceUpsertResponse>;
6659
6851
  declare function upsertRecordStoreSources(store: RecordStore, items: readonly SourceUpsertItem[], options?: SourceUpsertOptions): Promise<SourceUpsertBatchResult>;
6852
+ declare function recordStorePurgeStatus(store: RecordStore, operationId: string): Promise<null | PurgeStatus>;
6660
6853
  declare function previewRecordStorePurge(store: RecordStore, selector: PurgeSelector): Promise<PurgePreview>;
6661
- declare function purgeRecordStoreGraph(store: RecordStore, selector: PurgeSelector, operationKey: string): Promise<DeletionReceipt>;
6854
+ declare function beginRecordStorePurge(store: RecordStore, request: PurgeRequest, blobStore?: BlobStore): Promise<PurgeStatus>;
6855
+ declare function resumeRecordStorePurge(store: RecordStore, operationId: string, blobStore?: BlobStore): Promise<PurgeStatus>;
6856
+ /** Compatibility convenience that performs preview, deletion, and configured byte cleanup. */
6857
+ declare function purgeRecordStoreGraph(store: RecordStore, selector: PurgeSelector, operationId: string, blobStore?: BlobStore): Promise<DeletionReceipt>;
6858
+ declare function recordStoreErasureTargetIds(store: RecordStore, candidateNoteIds?: readonly string[]): Promise<Set<string>>;
6662
6859
  /**
6663
6860
  * @implements @.aiwg/adrs/ADR-011-shard-server-conformance-and-version-negotiation.md
6664
6861
  * @source @packages/core/src/shard/schema-validator.ts
6665
6862
  * @created 2026-07-17
6666
6863
  * @agent Codex
6667
6864
  */
6668
- declare const VERSION = "2026.9.5";
6669
- export { type ArchiveInfo, ArchiveManager, type AttachInput, type AttachmentBlobRecord, type AttachmentBlobRow, type AttachmentProjectionResult, type AttachmentRecord, type AttachmentRow, AttachmentsRepository, type BackendCandidate, type BackendCapabilities, type BackendConcept, type BackendLink, type BackendListOptions, type BackendNote, type BackendNoteFull, type BackendProvenanceEdge, type BackendRequest, type BackendSearchHit, type BackendSearchQueryOptions, type BackendSearchResult, type BackendSelection, type BackendSemanticTier, type BackendStartupCost, BlobGcOptions, BlobGcResult, BlobReconcileOptions, BlobReconcileResult, BlobStore, type BridgeCapability, BridgeInferenceProvider, type BridgeProviderInfo, type BrowserNoteExport, CORE_V1_COMPONENTS, CURRENT_MIGRATION_HEAD, type CanonicalAttachInput, CanonicalAttachmentsRepository, type CanonicalNoteCreateInput, type CanonicalNoteUpdateInput, type CanonicalNoteView, CanonicalNotesRepository, type CapabilityInfo, CapabilityManager, type CapabilityName, type CapabilityState, type CaptureKnowledgeInput, CaptureKnowledgeInputSchema, type CaptureKnowledgeResult, type CollectionCreateInput, type CollectionNoteRecord, type NativeCollection as CollectionRecord, type CollectionRow, CollectionsRepository, CommunitiesRepository, type NativeCommunityAssignment as CommunityAssignmentRecord, type CommunityAssignmentView, type CommunityCreateInput, type CommunityFilterDefinition, type CommunityGraph, type CommunityOptions, type NativeCommunity as CommunityRecord, type NativeCommunitySet as CommunitySetRecord, type CommunitySourceDescriptor, type CommunitySourceType, type CommunitySummary, type CompletionRequest, type CompletionResponse, type ConditionResult, type ConfigureInferenceRuntimeOptions, type ConfiguredInferenceProvider, type ConfiguredInferenceRuntime, type CooldownConfig, type CooldownEvent, type CosineSemanticProviderOptions, type CreatePGliteOptions, type CreateRecordStoreOptions, type CspDirectiveName, type CspDirectives, type CspViolationReport, DATASET_EXECUTION_CAPABILITY_IDS, DATASET_EXECUTION_CONTRACT, DATASET_EXECUTION_SCHEMA_VERSION, DATASET_INGEST_CONTRACT, DATASET_INGEST_SCHEMA_VERSION, DATASET_LINEAGE_CONTRACT, DATASET_LINEAGE_SCHEMA_VERSION, DATASET_MATERIALIZATION_CONTRACT, DATASET_MATERIALIZATION_KINDS, DATASET_MATERIALIZATION_SCHEMA_VERSION, DB_SNAPSHOT_SCHEMA_VERSION, DEFAULT_LARGE_DOCUMENT_CHARS, DEFAULT_LARGE_DOCUMENT_CHUNKS, type DataBackend, type DatabaseClient, type DatasetBenchmarkEvidence, type DatasetCapabilityDeclaration, type DatasetCapabilityDegradation, type DatasetCapabilityDiagnostic, type DatasetCapabilityDiagnosticCode, type DatasetCapabilityEvidence, type DatasetCapabilityLimits, type DatasetCapabilityNegotiationRequest, type DatasetCapabilityNegotiationResult, type DatasetCapabilityRequirement, type DatasetCapabilityStatus, type DatasetCapabilityWireResult, type DatasetCheckpoint, type DatasetDestinationScope, type DatasetDeterminismClass, type DatasetDigest, type DatasetExecutionCapabilityDescriptor, type DatasetExecutionCapabilityId, type DatasetExecutionDataClass, type DatasetExecutionMaturity, type DatasetExecutionPlane, type DatasetImplementationIdentity, type DatasetIncrementalParityResult, DatasetIngestError, type DatasetIngestErrorCode, DatasetIngestExecutor, type DatasetIngestHooks, type DatasetIngestMode, type DatasetIngestStore, type DatasetIngestTransaction, DatasetLineageLedger, type DatasetLineageLedgerOptions, type DatasetMaterializationAdapter, type DatasetMaterializationArtifact, DatasetMaterializationError, type DatasetMaterializationKind, type DatasetMaterializationOperation, type DatasetMaterializationProfile, type DatasetMaterializationReceipt, type DatasetMaterializationRequest, type DatasetMeasuredResources, type DatasetMutation, type DatasetMutationBatch, type DatasetOptionalCapabilityRequirement, type DatasetPrivacyBoundary, type DatasetPrivacyDecision, type DatasetProcessingPlan, type DatasetProfileNegotiationRequest, type DatasetProfileNegotiationResult, type DatasetProfileStatus, type DatasetRecordAuthorizer, type DatasetRecordRejection, type DatasetRetrievalRequest, type DatasetRetrievalResponse, type DatasetRunAttempt, type DatasetRunReceipt, type DatasetRunState, type DatasetRunStatus, type DatasetSourceRecord, type DatasetSourceSnapshot, type DatasetStoredRecord, type DatasetTombstoneMutation, type DatasetUpsertMutation, type DatasetVerificationState, type DbSnapshot, type DbSnapshotCompat, type DbSnapshotCompression, type DbSnapshotExpectations, type DbSnapshotMeta, type DbSnapshotSource, DbSnapshotVersionError, type DeletionReceipt, type DeletionReceiptRecord, type DiscoveredProvider, type DiscoveryOptions, type DumpDbSnapshotOptions, type DumpableDb, EMBED_REQUEST_KIND, EMBED_RESPONSE_KIND, type EmbedFunction, type EmbedFunctionOptions, type EmbedRequest, type EmbedRequestMessage, type EmbedResponse, type EmbedResponseMessage, type EmbedTransportPort, type EmbedWorkerOptions, type EmbeddingCompatibilityPolicy, type EmbeddingConfigRow, type EmbeddingMemberRow, type EmbeddingRow, type EmbeddingSetCreateInput, type EmbeddingSetCriteria, type EmbeddingSetDescriptor, type EmbeddingSetEmbeddingInput, type EmbeddingSetFreshness, type EmbeddingSetKind, type EmbeddingSetMode, type EmbeddingSetRow, type EmbeddingSetSelector, EmbeddingSetsRepository, type EmbeddingTaskSelectionOptions, type EnqueueJobInput, type ErrorCategory, type EventMap, type EvidenceLocator, type ExecuteDatasetBatchOptions, ExportOptions, FORTEMI_BROWSER_LOCAL_DATASET_EXECUTION_DESCRIPTOR, FORTEMI_COMPATIBILITY_PATH, FORTEMI_COMPATIBILITY_STATES, FORTEMI_PORTABLE_SHARD_DATASET_EXECUTION_DESCRIPTOR, FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES, FORTEMI_SERVER_COMPATIBILITY_REVISION, FORTEMI_STATIC_CACHE_DATASET_EXECUTION_DESCRIPTOR, type FallbackEvent, FallbackRouter, type FallbackRouterConfig, type FetchFortemiCompatibilityOptions, type FortemiBridge, type FortemiBridgeCapabilities, type FortemiBridgeHost, type FortemiCompatibilityCapability, type FortemiCompatibilityResponse, type FortemiCompatibilityState, type FortemiCompatibilityValidationResult, type FortemiConfig, type FortemiCore, type FortemiInferenceRouter, type FortemiRequiredCompatibilityCapability, type FortemiSecretStore, type FortemiToolDefinition, FortemiToolManifest, type FullV1SnapshotImportOptions, type GetNoteInput, GetNoteInputSchema, type GpuCapabilities, type GraphCommunity, type GraphEdge, type NativeGraphEdge as GraphEdgeRecord, type GraphNode, GraphRepository, type NativeGraphSource as GraphSourceRecord, type IDisposable, IdbRecordStore, ImportOptions, ImportResult, type InferenceCapabilities, type InferenceProvider, type InferenceRuntimeConfig, type InferenceTask, JOB_CAPABILITIES, JOB_PRIORITIES, type JobQueueOptions, JobQueueWorker, type JobStatus, type JobType, type JournalEntry, LINEAGE_ENTITY_KINDS, LINEAGE_RELATIONSHIP_KINDS, LOCAL_ENDPOINTS, type LegacyInferenceProviderConfig, type LegacyMigrationReport, LifecyclePurgeRepository, type LineageActivity, type LineageAgent, type LineageAssertion, type LineageAssertionKind, type LineageAuthorizationPolicy, type LineageCorrection, type LineageEntity, type LineageEntityKind, type LineageEvidence, type LineageEvidenceReference, type LineageLedgerArchive, type LineageLossItem, type LineageLossReceipt, type LineagePrivacy, type LineageProjection, type LineageProjectionCapabilities, type LineageRelationshipKind, type LineageTraversalEdge, type LineageTraversalNode, type LineageTraversalRequest, type LineageTraversalResult, type LineageValidationCode, LineageValidationError, type NativeLink as LinkRecord, type LinkRecord0, type LinkRow, LinksRepository, type ListNotesInput, ListNotesInputSchema, type LlmCapabilityOptions, type LlmCompleteFn, type LlmCompleteOptions, type LoadedPluginScript, type LocalEndpoint, type ManageArchiveInput, ManageArchiveInputSchema, type ManageArchiveResult, type ManageAttachmentsInput, ManageAttachmentsInputSchema, type ManageAttachmentsResult, type ManageCapabilitiesInput, ManageCapabilitiesInputSchema, type ManageCapabilitiesResult, type ManageCollectionsInput, ManageCollectionsInputSchema, type ManageCollectionsResult, type ManageLinksInput, ManageLinksInputSchema, type ManageLinksResult, type ManageNoteInput, ManageNoteInputSchema, type ManageNoteResult, type ManageTagsInput, ManageTagsInputSchema, type ManageTagsResult, MemoryDatasetIngestStore, MemoryRecordStore, type MetadataPredicate, type Migration, MigrationRunner, type ModelCategory, type ModelFitResult, type ModelInfo, type NativeNamedLocation as NamedLocation, type NativeAttachmentProjection as NativeAttachmentRecord, type NativeNote as NativeNoteRecord, type NoteCreateInput, type NoteFull, type NoteListOptions, type NoteOriginalRecord, type NoteProjectionResult, type NoteRecord0, type NoteRevisedCurrentRecord, type NoteRevision, type NoteRevisionRecord, type NativeNoteSkosTag as NoteSkosAssignment, type NoteSkosTag, type NoteSummary, type NoteTagRecord, type NoteUpdateInput, NotesRepository, OpenAICompatibleProvider, type OpenAIProviderConfig, type OpenShardOptions, type OriginalContentRevision, type PGliteBackendOptions, PGliteStorageBackend, PGliteStorageBackendFactory, PGliteWorkerClient, PGliteWorkerStorageBackend, PGliteWorkerStorageBackendFactory, type PGliteWorkerStorageBackendFactoryOptions, type PaginatedResult, type PersistenceMode, type PluginCspOptions, type PluginScriptDescriptor, type PluginScriptPolicy, type PrefetchOptions, type PrefetchResult, type PresenceTrackedRecord, type ProbeResult, type ProbeStatus, type NativeProvenanceActivity as ProvenanceActivity, type NativeProvenanceRecord as ProvenanceCapture, type NativeProvenanceEdge as ProvenanceDerivation, type NativeProvenanceDevice as ProvenanceDevice, type ProvenanceEdge, type NativeProvenanceLocation as ProvenanceLocation, ProvenanceRepository, type NativeTimestampRange as ProvenanceTimeRange, type ProviderCapabilities, type ProviderCostTier, type ProviderDataClass, type ProviderPrivacyTier, type ProviderProfile, ProviderRegistry, type ProviderRoutePolicy, type ProviderRouteProbeResult, type ProviderRouteRequirements, type ProviderRouteSelection, type ProviderRouteValidation, type ProviderRouteValidationIssue, type ProviderRouteValidationSeverity, type ProviderTier, type PurgeCounts, type PurgePreview, type PurgeSelector, type QueryExecutor, type QueryResult, RECORD_COLLECTIONS, RECORD_SCHEMA_VERSION, RECORD_STORE_CAPABILITIES, REGISTERED_METADATA_PATHS, type RecommendedTier, type RecordBackendManageNoteResult, type RecordBackendOptions, type RecordCollectionName, type RecordCollections, type RecordListOptions, type RecordMutation, type RecordProjectionResult, type RecordProvenanceInput, type RecordStore, type RecordStoreCapabilities, type RegisteredMetadataPath, type RemoteBackendConfig, RemoteBackendError, type RemoteBackendErrorKind, type RemoteBackendPaths, type RemoteDataBackend, type RemoteManageNoteInput, type RemoteManageNoteResult, type RemoteProvenanceGraph, type RemoteSearchDegradation, type RemoteSearchMetadata, type RemoteSearchMode, type RemoteSearchOptions, type RemoteSearchResult, type ResolvedEmbeddingRow, type ResolvedEmbeddingSet, type RestoreDbSnapshotOptions, type RouteHandler, SOURCE_UPSERT_CONTRACT_VERSION, SOURCE_UPSERT_MAX_ITEMS, SUPPORTED_PGLITE_VERSION, type SWRegistrationResult, type SearchFacets, type SearchInput, SearchInputSchema, type SearchOptions, SearchRepository, type SearchResponse, type SearchResult, ShardBackend, type ShardBackendOptions, ShardCapabilityReport, ShardCollection, ShardComponent, type ShardComponentStore, ShardEmbedding, ShardEmbeddingConfig, ShardEmbeddingSet, ShardEmbeddingSetMember, ShardExportResult, ShardLink, type ShardListOptions, ShardLossEntry, ShardManifest, ShardNote, type ShardNoteFull, ShardNoteSkosTag, ShardOperation, ShardProfileRegistryEntry, ShardProvenanceEdge, type ShardReader, type ShardReaderNote, type ShardReaderSource, type ShardSchemaValidationResult, type ShardSearchOptions, type ShardSearchRankedNote, type ShardSearchResult, type ShardSearchWeights, ShardSkosConcept, ShardSkosRelation, ShardSkosScheme, ShardTag, ShardTemplate, type SimilarityGraphCacheKey, type SimilarityGraphOptions, type SimilarityGraphRequest, type SimilarityGraphResult, type NativeSkosCollection as SkosCollection, type NativeSkosCollectionMember as SkosCollectionMember, type SkosConcept, type NativeSkosConcept as SkosConceptRecord, type NativeSkosLabel as SkosLabel, type NativeSkosMapping as SkosMapping, type NativeSkosMembership as SkosMembership, type NativeSkosNote as SkosNote, type SkosRelation, SkosRepository, type SkosScheme, type NativeSkosScheme as SkosSchemeRecord, type SourceIdentityInput, type SourceIdentityRecord, type SourceImportBatchRecord, type SourceImportRunRecord, type SourceUpsertBatchOutcome, type SourceUpsertBatchResult, type SourceUpsertItem, type SourceUpsertItemResult, type SourceUpsertOptions, type SourceUpsertOutcome, type SourceUpsertPolicy, type SourceUpsertReasonCode, SourceUpsertRepository, type SourceUpsertRequest, type SourceUpsertRequestItem, type SourceUpsertResponse, type SourceUpsertScope, type StaticSemanticProvider, type StorageBackend, type StorageBackendFactory, type StorageOpenRequest, type StorageTopology, type StreamChunk, type NativeTag as TagRecord, TagsRepository, type TemplateCreateInput, type NativeTemplate as TemplateRecord, TemplatesRepository, TransactionProxy, TypedEventBus, VERSION, type VectorEntry, type VirtualEmbeddingSetDefinition, type VirtualEmbeddingSetSource, type VirtualEmbeddingSetValidationError, type VirtualMaterializationPolicy, type VramTier, type WorkerRequest, type WorkerResponse, aiRevisionHandler, allMigrations, appendPluginScript, assertShardComponentRecord, buildMetadataPredicateConditions, buildNoteConditions, buildPluginCsp, captureKnowledge, chunkText, classifyError, classifyModel, clearPrefetchedShard, collectionFromShard, collectionToShard, compareDatasetIncrementalParity, computeBlobHash, computeHash, computeLineageDigest, computeSri, conceptTaggingHandler, configureInferenceRuntime, cosineSimilarity, createBridgeInferenceProviders, createCosineSemanticProvider, createCspReportHandler, createFortemi, createLegacyProvider, createLocalProviderProfile, createPGliteBackend, createPGliteInstance, createRecordBackend, createRecordStore, createRemoteBackend, createRoutes, createShardBackend, createShardCapabilityReport, createWorkerEmbedFunction, datasetDestinationScopeKey, defaultStorageBackendFactory, defineInferenceProvider, defineInferenceRuntime, defineLegacyInferenceProvider, defineOpenAICompatibleProvider, deriveDatasetIngestIdempotencyKey, detectCommunities, detectGpuCapabilities, detectInferenceCapabilities, digestDatasetMaterializationValue, discoverLocalProviders, dropAttachmentProjection, dropNoteProjection, dumpDbSnapshot, embeddingConfigToShard, embeddingFromShard, embeddingGenerationHandler, embeddingSetFromShard, embeddingSetMemberToShard, embeddingSetToShard, embeddingToShard, enqueueFullWorkflow, enqueueJob, enqueueNoteCreationJobs, estimateModelFit, estimateVramMB, estimateVramTier, executeDatasetMaterialization, executeDatasetRetrieval, exportFullV1Snapshot, exportShard, exportShardFromRecords, exportShardFromRecordsWithReport, exportShardWithReport, fetchAndValidateFortemiCompatibility, fetchPluginScript, formatFortemiCompatibilitySummary, fortemiCompatibilityUrl, fortemiManifest, fromPrefetched, generateId, getConfiguredInferenceProviderId, getEmbedFunction, getEmbeddingTaskSelectionOptions, getFortemiBridge, getFortemiSecretStore, getJobQueueStatus, getKnowledgeShardContractReceipt, getKnowledgeShardProfileRegistry, getKnowledgeShardSchema, getLlmFunction, getNote, getPrefetchedSha256, getProviderRouteRequirementIssue, handleEmbedRequests, hasFortemiSecureSecrets, importFullV1Snapshot, importShard, importShardToRecords, inferInferenceTaskCapability, inferLocalEmbeddingDimensions, isPluginScriptAllowed, isShardPrefetched, linkFromShard, linkToShard, linkingHandler, listNotes, manageArchive, manageAttachments, manageCapabilities, manageCollections, manageLinks, manageNote, manageTags, matchRoute, mergeInferenceRuntimeConfigs, migrateLegacyBlobStore, negotiateDatasetExecutionCapabilities, negotiateDatasetExecutionCapabilitiesFromWire, negotiateDatasetMaterializationProfile, noteFromShard, noteSkosTagToShard, noteToShard, openShard, packTarGz, parseCspReport, prefetchShard, previewRecordStorePurge, profileSupportError, projectAttachments, projectNotes, projectRecords, provenanceEdgeToShard, providerSatisfiesRouteRequirements, purgeRecordStoreGraph, registerLlmCapability, registerSemanticCapability, registerSemanticCapabilityWorker, registerServiceWorker, restoreDbSnapshot, searchTool, selectBackend, selectEmbeddingTask, selectLlmModel, setEmbedFunction, setEmbeddingTaskSelectionOptions, setLlmFunction, sha256Hex, skosConceptToShard, skosRelationToShard, skosSchemeToShard, suggestTags, tagsToShard, templateToShard, titleGenerationHandler, unpackTarGz, unregisterLlmCapability, unregisterSemanticCapability, upsertRecordStoreRequest, upsertRecordStoreSources, urlLinkToShard, validateChecksums, validateCoreV1ShardArchive, validateDatasetBenchmarkEvidence, validateDatasetExecutionDescriptor, validateDatasetExecutionRequest, validateFortemiCompatibilityResponse, validateFullV1ShardArchive, validateProviderRoute, validateRecordV1ShardArchive, validateShardArchive, validateShardComponentRecord, validateShardManifest, verifyDbSnapshotMeta, verifySri };
6865
+ declare const VERSION = "2026.9.7";
6866
+ export { type ArchiveInfo, ArchiveManager, type AttachInput, type AttachmentBlobRecord, type AttachmentBlobRow, type AttachmentProjectionResult, type AttachmentRecord, type AttachmentRow, AttachmentsRepository, type BackendCandidate, type BackendCapabilities, type BackendConcept, type BackendLink, type BackendListOptions, type BackendNote, type BackendNoteFull, type BackendProvenanceEdge, type BackendRequest, type BackendSearchHit, type BackendSearchQueryOptions, type BackendSearchResult, type BackendSelection, type BackendSemanticTier, type BackendStartupCost, BlobGcOptions, BlobGcResult, BlobReconcileOptions, BlobReconcileResult, BlobStore, type BridgeCapability, BridgeInferenceProvider, type BridgeProviderInfo, type BrowserNoteExport, CORE_V1_COMPONENTS, CURRENT_MIGRATION_HEAD, type CanonicalAttachInput, CanonicalAttachmentsRepository, type CanonicalNoteCreateInput, type CanonicalNoteUpdateInput, type CanonicalNoteView, CanonicalNotesRepository, type CapabilityInfo, CapabilityManager, type CapabilityName, type CapabilityState, type CaptureKnowledgeInput, CaptureKnowledgeInputSchema, type CaptureKnowledgeResult, type CollectionCreateInput, type CollectionNoteRecord, type NativeCollection as CollectionRecord, type CollectionRow, CollectionsRepository, CommunitiesRepository, type NativeCommunityAssignment as CommunityAssignmentRecord, type CommunityAssignmentView, type CommunityCreateInput, type CommunityFilterDefinition, type CommunityGraph, type CommunityOptions, type NativeCommunity as CommunityRecord, type NativeCommunitySet as CommunitySetRecord, type CommunitySourceDescriptor, type CommunitySourceType, type CommunitySummary, type CompletionRequest, type CompletionResponse, type ConditionResult, type ConfigureInferenceRuntimeOptions, type ConfiguredInferenceProvider, type ConfiguredInferenceRuntime, type CooldownConfig, type CooldownEvent, type CosineSemanticProviderOptions, type CreatePGliteOptions, type CreateRecordStoreOptions, type CspDirectiveName, type CspDirectives, type CspViolationReport, DATASET_EXECUTION_CAPABILITY_IDS, DATASET_EXECUTION_CONTRACT, DATASET_EXECUTION_SCHEMA_VERSION, DATASET_INGEST_CONTRACT, DATASET_INGEST_SCHEMA_VERSION, DATASET_LINEAGE_CONTRACT, DATASET_LINEAGE_SCHEMA_VERSION, DATASET_MATERIALIZATION_CONTRACT, DATASET_MATERIALIZATION_KINDS, DATASET_MATERIALIZATION_SCHEMA_VERSION, DB_SNAPSHOT_SCHEMA_VERSION, DEFAULT_LARGE_DOCUMENT_CHARS, DEFAULT_LARGE_DOCUMENT_CHUNKS, type DataBackend, type DatabaseClient, type DatasetBenchmarkEvidence, type DatasetCapabilityDeclaration, type DatasetCapabilityDegradation, type DatasetCapabilityDiagnostic, type DatasetCapabilityDiagnosticCode, type DatasetCapabilityEvidence, type DatasetCapabilityLimits, type DatasetCapabilityNegotiationRequest, type DatasetCapabilityNegotiationResult, type DatasetCapabilityRequirement, type DatasetCapabilityStatus, type DatasetCapabilityWireResult, type DatasetCheckpoint, type DatasetDestinationScope, type DatasetDeterminismClass, type DatasetDigest, type DatasetExecutionCapabilityDescriptor, type DatasetExecutionCapabilityId, type DatasetExecutionDataClass, type DatasetExecutionMaturity, type DatasetExecutionPlane, type DatasetImplementationIdentity, type DatasetIncrementalParityResult, DatasetIngestError, type DatasetIngestErrorCode, DatasetIngestExecutor, type DatasetIngestHooks, type DatasetIngestMode, type DatasetIngestStore, type DatasetIngestTransaction, DatasetLineageLedger, type DatasetLineageLedgerOptions, type DatasetMaterializationAdapter, type DatasetMaterializationArtifact, DatasetMaterializationError, type DatasetMaterializationKind, type DatasetMaterializationOperation, type DatasetMaterializationProfile, type DatasetMaterializationReceipt, type DatasetMaterializationRequest, type DatasetMeasuredResources, type DatasetMutation, type DatasetMutationBatch, type DatasetOptionalCapabilityRequirement, type DatasetPrivacyBoundary, type DatasetPrivacyDecision, type DatasetProcessingPlan, type DatasetProfileNegotiationRequest, type DatasetProfileNegotiationResult, type DatasetProfileStatus, type DatasetRecordAuthorizer, type DatasetRecordRejection, type DatasetRetrievalRequest, type DatasetRetrievalResponse, type DatasetRunAttempt, type DatasetRunReceipt, type DatasetRunState, type DatasetRunStatus, type DatasetSourceRecord, type DatasetSourceSnapshot, type DatasetStoredRecord, type DatasetTombstoneMutation, type DatasetUpsertMutation, type DatasetVerificationState, type DbSnapshot, type DbSnapshotCompat, type DbSnapshotCompression, type DbSnapshotExpectations, type DbSnapshotMeta, type DbSnapshotSource, DbSnapshotVersionError, type DeletionReceipt, type DeletionReceiptRecord, type DiscoveredProvider, type DiscoveryOptions, type DumpDbSnapshotOptions, type DumpableDb, EMBED_REQUEST_KIND, EMBED_RESPONSE_KIND, type EmbedFunction, type EmbedFunctionOptions, type EmbedRequest, type EmbedRequestMessage, type EmbedResponse, type EmbedResponseMessage, type EmbedTransportPort, type EmbedWorkerOptions, type EmbeddingCompatibilityPolicy, type EmbeddingConfigRow, type EmbeddingMemberRow, type EmbeddingRow, type EmbeddingSetCreateInput, type EmbeddingSetCriteria, type EmbeddingSetDescriptor, type EmbeddingSetEmbeddingInput, type EmbeddingSetFreshness, type EmbeddingSetKind, type EmbeddingSetMode, type EmbeddingSetRow, type EmbeddingSetSelector, EmbeddingSetsRepository, type EmbeddingTaskSelectionOptions, type EnqueueJobInput, type ErrorCategory, type EventMap, type EvidenceLocator, type EvidenceSourceIdentity, type EvidenceTextSnapshot, type EvidenceTextUnit, type ExecuteDatasetBatchOptions, ExportOptions, FORTEMI_BROWSER_LOCAL_DATASET_EXECUTION_DESCRIPTOR, FORTEMI_COMPATIBILITY_PATH, FORTEMI_COMPATIBILITY_STATES, FORTEMI_PORTABLE_SHARD_DATASET_EXECUTION_DESCRIPTOR, FORTEMI_REQUIRED_COMPATIBILITY_CAPABILITIES, FORTEMI_SERVER_COMPATIBILITY_REVISION, FORTEMI_STATIC_CACHE_DATASET_EXECUTION_DESCRIPTOR, type FallbackEvent, FallbackRouter, type FallbackRouterConfig, type FetchFortemiCompatibilityOptions, type FortemiBridge, type FortemiBridgeCapabilities, type FortemiBridgeHost, type FortemiCompatibilityCapability, type FortemiCompatibilityResponse, type FortemiCompatibilityState, type FortemiCompatibilityValidationResult, type FortemiConfig, type FortemiCore, type FortemiInferenceRouter, type FortemiRequiredCompatibilityCapability, type FortemiSecretStore, type FortemiToolDefinition, FortemiToolManifest, type FullV1SnapshotImportOptions, type GetNoteInput, GetNoteInputSchema, type GpuCapabilities, type GraphCommunity, type GraphEdge, type NativeGraphEdge as GraphEdgeRecord, type GraphNode, GraphRepository, type NativeGraphSource as GraphSourceRecord, type IDisposable, IdbRecordStore, ImportOptions, ImportResult, type InferenceCapabilities, type InferenceProvider, type InferenceRuntimeConfig, type InferenceTask, JOB_CAPABILITIES, JOB_PRIORITIES, type JobQueueOptions, JobQueueWorker, type JobStatus, type JobType, type JournalEntry, LIFECYCLE_PURGE_CONTRACT_VERSION, LIFECYCLE_PURGE_MAX_NOTE_IDS, LIFECYCLE_PURGE_PREVIEW_TTL_SECONDS, LINEAGE_ENTITY_KINDS, LINEAGE_RELATIONSHIP_KINDS, LOCAL_ENDPOINTS, type LegacyInferenceProviderConfig, type LegacyMigrationReport, type LifecyclePurgeBlobCleanupRecord, type LifecyclePurgeErasureTargetRecord, type LifecyclePurgeOperationRecord, type LifecyclePurgePreviewRecord, LifecyclePurgeRepository, type LineageActivity, type LineageAgent, type LineageAssertion, type LineageAssertionKind, type LineageAuthorizationPolicy, type LineageCorrection, type LineageEntity, type LineageEntityKind, type LineageEvidence, type LineageEvidenceReference, type LineageLedgerArchive, type LineageLossItem, type LineageLossReceipt, type LineagePrivacy, type LineageProjection, type LineageProjectionCapabilities, type LineageRelationshipKind, type LineageTraversalEdge, type LineageTraversalNode, type LineageTraversalRequest, type LineageTraversalResult, type LineageValidationCode, LineageValidationError, type NativeLink as LinkRecord, type LinkRecord0, type LinkRow, LinksRepository, type ListNotesInput, ListNotesInputSchema, type LlmCapabilityOptions, type LlmCompleteFn, type LlmCompleteOptions, type LoadedPluginScript, type LocalEndpoint, type ManageArchiveInput, ManageArchiveInputSchema, type ManageArchiveResult, type ManageAttachmentsInput, ManageAttachmentsInputSchema, type ManageAttachmentsResult, type ManageCapabilitiesInput, ManageCapabilitiesInputSchema, type ManageCapabilitiesResult, type ManageCollectionsInput, ManageCollectionsInputSchema, type ManageCollectionsResult, type ManageLinksInput, ManageLinksInputSchema, type ManageLinksResult, type ManageNoteInput, ManageNoteInputSchema, type ManageNoteResult, type ManageTagsInput, ManageTagsInputSchema, type ManageTagsResult, MemoryDatasetIngestStore, MemoryRecordStore, type MetadataPredicate, type Migration, MigrationRunner, type ModelCategory, type ModelFitResult, type ModelInfo, type NativeNamedLocation as NamedLocation, type NativeAttachmentProjection as NativeAttachmentRecord, type NativeNote as NativeNoteRecord, type NoteCreateInput, type NoteFull, type NoteListOptions, type NoteOriginalRecord, type NoteProjectionResult, type NoteRecord0, type NoteRevisedCurrentRecord, type NoteRevision, type NoteRevisionRecord, type NativeNoteSkosTag as NoteSkosAssignment, type NoteSkosTag, type NoteSummary, type NoteTagRecord, type NoteUpdateInput, NotesRepository, OpenAICompatibleProvider, type OpenAIProviderConfig, type OpenShardOptions, type OriginalContentRevision, type PGliteBackendOptions, PGliteStorageBackend, PGliteStorageBackendFactory, PGliteWorkerClient, PGliteWorkerStorageBackend, PGliteWorkerStorageBackendFactory, type PGliteWorkerStorageBackendFactoryOptions, type PaginatedResult, type PersistenceMode, type PluginCspOptions, type PluginScriptDescriptor, type PluginScriptPolicy, type PrefetchOptions, type PrefetchResult, type PresenceTrackedRecord, type ProbeResult, type ProbeStatus, type NativeProvenanceActivity as ProvenanceActivity, type NativeProvenanceRecord as ProvenanceCapture, type NativeProvenanceEdge as ProvenanceDerivation, type NativeProvenanceDevice as ProvenanceDevice, type ProvenanceEdge, type NativeProvenanceLocation as ProvenanceLocation, ProvenanceRepository, type NativeTimestampRange as ProvenanceTimeRange, type ProviderCapabilities, type ProviderCostTier, type ProviderDataClass, type ProviderPrivacyTier, type ProviderProfile, ProviderRegistry, type ProviderRoutePolicy, type ProviderRouteProbeResult, type ProviderRouteRequirements, type ProviderRouteSelection, type ProviderRouteValidation, type ProviderRouteValidationIssue, type ProviderRouteValidationSeverity, type ProviderTier, type PurgeCounts, type PurgeOutcome, type PurgePreview, type PurgeReceiptPolicy, type PurgeRequest, type PurgeSelector, type PurgeStatus, type QueryExecutor, type QueryResult, RECORD_COLLECTIONS, RECORD_SCHEMA_VERSION, RECORD_STORE_CAPABILITIES, REGISTERED_METADATA_PATHS, type RecommendedTier, type RecordBackendManageNoteResult, type RecordBackendOptions, type RecordCollectionName, type RecordCollections, type RecordJournalKey, type RecordListOptions, type RecordMutation, type RecordProjectionResult, type RecordProvenanceInput, type RecordStore, type RecordStoreCapabilities, type RegisteredMetadataPath, type RemoteBackendConfig, RemoteBackendError, type RemoteBackendErrorKind, type RemoteBackendPaths, type RemoteDataBackend, type RemoteEvidenceResolutionOptions, type RemoteManageNoteInput, type RemoteManageNoteResult, type RemoteProvenanceGraph, type RemoteSearchDegradation, type RemoteSearchMetadata, type RemoteSearchMode, type RemoteSearchOptions, type RemoteSearchResult, type ResolvedEmbeddingRow, type ResolvedEmbeddingSet, type RestoreDbSnapshotOptions, type RouteHandler, SOURCE_UPSERT_CONTRACT_VERSION, SOURCE_UPSERT_MAX_ITEMS, SUPPORTED_PGLITE_VERSION, type SWRegistrationResult, type SearchEvidenceLocator, type SearchEvidenceOmission, type SearchEvidenceScope, type SearchEvidenceSet, type SearchFacets, type SearchInput, SearchInputSchema, type SearchOptions, SearchRepository, type SearchResponse, type SearchResult, ShardBackend, type ShardBackendOptions, ShardCapabilityReport, ShardCollection, ShardComponent, type ShardComponentStore, ShardEmbedding, ShardEmbeddingConfig, ShardEmbeddingSet, ShardEmbeddingSetMember, ShardExportResult, ShardLink, type ShardListOptions, ShardLossEntry, ShardManifest, ShardNote, type ShardNoteFull, ShardNoteSkosTag, ShardOperation, ShardProfileRegistryEntry, ShardProvenanceEdge, type ShardReader, type ShardReaderNote, type ShardReaderSource, type ShardSchemaValidationResult, type ShardSearchOptions, type ShardSearchRankedNote, type ShardSearchResult, type ShardSearchWeights, ShardSkosConcept, ShardSkosRelation, ShardSkosScheme, ShardTag, ShardTemplate, type SimilarityGraphCacheKey, type SimilarityGraphOptions, type SimilarityGraphRequest, type SimilarityGraphResult, type NativeSkosCollection as SkosCollection, type NativeSkosCollectionMember as SkosCollectionMember, type SkosConcept, type NativeSkosConcept as SkosConceptRecord, type NativeSkosLabel as SkosLabel, type NativeSkosMapping as SkosMapping, type NativeSkosMembership as SkosMembership, type NativeSkosNote as SkosNote, type SkosRelation, SkosRepository, type SkosScheme, type NativeSkosScheme as SkosSchemeRecord, type SourceIdentityInput, type SourceIdentityRecord, type SourceImportBatchRecord, type SourceImportRunRecord, type SourceUpsertBatchOutcome, type SourceUpsertBatchResult, type SourceUpsertItem, type SourceUpsertItemResult, type SourceUpsertOptions, type SourceUpsertOutcome, type SourceUpsertPolicy, type SourceUpsertReasonCode, SourceUpsertRepository, type SourceUpsertRequest, type SourceUpsertRequestItem, type SourceUpsertResponse, type SourceUpsertScope, type StaticSemanticProvider, type StorageBackend, type StorageBackendFactory, type StorageOpenRequest, type StorageTopology, type StreamChunk, type NativeTag as TagRecord, TagsRepository, type TemplateCreateInput, type NativeTemplate as TemplateRecord, TemplatesRepository, TransactionProxy, TypedEventBus, VERSION, type VectorEntry, type VirtualEmbeddingSetDefinition, type VirtualEmbeddingSetSource, type VirtualEmbeddingSetValidationError, type VirtualMaterializationPolicy, type VramTier, type WorkerRequest, type WorkerResponse, aiRevisionHandler, allMigrations, appendPluginScript, assertShardComponentRecord, beginRecordStorePurge, bindSearchEvidence, buildMetadataPredicateConditions, buildNoteConditions, buildPluginCsp, captureKnowledge, chunkText, classifyError, classifyModel, clearPrefetchedShard, collectionFromShard, collectionToShard, compareDatasetIncrementalParity, computeBlobHash, computeHash, computeLineageDigest, computeSri, conceptTaggingHandler, configureInferenceRuntime, cosineSimilarity, createBridgeInferenceProviders, createCosineSemanticProvider, createCspReportHandler, createFortemi, createLegacyProvider, createLocalProviderProfile, createPGliteBackend, createPGliteInstance, createRecordBackend, createRecordStore, createRemoteBackend, createRoutes, createSearchEvidenceSet, createShardBackend, createShardCapabilityReport, createWorkerEmbedFunction, datasetDestinationScopeKey, defaultStorageBackendFactory, defineInferenceProvider, defineInferenceRuntime, defineLegacyInferenceProvider, defineOpenAICompatibleProvider, deriveDatasetIngestIdempotencyKey, detectCommunities, detectGpuCapabilities, detectInferenceCapabilities, digestDatasetMaterializationValue, discoverLocalProviders, dropAttachmentProjection, dropNoteProjection, dumpDbSnapshot, embeddingConfigToShard, embeddingFromShard, embeddingGenerationHandler, embeddingSetFromShard, embeddingSetMemberToShard, embeddingSetToShard, embeddingToShard, enqueueFullWorkflow, enqueueJob, enqueueNoteCreationJobs, estimateModelFit, estimateVramMB, estimateVramTier, executeDatasetMaterialization, executeDatasetRetrieval, exportFullV1Snapshot, exportShard, exportShardFromRecords, exportShardFromRecordsWithReport, exportShardWithReport, fetchAndValidateFortemiCompatibility, fetchPluginScript, formatFortemiCompatibilitySummary, fortemiCompatibilityUrl, fortemiManifest, fromPrefetched, generateId, getConfiguredInferenceProviderId, getEmbedFunction, getEmbeddingTaskSelectionOptions, getFortemiBridge, getFortemiSecretStore, getJobQueueStatus, getKnowledgeShardContractReceipt, getKnowledgeShardProfileRegistry, getKnowledgeShardSchema, getLlmFunction, getNote, getPrefetchedSha256, getProviderRouteRequirementIssue, handleEmbedRequests, hasFortemiSecureSecrets, importFullV1Snapshot, importShard, importShardToRecords, inferInferenceTaskCapability, inferLocalEmbeddingDimensions, isPluginScriptAllowed, isShardPrefetched, linkFromShard, linkToShard, linkingHandler, listNotes, manageArchive, manageAttachments, manageCapabilities, manageCollections, manageLinks, manageNote, manageTags, matchRoute, mergeInferenceRuntimeConfigs, mergeSearchEvidenceSets, migrateLegacyBlobStore, negotiateDatasetExecutionCapabilities, negotiateDatasetExecutionCapabilitiesFromWire, negotiateDatasetMaterializationProfile, noteFromShard, noteSkosTagToShard, noteToShard, openShard, packTarGz, parseCspReport, parseSearchEvidenceLocator, parseSearchEvidenceSet, prefetchShard, previewRecordStorePurge, profileSupportError, projectAttachments, projectNotes, projectRecords, provenanceEdgeToShard, providerSatisfiesRouteRequirements, purgeRecordStoreGraph, recordStoreErasureTargetIds, recordStorePurgeStatus, registerLlmCapability, registerSemanticCapability, registerSemanticCapabilityWorker, registerServiceWorker, resolveSearchEvidence, restoreDbSnapshot, resumeRecordStorePurge, searchTool, selectBackend, selectEmbeddingTask, selectLlmModel, setEmbedFunction, setEmbeddingTaskSelectionOptions, setLlmFunction, sha256Hex, skosConceptToShard, skosRelationToShard, skosSchemeToShard, suggestTags, tagsToShard, templateToShard, titleGenerationHandler, unpackTarGz, unregisterLlmCapability, unregisterSemanticCapability, upsertRecordStoreRequest, upsertRecordStoreSources, urlLinkToShard, validateChecksums, validateCoreV1ShardArchive, validateDatasetBenchmarkEvidence, validateDatasetExecutionDescriptor, validateDatasetExecutionRequest, validateFortemiCompatibilityResponse, validateFullV1ShardArchive, validateProviderRoute, validateRecordV1ShardArchive, validateShardArchive, validateShardComponentRecord, validateShardManifest, verifyDbSnapshotMeta, verifySri };