Skip to content

Commit 40570d6

Browse files
feat(knowledge): knowledge-turso moves into objectstack — Apache-2.0, platform embedder and splitter, generations, the contract suite (#37388)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ88NDT2MrJFi2ZJy4HVSApob)_ Fixes #37107 Clause-②: yes Metadata-protocol: none ## 维护者速读 - 本地开发(默认 SQLite)和不用 PostgreSQL 的部署,现在也能用开源自带的向量知识库:向量存在项目数据目录下单独的 knowledge.db 文件里,中文检索可用;换嵌入模型时在旁边建新索引,建好再切换,旧索引在此期间照常回答。 - 属于「知识检索平台化」专题:把原来放在 cloud 仓库的 libSQL 向量库搬进开源框架(Apache-2.0),改用平台统一的嵌入器和切分器,并通过与 pgvector 同一套契约测试。 - 新包默认不启用,撤回只需不注册该插件;它绝不写平台自己的数据库文件;在没有 libSQL 原生构建的平台(Windows ARM)上照常启动,只是知识源回答「暂不可用」。 - 已按第一轮复核修完:只认旧版完整表结构,不会误删登记表或别人的表;远程库每次请求有 10 秒上限(按单次请求计时,重建一整批也不会超时;超时只回滚、不会事后提交);并补上「限定范围检索」。 - 要你做的:无(专题席位做差量复核;cloud 仓库删除旧包是另一张 cloud 卡)。 ## What changes **`@objectstack/knowledge-turso` moves into `packages/plugins/knowledge-turso`** (Apache-2.0 `LICENSE` text, settling cloud ADR-0119 D5's mixed licence). Same package name; the next version publishes from here, in the fixed version group. - **Its own libSQL database, never the platform's file.** `url` option (`file:`, `:memory:`, `libsql://`), else `file:` + project root + `/.objectstack/data/knowledge.db` (`defaultStoreUrl`, for #37102 to name). A URL naming `objectstack.db`, `dev.db`, `standalone.db` or the file `OS_DATABASE_URL` names (a URL or a bare path) is refused, compared percent-decoded, without case, as the file a link resolves to, and with SQLite's `-wal` / `-shm` / `-journal` side files read as their database (os-bob's #37106 measurement, comment 7143523345: two engines on one file lose rows). On a file: `PRAGMA journal_mode = WAL` and a busy timeout (`busyTimeoutMs`, default 5000). In one process all database work of one client runs through one queue: a write transaction holds its connection across awaits, and a second in-process writer would otherwise wait in SQLite's synchronous busy handler on the very thread the holder needs. On a remote URL each request is bounded on its own (`requestTimeoutMs`, default 10000): a statement, a document's batch (a write sends each document's statements as one batch, so a 100-document page is ~100 requests), opening a transaction, a commit or rollback. Past it the call answers `503 SERVICE_UNAVAILABLE` naming `requestTimeoutMs`, and the queue moves on. A request that times out inside a write is followed by a rollback, never a commit; only a commit that itself times out may still land, and its remedy says so (writes are idempotent). - **Platform embedder and splitter.** The package's own embedding provider, hash embedder and chunker are deleted; it reads the kernel `embedder` service at each call (or `embedder`), reports `embedding` (model, dimensions, maxInputTokens), and declares `capabilities.chunks`. - **Layout (card item 4).** `knowledge_generation` (source_id, generation, fingerprint, recipe_hash, dim, model, state, created_at) with two partial unique indexes: one `active` and one `building` row per source; the second is the lock row that keeps one builder per source. One passage table per source and generation, `knowledge_SOURCE_gN` (chunk_id PK, document_id, source_record_id, organization_id, content, title, heading_path, doc_hash, chunk_hash, metadata, embedding `F32_BLOB(dim)`). Source ids are held to the spec's `^[a-z_][a-z0-9_]*$` before any SQL (refused `400 VALIDATION_ERROR`); every value is a bind parameter. The unique index keeps one generation under construction per source, not one builder: a second `beginBuild` under the same fingerprint joins the build, one under another fingerprint replaces it, and the first builder's writes are then refused 409. - **Generations (card item 5; ADR-0161 K7, K8 item 8).** Writes go to the generation of the carried fingerprint (active or building), else `409 KNOWLEDGE_REBUILD_REQUIRED`; a search under another fingerprint than the active one's is refused the same way ("is being rebuilt" while a build for it runs). `beginBuild` under a new fingerprint creates `knowledge_SOURCE_gN+1` beside the active table; a build of a third fingerprint drops the unfinished one. `completeBuild` makes it active, records the recipe hash, drops the old table. `indexStatus` answers fingerprint, recipeHash and `building`. Unlike knowledge-pgvector (which refuses a second generation, #37101), this store runs the suite with `generations: true`. - **Legacy table (card item 4, last bullet).** A `knowledge_SOURCE` table of the cloud releases, recognised by exactly their seven columns and an `F32_BLOB` vector, is never served. A table of any other shape under a store name (the store's own generation table, another source's generation table, a table the store did not make in a shared database) is neither served nor dropped; `openGeneration` remakes a table only when it has the passage shape: search answers `KNOWLEDGE_REBUILD_REQUIRED`, a write outside a build is refused, `beginBuild` opens generation 1 as building, and `completeBuild` drops the legacy table. - **Search.** Exact cosine scan (`vector_distance_cos`) with the organization filter, the record scope and the metadata `filter` (JSON equality per top-level key) in the same `WHERE`, before ranking; hits carry `docHash` and `headingPath`. No DiskANN index: `vector_top_k` ranks before it filters, which breaks K8 item 9, and it is what made os-bob's 1,000 × 1,536 file 329 MB with a 21.8 s build. Measured here without it: 1,000 passages 8.3 MB, write 0.7 s, search ~5 ms; 10,000 passages 82 MB, write 7.2 s, search ~52 ms (Linux x64). Docs say so and point larger sources at pgvector. - **Record scope (#37308, merged as 98b17fe), as knowledge-pgvector.** A scope with no term that has ids answers `[]` before any query; terms are ORed inside the organization-filtered `WHERE`. A `record` term matches `source_record_id`; a `metadata` term matches a stored string or number equal to an id as text, or a list with such an element, by the field's stored key (bound, never a JSON path). Each term's ids go as one bound JSON array. The suite declares `implements.scope: true`. - **listDocuments (card item 6)**, byte-order cursor, the generation writes go to. A passage whose `chunk_hash` is stored is not re-embedded; a passage removed by a concurrent write is re-planned (3 attempts), as in pgvector. - **Degrades instead of crashing (os-bob comment, Windows on ARM).** `@libsql/client` is imported lazily in `start()`; a failed load (no native build), an unopenable file or a refused URL registers the adapter unavailable: boot continues, `healthCheck` `ok: false`, every call `503 SERVICE_UNAVAILABLE`, one-sentence message, reason in `remedy`. - **Wiring (named in the claim).** `.changeset/config.json` fixed group; `pnpm-lock.yaml` (no new external dependency: `@libsql/client@0.18.0` is already in the lockfile); one ledger row `@objectstack/knowledge-turso: [KNOWLEDGE_REBUILD_REQUIRED]` in `packages/spec/src/api/error-code-ledger.zod.ts` (its docs mirror lists codes only, unchanged); `packages/spec/llms.txt` package count 77 → 78 (`check:llms-txt` demanded it). - **Settings hint made false by this PR, fixed (claim amended).** `knowledge.manifest.ts`: the Turso "Test connection" hint said the package "this platform does not ship", from the ObjectOS Cloud monorepo, and that a store with no URL reuses the tenant's primary libSQL connection; both are now false. It now names the plugin registered beside the knowledge service and its default file; header list updated; the two tests re-pinned as properties. Minimal, as #37104 rewrites this manifest. - **Docs.** `content/docs/protocol/knowledge.mdx` new section 4.2, overview diagram, contract paragraph, example, status table; `content/docs/ai/knowledge-rag.mdx` new section "Local vector store: a libSQL file". ## Why Card #37107 (ADR-0161 Execution row 7; cloud ADR-0119 D5 「都放开源」): every deployment not on PostgreSQL, `os dev` included, gets an open vector store that follows the platform's embedder, splitter, listing and fingerprint contract. ## Tests `packages/plugins/knowledge-turso`, 143 cases, no service or image (libSQL runs in-process): - `contract.test.ts` — `runKnowledgeAdapterContract` with every member declared (`listDocuments`, `chunks`, `organizationIds`, `indexStatus`, `builds`, `refusesOtherFingerprint`, `generations`, `scope`) on `:memory:` and on a `file:` URL: 92/92. - `acceptance.test.ts` (42, both stores plus two request-bound cases): Chinese text found with a fixed fake embedder; same content re-upserted → no embed call, changed passage → only it embedded; model changed at the same width and at another width → through `KnowledgeService` the search is refused, a complete reindex builds `_g2`, `_g1` is dropped, the generation row records the new width and model; mid-build the old generation answers its own fingerprint and the new one is "being rebuilt", a third fingerprint abandons the unfinished build and a write under the abandoned fingerprint is refused; two organizations never see each other's hits (topK 1, filter before ranking); metadata filter by JSON type (`2` vs `"2"`); legacy table → `KNOWLEDGE_REBUILD_REQUIRED`, write refused, `indexStatus` empty, then a reindex replaces and drops it; another source's generation table never read as legacy; a source named `generation` reindexed with the store's generation table intact and other sources still answering; a table the store did not make under a legacy name kept through a reindex, and under a generation name refused and kept; a passage table left without its generation row remade afresh, not adopted; a write whose generation is switched while it embeds refused 409, never written elsewhere; a record scope by stored key (a dotted name is a key), strings and numbers only (a boolean or object matches no id), a quote in a name, an injection-shaped id matching nothing; 12 concurrent upserts and searches on one `:memory:` client all succeed; an unsafe source id refused before SQL; no client / no embedder → `SERVICE_UNAVAILABLE` with the reason only in `remedy`, `listDocuments` included (503, not 409); a request that never answers is bounded by `requestTimeoutMs` and the queue moves on; on a slow client (15 ms a request, 120 ms bound) a page of 40 documents of 2 passages is written whole, twice; a write whose second batch hangs answers 503 naming `requestTimeoutMs` and nothing of it lands, then the next write goes through; a table with the legacy column names but no `F32_BLOB` vector is not legacy; a search whose generation is switched at every embed stops after three attempts (503); a source id outside the pattern is `400 VALIDATION_ERROR`, an 80-character one accepted. - `plugin.test.ts` (9): default URL; platform database refused by name (percent-encoded and differently cased too) and by `OS_DATABASE_URL` (a URL or a bare path); an undecodable `file:` URL refused; side files and links (a linked file, a linked directory) refused; the remote default bound (`requestBoundFor`); the opened file is in WAL with the generation table; a `@libsql/client` that fails to load (mocked `win32-arm64-msvc` error) registers an unavailable adapter and boot continues; a kernel embedder registered after `start` is read. Single-change ablations, each restored: the old legacy rule (4 red), `openGeneration` remaking a foreign table (2 red), the fresh-table `DROP` (2 red), `listDocuments` comparing before the embedder (1 red), the request bound (1 red), the old whole-turn bound (both request-bound cases red), a commit instead of a rollback after a timeout (1 red), the vector-type half (2 red), the `VALIDATION_ERROR` code (2 red), the search retry bound (2 red), the remote default (1 red), the side-file reading (1 red), the write-time generation recheck (2 red), the scope scalar guard (2 red), the scope `WHERE` (12 red in the suite). Not covered here: two processes writing one file (the busy timeout is set and pinned by `PRAGMA`, not by a two-process race). Scope ids are compared with a stored number's SQLite text: exponent forms and numbers past 15 significant digits match no id here (fewer hits, never more; the service's check after the answer stays the guard). ## Acceptance notes - `carrier: cloud` — `packages/knowledge-turso` in the cloud repo is now a duplicate; its removal is the cloud card the card names (out of scope). Nothing in cloud imports the package outside its own directory (searched cloud `origin/main`). - `carrier: #37102` — the runtime mount names the store's path; `defaultStoreUrl(projectRoot)` and `PLATFORM_DATABASE_FILES` are exported for it. - noted, not filed — the `knowledge` settings namespace (`turso_url`, `turso_auth_token`) is still read by no plugin; #37104 rewrites the manifest. - Breaking for npm consumers of the cloud-repo 6.x releases (removed exports and options, listed in the changeset); the version moves from 6.9.0 to this repo's track. ## Verification Two-minute check: `pnpm --filter @objectstack/knowledge-turso test` → `Test Files 3 passed (3)`, `Tests 143 passed (143)`. Read first: `src/turso-adapter.ts` `beginBuild` / `completeBuild` / `writeTarget` (generation switching), `hasLegacy` / `openGeneration` with `tableShape` in `src/sql.ts` (the legacy rule), the `serial` queue and its bound at its top, and `src/plugin.ts` `resolveStoreUrl` (the platform-file refusal). <details><summary>Local gates at head 796b204: 133 of 134 derived families exit 0, 1 not measured; CI at 796b204: 62 success, 9 skipped, 0 failed</summary> - `node scripts/pm/dispatch-gates.mjs --ran` (with exit codes): 134 derived famil(ies) accounted for, 133 run, 1 NOT-MEASURED (1 derived from a recorded exit 3). - `pnpm --filter @objectstack/knowledge-turso test`: Test Files 3 passed (3), Tests 143 passed (143) (lock VERDICT command-exit 0). `typecheck` (incl. `check:test-typecheck`) and `build` exit 0. - `service-settings`: `knowledge.manifest.test.ts` 25/25; `typecheck` exit 0. - `check:llms-txt` green at 78 packages. `check:error-code-provenance`, `check:docs`, `check:package-naming`, `check:changeset-no-major`, `check:dual-build-cjs-loads`, `check:published-readme-exports`, `check:skill-examples` exit 0 at this head. - NOT MEASURED locally (exit 3, prerequisite not met): `check-plugin-teardown-shape --self-test` (needs an unshallow clone; its scan passed). - No `.github/workflows` edit: the libSQL suite runs in the normal test shards, no service image needed. Dogfood battery: n/a (no `!` in the title, no narrowing arm). - History: `56f3dc5e` (first hand-back) → `68654e1d` merges `main` at `db77cc49` (brings #37342) → `9c469ddf` the record scope → `f073750a` review round 1 (seat comment 7179839476) → `796b204c` review round 2 (seat comment 7180860083). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (CI). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed (none change for a ledger row; `check:error-code-provenance` and `check:docs` green). - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbaMuehXzctoWq7iRsV)_ <!-- signed: repo:cloud#1 · os-warren · session_01JQwxbaMuehXzctoWq7iRsV --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f9dd033 commit 40570d6

23 files changed

Lines changed: 2885 additions & 37 deletions
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/knowledge-turso': patch
3+
'@objectstack/spec': patch
4+
'@objectstack/service-settings': patch
5+
---
6+
7+
feat(knowledge): the libSQL vector store moves into the open framework, with generations, listing and the adapter contract suite
8+
9+
Clause-②: yes
10+
Metadata-protocol: none
11+
12+
ADR-0161 Execution row 7; cloud ADR-0119 D5 (#37107).
13+
14+
- **`@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.
15+
- **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.
16+
- **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_<source>_g<n>`. 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_<source>` with exactly their columns) is never served: a search answers `KNOWLEDGE_REBUILD_REQUIRED`, and the table is dropped when the first complete reindex finishes.
17+
- **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.
18+
- **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`.
19+
- **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.
20+
- The package runs `runKnowledgeAdapterContract` with every member declared (`scope` included), on `:memory:` and on a `file:` URL, in its own unit tests.

‎.changeset/config.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979
"@objectstack/service-storage",
8080
"@objectstack/knowledge-memory",
8181
"@objectstack/knowledge-pgvector",
82+
"@objectstack/knowledge-turso",
8283
"@objectstack/knowledge-ragflow",
8384
"@objectstack/embedder-openai",
8485
"@objectstack/account",

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Part of the [AI module](/docs/ai) — how agents retrieve knowledge through the
99
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.
1010

1111
<Callout type="info">
12-
**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).
12+
**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).
1313
</Callout>
1414

