diff --git a/.changeset/37107-knowledge-turso.md b/.changeset/37107-knowledge-turso.md new file mode 100644 index 00000000000..fb22059f820 --- /dev/null +++ b/.changeset/37107-knowledge-turso.md @@ -0,0 +1,20 @@ +--- +'@objectstack/knowledge-turso': patch +'@objectstack/spec': patch +'@objectstack/service-settings': patch +--- + +feat(knowledge): the libSQL vector store moves into the open framework, with generations, listing and the adapter contract suite + +Clause-②: yes +Metadata-protocol: none + +ADR-0161 Execution row 7; cloud ADR-0119 D5 (#37107). + +- **`@objectstack/knowledge-turso` now ships from this repository**, Apache-2.0 (its `LICENSE` file is the Apache-2.0 text). `KnowledgeTursoPlugin` registers a `TursoKnowledgeAdapter` (adapter id `turso`) that keeps passages and vectors in a libSQL database of its own with libSQL's native vectors: the `url` option (`file:`, `:memory:`, `libsql://`), else `knowledge.db` under the project's `.objectstack/data/` (`defaultStoreUrl`). A URL naming the platform's own database file (`objectstack.db`, `dev.db`, `standalone.db`, or the file `OS_DATABASE_URL` names) is refused: two engines writing one SQLite file lose rows. On a file the store sets WAL and a busy timeout (`busyTimeoutMs`, default 5000), and in one process every call of the store runs its database work one at a time. On a remote database (`libsql://`) each request is bounded (`requestTimeoutMs`, default 10000; a write sends one request per document): past it the call answers `SERVICE_UNAVAILABLE`, a write stopped before its commit is rolled back, and the queue moves on. +- **The platform embedder and splitter.** The package's own OpenAI embedding provider, hash embedder and chunker are gone: it embeds with the kernel's `embedder` service, read at each call (or the `embedder` option), reports `embedding` (model, dimensions, input limit), and declares `capabilities.chunks`, indexing the service's passages as given. Removed exports of the cloud-repo releases: `HashEmbedder`, `HashEmbeddingProvider`, `EmbeddingProvider`, `TursoAdapterOptions` and the default export; removed options: `embedding` (now `embedder`), `chunkTarget`, `overFetch`, and `adapterConfig.tableName` / `dimensions` on a source. +- **Generations under the index fingerprint (ADR-0161 K7; K8, item 8).** A generation table `knowledge_generation` and one passage table per source and generation, `knowledge__g`. A write or a search under another fingerprint is refused `409 KNOWLEDGE_REBUILD_REQUIRED` (registered in the error-code ledger for this package). `beginBuild` under a new fingerprint opens a generation beside the active one, which keeps answering its own fingerprint; `completeBuild` switches to it, records the recipe hash and drops the old table; `indexStatus` answers the fingerprint, the recipe hash and whether a build is under way. The unique index keeps one generation under construction per source; it does not refuse a second builder: a second `beginBuild` under the same fingerprint joins the build, and one under another fingerprint replaces it, after which the first builder's writes are refused `KNOWLEDGE_REBUILD_REQUIRED`. Either way no generation mixes two fingerprints. A table of the cloud-repo releases (`knowledge_` with exactly their columns) is never served: a search answers `KNOWLEDGE_REBUILD_REQUIRED`, and the table is dropped when the first complete reindex finishes. +- **Listing, hashes, organizations.** `listDocuments` pages the generation the writes go to, each document's `docHash` as stored; hits carry `docHash` and the passage's `headingPath`; the organization filter, the record scope (`scope`, ADR-0161 K8 item 17) and the metadata `filter` run in SQL before ranking, by an exact cosine scan (no DiskANN index, which ranks before it filters). A passage whose text is unchanged is not embedded again. +- **When it cannot run**, because the database cannot be opened or `@libsql/client` has no native build for the platform (Windows on ARM), the plugin still registers and boot goes on; `healthCheck` answers `ok: false` and every call answers `503 SERVICE_UNAVAILABLE`, its reason in the error's `remedy`. +- **Settings → Knowledge, "Test connection" on Turso** no longer says the package ships from another repository, or that a store with no URL reuses the platform's database: it names `@objectstack/knowledge-turso`, registered beside the knowledge service, and its default file. +- The package runs `runKnowledgeAdapterContract` with every member declared (`scope` included), on `:memory:` and on a `file:` URL, in its own unit tests. diff --git a/.changeset/config.json b/.changeset/config.json index ae2e090afd0..7a541b01df2 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -79,6 +79,7 @@ "@objectstack/service-storage", "@objectstack/knowledge-memory", "@objectstack/knowledge-pgvector", + "@objectstack/knowledge-turso", "@objectstack/knowledge-ragflow", "@objectstack/embedder-openai", "@objectstack/account", diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index fac4b859c1b..9f82bf85b26 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -9,7 +9,7 @@ Part of the [AI module](/docs/ai) — how agents retrieve knowledge through the ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable backends (RAGFlow, LlamaIndex, Dify, custom pgvector, …) with one call: `KnowledgeService.search(query, { sourceIds?, topK? })`. The framework defines the contract and runs permission-aware filtering; the adapter plugin does the actual retrieval. See [the protocol design](/docs/protocol/knowledge) for the rationale. -**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@objectstack/knowledge-ragflow`, `@objectstack/knowledge-pgvector`), the `@objectstack/embedder-openai` embedder, and the permission-aware retrieval + event sync below all ship in the **open-source framework**. The workflow is: declare your knowledge sources, pick an adapter, and call `search` — retrieval respects the same row-level security as any ObjectQL query. Only the in-product chat *runtime* that consumes retrieval ships in ObjectOS; see the callout under [Retrieving knowledge](#retrieving-knowledge). +**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@objectstack/knowledge-ragflow`, `@objectstack/knowledge-pgvector`, `@objectstack/knowledge-turso`), the `@objectstack/embedder-openai` embedder, and the permission-aware retrieval + event sync below all ship in the **open-source framework**. The workflow is: declare your knowledge sources, pick an adapter, and call `search` — retrieval respects the same row-level security as any ObjectQL query. Only the in-product chat *runtime* that consumes retrieval ships in ObjectOS; see the callout under [Retrieving knowledge](#retrieving-knowledge). ## Wiring @@ -212,6 +212,20 @@ new KnowledgePgvectorPlugin({ queryPrefix: '' /* e.g. BGE's query instruction */ Details — the tables, an approximate index as an operator's step, rebuilds — are in [the protocol's pgvector section](/docs/protocol/knowledge#41-knowledge-pgvector--the-open-vector-store-on-postgresql). +## Local vector store: a libSQL file + +`@objectstack/knowledge-turso` keeps passages and vectors in a libSQL file of its own — by default `knowledge.db` under the project's `.objectstack/data/`, never the platform database's file — so a deployment on SQLite gets semantic search, Chinese text included, with no database server to run. Until `os dev` mounts it for you, add the package and register `KnowledgeTursoPlugin` beside the knowledge service yourself. Point a source at it with `adapter: 'turso'`: + +```ts +new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL +``` + +- It searches by an exact scan; the organization filter, the record scope and the metadata `filter` run in SQL before ranking. 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms; larger sources belong on pgvector. +- A changed model or split is rebuilt beside the old index, which keeps answering until the reindex completes. +- Where libSQL has no native build (Windows on ARM), boot goes on and its sources answer `SERVICE_UNAVAILABLE`. + +Details are in [the protocol's turso section](/docs/protocol/knowledge#42-knowledge-turso--the-open-vector-store-in-a-libsql-file). + ## Why we did not build a vector DB Mature OSS (RAGFlow, LlamaIndex, Dify) already nail embedding, hybrid retrieval, rerank, and OCR. ObjectStack's value is **the metadata-native source declaration, one structural split for every adapter, and the permission-aware filter on top of those engines** — not yet-another-RAG-stack. Customers pick the retrieval engine that matches their data; we make sure it talks to ObjectStack the same way every time. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index b3e64e2afdc..babfc92160b 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -84,6 +84,8 @@ delegates the rest to plugins. │ • Event sync (record.* → upsert) │ │ (reference impl, REST) │ │ • Audit + metrics │ │ • knowledge-pgvector │ │ │ │ (PostgreSQL + pgvector) │ +│ │ │ • knowledge-turso │ +│ │ │ (libSQL file, local) │ │ Registers `knowledge` service │ │ (llamaindex / dify: planned)│ └──────────────────────────────────────┘ └──────────────────────────────┘ ▲ @@ -374,7 +376,8 @@ keeps generations, the switch at the end of a build. `implements` declares the o checks the declaration against the adapter. `./testing` is a test-only, ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it. `knowledge-memory` runs it as the reference implementation; `knowledge-pgvector` -runs it against a live PostgreSQL in CI. +runs it against a live PostgreSQL in CI; `knowledge-turso` runs it on libSQL +`:memory:` and on a `file:` URL in its own unit tests. ### 3.5 The split @@ -485,6 +488,7 @@ import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory'; import { KnowledgeRagflowPlugin } from '@objectstack/knowledge-ragflow'; import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector'; +import { KnowledgeTursoPlugin } from '@objectstack/knowledge-turso'; defineStack({ plugins: [ @@ -495,6 +499,7 @@ defineStack({ apiKey: process.env.RAGFLOW_KEY!, }), new KnowledgePgvectorPlugin(), // self-hosted, PostgreSQL + pgvector + new KnowledgeTursoPlugin(), // local / not on PostgreSQL, a libSQL file ], }); ``` @@ -569,6 +574,56 @@ an exact scan. sensitive as the record it came from, and it is in every backup of the database. +### 4.2 `knowledge-turso` — the open vector store in a libSQL file + +`@objectstack/knowledge-turso` keeps a source's passages and vectors in a +[libSQL](https://github.com/tursodatabase/libsql) database of its own, with +libSQL's native vectors (`F32_BLOB`, `vector32`, `vector_distance_cos`): the +store for local development and for a deployment not on PostgreSQL. It takes +the service's passages, embeds them with the kernel's `embedder` service (or +the `embedder` it is given), and answers a search by an exact scan. + +- **Which database.** The `url` option (`file:`, `:memory:` or a + `libsql://` Turso URL), else `knowledge.db` under the project's + `.objectstack/data/`, beside the platform database. Never the platform's + own file: two engines writing one SQLite file in one process lose rows, so a + URL naming `objectstack.db`, `dev.db`, `standalone.db` or the file + `OS_DATABASE_URL` names is refused. On a file the store sets WAL and a busy + timeout (`busyTimeoutMs`, default 5000); in one process every call of the + store runs its database work one at a time. +- **Tables.** `knowledge_generation`, one row per source and generation + (fingerprint, recipe hash, width, model, active or being built; at most one + of each per source, by a unique index — a second build joins the one under + way when its fingerprint is the same, and replaces it otherwise, so the + first builder's writes are then refused), and one passage table per source and generation, + `knowledge__g`, its vector column sized for that generation. A + source id that is not snake_case is refused before + any SQL. +- **Search.** An exact scan by cosine distance; the organization filter, the + [record scope](#record-scope) and the metadata `filter` (JSON equality per + key) run in the same `WHERE`, before ranking. The store creates no DiskANN index: `vector_top_k` ranks + before it filters, and with one, 1,000 vectors of 1,536 dimensions grew a + file from 8.2 MB to 329 MB and took 21.8 s to index. Without it the same + 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 take 82 MB and + about 50 ms. A larger source belongs on `knowledge-pgvector`. +- **Rebuilds.** A changed fingerprint is refused (§3.6). A complete reindex + under a new fingerprint builds a new generation table beside the active + one, which keeps answering its own fingerprint, and switches at the end of + the build; the old table is dropped. A build of a third fingerprint + abandons one left unfinished. A table of the package's earlier releases + (`knowledge_` with exactly their columns) is never served: a search + answers `KNOWLEDGE_REBUILD_REQUIRED`, and the table is dropped when the first + complete reindex finishes. A table of any other shape under one of the + store's names is neither served nor dropped. +- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is + not embedded again within a generation. +- **When it cannot run.** A database that cannot be opened, or a platform + with no native libSQL build (there is none for Windows on ARM): the plugin + still registers and boot goes on; it warns with the reason, `healthCheck` + answers `ok: false`, and every call answers `SERVICE_UNAVAILABLE`. +- **The text is stored.** Each row holds its passage's text, as sensitive as + the record it came from, and in every copy of the file. + --- ## 5. Permission-aware retrieval (the unique value-add) @@ -928,6 +983,7 @@ up. | `knowledge-llamaindex` | ⏳ Phase 2 | | | `knowledge-dify` | ⏳ Phase 3 / community | | | `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) | +| `knowledge-turso` | ✅ | A libSQL file of its own; exact scan, organization, record scope and metadata filter in SQL, a generation built beside the active one (§4.2) | ### 7.1 Non-goals for Phase 1 diff --git a/packages/plugins/knowledge-turso/LICENSE b/packages/plugins/knowledge-turso/LICENSE new file mode 100644 index 00000000000..16bc23f4043 --- /dev/null +++ b/packages/plugins/knowledge-turso/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, + in at least one of the following places: within a NOTICE + text file distributed as part of the Derivative Works; within + the Source form or documentation, if provided along with + the Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the + License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 ObjectStack + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md new file mode 100644 index 00000000000..281fb3bf6f8 --- /dev/null +++ b/packages/plugins/knowledge-turso/README.md @@ -0,0 +1,67 @@ +# @objectstack/knowledge-turso + +`IKnowledgeAdapter` on [libSQL](https://github.com/tursodatabase/libsql)'s native vectors — the open vector store for local development (`os dev`) and for deployments not on PostgreSQL. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in a libSQL database of its own, and answers `search()` by an exact cosine scan. + +```ts +import { ObjectKernel } from '@objectstack/core'; +import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; +import { KnowledgeTursoPlugin } from '@objectstack/knowledge-turso'; + +const kernel = new ObjectKernel(); +kernel.use(new KnowledgeServicePlugin({ + sources: [{ id: 'task_notes', label: 'Notes', adapter: 'turso', + source: { kind: 'object', object: 'task', contentFields: ['notes'] }}], +})); +kernel.use(new KnowledgeTursoPlugin()); // .objectstack/data/knowledge.db +``` + +## Options + +| Option | Default | | +|:--|:--|:--| +| `id` | `'turso'` | The adapter id a source names in `adapter`. | +| `url` | `file:` + `/.objectstack/data/knowledge.db` | A `file:` URL, `:memory:`, or a `libsql://` (Turso) URL. Never the platform's own database file. | +| `authToken` | — | The token of a `libsql://` URL. | +| `client` | — | A libSQL client to use as it is (not configured, not closed by the plugin). | +| `busyTimeoutMs` | `5000` | How long a write waits for another process's lock on a `file:` store. | +| `requestTimeoutMs` | `10000` for a remote URL | The longest one request to a remote database may take (each statement, each document's batch of a write, each commit) before the call answers `SERVICE_UNAVAILABLE`. A write stopped before its commit is rolled back, never committed. None for a file or `:memory:`; for a `client` given as it is, only when set. | +| `projectRoot` | `process.cwd()` | The directory the default file is under. | +| `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. | +| `embedder` | the kernel's `embedder` service | The embedder to call, read at each call. | + +## Its own file, never the platform's + +The store opens a libSQL file of its own. Two engines writing one SQLite file in one process lose rows (measured: a row lost silently under WAL, a failed commit in delete mode), so a URL that names the platform's database — `objectstack.db`, `dev.db`, `standalone.db`, or the file `OS_DATABASE_URL` names, compared as the file a link resolves to and with SQLite's `-wal`, `-shm` and `-journal` side files read as their database — is refused: the plugin registers, warns, and every call answers `SERVICE_UNAVAILABLE`. + +On a file the store sets WAL and a busy timeout: without them a second process writing the same file lost most of its writes in measurement. Within one process every call of the store runs its database work one at a time. + +## Tables + +- `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model, and whether it is active or being built. At most one of each per source, by a unique index. It does not refuse a second builder: a second build under the same fingerprint joins the one under way, and one under another fingerprint replaces it, after which the first builder's writes are refused `KNOWLEDGE_REBUILD_REQUIRED`. No generation mixes two fingerprints. +- `knowledge__g` — the passages of one generation of one source, with an `F32_BLOB()` vector column sized for that generation. + +## Search + +An exact scan by cosine distance (`vector_distance_cos`). The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) run in the same `WHERE`, before ranking — libSQL's DiskANN index (`vector_top_k`) ranks first and filters after, so the store creates none. Measured on Linux x64 with 1,536-wide vectors: 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 passages take 82 MB and a search about 50 ms. (With a DiskANN index the same 1,000 vectors grew a file to 329 MB, and the index build took 21.8 s.) For larger sources, use `@objectstack/knowledge-pgvector`. + +## Rebuilds + +Every source's index is built under one index fingerprint (the embedding model and dimensions, the split, the content list — ADR-0161 K7). A write or a search under another fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED` (409) and never served from the stored vectors. A complete reindex under a new fingerprint builds a new generation table beside the active one (the old one keeps answering its own fingerprint meanwhile) and switches to it when the reindex completes; the old table is then dropped. A passage whose text is unchanged is not embedded again within a generation. + +A table written by this package's earlier releases (`knowledge_`, from the cloud repository) is never served: a search answers "reindex needed", and the table is dropped when the first complete reindex finishes. It is recognised by its exact columns: a table of any other shape under a store's table name, one the store did not make in a shared database, is never served and never dropped. + +## When it cannot run + +When the database cannot be opened, or `@libsql/client` has no native build for the platform (there is none for Windows on ARM), the plugin still registers and boot goes on: it warns with the reason, `healthCheck` answers `ok: false`, and every call answers `SERVICE_UNAVAILABLE` (one sentence; the reason travels in the error's `remedy`, for the operator). + +## What it stores + +Each row holds its passage's text, title and metadata as well as its vector: the text is as sensitive as the record it came from, and it is in every copy of the file. + +## Tests + +`pnpm test` runs the adapter contract suite of `@objectstack/service-knowledge/testing` on `:memory:` and on a `file:` URL, and the acceptance cases. libSQL runs in the test process: no service, no image. + +## License + +Apache-2.0. See [LICENSING.md](../../../LICENSING.md). diff --git a/packages/plugins/knowledge-turso/package.json b/packages/plugins/knowledge-turso/package.json new file mode 100644 index 00000000000..da181781ab3 --- /dev/null +++ b/packages/plugins/knowledge-turso/package.json @@ -0,0 +1,66 @@ +{ + "name": "@objectstack/knowledge-turso", + "version": "18.6.0", + "license": "Apache-2.0", + "description": "libSQL (Turso) knowledge adapter for ObjectStack: an open vector store in a libSQL file of its own, for local development and deployments not on PostgreSQL.", + "type": "commonjs", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "sideEffects": false, + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "scripts": { + "build": "tsup --config ../../../tsup.config.ts && node ../../../scripts/check-dts-emitted.mjs", + "dev": "tsc -w", + "test": "vitest run", + "typecheck": "tsc --noEmit && pnpm check:test-typecheck", + "check:test-typecheck": "tsx ../../../scripts/check-test-typecheck.mts --self-test && tsx ../../../scripts/check-test-typecheck.mts --package packages/plugins/knowledge-turso --project tsconfig.test.json" + }, + "dependencies": { + "@libsql/client": "^0.18.0", + "@objectstack/core": "workspace:*", + "@objectstack/spec": "workspace:*" + }, + "devDependencies": { + "@objectstack/service-knowledge": "workspace:*", + "@types/node": "^26.6.5", + "tsx": "^4.23.15", + "typescript": "^6.0.3", + "vitest": "^4.1.11" + }, + "keywords": [ + "objectstack", + "knowledge", + "rag", + "turso", + "libsql", + "sqlite", + "vector-search" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/objectstack-ai/objectstack.git", + "directory": "packages/plugins/knowledge-turso" + }, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist", + "README.md", + "CHANGELOG.md" + ], + "engines": { + "node": ">=22.0.0" + } +} diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts new file mode 100644 index 00000000000..dcee6d09574 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -0,0 +1,559 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The acceptance cases of the move into objectstack, beside the contract + * suite, on `:memory:` and on a `file:` URL: Chinese text found with a fixed + * fake embedder, an unchanged passage not embedded again, a changed model (the + * same width and another) built as a new generation table while the old one is + * not served under the new fingerprint and then dropped, two organizations that + * never see each other's hits, a table of the store's earlier releases + * answered "reindex needed" and then replaced, the metadata filter run before + * ranking, and one queue for concurrent calls on a single-connection database. + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { Client } from '@libsql/client'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext, IDataEngine, IEmbedder } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KnowledgeService } from '@objectstack/service-knowledge'; +import { KNOWLEDGE_REBUILD_REQUIRED, TursoKnowledgeAdapter } from '../index.js'; +import { FakeEmbedder, storeOf, type StoreKind } from './turso.testkit.js'; + +const source = (id: string, extra: Record = {}): KnowledgeSource => + ({ + id, + label: id, + adapter: 'under_test', + source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'], ...extra }, + }) as KnowledgeSource; + +const FP_A = { fingerprint: 'fp-test:a', recipeHash: 'rh-test:1' }; +const ctx = (s: KnowledgeSource, index = FP_A): AdapterContext => ({ source: s, reason: 'manual', index }); + +function doc(s: KnowledgeSource, n: string, content: string, extra: Partial = {}): KnowledgeDocument { + const id = `${s.id}:${n}`; + return { + id, + sourceId: s.id, + sourceRecordId: n, + content, + title: `Title ${n}`, + metadata: { status: 'published' }, + chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }], + ...extra, + }; +} + +const SYSTEM = { positions: [], permissions: [], systemPermissions: [], isSystem: true } as unknown as ExecutionContext; + +type Row = Record; + +/** A data-engine double for the service's paged walk: rows by id order, `id > cursor`, a limit, and `id IN (…)`. */ +function rowsEngine(rows: Row[]): IDataEngine { + const matches = (row: Row, where: Record | undefined): boolean => { + for (const [key, value] of Object.entries(where ?? {})) { + if (key === '$and') { + if (!(value as Row[]).every((c) => matches(row, c))) return false; + continue; + } + if (value !== null && typeof value === 'object') { + const v = value as { $gt?: unknown; $in?: unknown[] }; + if (v.$in !== undefined && !v.$in.map(String).includes(String(row[key]))) return false; + if (v.$gt !== undefined && !(String(row[key]) > String(v.$gt))) return false; + continue; + } + if (row[key] !== value) return false; + } + return true; + }; + return { + find: async (_object: string, query: { where?: Row; limit?: number }) => + rows + .filter((r) => matches(r, query?.where)) + .sort((a, b) => (String(a.id) < String(b.id) ? -1 : 1)) + .slice(0, typeof query?.limit === 'number' ? query.limit : undefined) + .map((r) => ({ ...r })), + count: async (_object: string, query: { where?: Row }) => rows.filter((r) => matches(r, query?.where)).length, + } as unknown as IDataEngine; +} + +async function tables(client: Client, like: string): Promise { + const found = await client.execute({ + sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE ? ORDER BY name", + args: [like], + }); + return found.rows.map((r) => String(r.name)); +} + +async function refusal(promise: Promise): Promise> { + return promise.then( + () => { + throw new Error('expected a refusal, got an answer'); + }, + (e: unknown) => e as Record, + ); +} + +for (const kind of ['memory', 'file'] as StoreKind[]) { + describe(`knowledge-turso acceptance on ${kind === 'memory' ? ':memory:' : 'a file: URL'}`, () => { + const store = storeOf(kind); + afterAll(() => store.closeAll()); + + it('indexes Chinese text and finds it with a fixed fake embedder', async () => { + const adapter = store.adapter(); + const s = source('zh'); + await adapter.upsert( + [doc(s, '1', '合同到期前三十天提醒客户续约'), doc(s, '2', '仓库盘点每月一次,由物流部负责')], + ctx(s), + ); + const hits = await adapter.search('客户续约提醒', { source: s, topK: 5, index: { fingerprint: FP_A.fingerprint } }); + expect(hits[0]).toMatchObject({ documentId: `${s.id}:1`, snippet: '合同到期前三十天提醒客户续约' }); + expect(hits[0].score).toBeGreaterThan(0.3); + }); + + it('does not embed a passage again when its text is unchanged; embeds only what changed', async () => { + const embedder = new FakeEmbedder(); + const adapter = store.adapter({ embedder }); + const s = source('rehash'); + const two = (second: string): KnowledgeDocument => ({ + ...doc(s, '1', `granite quarry. ${second}`), + chunks: [ + { id: `${s.id}:1#0`, documentId: `${s.id}:1`, index: 0, content: 'granite quarry' }, + { id: `${s.id}:1#1`, documentId: `${s.id}:1`, index: 1, content: second }, + ], + }); + await adapter.upsert([two('marble cliffs')], ctx(s)); + expect(embedder.texts).toEqual(['granite quarry', 'marble cliffs']); + await adapter.upsert([two('marble cliffs')], ctx(s)); + expect(embedder.calls).toBe(1); + await adapter.upsert([two('basalt columns')], ctx(s)); + expect(embedder.texts.slice(2)).toEqual(['basalt columns']); + const hits = await adapter.search('basalt granite', { source: s, topK: 5 }); + expect(hits.map((h) => h.chunkId).sort()).toEqual([`${s.id}:1#0`, `${s.id}:1#1`]); + }); + + for (const [label, next] of [ + ['the same width', () => new FakeEmbedder(64, 'fake-other-model')], + ['another width', () => new FakeEmbedder(96, 'fake-wider-model')], + ] as const) { + it(`a changed model (${label}) builds a new generation table; the old one is not served under the new fingerprint, then dropped`, async () => { + let embedder: IEmbedder = new FakeEmbedder(64, 'fake-first-model'); + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: () => embedder }); + const s = source(`model_${label.replace(/\W/g, '_')}`); + const rows: Row[] = [ + { id: 'r1', body: 'glacier valley ice', status: 'published' }, + { id: 'r2', body: 'harbour crane night', status: 'published' }, + ]; + const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); + svc.registerAdapter('under_test', adapter); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2 }); + expect(await tables(client, `knowledge_${s.id}_g%`)).toEqual([`knowledge_${s.id}_g1`]); + const before = await adapter.indexStatus(ctx(s)); + + embedder = next(); + // The new model's fingerprint is not the stored one: refused, never ranked against the old vectors. + expect(await refusal(svc.search('glacier', { topK: 5, executionContext: SYSTEM }))).toMatchObject({ + code: KNOWLEDGE_REBUILD_REQUIRED, + status: 409, + }); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); + expect(await tables(client, `knowledge_${s.id}_g%`)).toEqual([`knowledge_${s.id}_g2`]); + const after = await adapter.indexStatus(ctx(s)); + expect(after.fingerprint).toBeDefined(); + expect(after.fingerprint).not.toBe(before.fingerprint); + const hits = await svc.search('glacier', { topK: 5, executionContext: SYSTEM }); + expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + const width = await client.execute( + `SELECT dim, model FROM knowledge_generation WHERE source_id = '${s.id}'`, + ); + expect(width.rows.map((r) => [Number(r.dim), r.model])).toEqual([[embedder.dimensions, embedder.model]]); + }); + } + + it('while a build runs, the old generation answers its own fingerprint and the new one is refused as being rebuilt', async () => { + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + const s = source('midbuild'); + await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s)); + const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' }; + await adapter.beginBuild(ctx(s, FP_B)); + expect(await tables(client, `knowledge_${s.id}_g%`)).toEqual([`knowledge_${s.id}_g1`, `knowledge_${s.id}_g2`]); + const err = await refusal(adapter.search('granite', { source: s, topK: 5, index: { fingerprint: FP_B.fingerprint } })); + expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); + expect(String(err.message)).toMatch(/is being rebuilt/); + // A third fingerprint abandons the unfinished build: one builder per source. + const FP_C = { fingerprint: 'fp-test:c', recipeHash: 'rh-test:1' }; + await adapter.beginBuild(ctx(s, FP_C)); + const rows = await client.execute(`SELECT generation, fingerprint, state FROM knowledge_generation WHERE source_id = '${s.id}' ORDER BY generation`); + expect(rows.rows.map((r) => [Number(r.generation), r.fingerprint, r.state])).toEqual([ + [1, FP_A.fingerprint, 'active'], + [2, FP_C.fingerprint, 'building'], + ]); + await expect(adapter.upsert([doc(s, '1', 'marble')], ctx(s, FP_B))).rejects.toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED }); + expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint, building: true }); + }); + + it("two organizations never see each other's hits: the filter runs in SQL, before ranking", async () => { + const adapter = store.adapter(); + const s = source('orgs'); + await adapter.upsert( + [ + doc(s, 'a', 'alpine meadow harbour', { organizationId: 'org_a' }), + doc(s, 'b', 'alpine meadow alpine meadow', { organizationId: 'org_b' }), + ], + ctx(s), + ); + const asA = await adapter.search('alpine meadow', { source: s, topK: 1, organizationIds: ['org_a'] }); + expect(asA.map((h) => h.documentId)).toEqual([`${s.id}:a`]); + const asB = await adapter.search('alpine meadow harbour', { source: s, topK: 5, organizationIds: ['org_b'] }); + expect(asB.map((h) => h.documentId)).toEqual([`${s.id}:b`]); + }); + + it('the metadata filter runs before ranking, by JSON equality', async () => { + const adapter = store.adapter(); + const s = source('meta'); + await adapter.upsert( + [ + doc(s, '1', 'tidal pool tidal pool', { metadata: { status: 'draft', pinned: true, rank: 2 } }), + doc(s, '2', 'tidal pool rocks', { metadata: { status: 'published', pinned: false, rank: 2 } }), + ], + ctx(s), + ); + const top = await adapter.search('tidal pool', { source: s, topK: 1, filter: { status: 'published' } }); + expect(top.map((h) => h.documentId)).toEqual([`${s.id}:2`]); + expect((await adapter.search('tidal', { source: s, topK: 5, filter: { pinned: true } })).map((h) => h.documentId)).toEqual([`${s.id}:1`]); + expect((await adapter.search('tidal', { source: s, topK: 5, filter: { rank: 2 } })).length).toBe(2); + expect(await adapter.search('tidal', { source: s, topK: 5, filter: { rank: '2' } })).toEqual([]); + }); + + it('a record scope matches a field by its stored key, and a string or number only, bound as values', async () => { + const adapter = store.adapter(); + const s = source('scoped'); + await adapter.upsert( + [ + doc(s, '1', 'harbour rules', { metadata: { 'policy.id': 'p1', flag: true } }), + doc(s, '2', 'harbour rules', { metadata: { policy: { id: 'p1' }, flag: 'true' } }), + doc(s, '3', 'harbour rules', { metadata: { "it's": ['x', 7.5] } }), + ], + ctx(s), + ); + const ids = async (scope: NonNullable[1]['scope']>) => + (await adapter.search('harbour rules', { source: s, topK: 5, scope })).map((h) => h.documentId).sort(); + // A dotted name is a key, never a JSON path into a nested object. + expect(await ids([{ kind: 'metadata', field: 'policy.id', ids: ['p1'] }])).toEqual([`${s.id}:1`]); + // A boolean matches no id, by either spelling; the string 'true' does. An object matches nothing. + expect(await ids([{ kind: 'metadata', field: 'flag', ids: ['true'] }])).toEqual([`${s.id}:2`]); + expect(await ids([{ kind: 'metadata', field: 'flag', ids: ['1'] }])).toEqual([]); + expect(await ids([{ kind: 'metadata', field: 'policy', ids: ['{"id":"p1"}'] }])).toEqual([]); + // A quote in a name is a value; a number in a list matches its text. + expect(await ids([{ kind: 'metadata', field: "it's", ids: ['7.5'] }])).toEqual([`${s.id}:3`]); + expect(await ids([{ kind: 'record', ids: ["1' OR '1'='1"] }])).toEqual([]); + }); + + it("a table of the store's earlier releases answers 'reindex needed', and is replaced by the first build", async () => { + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + const s = source('legacy'); + // The cloud-repo release's layout: no generation, no hashes, no organization. + await client.execute(`CREATE TABLE knowledge_legacy ( + chunk_id TEXT PRIMARY KEY, document_id TEXT NOT NULL, source_record_id TEXT, content TEXT NOT NULL, + title TEXT, metadata TEXT, embedding F32_BLOB(64) NOT NULL)`); + await client.execute({ + sql: "INSERT INTO knowledge_legacy VALUES ('legacy:r1#0', 'legacy:r1', 'r1', 'glacier', NULL, '{}', vector32(?))", + args: [`[${[1, ...new Array(63).fill(0)].join(',')}]`], + }); + + expect(await refusal(adapter.search('glacier', { source: s, topK: 5 }))).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); + // A write outside a build would mix the new store with the old table: refused. + expect(await refusal(adapter.upsert([doc(s, 'r1', 'glacier')], ctx(s)))).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED }); + expect(await adapter.indexStatus(ctx(s))).toEqual({}); + + const rows: Row[] = [{ id: 'r1', body: 'glacier valley ice', status: 'published' }]; + const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); + svc.registerAdapter('under_test', adapter); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect(await tables(client, 'knowledge_legacy%')).toEqual(['knowledge_legacy_g1']); + const hits = await svc.search('glacier', { topK: 5, executionContext: SYSTEM }); + expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + }); + + it('a generation table of another source is never taken for a legacy table', async () => { + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + // Source `a`'s first generation is `knowledge_a_g1`, the legacy name of a source `a_g1`. + await adapter.upsert([doc(source('a'), '1', 'copper kettle')], ctx(source('a'))); + expect(await adapter.search('copper', { source: source('a_g1'), topK: 5 })).toEqual([]); + await adapter.upsert([doc(source('a_g1'), '1', 'copper wire')], ctx(source('a_g1'))); + expect((await adapter.search('copper', { source: source('a'), topK: 5 })).map((h) => h.snippet)).toEqual(['copper kettle']); + expect((await adapter.search('copper', { source: source('a_g1'), topK: 5 })).map((h) => h.snippet)).toEqual(['copper wire']); + }); + + it("the store's own generation table is never taken for a legacy table, whatever the source is called", async () => { + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + const other = source('other'); + await adapter.upsert([doc(other, '1', 'amber lamp')], ctx(other)); + // `knowledge_generation` is the legacy name a source `generation` would have. + const s = source('generation'); + expect(await adapter.search('amber', { source: s, topK: 5 })).toEqual([]); + const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'amber resin', status: 'published' }]) }); + svc.registerAdapter('under_test', adapter); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect(await tables(client, 'knowledge_generation')).toEqual(['knowledge_generation']); + expect((await adapter.search('amber', { source: other, topK: 5 })).map((h) => h.snippet)).toEqual(['amber lamp']); + expect((await adapter.search('amber', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + }); + + it('a table with the legacy columns but no F32_BLOB vector is not a legacy table', async () => { + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + await client.execute(`CREATE TABLE knowledge_blobs ( + chunk_id TEXT PRIMARY KEY, document_id TEXT NOT NULL, source_record_id TEXT, content TEXT NOT NULL, + title TEXT, metadata TEXT, embedding BLOB)`); + const s = source('blobs'); + expect(await adapter.search('x', { source: s, topK: 5 })).toEqual([]); + await adapter.upsert([doc(s, '1', 'flint')], ctx(s)); + await adapter.completeBuild(ctx(s)); + expect(await tables(client, 'knowledge_blobs%')).toEqual(['knowledge_blobs', 'knowledge_blobs_g1']); + }); + + it('a search whose generation keeps being switched under it stops after three attempts, SERVICE_UNAVAILABLE', async () => { + const client = store.client(); + const s = source('churn'); + const builder = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + await builder.upsert([doc(s, '1', 'spruce')], ctx(s)); + let n = 0; + const churning = new (class extends FakeEmbedder { + override async embed(texts: string[]): Promise { + const next = { fingerprint: `fp-test:churn-${++n}`, recipeHash: 'rh-test:1' }; + await builder.beginBuild(ctx(s, next)); + await builder.completeBuild(ctx(s, next)); + return super.embed(texts); + } + })(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: churning }); + expect(await refusal(adapter.search('spruce', { source: s, topK: 5 }))).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(n).toBe(3); + }); + + it('a table the store did not make is never dropped, under a legacy name or a generation name', async () => { + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + // A database shared with an application that keeps a table of its own. + await client.execute('CREATE TABLE knowledge_articles (id TEXT PRIMARY KEY, body TEXT)'); + await client.execute("INSERT INTO knowledge_articles VALUES ('a1', 'kept')"); + const s = source('articles'); + expect(await adapter.search('kept', { source: s, topK: 5 })).toEqual([]); + const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'slate roof', status: 'published' }]) }); + svc.registerAdapter('under_test', adapter); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect((await client.execute('SELECT body FROM knowledge_articles')).rows.map((r) => r.body)).toEqual(['kept']); + // Under the name of a generation table it is refused, and left as it is. + await client.execute('CREATE TABLE knowledge_notes_g1 (id TEXT PRIMARY KEY, body TEXT)'); + const notes = source('notes'); + expect(await refusal(adapter.upsert([doc(notes, '1', 'x')], ctx(notes)))).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(await tables(client, 'knowledge_notes_g1')).toEqual(['knowledge_notes_g1']); + }); + + it('a write planned for a generation switched while it embedded is refused, never written into another', async () => { + const client = store.client(); + const s = source('switched'); + const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' }; + const other = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + await other.upsert([doc(s, '1', 'birch bark')], ctx(s)); + // While this adapter's embedder answers, another builder switches the source to FP_B. + const switching = new (class extends FakeEmbedder { + override async embed(texts: string[]): Promise { + await other.beginBuild(ctx(s, FP_B)); + await other.completeBuild(ctx(s, FP_B)); + return super.embed(texts); + } + })(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: switching }); + expect(await refusal(adapter.upsert([doc(s, '2', 'birch twig')], ctx(s)))).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED }); + expect(await other.search('birch', { source: s, topK: 5, index: FP_B })).toEqual([]); + }); + + it('a first generation is made afresh: a passage table left without its generation row is never adopted', async () => { + const client = store.client(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }); + const s = source('fresh'); + await adapter.upsert([doc(s, 'old', 'cedar chest')], ctx(s)); + await client.execute({ sql: 'DELETE FROM knowledge_generation WHERE source_id = ?', args: [s.id] }); + await adapter.upsert([doc(s, 'new', 'cedar fence')], ctx(s)); + expect((await adapter.search('cedar', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.id}:new`]); + }); + + it('concurrent calls on one client are queued, never refused for a held connection', async () => { + const adapter = store.adapter(); + const s = source('queue'); + await adapter.upsert([doc(s, '0', 'seed passage')], ctx(s)); + const work = Array.from({ length: 12 }, (_, i) => + i % 2 === 0 + ? adapter.upsert([doc(s, String(i), `passage number ${i} lantern`)], ctx(s)) + : adapter.search('lantern', { source: s, topK: 3 }), + ); + await expect(Promise.all(work)).resolves.toBeDefined(); + expect((await adapter.search('lantern', { source: s, topK: 10 })).length).toBe(6); + }); + + it('refuses a source id that cannot name a table, before any SQL', async () => { + const adapter = store.adapter(); + const bad = source('x"; DROP TABLE knowledge_generation; --'); + await expect(adapter.upsert([doc(bad, '1', 'x')], ctx(bad))).rejects.toThrow(/cannot name a table/); + expect(await refusal(adapter.listDocuments(ctx(bad), { limit: 1 }))).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + // The spec's own pattern, of any length. + const long = source(`s_${'a'.repeat(80)}`); + await adapter.upsert([doc(long, '1', 'long name')], ctx(long)); + expect((await adapter.search('long name', { source: long, topK: 1 })).length).toBe(1); + await expect(adapter.search('x', { source: bad, topK: 1 })).rejects.toThrow(/cannot name a table/); + }); + }); +} + +describe('knowledge-turso without a database or an embedder', () => { + it('answers every call SERVICE_UNAVAILABLE in one sentence; the reason is operator text in remedy and healthCheck', async () => { + const adapter = new TursoKnowledgeAdapter({ embedder: new FakeEmbedder(), unavailable: 'no native build for win32-arm64' }); + const s = source('none'); + const err = await refusal(adapter.search('x', { source: s, topK: 1 })); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(String(err.message)).not.toMatch(/win32/); + expect(err.remedy).toBe('no native build for win32-arm64'); + expect(await adapter.healthCheck()).toEqual({ ok: false, message: expect.stringContaining('win32-arm64') }); + }); + + it('answers SERVICE_UNAVAILABLE without an embedder, before reading the index', async () => { + const store = storeOf('memory'); + const adapter = store.adapter({ embedder: () => undefined }); + expect(await refusal(adapter.search('x', { source: source('e'), topK: 1 }))).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(adapter.embedding).toBeUndefined(); + store.closeAll(); + }); + + it('bounds a request that never answers: SERVICE_UNAVAILABLE, and the queue moves on', async () => { + let stalls = true; + const store = storeOf('memory'); + const real = store.client(); + // A client whose next request hangs, as a remote database can. + const client = new Proxy(real, { + get(target, key, receiver) { + if (key === 'execute') { + return (...args: Parameters) => { + if (stalls) { + stalls = false; + return new Promise(() => undefined); + } + return target.execute(...args); + }; + } + const value = Reflect.get(target, key, receiver) as unknown; + return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target) : value; + }, + }) as Client; + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder(), requestTimeoutMs: 50 }); + const health = await adapter.healthCheck(); + expect(health).toMatchObject({ ok: false, message: expect.stringContaining('did not answer in time') }); + expect(await adapter.healthCheck()).toEqual({ ok: true, message: 'libSQL vectors ready' }); + expect(() => new TursoKnowledgeAdapter({ client, embedder: new FakeEmbedder(), requestTimeoutMs: 0 })).toThrow(RangeError); + store.closeAll(); + }); + + it('answers listDocuments SERVICE_UNAVAILABLE without an embedder, never KNOWLEDGE_REBUILD_REQUIRED', async () => { + const store = storeOf('memory'); + const client = store.client(); + const s = source('listed'); + await new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() }).upsert([doc(s, '1', 'x')], ctx(s)); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: () => undefined }); + // Without an embedder the service's fingerprint is another one: answered 503, not 409. + const other = { fingerprint: 'fp-test:no-embedder', recipeHash: 'rh-test:1' }; + expect(await refusal(adapter.listDocuments(ctx(s, other), { limit: 5 }))).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + store.closeAll(); + }); +}); + +/** A client whose every request (and every request of its transactions) is delayed by `ms`; `stallAt` hangs the Nth. */ +function slowClient(real: Client, ms: number, stallAt?: (request: number) => boolean): Client { + let request = 0; + const delayed = (target: T, methods: string[], wrap?: (v: unknown) => unknown): T => + new Proxy(target, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (typeof key !== 'string' || !methods.includes(key)) return fn; + return async (...args: unknown[]) => { + request += 1; + if (stallAt?.(request)) return new Promise(() => undefined); + await new Promise((r) => setTimeout(r, ms)); + const answered = await (fn(...args) as Promise); + return key === 'transaction' && wrap ? wrap(answered) : answered; + }; + }, + }); + return delayed(real, ['execute', 'batch', 'transaction'], (tx) => delayed(tx as object, ['execute', 'batch', 'commit', 'rollback'])); +} + +describe('knowledge-turso with a request bound (a remote database)', () => { + it('bounds each request, not a page: a page of 40 documents on a slow database is written whole', async () => { + const store = storeOf('file'); + const client = slowClient(store.client(), 15); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder(), requestTimeoutMs: 120 }); + const s = source('slow'); + const docs = Array.from({ length: 40 }, (_, i) => + doc(s, String(i), `heron ${i}`, { + chunks: [0, 1].map((index) => ({ + id: `${s.id}:${i}#${index}`, + documentId: `${s.id}:${i}`, + index, + content: `heron ${i} ${index === 0 ? 'wading' : 'flying'}`, + })), + }), + ); + await adapter.upsert(docs, ctx(s)); + // Again, unchanged: every passage is rewritten in place, still within the bound. + await adapter.upsert(docs, ctx(s)); + expect((await adapter.listDocuments(ctx(s), { limit: 100 })).documents.length).toBe(40); + store.closeAll(); + }); + + it('a request that stalls inside a write answers SERVICE_UNAVAILABLE naming requestTimeoutMs, and nothing of the write lands', async () => { + const store = storeOf('file'); + const real = store.client(); + const s = source('stall'); + const plain = new TursoKnowledgeAdapter({ id: 'under_test', client: real, embedder: new FakeEmbedder() }); + await plain.upsert([doc(s, 'seed', 'otter')], ctx(s)); + let batches = 0; + // The second batch inside a write transaction hangs, as a remote database can: the first document is written by then. + const client = slowClient(real, 0, () => false); + const hanging = new Proxy(client, { + get(t, key) { + if (key !== 'transaction') return Reflect.get(t, key, t); + return async (...args: unknown[]) => { + const tx = await (t.transaction as (...a: unknown[]) => Promise).apply(t, args); + return new Proxy(tx, { + get(x, k) { + const v = Reflect.get(x, k, x) as unknown; + if (k === 'batch' && ++batches === 2) return () => new Promise(() => undefined); + return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(x) : v; + }, + }); + }; + }, + }) as Client; + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: hanging, embedder: new FakeEmbedder(), requestTimeoutMs: 80 }); + const err = await refusal(adapter.upsert([doc(s, 'a', 'otter pup'), doc(s, 'b', 'otter den')], ctx(s))); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, remedy: expect.stringContaining('requestTimeoutMs') }); + await new Promise((r) => setTimeout(r, 100)); + expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.map((d) => d.documentId)).toEqual([`${s.id}:seed`]); + // The next write goes through. + await adapter.upsert([doc(s, 'a', 'otter pup')], ctx(s)); + expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.length).toBe(2); + store.closeAll(); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts new file mode 100644 index 00000000000..15d9f5bb368 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The `IKnowledgeAdapter` contract suite (ADR-0161 K8, rule 1) on libSQL, on +// `:memory:` and on a `file:` URL: the same suite every adapter runs, each case +// on a fresh adapter with a database of its own. This store builds a second +// generation beside the first, so every member is declared. + +import { afterAll, describe } from 'vitest'; +import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing'; +import { storeOf } from './turso.testkit.js'; + +for (const kind of ['memory', 'file'] as const) { + describe(`knowledge-turso on ${kind === 'memory' ? ':memory:' : 'a file: URL'}`, () => { + const store = storeOf(kind); + afterAll(() => store.closeAll()); + + runKnowledgeAdapterContract({ + name: `knowledge-turso (${kind})`, + makeAdapter: () => store.adapter(), + implements: { + listDocuments: true, + chunks: true, + organizationIds: true, + indexStatus: true, + builds: true, + refusesOtherFingerprint: true, + generations: true, + scope: true, + }, + }); + }); +} diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts new file mode 100644 index 00000000000..411bf6675de --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The plugin: where the store's file is by default, the platform's own + * database file refused, WAL and the busy timeout on the file it opens, and a + * platform with no native libSQL build degrading to a store that says so, + * never a failed boot. + */ + +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { PluginContext } from '@objectstack/core'; +import type { IKnowledgeAdapter, IKnowledgeService } from '@objectstack/spec/contracts'; +import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; +import { DEFAULT_REQUEST_TIMEOUT_MS, KnowledgeTursoPlugin, defaultStoreUrl, requestBoundFor, resolveStoreUrl } from '../index.js'; +import { FakeEmbedder } from './turso.testkit.js'; + +/** A plugin context with a knowledge service that records registrations, an embedder, and a logger that records. */ +function contextOf(services: Record = {}) { + const adapters = new Map(); + const logs: Array<['info' | 'warn', string]> = []; + const svc = { registerAdapter: (id: string, a: IKnowledgeAdapter) => adapters.set(id, a) } as unknown as IKnowledgeService; + // Read live: a case may register a service after start. + const all = services; + if (!(KNOWLEDGE_SERVICE in all)) all[KNOWLEDGE_SERVICE] = svc; + if (!(EMBEDDER_SERVICE in all)) all[EMBEDDER_SERVICE] = new FakeEmbedder(); + const ctx = { + getService: (name: string) => { + if (!(name in all) || all[name] === undefined) throw new Error(`no service ${name}`); + return all[name]; + }, + logger: { + info: (m: string) => logs.push(['info', m]), + warn: (m: string) => logs.push(['warn', m]), + debug: () => undefined, + error: () => undefined, + }, + } as unknown as PluginContext; + return { ctx, adapters, logs }; +} + +const dirs: string[] = []; +const tempDir = () => { + const dir = mkdtempSync(join(tmpdir(), 'knowledge-turso-plugin-')); + dirs.push(dir); + return dir; +}; + +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); + vi.doUnmock('@libsql/client'); + vi.resetModules(); +}); + +describe('resolveStoreUrl', () => { + it("defaults to knowledge.db under the project's .objectstack/data, beside the platform database", () => { + expect(resolveStoreUrl({ projectRoot: '/srv/app', env: {} })).toEqual({ + url: 'file:/srv/app/.objectstack/data/knowledge.db', + from: 'the default location', + }); + expect(defaultStoreUrl('/srv/app')).toBe('file:/srv/app/.objectstack/data/knowledge.db'); + }); + + it("refuses the platform's own database file, by name and by the platform's URL", () => { + for (const url of ['file:/srv/app/.objectstack/data/objectstack.db', 'file:./.objectstack/data/dev.db']) { + expect(resolveStoreUrl({ url, env: {} })).toMatchObject({ reason: expect.stringContaining("platform's own database file") }); + } + expect( + resolveStoreUrl({ url: 'file:/var/data/app.db', env: { OS_DATABASE_URL: 'sqlite:///var/data/app.db' } }), + ).toMatchObject({ reason: expect.stringContaining("platform's own database file") }); + // Percent-encoded and differently cased spellings name the same file; a bare path is a platform URL too. + for (const url of ['file:/srv/app/objectstack%2Edb', 'file:/srv/app/ObjectStack.db', 'file:/srv/app/%64ev.db']) { + expect(resolveStoreUrl({ url, env: {} })).toMatchObject({ reason: expect.stringContaining("platform's own database file") }); + } + expect(resolveStoreUrl({ url: 'file:/var/data/App.db', env: { OS_DATABASE_URL: '/var/data/app.db' } })).toMatchObject({ + reason: expect.stringContaining("platform's own database file"), + }); + expect(resolveStoreUrl({ url: 'file:/var/data/%zz.db', env: {} })).toMatchObject({ reason: expect.stringContaining('not a valid file: URL') }); + // SQLite's side files belong to their database. + for (const url of ['file:/srv/app/objectstack.db-wal', 'file:/srv/app/dev.db-shm', 'file:/var/data/app.db-journal']) { + expect(resolveStoreUrl({ url, env: { OS_DATABASE_URL: '/var/data/app.db' } })).toMatchObject({ + reason: expect.stringContaining("platform's own database file"), + }); + } + expect(resolveStoreUrl({ url: 'file:/var/data/knowledge.db', env: { OS_DATABASE_URL: 'file:/var/data/app.db' } })).toEqual({ + url: 'file:/var/data/knowledge.db', + from: 'the plugin option `url`', + }); + }); + + it("refuses a link to the platform's file: the file it resolves to is compared", () => { + const dir = mkdtempSync(join(tmpdir(), 'knowledge-turso-link-')); + try { + writeFileSync(join(dir, 'app.db'), ''); + symlinkSync(join(dir, 'app.db'), join(dir, 'knowledge.db')); + symlinkSync(dir, join(dir, 'alias')); + const env = { OS_DATABASE_URL: `file:${join(dir, 'app.db')}` }; + expect(resolveStoreUrl({ url: `file:${join(dir, 'knowledge.db')}`, env })).toMatchObject({ reason: expect.stringContaining("platform's own database file") }); + expect(resolveStoreUrl({ url: `file:${join(dir, 'alias', 'app.db')}`, env })).toMatchObject({ reason: expect.stringContaining("platform's own database file") }); + expect(resolveStoreUrl({ url: `file:${join(dir, 'alias', 'other.db')}`, env })).toMatchObject({ url: `file:${join(dir, 'alias', 'other.db')}` }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('bounds requests by default on a remote URL only', () => { + expect(requestBoundFor('libsql://db.example.turso.io')).toBe(DEFAULT_REQUEST_TIMEOUT_MS); + expect(requestBoundFor('https://db.example.turso.io')).toBe(DEFAULT_REQUEST_TIMEOUT_MS); + expect(requestBoundFor('file:/srv/app/.objectstack/data/knowledge.db')).toBeUndefined(); + expect(requestBoundFor(':memory:')).toBeUndefined(); + expect(requestBoundFor('file:/srv/k.db', 250)).toBe(250); + }); + + it('accepts :memory: and libsql:// URLs, refuses anything else', () => { + expect(resolveStoreUrl({ url: ':memory:', env: {} })).toMatchObject({ url: ':memory:' }); + expect(resolveStoreUrl({ url: 'libsql://db.example.turso.io', env: {} })).toMatchObject({ url: 'libsql://db.example.turso.io' }); + expect(resolveStoreUrl({ url: 'postgres://x', env: {} })).toMatchObject({ reason: expect.any(String) }); + }); +}); + +describe('KnowledgeTursoPlugin', () => { + it('opens its own file under the project directory with WAL and a busy timeout, and registers a ready adapter', async () => { + const root = tempDir(); + const { ctx, adapters, logs } = contextOf(); + const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {} }); + await plugin.start(ctx); + const adapter = adapters.get('turso')!; + expect(adapter).toBeDefined(); + expect(await adapter.healthCheck!()).toMatchObject({ ok: true }); + expect(logs.filter(([level]) => level === 'warn')).toEqual([]); + const { createClient } = await import('@libsql/client'); + const probe = createClient({ url: `file:${join(root, '.objectstack', 'data', 'knowledge.db')}` }); + expect((await probe.execute('PRAGMA journal_mode')).rows[0].journal_mode).toBe('wal'); + expect((await probe.execute("SELECT name FROM sqlite_master WHERE name = 'knowledge_generation'")).rows).toHaveLength(1); + probe.close(); + await plugin.destroy(); + await plugin.destroy(); // a second call is a no-op + }); + + it("registers an adapter that answers SERVICE_UNAVAILABLE when given the platform's database file; boot goes on", async () => { + const { ctx, adapters, logs } = contextOf(); + await new KnowledgeTursoPlugin({ url: `file:${join(tempDir(), 'objectstack.db')}`, env: {} }).start(ctx); + const adapter = adapters.get('turso')!; + expect(await adapter.healthCheck!()).toMatchObject({ ok: false }); + expect(logs.some(([level, m]) => level === 'warn' && m.includes("platform's own database file"))).toBe(true); + }); + + it('degrades to a store that says so when @libsql/client has no native build for the platform', async () => { + vi.doMock('@libsql/client', () => { + throw new Error("Cannot find module '@libsql/win32-arm64-msvc'"); + }); + vi.resetModules(); + const { KnowledgeTursoPlugin: Fresh } = await import('../plugin.js'); + const { ctx, adapters, logs } = contextOf(); + await new Fresh({ url: ':memory:', env: {} }).start(ctx); + const adapter = adapters.get('turso')!; + const err = await adapter + .search('x', { source: { id: 's', label: 's', adapter: 'turso', source: { kind: 'object', object: 'o', contentFields: ['b'] } } as never, topK: 1 }) + .catch((e: unknown) => e); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(logs.some(([level, m]) => level === 'warn' && m.includes('@libsql/client could not be loaded'))).toBe(true); + }); + + it('reads the kernel embedder at each call, so one registered after start is used', async () => { + const services: Record = { [EMBEDDER_SERVICE]: undefined }; + const { ctx, adapters } = contextOf(services); + await new KnowledgeTursoPlugin({ url: ':memory:', env: {} }).start(ctx); + const adapter = adapters.get('turso')!; + expect(adapter.embedding).toBeUndefined(); + services[EMBEDDER_SERVICE] = new FakeEmbedder(32, 'late-model'); + expect(adapter.embedding).toEqual({ dimensions: 32, model: 'late-model' }); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/__tests__/turso.testkit.ts b/packages/plugins/knowledge-turso/src/__tests__/turso.testkit.ts new file mode 100644 index 00000000000..219d8678f44 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/turso.testkit.ts @@ -0,0 +1,90 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What this package's test files share: a fixed fake embedder, and stores on + * `:memory:` and on a `file:` URL, each adapter in a database of its own. No + * service, no image, no credentials: libSQL runs in the test process. + */ + +import { createHash } from 'node:crypto'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createClient, type Client } from '@libsql/client'; +import type { IEmbedder } from '@objectstack/spec/contracts'; +import { TursoKnowledgeAdapter, type TursoKnowledgeAdapterOptions } from '../index.js'; + +/** + * A fixed embedder for tests: each lower-cased Latin word, and each CJK + * character, hashed into one of `dimensions` slots, counted, and the vector + * scaled to unit length. Two texts sharing words (or characters) point the + * same way; texts sharing none are orthogonal. It counts its calls and the + * texts it embedded. + */ +export class FakeEmbedder implements IEmbedder { + readonly id = 'fake'; + readonly dimensions: number; + model: string; + calls = 0; + texts: string[] = []; + + constructor(dimensions = 64, model = 'fake-bag-of-words') { + this.dimensions = dimensions; + this.model = model; + } + + async embed(texts: string[]): Promise { + this.calls += 1; + this.texts.push(...texts); + return texts.map((t) => this.vector(t)); + } + + private vector(text: string): number[] { + const v = new Array(this.dimensions).fill(0); + const tokens = text.toLowerCase().match(/[a-z0-9]+|[一-鿿]/g) ?? []; + for (const token of tokens) { + const slot = createHash('sha256').update(token).digest().readUInt32BE(0) % this.dimensions; + v[slot] += 1; + } + const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)); + return norm === 0 ? v : v.map((x) => x / norm); + } +} + +export type StoreKind = 'memory' | 'file'; + +/** + * Makes adapters on fresh databases of one kind: `:memory:` (one database per + * client) or a `file:` URL in a temporary directory (one file per adapter). + * `closeAll` closes every client it made and removes the directory. + */ +export function storeOf(kind: StoreKind) { + const clients: Client[] = []; + let dir: string | undefined; + let n = 0; + const url = (): string => { + if (kind === 'memory') return ':memory:'; + dir ??= mkdtempSync(join(tmpdir(), 'knowledge-turso-')); + return `file:${join(dir, `store-${++n}.db`)}`; + }; + const client = (at: string = url()): Client => { + const made = createClient({ url: at, ...(kind === 'file' ? { timeout: 5000 } : {}) }); + clients.push(made); + return made; + }; + return { + kind, + /** A fresh database's URL. */ + url, + /** A client of a fresh database (or of `at`). */ + client, + adapter(opts: Partial = {}): TursoKnowledgeAdapter { + return new TursoKnowledgeAdapter({ id: 'under_test', client: client(), embedder: new FakeEmbedder(), ...opts }); + }, + closeAll(): void { + for (const c of clients.splice(0)) c.close(); + if (dir) rmSync(dir, { recursive: true, force: true }); + dir = undefined; + }, + }; +} diff --git a/packages/plugins/knowledge-turso/src/index.ts b/packages/plugins/knowledge-turso/src/index.ts new file mode 100644 index 00000000000..29b41d7bdf7 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/index.ts @@ -0,0 +1,18 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +export { + KNOWLEDGE_REBUILD_REQUIRED, + TursoKnowledgeAdapter, + type TursoKnowledgeAdapterOptions, +} from './turso-adapter.js'; +export { + DEFAULT_KNOWLEDGE_FILE, + DEFAULT_REQUEST_TIMEOUT_MS, + KnowledgeTursoPlugin, + PLATFORM_DATABASE_FILES, + defaultStoreUrl, + requestBoundFor, + resolveStoreUrl, + type KnowledgeTursoPluginOptions, +} from './plugin.js'; +export { GENERATION_TABLE, SAFE_SOURCE_ID, generationTable, legacyTable } from './sql.js'; diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts new file mode 100644 index 00000000000..953c9777303 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -0,0 +1,289 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { mkdirSync, realpathSync } from 'node:fs'; +import { basename, dirname, resolve as resolvePath } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { Client } from '@libsql/client'; +import type { Plugin, PluginContext } from '@objectstack/core'; +import type { IEmbedder, IKnowledgeService } from '@objectstack/spec/contracts'; +import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; +import { TursoKnowledgeAdapter } from './turso-adapter.js'; + +/** The store's file name when no `url` is given, beside the platform's own database. */ +export const DEFAULT_KNOWLEDGE_FILE = 'knowledge.db'; + +/** + * The file names the platform's own SQLite database takes under + * `.objectstack/data/` (the runtime's default and its two legacy names). The + * store never opens one: two engines writing one SQLite file in one process + * lose rows. + */ +export const PLATFORM_DATABASE_FILES: readonly string[] = ['objectstack.db', 'dev.db', 'standalone.db']; + +/** Options of {@link KnowledgeTursoPlugin}. */ +export interface KnowledgeTursoPluginOptions { + /** Adapter id, the value of `KnowledgeSource.adapter`. @default 'turso' */ + id?: string; + /** + * The libSQL URL of the store: a `file:` URL, `:memory:`, or a `libsql://` + * (Turso) URL. Absent: {@link defaultStoreUrl} — `knowledge.db` under the + * project's `.objectstack/data/`. Never the platform's own database file. + */ + url?: string; + /** The auth token of a `libsql://` URL. */ + authToken?: string; + /** + * A libSQL client the store uses as it is (the plugin neither configures nor + * closes it). It must not be a client of the platform's own database file. + */ + client?: Client; + /** + * How long a write waits for another process holding the file's lock, in + * milliseconds (SQLite's busy timeout; `file:` URLs only). @default 5000 + */ + busyTimeoutMs?: number; + /** + * The longest one request to the database (a statement, a document's batch, + * a commit) may take before the call answers + * `SERVICE_UNAVAILABLE`, for a remote database (`libsql://`, `https://`, + * `wss://`), whose requests have no bound of their own. Applies to a + * `client` given as it is only when set. + * @default 10000 for a remote URL; none for a file or `:memory:` + */ + requestTimeoutMs?: number; + /** Text put before every query before it is embedded (see the adapter's option). */ + queryPrefix?: string; + /** The embedder to call. Absent: the kernel's `embedder` service, read at each call. */ + embedder?: IEmbedder; + /** The project directory the default file is under. @default process.cwd() */ + projectRoot?: string; + /** The environment the platform's database URL is read from. @default process.env */ + env?: Record; +} + +/** The store's default URL: `file:` + `/.objectstack/data/knowledge.db`. */ +export function defaultStoreUrl(projectRoot: string = process.cwd()): string { + return `file:${resolvePath(projectRoot, '.objectstack', 'data', DEFAULT_KNOWLEDGE_FILE)}`; +} + +/** The bound on one request to a remote database (`requestTimeoutMs`). */ +export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; + +/** The request bound a store on `url` gets: the one given, else the default for a remote URL, else none. */ +export function requestBoundFor(url: string, given?: number): number | undefined { + if (given !== undefined) return given; + return fileOf(url) === undefined && url !== ':memory:' ? DEFAULT_REQUEST_TIMEOUT_MS : undefined; +} + +/** The local file a `file:` URL names, or `undefined` for any other URL. */ +export function fileOf(url: string): string | undefined { + if (!/^file:/i.test(url)) return undefined; + const rest = url.slice('file:'.length).split('?')[0]; + if (rest.startsWith('//')) { + try { + return fileURLToPath(url.split('?')[0]); + } catch { + return undefined; + } + } + try { + // libSQL percent-decodes the path it opens; so is the name compared here. + return resolvePath(decodeURIComponent(rest)); + } catch { + return undefined; + } +} + +/** SQLite's side files of a database file: its write-ahead log, shared memory and rollback journal. */ +const SIDE_FILE = /-(wal|shm|journal)$/; + +/** + * A database file as it is compared: its real path where it (or its directory) + * exists, lower-cased, and a side file read as the database it belongs to. + */ +function canonicalFile(file: string): string { + let real = file; + try { + real = realpathSync(file); + } catch { + try { + real = resolvePath(realpathSync(dirname(file)), basename(file)); + } catch { + /* neither exists yet: compared as written */ + } + } + return real.toLowerCase().replace(SIDE_FILE, ''); +} + +/** The file a platform database URL names: a `file:` / `sqlite:` URL, or a bare path. */ +function platformFileOf(url: string): string | undefined { + const trimmed = url.trim(); + if (trimmed === '' || trimmed === ':memory:') return undefined; + if (/^sqlite:/i.test(trimmed)) return fileOf(trimmed.replace(/^sqlite:(\/\/)?/i, 'file:')); + if (/^file:/i.test(trimmed)) return fileOf(trimmed); + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) return undefined; + return resolvePath(trimmed); +} + +/** The libSQL URL the store opens, and where it was read from — or why there is none. */ +export function resolveStoreUrl( + opts: Pick, +): { url: string; from: string } | { url?: undefined; reason: string } { + const given = opts.url?.trim(); + const url = given === undefined || given === '' ? defaultStoreUrl(opts.projectRoot) : given; + const from = given === undefined || given === '' ? 'the default location' : 'the plugin option `url`'; + if (!/^(file:|libsql:\/\/|https?:\/\/|wss?:\/\/)/i.test(url) && url !== ':memory:') { + return { reason: 'its `url` option is not a file:, :memory: or libsql:// URL.' }; + } + const file = fileOf(url); + if (file === undefined && /^file:/i.test(url)) { + return { reason: 'its `url` option is not a valid file: URL.' }; + } + if (file !== undefined) { + const env = opts.env ?? process.env; + // Compared as the file it resolves to (a link to the platform's file is that + // file), without case (on a case-insensitive file system two spellings are + // one file), and with SQLite's side files read as their database. + const platform = [env.OS_DATABASE_URL, env.DATABASE_URL] + .map((u) => (u === undefined ? undefined : platformFileOf(u))) + .filter((f): f is string => f !== undefined) + .map((f) => canonicalFile(f)); + const store = canonicalFile(file); + if (platform.includes(store) || PLATFORM_DATABASE_FILES.includes(basename(store))) { + return { + reason: + `its URL names the platform's own database file (${basename(file)}). The store keeps a libSQL file of its ` + + `own: two engines writing one SQLite file lose rows. Give it another file, such as ${DEFAULT_KNOWLEDGE_FILE} beside it.`, + }; + } + } + return { url, from }; +} + +/** + * `KnowledgeTursoPlugin` — registers a {@link TursoKnowledgeAdapter} with the + * host's `IKnowledgeService` during `start()`. + * + * It opens a libSQL database of its own — by default `knowledge.db` under the + * project's `.objectstack/data/`, beside the platform's database and never + * the platform's file — with WAL and a busy timeout on a file. When the + * database cannot be opened, or `@libsql/client` has no native build for the + * platform (there is none for Windows on ARM), the adapter still registers: + * boot continues, the warning says why, its `healthCheck` answers + * `ok: false`, and every call answers `SERVICE_UNAVAILABLE`. + */ +export class KnowledgeTursoPlugin implements Plugin { + name = 'com.objectstack.plugin.knowledge-turso'; + version = '0.1.0'; + type = 'standard' as const; + + private readonly opts: KnowledgeTursoPluginOptions; + private owned?: Client; + + constructor(opts: KnowledgeTursoPluginOptions = {}) { + this.opts = opts; + } + + async init(_ctx: PluginContext): Promise { + // No-op: registration happens in start() once IKnowledgeService is up. + } + + async start(ctx: PluginContext): Promise { + let svc: IKnowledgeService | undefined; + try { + svc = ctx.getService(KNOWLEDGE_SERVICE); + } catch { + ctx.logger.warn?.('KnowledgeTursoPlugin: IKnowledgeService not registered — install KnowledgeServicePlugin first.'); + return; + } + + let client: Client | undefined = this.opts.client; + let unavailable: string | undefined; + let requestTimeoutMs = this.opts.requestTimeoutMs; + if (!client) { + const target = resolveStoreUrl(this.opts); + if (target.url === undefined) { + unavailable = target.reason; + } else { + requestTimeoutMs = requestBoundFor(target.url, requestTimeoutMs); + const opened = await openClient(target.url, this.opts); + if ('client' in opened) client = this.owned = opened.client; + else unavailable = opened.reason; + } + } + + // Read at each call, never cached: the kernel's embedder may register + // after this plugin starts, or be replaced (ADR-0161 K8, item 6). + const embedder = (): IEmbedder | undefined => { + if (this.opts.embedder) return this.opts.embedder; + try { + return ctx.getService(EMBEDDER_SERVICE); + } catch { + return undefined; + } + }; + + const adapter = new TursoKnowledgeAdapter({ + id: this.opts.id, + ...(client ? { client } : { unavailable }), + embedder, + queryPrefix: this.opts.queryPrefix, + ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }), + }); + svc.registerAdapter(adapter.id, adapter); + + const health = await adapter.healthCheck(); + if (health.ok) { + ctx.logger.info?.(`KnowledgeTursoPlugin: adapter '${adapter.id}' registered (${health.message}).`); + } else { + ctx.logger.warn?.( + `KnowledgeTursoPlugin: adapter '${adapter.id}' registered but not ready; its sources answer ` + + `SERVICE_UNAVAILABLE until this is fixed. ${health.message ?? ''}`, + ); + } + } + + async destroy(): Promise { + const client = this.owned; + this.owned = undefined; + try { + client?.close(); + } catch { + /* already closed */ + } + } +} + +/** + * Loads `@libsql/client` and opens the store's database. The client is loaded + * here, not at module load, so a platform without its native build (Windows + * on ARM) gets a store that says so rather than a boot that fails. + */ +async function openClient( + url: string, + opts: Pick, +): Promise<{ client: Client } | { reason: string }> { + let createClient: typeof import('@libsql/client').createClient; + try { + ({ createClient } = await import('@libsql/client')); + } catch (err) { + return { + reason: + `@libsql/client could not be loaded on ${process.platform}-${process.arch} ` + + `(${err instanceof Error ? err.message : String(err)}). libSQL publishes no native build for every ` + + 'platform (none for Windows on ARM); use knowledge-pgvector there.', + }; + } + const file = fileOf(url); + try { + if (file !== undefined) mkdirSync(dirname(file), { recursive: true }); + const client = createClient({ + url, + ...(opts.authToken === undefined ? {} : { authToken: opts.authToken }), + ...(file === undefined ? {} : { timeout: opts.busyTimeoutMs ?? 5000 }), + }); + return { client }; + } catch (err) { + return { reason: `the database at ${file ?? 'the given URL'} could not be opened (${err instanceof Error ? err.message : String(err)}).` }; + } +} diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts new file mode 100644 index 00000000000..6e42e4c4592 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -0,0 +1,171 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The SQL of the libSQL store: its generation table, its passage tables (one + * per source and generation), and the shapes of their names. SQLite cannot + * bind an identifier, so every table name is built from a source id held to + * {@link SAFE_SOURCE_ID} and a generation number, and is double-quoted; every + * value is a bind parameter. + */ + +/** + * A source id this module puts into a table name: the spec's snake_case + * source id (`KnowledgeSource.id`), the spec's own pattern. Anything else is + * refused before it reaches a string. + */ +export const SAFE_SOURCE_ID = /^[a-z_][a-z0-9_]*$/; + +/** The generation table: one row per generation of a source. */ +export const GENERATION_TABLE = 'knowledge_generation'; + +/** Refuses a source id that cannot be put into a table name. */ +export function assertSourceId(sourceId: string): void { + if (!SAFE_SOURCE_ID.test(sourceId)) { + throw Object.assign( + new Error( + `knowledge-turso: source id '${sourceId}' cannot name a table (snake_case: lower-case letters, digits and ` + + 'underscores).', + ), + { code: 'VALIDATION_ERROR', status: 400 }, + ); + } +} + +/** The passage table of one generation of one source: `knowledge__g`. */ +export function generationTable(sourceId: string, generation: number): string { + assertSourceId(sourceId); + if (!Number.isInteger(generation) || generation < 1) { + throw new RangeError(`knowledge-turso: a generation is a positive integer, got ${String(generation)}`); + } + return `knowledge_${sourceId}_g${generation}`; +} + +/** + * The table the store held a source in before it kept generations + * (`knowledge_`, written by the adapter's cloud-repo releases). It is + * never served: a source that still has one answers "reindex needed", and it + * is dropped when the source's first generation becomes active. + */ +export function legacyTable(sourceId: string): string { + assertSourceId(sourceId); + return `knowledge_${sourceId}`; +} + +/** The columns of a table of the cloud-repo releases, exactly, in no order. */ +const LEGACY_COLUMNS = ['chunk_id', 'content', 'document_id', 'embedding', 'metadata', 'source_record_id', 'title']; + +/** The columns of a generation's passage table, exactly, in no order. */ +const PASSAGE_COLUMNS = [ + 'chunk_hash', + 'chunk_id', + 'content', + 'doc_hash', + 'document_id', + 'embedding', + 'heading_path', + 'metadata', + 'organization_id', + 'source_record_id', + 'title', +]; + +/** What a table found under a name is, read from `pragma_table_info` rows. */ +export type TableShape = 'none' | 'legacy' | 'passage' | 'other'; + +/** + * Reads a table's shape from its columns (`name`, `type`): `legacy` only for + * the exact column set of the cloud-repo releases with an `F32_BLOB` vector, + * `passage` only for the exact set this module makes, `other` for anything + * else (a table the store did not make, never dropped or served), `none` for + * no table. + */ +export function tableShape(columns: ReadonlyArray<{ name: unknown; type: unknown }>): TableShape { + if (columns.length === 0) return 'none'; + const names = columns.map((c) => String(c.name)).sort(); + const vector = columns.find((c) => c.name === 'embedding'); + const isVector = vector !== undefined && /^F32_BLOB\(\d+\)$/i.test(String(vector.type).replace(/\s+/g, '')); + const same = (want: string[]) => names.length === want.length && names.every((n, i) => n === want[i]); + if (isVector && same(LEGACY_COLUMNS)) return 'legacy'; + if (isVector && same(PASSAGE_COLUMNS)) return 'passage'; + return 'other'; +} + +/** `"name"`, for a name built by this module. */ +export function quoted(table: string): string { + return `"${table}"`; +} + +/** The statements that make the generation table and its two one-row-per-source rules. */ +export function generationDdl(): string[] { + const t = quoted(GENERATION_TABLE); + return [ + `CREATE TABLE IF NOT EXISTS ${t} ( + source_id TEXT NOT NULL, + generation INTEGER NOT NULL, + fingerprint TEXT, + recipe_hash TEXT, + dim INTEGER NOT NULL, + model TEXT, + state TEXT NOT NULL CHECK (state IN ('active', 'building')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), + PRIMARY KEY (source_id, generation) +)`, + // One active generation per source, and one under construction. The + // second keeps one generation under construction, not one builder: a + // second build joins it (same fingerprint) or replaces it (another). + `CREATE UNIQUE INDEX IF NOT EXISTS "knowledge_generation_active" ON ${t} (source_id) WHERE state = 'active'`, + `CREATE UNIQUE INDEX IF NOT EXISTS "knowledge_generation_building" ON ${t} (source_id) WHERE state = 'building'`, + ]; +} + +/** + * The statements that make a generation's passage table afresh. The DROP + * first: a table left behind by a generation row deleted by hand is never + * adopted by a new generation of the same number. + */ +export function passageTableDdl(table: string, dimensions: number): string[] { + if (!Number.isInteger(dimensions) || dimensions < 1) { + throw new RangeError(`knowledge-turso: vector dimensions must be a positive integer, got ${String(dimensions)}`); + } + return [ + `DROP TABLE IF EXISTS ${quoted(table)}`, + `CREATE TABLE ${quoted(table)} ( + chunk_id TEXT NOT NULL PRIMARY KEY, + document_id TEXT NOT NULL, + source_record_id TEXT, + organization_id TEXT, + content TEXT NOT NULL, + title TEXT, + heading_path TEXT, + doc_hash TEXT, + chunk_hash TEXT NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}', + embedding F32_BLOB(${dimensions}) NOT NULL +)`, + `CREATE INDEX ${quoted(`${table}_document`)} ON ${quoted(table)} (document_id)`, + ]; +} + +/** The text a vector is bound as, for `vector32(?)`: `[x,y,…]`. */ +export function vectorLiteral(vector: readonly number[]): string { + return `[${vector.map((x) => (Number.isFinite(x) ? String(x) : '0')).join(',')}]`; +} + +/** + * The canonical JSON text of the value at one top-level key of a row's + * `metadata`, for an equality filter: the right-hand side is the filter + * value's `JSON.stringify`, passed through `json()`. `json_each` gives SQL + * values; booleans and null come back as their JSON spelling, objects and + * arrays as their minified text, everything else as `json_quote(value)`. + */ +export const METADATA_VALUE_JSON = `CASE type + WHEN 'true' THEN 'true' WHEN 'false' THEN 'false' WHEN 'null' THEN 'null' + WHEN 'object' THEN json(value) WHEN 'array' THEN json(value) + ELSE json_quote(value) END`; + +/** + * The `json_each` types a record-scope `metadata` term compares (ADR-0161 K8, + * item 17): a string, or a number read as its text, so the stored number 7 + * matches the id `'7'`. Booleans, null and objects match no id. + */ +export const SCOPE_SCALAR_TYPES = `('text', 'integer', 'real')`; diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts new file mode 100644 index 00000000000..453c37090a6 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -0,0 +1,964 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { createHash } from 'node:crypto'; +import type { Client, InArgs, InStatement, Transaction } from '@libsql/client'; +import type { + AdapterContext, + AdapterEmbeddingDescriptor, + AdapterIndexStatus, + AdapterListDocumentsOptions, + AdapterListDocumentsPage, + AdapterSearchOptions, + IEmbedder, + IKnowledgeAdapter, +} from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeHit } from '@objectstack/spec/ai'; +import { + GENERATION_TABLE, + METADATA_VALUE_JSON, + SCOPE_SCALAR_TYPES, + type TableShape, + tableShape, + assertSourceId, + generationDdl, + generationTable, + legacyTable, + passageTableDdl, + quoted, + vectorLiteral, +} from './sql.js'; + +/** Options of {@link TursoKnowledgeAdapter}. */ +export interface TursoKnowledgeAdapterOptions { + /** Adapter id, the value of `KnowledgeSource.adapter`. @default 'turso' */ + id?: string; + /** + * The libSQL client of the store's own database (a `file:` URL, `:memory:` + * or `libsql://`). Absent: the store has no database, and every call + * answers `SERVICE_UNAVAILABLE` naming `unavailable`. + */ + client?: Client; + /** Why there is no client, said by every call when `client` is absent. */ + unavailable?: string; + /** + * The embedder the store calls, or a getter read at each call (the kernel's + * `embedder` service may register after this adapter). Its `dimensions` + * size a new generation's vector column; its `model` and `dimensions` are + * what the adapter reports to the knowledge service's index fingerprint. + */ + embedder: IEmbedder | (() => IEmbedder | undefined); + /** + * Text put before every QUERY before it is embedded, for an asymmetric + * model that embeds questions and passages differently. Passages are + * embedded as they are. It changes no stored vector, so it is not part of + * the index fingerprint (ADR-0161 K8, item 15). + */ + queryPrefix?: string; + /** + * The longest one request to the database may take, in milliseconds — each + * statement, and each commit or rollback, on its own — before the call + * answers `SERVICE_UNAVAILABLE` and the queue moves on. For a remote + * database (`libsql://`), whose requests have no bound of their own: one + * stalled request would otherwise hold every source of the client, and the + * boot that awaits the health check. A write of many passages makes many + * requests, so the bound never grows with the size of a page. Absent: no + * bound (a `file:` store waits only for the busy timeout). + */ + requestTimeoutMs?: number; +} + +/** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */ +export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; + +/** How many times {@link TursoKnowledgeAdapter.upsert} plans a batch again when a concurrent write removed a passage it meant to keep. */ +const UPSERT_ATTEMPTS = 3; + +/** How many times {@link TursoKnowledgeAdapter.search} runs again when the active generation was switched under it. */ +const SEARCH_ATTEMPTS = 3; + +/** A generation row: one index of one source under one fingerprint. */ +interface GenerationRow { + generation: number; + fingerprint: string | null; + recipeHash: string | null; + dim: number; + state: 'active' | 'building'; +} + +/** A source's generations: the active one, and the one under construction. */ +interface SourceGenerations { + active?: GenerationRow; + building?: GenerationRow; +} + +/** + * Every call of every adapter on one libSQL client runs its database work one + * at a time. A transaction holds its connection across awaits, and a second + * writer on another connection of the same process would wait in SQLite's + * busy handler — synchronously, on the thread the holder needs to commit — so + * in-process work is queued here instead; other processes are kept apart by + * SQLite's own lock and the busy timeout. + */ +const queues = new WeakMap>(); + +function serial(client: Client, work: () => Promise): Promise { + const before = queues.get(client) ?? Promise.resolve(); + const run = before.then(work, work); + queues.set(client, run.then(() => undefined, () => undefined)); + return run; +} + +/** + * A view of `client` whose every request — `execute`, `batch`, opening a + * transaction, and a transaction's `execute`, `batch`, `commit` and + * `rollback` — is bounded by `ms` on its own. Everything else is the client's. + */ +function boundedClient(client: Client, ms: number): Client { + const bound = (target: T, methods: readonly string[], wrap?: (answered: unknown) => unknown): T => + new Proxy(target, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (typeof key !== 'string' || !methods.includes(key)) return fn; + return async (...args: unknown[]) => { + const answered = await withTimeout(fn(...args) as Promise, ms, key === 'commit'); + return wrap && key === 'transaction' ? wrap(answered) : answered; + }; + }, + }); + return bound(client, ['execute', 'batch', 'transaction'], (tx) => + bound(tx as Transaction, ['execute', 'batch', 'commit', 'rollback']), + ); +} + +/** + * `work`, or `SERVICE_UNAVAILABLE` when it has not settled within `ms`. A + * statement that times out inside a transaction is followed by a rollback, + * never a commit, so nothing it began lands; only a COMMIT that times out + * (`commit`) may still land, and its refusal says so. + */ +function withTimeout(work: Promise, ms: number, commit = false): Promise { + let timer: ReturnType | undefined; + const late = new Promise((_, reject) => { + timer = setTimeout( + () => + reject( + notReady( + 'its database did not answer in time', + `A request to the libSQL database took longer than ${ms} ms (the store's \`requestTimeoutMs\`); check that ` + + 'the database is reachable, or raise the bound.' + + (commit + ? ' It was the commit of a write: that write may still be applied. Writes are idempotent, so retry it.' + : ''), + ), + ), + ms, + ); + }); + // The stalled request settles on its own later; nothing waits for it. + work.catch(() => undefined); + return Promise.race([work, late]).finally(() => clearTimeout(timer)); +} + +/** + * `TursoKnowledgeAdapter` — an `IKnowledgeAdapter` on libSQL's native vectors + * (`F32_BLOB` columns, `vector32`, `vector_distance_cos`): the open vector + * store for local development and for deployments not on PostgreSQL (cloud + * ADR-0119 D5; ADR-0161 Execution, row 7). + * + * ## Storage + * + * In a libSQL database of its own — never the platform's database file: two + * engines writing one SQLite file in one process lose rows. A generation + * table, `knowledge_generation` (source, generation, fingerprint, recipe hash, + * vector width, model, state), and one passage table per source and + * generation, `knowledge__g`, whose vector column is sized for that + * generation's width. A passage row holds its chunk and document ids, record + * id, organization, text, title, heading path, document hash, chunk hash, + * metadata and vector. The text is stored: it is as sensitive as the record it + * came from, and it is in every copy of the file. + * + * ## Search + * + * An exact scan by cosine distance, no approximate index: the organization + * filter (ADR-0161 K8, item 9) and the metadata-equality `filter` run in the + * same `WHERE`, before ranking, which libSQL's DiskANN index (`vector_top_k`) + * cannot do — it ranks first. A passage whose cosine similarity is not + * positive is not a hit. + * + * ## Generations (ADR-0161 K7; K8, item 8) + * + * A source holds an active generation and, while a build under another + * fingerprint runs, one generation under construction — at most one per + * source, by a unique index on the generation table. That index does not + * refuse a second builder: a second build under the same fingerprint joins + * the one under way, and one under another fingerprint replaces it (the first + * builder's writes are then refused). A write + * carrying `ctx.index` goes to the generation of that fingerprint and is + * refused `KNOWLEDGE_REBUILD_REQUIRED` when neither holds it; a search + * carrying another fingerprint than the active one's is refused the same way + * and never answered from it. A source that holds nothing takes the first + * fingerprint it is handed. `beginBuild` under a new fingerprint opens a + * generation table beside the active one (or takes up the one under + * construction for it; one under construction for a third fingerprint is + * abandoned and dropped); `completeBuild` makes it the active one, records the + * recipe hash, and drops the old table. + * + * A table the store's earlier releases wrote (`knowledge_`, no + * generation) is never served: a search answers "reindex needed", a write + * outside a build is refused, and the table is dropped when the first build's + * generation becomes active. + * + * ## Writes + * + * The adapter takes the service's passages (`capabilities.chunks`) and hashes + * the text of each (`chunk_hash`). A passage whose hash is already stored is + * not embedded again: its row is rewritten around the stored vector; when that + * row is gone by the time the write runs, the batch is planned again. Every + * embed call runs before the write transaction opens, so the database is never + * locked while the embedder answers. + * + * ## What a caller reads + * + * A refusal's message is one sentence: no driver text, no SQL, no file path. + * Operator text travels in the error's `remedy`, which `healthCheck`, the + * plugin's boot warning and the knowledge service's reindex result and log + * show. + */ +export class TursoKnowledgeAdapter implements IKnowledgeAdapter { + readonly id: string; + readonly capabilities = { chunks: true } as const; + /** The client every request goes through: the one given, bounded when `requestTimeoutMs` is set. */ + private readonly client?: Client; + /** The client as given, which keys the in-process queue shared by every adapter on it. */ + private readonly queueKey?: Client; + private readonly unavailable?: string; + private readonly resolveEmbedder: () => IEmbedder | undefined; + private readonly queryPrefix: string; + private isReady = false; + /** Sources whose legacy table is known to be absent. */ + private readonly noLegacy = new Set(); + + constructor(opts: TursoKnowledgeAdapterOptions) { + this.id = opts.id ?? 'turso'; + this.queueKey = opts.client; + this.unavailable = opts.unavailable; + const embedder = opts.embedder; + this.resolveEmbedder = typeof embedder === 'function' ? embedder : () => embedder; + this.queryPrefix = opts.queryPrefix ?? ''; + if (opts.requestTimeoutMs !== undefined && (!Number.isFinite(opts.requestTimeoutMs) || opts.requestTimeoutMs <= 0)) { + throw new RangeError(`knowledge-turso: requestTimeoutMs must be a positive number, got ${String(opts.requestTimeoutMs)}`); + } + this.client = + opts.client === undefined || opts.requestTimeoutMs === undefined + ? opts.client + : boundedClient(opts.client, opts.requestTimeoutMs); + } + + /** `work` on the queue of the client as given, shared with every adapter on that client. */ + private queued(_client: Client, work: () => Promise): Promise { + return serial(this.queueKey ?? _client, work); + } + + /** What the adapter reports about its embedder (ADR-0161 K8, item 6), read now. */ + get embedding(): AdapterEmbeddingDescriptor | undefined { + const embedder = this.resolveEmbedder(); + if (!embedder) return undefined; + return { + dimensions: embedder.dimensions, + ...(embedder.model === undefined ? {} : { model: embedder.model }), + ...(embedder.maxInputTokens === undefined ? {} : { maxInputTokens: embedder.maxInputTokens }), + }; + } + + async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { + if (docs.length === 0) return; + const client = this.requireClient(); + assertSourceId(ctx.source.id); + const embedder = this.requireEmbedder(); + await this.ready(); + // An unchanged passage is rewritten in place, keeping its vector. When its + // row is gone by the time the write runs (a concurrent write of the same + // document removed it), the write is rolled back and planned again, so the + // passage is embedded and inserted rather than lost. + for (let attempt = 1; ; attempt++) { + const target = await this.queued(client, () => this.writeTarget(ctx, embedder, true)); + const missing = await this.writePassages(docs, ctx.source.id, target!, embedder); + if (missing === undefined) return; + if (attempt >= UPSERT_ATTEMPTS) { + throw new Error( + `knowledge-turso: a concurrent write to source '${ctx.source.id}' removed passages this write meant to keep, ` + + `${UPSERT_ATTEMPTS} times while it ran; nothing of this batch was written. Retry the write.`, + ); + } + } + } + + /** + * One attempt of {@link upsert}: read the stored chunk hashes, embed what + * changed, write in one transaction. Answers `undefined` when written, or the + * id of an unchanged passage whose row was gone (the transaction is rolled + * back). + */ + private async writePassages( + docs: KnowledgeDocument[], + sourceId: string, + target: GenerationRow, + embedder: IEmbedder, + ): Promise { + const client = this.requireClient(); + const table = quoted(generationTable(sourceId, target.generation)); + const planned = docs.map((doc) => ({ + doc, + passages: passagesOf(doc).map((p) => ({ ...p, hash: chunkHash(p.content) })), + })); + const ids = docs.map((d) => d.id); + const stored = new Map(); + const existing = await this.queued(client, () => + client.execute({ + sql: `SELECT chunk_id, chunk_hash FROM ${table} WHERE document_id IN (SELECT value FROM json_each(?))`, + args: [JSON.stringify(ids)], + }), + ); + for (const row of existing.rows) stored.set(String(row.chunk_id), String(row.chunk_hash)); + + // Embed what changed, before the write transaction opens. + const toEmbed = planned.flatMap((p) => p.passages).filter((p) => stored.get(p.id) !== p.hash); + const vectors = toEmbed.length === 0 ? [] : await embedder.embed(toEmbed.map((p) => p.content)); + if (vectors.length !== toEmbed.length) { + throw new Error( + `knowledge-turso: the embedder answered ${vectors.length} vector(s) for ${toEmbed.length} passage(s); nothing was written.`, + ); + } + const vectorOf = new Map(); + toEmbed.forEach((p, i) => { + const v = vectors[i]; + if (!Array.isArray(v) || v.length !== target.dim) { + throw new Error( + `knowledge-turso: the embedder answered a ${Array.isArray(v) ? v.length : 'missing'}-wide vector for ` + + `passage '${p.id}', and this source's index holds ${target.dim}-wide vectors; nothing was written.`, + ); + } + vectorOf.set(p.id, v); + }); + + return this.queued(client, () => + this.transaction(async (tx) => { + // The generation may have been switched or abandoned while the embedder + // answered: write only into the one that was planned. + const still = await tx.execute({ + sql: `SELECT 1 FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ? AND generation = ? AND fingerprint IS ? AND dim = ?`, + args: [sourceId, target.generation, target.fingerprint, target.dim], + }); + if (still.rows.length === 0) return { commit: false, value: `${sourceId}#generation-${target.generation}` }; + // One request per document (its DELETE and its passages, as one batch + // inside the transaction): the request bound never meets a page's size. + for (const { doc, passages } of planned) { + const statements: InStatement[] = [ + { + sql: `DELETE FROM ${table} WHERE document_id = ? AND chunk_id NOT IN (SELECT value FROM json_each(?))`, + args: [doc.id, JSON.stringify(passages.map((p) => p.id))], + }, + ]; + const kept: Array = [undefined]; + for (const p of passages) { + const common: InArgs = [ + p.id, + doc.id, + doc.sourceRecordId ?? null, + doc.organizationId ?? null, + p.content, + doc.title ?? null, + p.headingPath === undefined ? null : JSON.stringify(p.headingPath), + doc.docHash ?? null, + p.hash, + JSON.stringify(doc.metadata ?? {}), + ]; + const vector = vectorOf.get(p.id); + if (vector === undefined) { + // Unchanged text: the stored vector stands; the rest of the row is rewritten. + statements.push({ + sql: `UPDATE ${table} SET document_id = ?2, source_record_id = ?3, organization_id = ?4, content = ?5, + title = ?6, heading_path = ?7, doc_hash = ?8, metadata = ?10 + WHERE chunk_id = ?1 AND chunk_hash = ?9`, + args: common, + }); + kept.push(p.id); + } else { + statements.push({ + sql: `INSERT INTO ${table} (chunk_id, document_id, source_record_id, organization_id, content, title, + heading_path, doc_hash, chunk_hash, metadata, embedding) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, vector32(?11)) + ON CONFLICT (chunk_id) DO UPDATE SET document_id = excluded.document_id, + source_record_id = excluded.source_record_id, organization_id = excluded.organization_id, + content = excluded.content, title = excluded.title, heading_path = excluded.heading_path, + doc_hash = excluded.doc_hash, chunk_hash = excluded.chunk_hash, metadata = excluded.metadata, + embedding = excluded.embedding`, + args: [...(common as unknown[]), vectorLiteral(vector)] as InArgs, + }); + kept.push(undefined); + } + } + const results = await tx.batch(statements); + // An unchanged passage whose row is gone: rolled back, and planned again. + const gone = results.findIndex((r, i) => kept[i] !== undefined && r.rowsAffected === 0); + if (gone !== -1) return { commit: false, value: kept[gone]! }; + } + return { commit: true, value: undefined }; + }), + ); + } + + async delete(documentIds: string[], ctx: AdapterContext): Promise { + if (documentIds.length === 0) return; + const client = this.requireClient(); + assertSourceId(ctx.source.id); + await this.ready(); + // From every generation of the source: a removed document leaves them all. + await this.queued(client, async () => { + const { active, building } = await this.generations(ctx.source.id); + for (const g of [active, building]) { + if (!g) continue; + await client.execute({ + sql: `DELETE FROM ${quoted(generationTable(ctx.source.id, g.generation))} WHERE document_id IN (SELECT value FROM json_each(?))`, + args: [JSON.stringify(documentIds)], + }); + } + }); + } + + async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise { + if (!Number.isInteger(opts.limit) || opts.limit < 1) { + throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`); + } + const client = this.requireClient(); + assertSourceId(ctx.source.id); + // The embedder first, as on every other call: without one the service's + // fingerprint carries no model or width, and comparing it would refuse a + // healthy index as one to rebuild. No embedder is SERVICE_UNAVAILABLE. + const embedder = this.requireEmbedder(); + await this.ready(); + return this.queued(client, async () => { + // The generation the writes go to (ADR-0161 K8, item 1). + const target = await this.writeTarget(ctx, embedder, false); + if (!target) return { documents: [] }; + const table = quoted(generationTable(ctx.source.id, target.generation)); + // SQLite compares TEXT by bytes (BINARY), both the order and the cursor. + const page = await client.execute({ + sql: `SELECT document_id, max(doc_hash) AS doc_hash FROM ${table} + WHERE ?1 IS NULL OR document_id > ?1 + GROUP BY document_id ORDER BY document_id LIMIT ?2`, + args: [opts.cursor ?? null, opts.limit + 1], + }); + const rows = page.rows.slice(0, opts.limit).map((r) => ({ + documentId: String(r.document_id), + docHash: r.doc_hash === null ? undefined : String(r.doc_hash), + })); + return { + documents: rows.map((r) => (r.docHash === undefined ? { documentId: r.documentId } : r)), + ...(page.rows.length > opts.limit ? { nextCursor: rows[rows.length - 1].documentId } : {}), + }; + }); + } + + async search(query: string, opts: AdapterSearchOptions): Promise { + return this.searchAttempt(query, opts, 1); + } + + /** One attempt of {@link search}; `attempt` counts the generation switches met so far. */ + private async searchAttempt(query: string, opts: AdapterSearchOptions, attempt: number): Promise { + // An empty organization set ranks nothing (ADR-0161 K8, item 9). + if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return []; + // A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17). + if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return []; + const client = this.requireClient(); + assertSourceId(opts.source.id); + // The embedder first: without one the service's fingerprint carries no + // model or width, and comparing it would refuse a healthy index as one to + // rebuild. No embedder is SERVICE_UNAVAILABLE, as on every other call. + const embedder = this.requireEmbedder(); + await this.ready(); + const { active, building } = await this.queued(client, () => this.generations(opts.source.id)); + if (!active) { + if (await this.queued(client, () => this.hasLegacy(opts.source.id))) { + throw rebuildRequired(opts.source.id, building !== undefined); + } + return []; + } + // Vectors of two fingerprints are never ranked against each other (K7, rule 5). + if (opts.index !== undefined && active.fingerprint !== opts.index.fingerprint) { + throw rebuildRequired(opts.source.id, building?.fingerprint === opts.index.fingerprint); + } + if (embedder.dimensions !== active.dim) throw rebuildRequired(opts.source.id, false); + const topK = Math.max(0, Math.floor(opts.topK)); + if (topK === 0) return []; + + // The query is embedded before the database is read. + const [vector] = await embedder.embed([`${this.queryPrefix}${query}`]); + if (!Array.isArray(vector) || vector.length !== active.dim) { + throw new Error( + `knowledge-turso: the embedder answered a ${Array.isArray(vector) ? vector.length : 'missing'}-wide query ` + + `vector, and this source's index holds ${active.dim}-wide vectors.`, + ); + } + if (vector.every((x) => x === 0)) return []; + + const args: unknown[] = [vectorLiteral(vector)]; + const where: string[] = []; + if (opts.organizationIds !== undefined) { + args.push(JSON.stringify(opts.organizationIds)); + where.push(`organization_id IN (SELECT value FROM json_each(?${args.length}))`); + } + if (opts.scope !== undefined) { + // The record scope (ADR-0161 K8, item 17), a union of terms, beside the + // organization filter so `topK` is filled from in-scope documents. Each + // term's ids go as one bound JSON array, a field name as a bound value + // compared with the stored keys (never put into a JSON path). A + // `metadata` term holds for a stored string or number equal to an id as + // text, or a list with such an element; any other value holds for nothing. + const terms: string[] = []; + for (const term of opts.scope) { + if (term.ids.length === 0) continue; + args.push(JSON.stringify(term.ids)); + const ids = `(SELECT value FROM json_each(?${args.length}))`; + if (term.kind === 'record') { + terms.push(`source_record_id IN ${ids}`); + continue; + } + args.push(term.field); + terms.push( + `EXISTS (SELECT 1 FROM json_each(metadata) AS m WHERE m.key = ?${args.length} AND (` + + `(m.type IN ${SCOPE_SCALAR_TYPES} AND CAST(m.value AS TEXT) IN ${ids}) OR ` + + `(m.type = 'array' AND EXISTS (SELECT 1 FROM json_each(m.value) AS e ` + + `WHERE e.type IN ${SCOPE_SCALAR_TYPES} AND CAST(e.value AS TEXT) IN ${ids}))))`, + ); + } + where.push(`(${terms.join(' OR ')})`); + } + for (const [key, value] of Object.entries(opts.filter ?? {})) { + args.push(key, JSON.stringify(value === undefined ? null : value)); + where.push( + `EXISTS (SELECT 1 FROM json_each(metadata) WHERE key = ?${args.length - 1} AND ${METADATA_VALUE_JSON} = json(?${args.length}))`, + ); + } + args.push(topK); + const table = quoted(generationTable(opts.source.id, active.generation)); + const result = await this.queued(client, async () => { + // The generation may have been switched while the query was embedded. + const now = await this.generations(opts.source.id); + if (now.active?.generation !== active.generation) return undefined; + return client.execute({ + sql: `SELECT * FROM ( + SELECT chunk_id, document_id, source_record_id, content, title, metadata, doc_hash, heading_path, + vector_distance_cos(embedding, vector32(?1)) AS distance + FROM ${table} + ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`} + ) ranked + WHERE distance < 1 + ORDER BY distance, chunk_id + LIMIT ?${args.length}`, + args: args as InArgs, + }); + }); + if (result === undefined) { + // Switched while the query was embedded: searched again, a bounded number of times. + if (attempt >= SEARCH_ATTEMPTS) { + throw notReady( + "its source's index was switched while it searched", + `The active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, + ); + } + return this.searchAttempt(query, opts, attempt + 1); + } + return result.rows.map((r) => { + const headingPath = parseJson(r.heading_path); + return { + chunkId: String(r.chunk_id), + documentId: String(r.document_id), + sourceId: opts.source.id, + ...(r.source_record_id === null ? {} : { sourceRecordId: String(r.source_record_id) }), + score: 1 - Number(r.distance), + snippet: String(r.content), + ...(r.title === null ? {} : { title: String(r.title) }), + metadata: asRecord(parseJson(r.metadata)), + // The stored hash, as given (ADR-0161 K8, item 3): the service's + // record-level freshness check compares it with the record as it reads now. + ...(r.doc_hash === null ? {} : { docHash: String(r.doc_hash) }), + // The passage's heading path, when the splitter gave it one (item 14). + ...(Array.isArray(headingPath) ? { headingPath: headingPath.map(String) } : {}), + }; + }); + } + + async indexStatus(ctx: AdapterContext): Promise { + const client = this.requireClient(); + assertSourceId(ctx.source.id); + await this.ready(); + const { active, building } = await this.queued(client, () => this.generations(ctx.source.id)); + const status: AdapterIndexStatus = {}; + if (active?.fingerprint != null) status.fingerprint = active.fingerprint; + if (active?.recipeHash != null) status.recipeHash = active.recipeHash; + if (building !== undefined) status.building = true; + return status; + } + + async beginBuild(ctx: AdapterContext): Promise { + const index = requireIndex(ctx, 'beginBuild'); + const client = this.requireClient(); + assertSourceId(ctx.source.id); + const embedder = this.requireEmbedder(); + await this.ready(); + await this.queued(client, async () => { + const legacy = await this.hasLegacy(ctx.source.id); + await this.transaction(async (tx) => { + const { active, building } = await this.generations(ctx.source.id, tx); + const fits = (g: GenerationRow | undefined) => + g !== undefined && g.fingerprint === index.fingerprint && g.dim === embedder.dimensions; + // Rebuilt inside the active generation, or the build under way taken up. + if (fits(active) || fits(building)) return { commit: true, value: undefined }; + if (building) { + // A build of another fingerprint left unfinished: replaced, one per source. + await tx.execute(`DROP TABLE IF EXISTS ${quoted(generationTable(ctx.source.id, building.generation))}`); + await tx.execute({ + sql: `DELETE FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ? AND generation = ?`, + args: [ctx.source.id, building.generation], + }); + } + // A source that holds nothing takes the fingerprint as its active one; + // beside an active generation, or a legacy table, it is built aside. + const state = active === undefined && !legacy ? 'active' : 'building'; + await this.openGeneration(tx, ctx.source.id, index.fingerprint, embedder, state); + return { commit: true, value: undefined }; + }); + }); + } + + async completeBuild(ctx: AdapterContext): Promise { + const index = requireIndex(ctx, 'completeBuild'); + const client = this.requireClient(); + assertSourceId(ctx.source.id); + await this.ready(); + await this.queued(client, async () => { + const legacy = await this.hasLegacy(ctx.source.id); + await this.transaction(async (tx) => { + const { active, building } = await this.generations(ctx.source.id, tx); + const t = quoted(GENERATION_TABLE); + if (building?.fingerprint === index.fingerprint) { + if (active) { + await tx.execute(`DROP TABLE IF EXISTS ${quoted(generationTable(ctx.source.id, active.generation))}`); + await tx.execute({ sql: `DELETE FROM ${t} WHERE source_id = ? AND generation = ?`, args: [ctx.source.id, active.generation] }); + } + await tx.execute({ + sql: `UPDATE ${t} SET state = 'active', recipe_hash = ? WHERE source_id = ? AND generation = ?`, + args: [index.recipeHash, ctx.source.id, building.generation], + }); + } else if (active?.fingerprint === index.fingerprint) { + await tx.execute({ + sql: `UPDATE ${t} SET recipe_hash = ? WHERE source_id = ? AND generation = ?`, + args: [index.recipeHash, ctx.source.id, active.generation], + }); + } else { + throw new Error( + `completeBuild: source '${ctx.source.id}' holds no generation for this fingerprint; call beginBuild first.`, + ); + } + // The table of the store's earlier releases goes once a generation is active. + if (legacy) await tx.execute(`DROP TABLE IF EXISTS ${quoted(legacyTable(ctx.source.id))}`); + return { commit: true, value: undefined }; + }); + if (legacy) this.noLegacy.add(ctx.source.id); + }); + } + + async healthCheck(): Promise<{ ok: boolean; message?: string }> { + try { + this.requireClient(); + await this.ready(); + return { ok: true, message: 'libSQL vectors ready' }; + } catch (err) { + const remedy = remedyOf(err); + return { ok: false, message: `${errorText(err)}${remedy === undefined ? '' : ` ${remedy}`}` }; + } + } + + // ── Internals ───────────────────────────────────────────────────── + + private requireClient(): Client { + if (!this.client) { + throw notReady('it has no libSQL database', this.unavailable ?? 'It was given no libSQL client.'); + } + return this.client; + } + + private requireEmbedder(): IEmbedder { + const embedder = this.resolveEmbedder(); + if (!embedder) { + throw Object.assign( + new Error( + 'knowledge-turso has no embedder: register an embedder service (Settings → AI & Embedder) or pass ' + + '`embedder` to the plugin. Passages are sent to that embedder\'s provider.', + ), + { code: 'SERVICE_UNAVAILABLE', status: 503 }, + ); + } + return embedder; + } + + /** + * Make the store ready once: WAL on a file (a store written by two + * processes without it loses writes), the vector functions proven present, + * then the generation table. Until that succeeds the next call tries again. + */ + private async ready(): Promise { + if (this.isReady) return; + const client = this.requireClient(); + await this.queued(client, async () => { + if (this.isReady) return; + try { + await client.execute('SELECT 1'); + } catch (err) { + throw notReady( + 'it cannot open its libSQL database', + `Opening the database failed: ${errorText(err)}. Check the store's URL, that its directory exists and is writable.`, + ); + } + try { + // A remote database or `:memory:` keeps its own journal; only a file takes WAL. + await client.execute('PRAGMA journal_mode = WAL'); + } catch { + /* not a local file: the server decides its journal */ + } + try { + await client.execute("SELECT vector_distance_cos(vector32('[1,0]'), vector32('[1,0]'))"); + } catch (err) { + throw notReady( + 'its database has no vector functions', + `The database answered: ${errorText(err)}. The store needs libSQL (vector32, vector_distance_cos); ` + + 'a plain SQLite build has neither.', + ); + } + try { + for (const statement of generationDdl()) await client.execute(statement); + } catch (err) { + throw notReady( + 'its generation table could not be created', + `Creating ${GENERATION_TABLE} failed (${errorText(err)}). Check that the database is writable.`, + ); + } + this.isReady = true; + }); + } + + /** The active generation of a source and the one under construction. */ + private async generations(sourceId: string, tx?: Transaction): Promise { + const found = await (tx ?? this.requireClient()).execute({ + sql: `SELECT generation, fingerprint, recipe_hash, dim, state FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ?`, + args: [sourceId], + }); + const out: SourceGenerations = {}; + for (const r of found.rows) { + const row: GenerationRow = { + generation: Number(r.generation), + fingerprint: r.fingerprint === null ? null : String(r.fingerprint), + recipeHash: r.recipe_hash === null ? null : String(r.recipe_hash), + dim: Number(r.dim), + state: r.state === 'building' ? 'building' : 'active', + }; + out[row.state === 'active' ? 'active' : 'building'] = row; + } + return out; + } + + /** + * Whether the source still has a table of the store's earlier releases: a + * `knowledge_` table with exactly their columns (`tableShape`). + * Any other table under that name, the store's own generation table or a + * table the store did not make, is never taken for one, so never dropped. + */ + private async hasLegacy(sourceId: string): Promise { + if (this.noLegacy.has(sourceId)) return false; + const table = legacyTable(sourceId); + const legacy = table !== GENERATION_TABLE && (await this.shapeOf(this.requireClient(), table)) === 'legacy'; + if (!legacy) this.noLegacy.add(sourceId); + return legacy; + } + + /** The shape of the table under `table`, if any (`tableShape`). */ + private async shapeOf(db: Pick, table: string): Promise { + const columns = await db.execute({ sql: 'SELECT name, type FROM pragma_table_info(?)', args: [table] }); + return tableShape(columns.rows.map((r) => ({ name: r.name, type: r.type }))); + } + + /** Opens the next generation of a source: its row, and its table made afresh. */ + private async openGeneration( + tx: Transaction, + sourceId: string, + fingerprint: string | undefined, + embedder: IEmbedder, + state: 'active' | 'building', + ): Promise { + const next = await tx.execute({ + sql: `SELECT coalesce(max(generation), 0) + 1 AS n FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ?`, + args: [sourceId], + }); + const generation = Number(next.rows[0].n); + const table = generationTable(sourceId, generation); + // A table already under this name is made afresh only when it is one of + // this store's passage tables (left behind by a generation row deleted + // by hand). Anything else is never dropped: a legacy table of another + // source can share the name (`knowledge__g1` is source `a_g1`'s), and + // so can a table the store did not make, in a shared database. + const shape = await this.shapeOf(tx, table); + if (shape === 'legacy' || shape === 'other') { + throw notReady( + `a table it did not make holds the name of source '${sourceId}''s next index`, + `The database holds a table '${table}' that is not one of this store's generation tables, so generation ` + + `${generation} of source '${sourceId}' cannot be built under that name. Rename or remove that table, or keep ` + + 'the store in a database of its own.', + ); + } + for (const statement of passageTableDdl(table, embedder.dimensions)) await tx.execute(statement); + await tx.execute({ + sql: `INSERT INTO ${quoted(GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) VALUES (?, ?, ?, ?, ?, ?)`, + args: [sourceId, generation, fingerprint ?? null, embedder.dimensions, embedder.model ?? null, state], + }); + return { generation, fingerprint: fingerprint ?? null, recipeHash: null, dim: embedder.dimensions, state }; + } + + /** + * The generation a write carrying `ctx.index` goes to: the active one, when + * its fingerprint is the one carried (or none is carried); the one under + * construction, when it is that one's. Refused when it is neither, when the + * embedder's width is not the generation's, or — outside a build — when the + * source still has a legacy table. A source that holds nothing gets its first + * generation (`create`), or none. Runs inside the client's queue. + */ + private async writeTarget( + ctx: AdapterContext, + embedder: IEmbedder, + create: boolean, + ): Promise { + const sourceId = ctx.source.id; + const fingerprint = ctx.index?.fingerprint; + const { active, building } = await this.generations(sourceId); + const checked = (g: GenerationRow): GenerationRow => { + if (embedder.dimensions !== g.dim) throw rebuildRequired(sourceId, false); + return g; + }; + if (building !== undefined && fingerprint !== undefined && building.fingerprint === fingerprint) return checked(building); + if (active === undefined) { + if (await this.hasLegacy(sourceId)) throw rebuildRequired(sourceId, building !== undefined); + if (!create) return undefined; + const opened = await this.transaction(async (tx) => { + // Opened by a concurrent call between the read and this transaction: use it. + const again = await this.generations(sourceId, tx); + if (again.active) return { commit: true, value: again.active }; + return { commit: true, value: await this.openGeneration(tx, sourceId, fingerprint, embedder, 'active') }; + }); + if (fingerprint !== undefined && opened.fingerprint !== fingerprint) throw rebuildRequired(sourceId, false); + return checked(opened); + } + if (fingerprint === undefined || active.fingerprint === fingerprint) return checked(active); + throw rebuildRequired(sourceId, false); + } + + /** + * Run `work` in one write transaction (`BEGIN IMMEDIATE`): committed when it + * answers `commit: true`, rolled back when it answers `commit: false` or + * throws. Called inside the client's queue. + */ + private async transaction(work: (tx: Transaction) => Promise<{ commit: boolean; value: T }>): Promise { + const tx = await this.requireClient().transaction('write'); + try { + const { commit, value } = await work(tx); + if (commit) await tx.commit(); + else await tx.rollback(); + return value; + } catch (err) { + await tx.rollback().catch(() => undefined); + throw err; + } finally { + tx.close(); + } + } +} + +/** The passages of a document: the service's `chunks`, or the whole text as one. Empty passages are not stored. */ +function passagesOf(doc: KnowledgeDocument): Array<{ id: string; content: string; headingPath?: string[] }> { + const passages: Array<{ id: string; content: string; headingPath?: string[] }> = + doc.chunks ?? [{ id: `${doc.id}#0`, content: doc.content }]; + return passages + .filter((p) => p.content.trim() !== '') + .map((p) => ({ id: p.id, content: p.content, ...(p.headingPath === undefined ? {} : { headingPath: p.headingPath }) })); +} + +/** The hash of the text the adapter embeds for a passage. */ +function chunkHash(text: string): string { + return `c1:${createHash('sha256').update(text).digest('hex')}`; +} + +function requireIndex(ctx: AdapterContext, member: string): NonNullable { + if (ctx.index === undefined) { + throw new Error(`${member}: the call carries no index fingerprint (ctx.index); it is made by the knowledge service.`); + } + return ctx.index; +} + +/** + * A refusal under another fingerprint (ADR-0161 K7, rules 4 and 5), or of a + * source whose only index is a table of the store's earlier releases. Its + * message is one sentence a search caller may read; what to do is operator + * text, carried in `remedy`. + */ +function rebuildRequired(sourceId: string, building: boolean): Error { + const message = building + ? `Knowledge source '${sourceId}' is being rebuilt under its new index fingerprint; it answers again when the ` + + 'rebuild completes.' + : `Knowledge source '${sourceId}' needs a rebuild: its index was built under another embedding model, split or ` + + 'content recipe, and it is not searched until a complete reindex has rebuilt it.'; + return Object.assign(new Error(message), { + code: KNOWLEDGE_REBUILD_REQUIRED, + status: 409, + remedy: + 'Run a complete reindex of the source. The store builds the new index beside the old one and switches to it ' + + 'when the reindex completes; the old index is then dropped.', + }); +} + +/** + * The store is not ready. The message is one sentence with no database + * detail, as a search caller may read it; what went wrong and what to do are + * operator text in `remedy`, shown by `healthCheck`, the plugin's boot warning + * and the knowledge service's log. + */ +export function notReady(diagnosis: string, detail: string): Error { + return Object.assign(new Error(`The knowledge store (libSQL) is not ready: ${diagnosis}.`), { + code: 'SERVICE_UNAVAILABLE', + status: 503, + remedy: detail, + }); +} + +/** The operator text an adapter error carries, if any. */ +function remedyOf(err: unknown): string | undefined { + const remedy = err !== null && typeof err === 'object' ? (err as { remedy?: unknown }).remedy : undefined; + return typeof remedy === 'string' && remedy !== '' ? remedy : undefined; +} + +function parseJson(value: unknown): unknown { + if (typeof value !== 'string') return undefined; + try { + return JSON.parse(value); + } catch { + return undefined; + } +} + +function asRecord(value: unknown): Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {}; +} + +function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} diff --git a/packages/plugins/knowledge-turso/tsconfig.json b/packages/plugins/knowledge-turso/tsconfig.json new file mode 100644 index 00000000000..db389588d2f --- /dev/null +++ b/packages/plugins/knowledge-turso/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "target": "ES2020", + // module re-set from the base's NodeNext: tsup bundles this package and it declares no "type": "module", so tsc resolves the way the bundler does. + "module": "ES2020", + "moduleResolution": "bundler", + "declaration": true, + "outDir": "./dist", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "forceConsistentCasingInFileNames": true, + "types": ["node"], + "rootDir": "./src" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/plugins/knowledge-turso/tsconfig.test.json b/packages/plugins/knowledge-turso/tsconfig.test.json new file mode 100644 index 00000000000..0e01c20f3c1 --- /dev/null +++ b/packages/plugins/knowledge-turso/tsconfig.test.json @@ -0,0 +1,10 @@ +// The TEST-layer type-check program, the `packages/plugins/**` family's shape +// (see `../knowledge-memory/tsconfig.test.json` for the reasons, which hold +// here unchanged). Module semantics only, as vitest executes the tests; +// strictness, `paths` and `types` are all inherited from `tsconfig.json`. +// No `test-typecheck-debt.json` beside it: its absence is the zero. +{ + "extends": ["./tsconfig.json", "../../../tsconfig.test.base.json"], + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/plugins/knowledge-turso/vitest.config.ts b/packages/plugins/knowledge-turso/vitest.config.ts new file mode 100644 index 00000000000..ae5a5981ba2 --- /dev/null +++ b/packages/plugins/knowledge-turso/vitest.config.ts @@ -0,0 +1,68 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { defineConfig } from 'vitest/config'; +import path from 'path'; + +export default defineConfig({ + test: { + // A late console.* must not redden a green suite (#10374): vitest's worker + // forwards console output over RPC and discards the promise, and a write + // landing after teardown's rpcDone() snapshot is rejected into an unhandled + // error — a fully green run that exits 1. Disarming removes the mechanism. + // Mechanism + measured costs: examples/app-showcase/vitest.config.ts. + // Enforced repo-wide by scripts/check-console-intercept-disarm.mjs. + disableConsoleIntercept: true, + globals: true, + environment: 'node', + }, + resolve: { + alias: [ + // Subpath BEFORE the bare package: `@objectstack/core` is a PREFIX match with a + // FILE replacement, so without this entry it swallows the published `./logger` + // subpath and resolves it to `…/core/src/index.ts/logger` — ENOTDIR at run time. + // Pinned by the published-subpath rule in `scripts/check-test-source-alias.mjs`, + // which derives the population from `@objectstack/core`'s own `exports` map. + { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, + { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, + // `./testing` (the adapter contract suite) BEFORE the bare package, and both + // anchored: a string `find` matches by PREFIX, so the bare entry would + // resolve the subpath to `…/src/index.ts/testing` — ENOTDIR at run time. + { + find: /^@objectstack\/service-knowledge\/testing$/, + replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'), + }, + { + find: /^@objectstack\/service-knowledge$/, + replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'), + }, + // #9457: ONE anchored rule for every `@objectstack/spec` namespace, in place + // of the hand-maintained list of the subpaths this package's tests happened + // to reach. A string `find` matches by PREFIX, so with a FILE replacement the + // bare `@objectstack/spec` entry also swallowed every published namespace the + // list had not reached — `cloud`, `integration` and `studio` among them — and + // resolved it to `…/spec/src/index.ts/`: `ENOTDIR`, at run time, from a + // config that reads as correct, naming whichever module performed the import + // rather than this table. + // + // spec's export map is UNIFORM — every published namespace is + // `src//index.ts`, with no FILE-shaped subpath of the kind + // `@objectstack/platform-objects/plugin` is — so one rule covers all of them + // and cannot go stale as tests reach new namespaces. Same shape as + // `packages/qa/downstream-contract` (PR #8129), `service-knowledge`, + // `service-settings` and `plugin-audit`; `packages/runtime` carries the pin + // over the rule (`src/spec-subpath-alias-coverage.pin.test.ts`). + // + // Kept from the enumeration because the reasons outlive it: `security` is + // reached transitively via `@objectstack/types` ([ADR-0105 D1] tenancy + // posture) and `shared` via `@objectstack/core`'s plural→singular fold + // (`pluralToSingular`, #7378). Neither is a reason to keep listing + // namespaces by hand. + { + find: /^@objectstack\/spec\/([a-z-]+)$/, + replacement: path.join(path.resolve(__dirname, '../..'), 'spec/src/$1/index.ts'), + }, + { find: /^@objectstack\/spec$/, replacement: path.resolve(__dirname, '../../spec/src/index.ts') }, + ], + }, +}); diff --git a/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts b/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts index 7c4833e92f6..be9f3365919 100644 --- a/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts +++ b/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts @@ -97,11 +97,13 @@ describe('knowledgeTestActionHandler', () => { expect(r.severity).toBe('warning'); }); - it('accepts turso with no URL (will reuse tenant connection)', async () => { + it('accepts turso with no URL (the plugin defaults to its own file)', async () => { const r = await knowledgeTestActionHandler({ values: { adapter: 'turso' } } as any); expect(r.ok).toBe(true); expect(r.severity).toBe('info'); - expect(r.message).toMatch(/reuse the tenant/); + // The plugin opens a file of its own, never the platform's database (#37107). + expect(r.message).toMatch(/knowledge\.db/); + expect(r.message).not.toMatch(/reuse the tenant/); }); it('accepts turso with local file URL', async () => { @@ -130,20 +132,19 @@ describe('knowledgeTestActionHandler', () => { expect(r.ok).toBe(true); }); - // The turso adapter's plugin package is NOT built in this repo, so the live-call - // hint an operator reads in Settings -> AI & Embedder cannot be a bare "Mount - // @objectstack/knowledge-turso": that instruction was un-followable — it named a - // package with no directory here and no statement of where it comes from. Pinned - // as a property (names the package AND where it ships), not as a literal, so the - // wording can be improved without the guard going stale. - it('turso live-call hint says where the out-of-repo package comes from', async () => { + // The turso adapter's plugin package is built in this repo since #37107. The + // live-call hint names the package and how a deployment registers it, and no + // longer says it ships elsewhere. Pinned as a property, not as a literal, so + // the wording can be improved without the guard going stale. + it('turso live-call hint names the package and how it is registered, not an outside origin', async () => { const r = await knowledgeTestActionHandler({ values: { adapter: 'turso', turso_url: 'file:./knowledge.db' }, } as any); expect(r.ok).toBe(true); const message = String(r.message); expect(message).toContain('@objectstack/knowledge-turso'); - expect(message).toMatch(/ObjectOS Cloud monorepo/); + expect(message).toMatch(/registered beside the knowledge service/); + expect(message).not.toMatch(/ObjectOS Cloud monorepo|does not ship/); // the un-followable form this card retired: named, with no origin stated expect(message).not.toMatch(/Mount @objectstack\/knowledge-turso to exercise live calls/); }); diff --git a/packages/services/service-settings/src/manifests/knowledge.manifest.ts b/packages/services/service-settings/src/manifests/knowledge.manifest.ts index 7c1e91f8b77..55961c5213f 100644 --- a/packages/services/service-settings/src/manifests/knowledge.manifest.ts +++ b/packages/services/service-settings/src/manifests/knowledge.manifest.ts @@ -10,25 +10,17 @@ import type { SettingsActionHandler } from '../settings-service.types.js'; * knowledge sources and any future agent that needs to embed ad-hoc * inputs. * - * Adapter list — two of these plugin packages are built in this repo and one - * is not, which is the difference that matters to an operator told to mount - * one of them: - * - memory @objectstack/knowledge-memory built here (dev / test ref) - * - ragflow @objectstack/knowledge-ragflow built here (external RAGFlow) - * - turso @objectstack/knowledge-turso NOT built here — libSQL native - * F32_BLOB, works for cloud - * Turso AND local file mode + * Adapter list — every one of these plugin packages is built in this repo: + * - memory @objectstack/knowledge-memory (dev / test ref) + * - ragflow @objectstack/knowledge-ragflow (external RAGFlow) + * - turso @objectstack/knowledge-turso libSQL native vectors, in a + * file of its own or on Turso; + * built here since #37107 (its + * 6.x releases came from the + * ObjectOS Cloud monorepo) * - * Spelled out for `turso` because the undated claim that used to stand here — - * "mirrors the plugin packages currently published" — stopped being true and - * nothing caught it. The package IS published on the public npm registry, but - * on its own version track: `latest` was 6.9.0 (published 2026-05-27) while - * this repo shipped 17.2.0, and 6.9.0 exact-pins `@objectstack/spec@6.9.0`, so - * mounting it into an app on this platform version resolves a SECOND spec - * rather than reusing this one. Its source lives in the ObjectOS Cloud - * monorepo (see this repo's README). Measured against the registry on - * 2026-08-23 with `@objectstack/spec` + `@objectstack/cli` as positive - * controls; re-measure before treating those numbers as current. + * None of them reads this namespace yet: a deployment registers the plugin + * beside the knowledge service itself. * * As with the AI manifest, the real adapter wiring happens in the * knowledge plugins; this manifest is the canonical settings surface @@ -187,7 +179,8 @@ export const knowledgeTestActionHandler: SettingsActionHandler = async ({ values ok: true, severity: 'info', message: - 'No URL configured — adapter will reuse the tenant\'s primary libSQL connection at runtime. ' + + 'No URL configured — the @objectstack/knowledge-turso plugin defaults to its own file, ' + + 'knowledge.db under .objectstack/data/, never the platform database. ' + FORM_CHECK_ONLY, }; } @@ -203,10 +196,8 @@ export const knowledgeTestActionHandler: SettingsActionHandler = async ({ values ok: true, severity: 'info', message: - `Turso adapter configured (${u}). ${FORM_CHECK_ONLY} Live calls need @objectstack/knowledge-turso, ` + - 'which this platform does not ship: it is built in the ObjectOS Cloud monorepo ' + - 'and published on its own version track, so check that it offers a release ' + - 'compatible with your platform version before mounting it.', + `Turso adapter configured (${u}). ${FORM_CHECK_ONLY} Live calls need the ` + + '@objectstack/knowledge-turso plugin registered beside the knowledge service, with this URL.', }; } diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 49428e2bcbc..175ca2853e2 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -178,9 +178,9 @@ function registerObject(rawConfig: unknown) { --- -## 7. Package Ecosystem (77 packages) +## 7. Package Ecosystem (78 packages) -The workspace publishes 77 packages under the `@objectstack` scope. The table +The workspace publishes 78 packages under the `@objectstack` scope. The table below is a curated entry-point list, not the full set — drivers, connectors, triggers, plugins and kernel-managed services each form their own family. diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 3f496f9c96a..78a4f03a300 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -1670,6 +1670,11 @@ export const ERROR_CODE_LEDGER = { '@objectstack/knowledge-pgvector': [ 'KNOWLEDGE_REBUILD_REQUIRED', ], + // [#37107] The libSQL store, moved in from the cloud repo: the same refusal, + // and also for a source whose only index is a table of its earlier releases. + '@objectstack/knowledge-turso': [ + 'KNOWLEDGE_REBUILD_REQUIRED', + ], '@objectstack/plugin-audit': [ 'FEEDS_DISABLED', 'FILES_DISABLED', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 97e1ba06f76..5ca043f062c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1826,6 +1826,34 @@ importers: specifier: ^4.1.11 version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1)) + packages/plugins/knowledge-turso: + dependencies: + '@libsql/client': + specifier: ^0.18.0 + version: 0.18.0 + '@objectstack/core': + specifier: workspace:* + version: link:../../core + '@objectstack/spec': + specifier: workspace:* + version: link:../../spec + devDependencies: + '@objectstack/service-knowledge': + specifier: workspace:* + version: link:../../services/service-knowledge + '@types/node': + specifier: ^26.6.5 + version: 26.6.5 + tsx: + specifier: ^4.23.15 + version: 4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6) + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vitest: + specifier: ^4.1.11 + version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1)) + packages/plugins/organizations: dependencies: '@objectstack/core':