1515
## Wiring
@@ -212,6 +212,20 @@ new KnowledgePgvectorPlugin({ queryPrefix: '' /* e.g. BGE's query instruction */
212212

213213
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).
214214

215+
## Local vector store: a libSQL file
216+
217+
`@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'`:
218+
219+
```ts
220+
new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL
221+
```
222+
223+
- 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.
224+
- A changed model or split is rebuilt beside the old index, which keeps answering until the reindex completes.
225+
- Where libSQL has no native build (Windows on ARM), boot goes on and its sources answer `SERVICE_UNAVAILABLE`.
226+
227+
Details are in [the protocol's turso section](/docs/protocol/knowledge#42-knowledge-turso--the-open-vector-store-in-a-libsql-file).
228+
215229
## Why we did not build a vector DB
216230

217231
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.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ delegates the rest to plugins.
8484
│ • Event sync (record.* → upsert) │ │ (reference impl, REST) │
8585
│ • Audit + metrics │ │ • knowledge-pgvector │
8686
│ │ │ (PostgreSQL + pgvector) │
87+
│ │ │ • knowledge-turso │
88+
│ │ │ (libSQL file, local) │
8789
│ Registers `knowledge` service │ │ (llamaindex / dify: planned)│
8890
└──────────────────────────────────────┘ └──────────────────────────────┘
8991
▲
@@ -374,7 +376,8 @@ keeps generations, the switch at the end of a build. `implements` declares the o
374376
checks the declaration against the adapter. `./testing` is a test-only,
375377
ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it.
376378
`knowledge-memory` runs it as the reference implementation; `knowledge-pgvector`
377-
runs it against a live PostgreSQL in CI.
379+
runs it against a live PostgreSQL in CI; `knowledge-turso` runs it on libSQL
380+
`:memory:` and on a `file:` URL in its own unit tests.
378381

379382
### 3.5 The split
380383

@@ -485,6 +488,7 @@ import { KnowledgeServicePlugin } from '@objectstack/service-knowledge';
485488
import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory';
486489
import { KnowledgeRagflowPlugin } from '@objectstack/knowledge-ragflow';
487490
import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector';
491+
import { KnowledgeTursoPlugin } from '@objectstack/knowledge-turso';
488492

489493
defineStack({
490494
plugins: [
@@ -495,6 +499,7 @@ defineStack({
495499
apiKey: process.env.RAGFLOW_KEY!,
496500
}),
497501
new KnowledgePgvectorPlugin(), // self-hosted, PostgreSQL + pgvector
502+
new KnowledgeTursoPlugin(), // local / not on PostgreSQL, a libSQL file
498503
],
499504
});
500505
```
@@ -569,6 +574,56 @@ an exact scan.
569574
sensitive as the record it came from, and it is in every backup of the
570575
database.
571576

577+
### 4.2 `knowledge-turso` — the open vector store in a libSQL file
578+
579+
`@objectstack/knowledge-turso` keeps a source's passages and vectors in a
580+
[libSQL](https://github.com/tursodatabase/libsql) database of its own, with
581+
libSQL's native vectors (`F32_BLOB`, `vector32`, `vector_distance_cos`): the
582+
store for local development and for a deployment not on PostgreSQL. It takes
583+
the service's passages, embeds them with the kernel's `embedder` service (or
584+
the `embedder` it is given), and answers a search by an exact scan.
585+
586+
- **Which database.** The `url` option (`file:`, `:memory:` or a
587+
`libsql://` Turso URL), else `knowledge.db` under the project's
588+
`.objectstack/data/`, beside the platform database. Never the platform's
589+
own file: two engines writing one SQLite file in one process lose rows, so a
590+
URL naming `objectstack.db`, `dev.db`, `standalone.db` or the file
591+
`OS_DATABASE_URL` names is refused. On a file the store sets WAL and a busy
592+
timeout (`busyTimeoutMs`, default 5000); in one process every call of the
593+
store runs its database work one at a time.
594+
- **Tables.** `knowledge_generation`, one row per source and generation
595+
(fingerprint, recipe hash, width, model, active or being built; at most one
596+
of each per source, by a unique index — a second build joins the one under
597+
way when its fingerprint is the same, and replaces it otherwise, so the
598+
first builder's writes are then refused), and one passage table per source and generation,
599+
`knowledge_<source>_g<n>`, its vector column sized for that generation. A
600+
source id that is not snake_case is refused before
601+
any SQL.
602+
- **Search.** An exact scan by cosine distance; the organization filter, the
603+
[record scope](#record-scope) and the metadata `filter` (JSON equality per
604+
key) run in the same `WHERE`, before ranking. The store creates no DiskANN index: `vector_top_k` ranks
605+
before it filters, and with one, 1,000 vectors of 1,536 dimensions grew a
606+
file from 8.2 MB to 329 MB and took 21.8 s to index. Without it the same
607+
1,000 passages take 8.3 MB and a search about 5 ms; 10,000 take 82 MB and
608+
about 50 ms. A larger source belongs on `knowledge-pgvector`.
609+
- **Rebuilds.** A changed fingerprint is refused (§3.6). A complete reindex
610+
under a new fingerprint builds a new generation table beside the active
611+
one, which keeps answering its own fingerprint, and switches at the end of
612+
the build; the old table is dropped. A build of a third fingerprint
613+
abandons one left unfinished. A table of the package's earlier releases
614+
(`knowledge_<source>` with exactly their columns) is never served: a search
615+
answers `KNOWLEDGE_REBUILD_REQUIRED`, and the table is dropped when the first
616+
complete reindex finishes. A table of any other shape under one of the
617+
store's names is neither served nor dropped.
618+
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
619+
not embedded again within a generation.
620+
- **When it cannot run.** A database that cannot be opened, or a platform
621+
with no native libSQL build (there is none for Windows on ARM): the plugin
622+
still registers and boot goes on; it warns with the reason, `healthCheck`
623+
answers `ok: false`, and every call answers `SERVICE_UNAVAILABLE`.
624+
- **The text is stored.** Each row holds its passage's text, as sensitive as
625+
the record it came from, and in every copy of the file.
626+
572627
---
573628

574629
## 5. Permission-aware retrieval (the unique value-add)
@@ -928,6 +983,7 @@ up.
928983
| `knowledge-llamaindex` | ⏳ Phase 2 | |
929984
| `knowledge-dify` | ⏳ Phase 3 / community | |
930985
| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) |
986+
| `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) |
931987

932988
### 7.1 Non-goals for Phase 1
933989

0 commit comments

Comments
 (0)