Skip to content

Commit 87af66e

Browse files
feat(core): requires knowledge mounts the knowledge service and one vector store (#37442)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ84BSz1obpkWFoBogsxn7rAx)_ Fixes #37102 Clause-②: yes Metadata-protocol: added Skills-docs: follow-up #37310 ## 维护者速读 - 用户能看到什么变化:应用声明需要“知识检索”后,平台自动装好检索服务和一个向量库(PostgreSQL 项目用同一个数据库,其他数据库用项目本地的一个文件);没有声明的部署前后完全一样。 - 为什么做:属于“知识检索平台化”专题,让本地开发和自建部署不用手工接线就有可用的检索。 - 出错会怎样:只影响声明了该能力的应用;检索源指向没装上的向量库时应用照常启动,检索会明确报错并说明可选的库;回退本改动即可恢复原状。 - 要你做什么:批准一次。本改动在两份对外技能文件里各补了一个能力名(受管的技能文件),需要你批准后才能合并。 ## What changes - **New capability token `knowledge`** in `PLATFORM_CAPABILITY_TOKENS` / `PLATFORM_CAPABILITY_PROVIDERS` (provider `@objectstack/service-knowledge`, edition `open`) and in core `CAPABILITY_PROVIDERS`. - **Store selection, shared by both boots** (`@objectstack/core`): `resolveKnowledgeStore` / `resolveCapabilityExtras` + `KNOWLEDGE_STORE_PROVIDERS`. PostgreSQL (driver `postgres` or a `postgres(ql)://` URL) → `KnowledgePgvectorPlugin` on the same URL; `:memory:` → in-memory turso; anything else → `KnowledgeTursoPlugin` on `knowledge.db` in the data directory (`.objectstack/data/`, or `<OS_HOME>/data/` when `OS_HOME` is set) with `urlFromSettings`. `knowledge-memory` is never mounted. - **`os serve`** reads the primary database it resolved and mounts the one store; an extra that cannot be imported or constructed now warns instead of being skipped silently. A host that mounts the service or a store itself keeps its own (`hasPluginMatching` on the identities). - **`@objectstack/verify`** `constructServedProviders` takes an optional `database` (default in-memory SQLite) and mounts the same store as serve. - **Unmounted adapter** (`service-knowledge`): service mounts, boot does not fail; at `kernel:bootstrapped` one `error` line per such source naming the mounted adapters; index and search of that source answer `SERVICE_UNAVAILABLE` 503 with the same message (existing code, no new error code). A multi-source search keeps the other sources' hits and names the refused one. - **Carry from #37107 (comment 7181713320)** (`knowledge-turso`): under the token the store URL comes from settings (`knowledge.turso_url` / `turso_auth_token`). `resolveSettingsStoreUrl` holds a saved `file:` URL to the realpath'd `.objectstack/data/` (symlink escape, `..`, the directory itself and the platform DB file are refused) and refuses a NUL or other control character, all before `createClient`. `resolveStoreUrl` refuses control characters too. - **The saved store URL is read at `kernel:bootstrapped`, not in `start()`** (`knowledge-turso`, fix round). The settings service answers a saved value only once its data engine is bound, in its own `kernel:ready` hook; a read in `start()` saw the manifest default while the saved row sat unread, so the store opened the default file whatever the operator had saved (`check:settings-bind-window` named it; reproduced on a real kernel, see Verification). Under `urlFromSettings` the adapter is now registered in `start()` with no database and answers `SERVICE_UNAVAILABLE` 503; the plugin registers its `kernel:bootstrapped` handler in `init()`, so it runs ahead of every handler a plugin registers in `start()`: the knowledge service's embedder, its reading of unmounted adapters, and the first build of #37099 find the store open. A store given `url` or `client` opens in `start()` as before. The plugin's `optionalDependencies` keep only the knowledge service: no ordering edge moves a `start()` read past the settings bind. - **Rework after contract record 7187791236 (FAIL on M1) and the seat's REWORK note:** - **M1, a percent-encoded control character is refused** (`knowledge-turso`). `resolveStoreUrl` and `resolveSettingsStoreUrl` tested the raw URL only, so a saved `file:…/k%00.db` passed both; libSQL decodes the path it opens and its native library ends the process on the NUL byte, at every boot. Both now read each `%XX` escape as the character it encodes and refuse a control character in either spelling, before anything touches the disk or the client. The check is in `resolveStoreUrl`, so the plugin's own `url` option holds too. - **S3, `@objectstack/knowledge-turso` is an optional dependency** of `@objectstack/cli` and `@objectstack/verify` (it was a hard one in the first round). Its libSQL client is a native module with an `os` / `cpu` list; as a hard dependency it would refuse the whole CLI install outside that list. `KNOWLEDGE_STORE_PROVIDERS.turso` and its `CapabilityExtra` carry `optional: true`. `os serve` already warns when an extra cannot be imported and boots on; `constructServedProviders` now does the same for an optional extra (any other provider it cannot load is still a thrown boot error). - **S4, the store's file follows `OS_HOME`** (`os start --home` sets it): `resolveKnowledgeStore` hands the store `stateDir`, and the data directory is then `<OS_HOME>/data/`, the directory the boot keeps the default platform database in (`resolveDatabaseStateDir`'s order). The settings confinement moves with it, so an operator can keep the file on the volume. Without `OS_HOME` nothing changes. New plugin option `stateDir`; `dataDirectoryOf` and `defaultStoreUrl` take it as a second argument. A database named by URL does not move the store (documented). - Docs (`knowledge-rag.mdx`): where the file is, what more than one replica means on MySQL, MongoDB or remote libSQL (one local file per replica, each indexing only its own writes: use a shared `libsql://` store or PostgreSQL), and an install without the libSQL client. - Changeset: the sentence about a host-mounted service no longer overstates (a host that mounts the service gets no store from the runtime). - **After the delta record 7193770862 (PASS) and the seat's note 7193780591: the auth token is checked too** (`knowledge-turso`, commit 664bd70). `turso_auth_token` is the second settings value handed to the libSQL client. A token with a NUL byte, a line break or another control character is refused in the plugin's one open path (`open()`), for the saved setting and for the `authToken` option alike, before the client is created; the store answers `SERVICE_UNAVAILABLE` with a reason that never quotes the token. It is read as written, with no percent-decoded reading: the client percent-decodes a URL (an `authToken` in a URL's query is already covered by M1's check), never this option, so `%00` in a token is three characters. Probed on the installed `@libsql/client` 0.18.0 before the change, to know what the check prevents: on a `file:` URL a NUL or a line break in the token opens and answers a query (exit 0, no abort: the native open ignores the token without a sync URL); on `http://` every request is rejected with a catchable `TypeError` (invalid header value); on `ws://` the connection was refused before the token was used, so that arm is unmeasured. So no process abort was found; the check turns a failure at every call into one refusal that names the setting. N4: the `knowledge.manifest.ts` jsdoc now names the state directory's data directory and both spellings of a control character. - Settings manifest + 11 locales: the `turso_url` example path is now `file:./.objectstack/data/knowledge.db`. - Docs: `content/docs/ai/knowledge-rag.mdx` gains "Turning it on: `requires: ['knowledge']`"; the old "Wiring" section is now "Wiring by hand". - **Skills enumeration rows only (Tier H)**, under the enumeration-row case (ruling A on #32584): the token's one `CAPABILITY_ROWS` line in `packages/spec/scripts/lib/platform-catalog.ts` and its regenerated page `skills/objectstack-project/references/platform-catalog.md` (`gen:skill-refs`, no hand edit), and the bare `knowledge` token added to the `@objectstack/service-` + token cell of the `requires:` table in `skills/objectstack-platform/SKILL.md`. No teaching, examples or evals: those ride #37310. - **Two ceilings, each raised by its row's measured delta and by no more** (nothing else cut, nothing rides along): - `skills/objectstack-platform/SKILL.md` (`scripts/check-skills-token-ratchet.mjs`): priced text 24591 to 24603 bytes (+12), 6148 to 6151 tokens (ceil(24591 / 4) = 6148, ceil(24603 / 4) = 6151). `main`'s row is 6149, with 1 token of headroom since #37568 took 2 bytes out of the file; that token is absorbed, so the ceiling moves 6149 to 6151 (+2), pinned at the measurement. History of the number: on the first three merges of `main` (4925039, cc38a91, 5dbcc02) the base was 24593 priced bytes and the row read 6152 (24605 bytes); #37568 then landed, and after the fourth merge (758e145) the row is re-pinned at 6151 (S5 of delta record 7196043543). The delta of the row itself is 12 bytes throughout. - the catalog's hand-written text (`packages/spec/scripts/platform-catalog.test.ts`): 6902 to 6939 bytes (+37), ceiling 1726 to 1735 tokens, pinned at the measurement. The row was first shortened from 50 to 37 bytes ("knowledge search and its vector store"). - **The two rulings the raise path names**, quoted: - Ruling A on #32584 (record 6819475461; maintainer, verbatim: 「同意 A」): "a product PR that adds an authorable `defineStack()` top-level key, or a live member of a schema symbol bound to a registered exhaustive skills section, carries the matching skills enumeration row in the same PR. Only that row; prose, examples and evals still go to the skills sub-card." - #32673 letter A (record 6840575378; maintainer, verbatim: 「32843 32673 同意」): "a PR that adds a metadata key and, under ruling A on #32584, carries the matching enumeration row in a published skill may raise that skill file's token cap by the row's measured delta, and by no more. The PR body cites ruling A and this ruling. Nothing else in the file is cut to make room, and no wider raise rides along." - **Skills readings** on this head against `main` 758e145 (lines; tokens as the ratchet prices them): `skills/objectstack-platform/SKILL.md` 421 to 421 lines, 6148 to 6151 tokens; `skills/objectstack-project/references/platform-catalog.md` (generated) 160 to 161 lines, 2878 to 2898 tokens; all `SKILL.md` files together 4961 to 4961 lines; the whole shipped bundle reads 299348 tokens, of which this PR adds 23 (3 + 20). - **`packages/cli/src/utils/boot-preparation-parity.test.ts`**: `resolveCapabilityExtras` is a `SERVE_ONLY` entry (the declaration boot reads a row's `extras` itself and composes no knowledge store: a store's `init()` declares nothing, its tables are its own). Editing the file put it in `check:test-source-alias`'s changed-file scope, so it now pays six dynamic imports its step modules reach at collection (six module-top side-effect imports, the gate's printed remedy). ## Tests - `packages/verify/src/harness.required-providers.test.ts`: `requires: ['realtime','knowledge']` on SQLite boots the service + turso (not pgvector), a record write is indexed and `search` finds it, a pgvector source is refused 503 while boot succeeds; no token → no service and `settings.getNamespace('knowledge')` rejects `SETTINGS_UNKNOWN_NAMESPACE`; host-mounted service unchanged. - `packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts` (new, live cell): the token's resolution on PostgreSQL picks pgvector on the same URL; a record write is indexed and `search_knowledge` finds it. **It has not run in CI on any commit of this PR**: the job with a PostgreSQL service, `temporal-conformance`, does not run on `pull_request`, and Test Core collects the file with both cases skipped. Its first CI run is the merge queue (the PR touches `packages/plugins/knowledge-pgvector/**`, which is in the `temporal_live` filter). It did run locally in the rework round, against PostgreSQL 16.15 with pgvector 0.6.0 from the distribution's package (CI pins pgvector 0.8.7): see Verification. - `packages/core/src/capability-composition.test.ts`: store selection arms (pg driver/URL, other DBs, in-memory, env fallback) and extras. - `packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts`: `resolveSettingsStoreUrl` (NUL/control, inside, outside, symlink escape, platform file) and the plugin never reaching a mocked `createClient` with a refused URL. Fix round: the settings double now answers a saved value only once bound, as the real service does, and the cases run a boot in kernel order (`init()`, `start()`, the bind, `kernel:bootstrapped`). New case: nothing is read and no file is made in `init()` or `start()`, the mounted adapter answers `SERVICE_UNAVAILABLE` / 503 until the boot completes, then the saved file opens and the default file is never made. - Rework round, `plugin.test.ts`: `%00`, `%0a`, `%0A`, `%7f`, a `file://` form and a `libsql://` URL are refused by both resolvers, with a control (`%20` and a doubly encoded `%2500` are names, not control characters); a saved `%00` or `%0a` URL never reaches a mocked `createClient`; a state directory moves the default file and the confinement. - Rework round, `harness.required-providers.test.ts`: **a real-kernel case for the file-database arm** (`constructServedProviders` with a `file:` database under a temporary `OS_HOME`, a `turso_url` saved from a `kernel:ready` handler: the store is healthy on the saved file, neither default file is made, a record write is found by search); **an install without the store** (the package made unimportable: the service is constructed, the store is not, one warning); the dependency pin now requires an `optional` store to be an optional dependency and nothing else. - Rework round, `capability-composition.test.ts`: `OS_HOME` is handed to the file arm as `stateDir`, and to no other arm. - Token round, `plugin.test.ts`: a token with a NUL byte, a trailing line break, a CR LF or U+007F never reaches a mocked `createClient`, through the settings door (on a `libsql://` URL and on a file inside the data directory) and through the `authToken` option; no log line quotes the token; controls: a JWT-shaped token and one with `%00` in it reach the client as written. - `packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts`: boot reading, coded index/search refusals, the plugin hook. - `packages/cli/test/serve-capability-identity.test.ts`: identity rows for the service and both stores. ## Acceptance notes - **Governed (Tier H)**: the diff touches `skills/**`, so this PR stays draft until the maintainer's approval. - **File surface**: the claim was widened twice. The take-over claim (7184318627) lists what the first round measured; claim amendment 7184431271 adds the four files this fix round needed (`packages/spec/scripts/platform-catalog.test.ts`, `skills/objectstack-platform/SKILL.md`, `scripts/check-skills-token-ratchet.mjs`, `packages/cli/src/utils/boot-preparation-parity.test.ts`), and the maintainer approved editing them in the card thread. - **Between `kernel:ready` and `kernel:bootstrapped`** a store whose URL is the operator's setting has no database yet: a record written by another plugin's `kernel:ready` handler is not indexed into it (the call answers 503). The knowledge service's own settings-configured embedder is provided at the same phase, so a deployment without a host-registered embedder indexed nothing in that window before either. The first build of #37099, now on `main` and merged here, builds the source after the store has opened and so covers such rows. - `@objectstack/knowledge-turso` is an **optional** dependency of `@objectstack/cli` and `@objectstack/verify` (S3). On an install without it `requires: ['knowledge']` on a non-PostgreSQL database boots with the service and a warning, and sources naming `turso` answer 503. - **Accepted nits, not changed** (the seat's record): N1, `file::memory:` and an empty `wasm-sqlite:` URL take the file arm; N2, the settings example `file:./.objectstack/data/knowledge.db` is read from the working directory and names the project's directory, so under `OS_HOME`, or from another working directory, it is refused with a message naming the right directory (it fails closed; the example text lives in the manifest and 11 locales). N3, the `ci.yml` step comment still says three `*.live-postgres.test.ts` files where there are now five: `.github/workflows/**` is outside this card's surface, so it is not edited here. - The double boot line for a source whose adapter is not mounted, and the publish-time refusal, are carried by #37479. - **#37099 (PR #37439) landed first; `main` is merged here and the first-build path re-checked.** Its after-boot build starts in the knowledge service's `kernel:bootstrapped` handler and reaches `getAdapter` through `readIndexState`, inside that method's own `try`. Read on a real kernel (see Verification): a store whose URL is a saved setting is open before the build starts (its handler is registered in `init()`, the service's in `start()`), and the build of its source ends `done`; a source naming an unmounted adapter is read as `unreadable`, is not built, and the boot goes on. Such a source is logged twice at boot, once at `error` by this PR's reading of unmounted adapters and once at `warn` by the build pass; one line would do (carried by #37479, not changed here). - **Merged with `main` four times** (`scripts/pm/os-regen-merge.sh`, no rebase): at 4925039 for a GitHub conflict in the `requires:` table row of `skills/objectstack-platform/SKILL.md` (resolved by keeping `main`'s provider cell whole and adding the bare `knowledge` token after `record-context`), at cc38a91 once #37439 had landed (no conflict), in the rework round at 5dbcc02 once #37477 and #37492 had landed (no conflict), and at 758e145 for S5 once #37568 had edited `skills/objectstack-platform/SKILL.md` (auto-merged, no conflict). After each, `git diff origin/main` names this PR's 38 files and nothing else; `gen:skill-refs` and `check:generated` leave the tree clean. - **Open PRs that will conflict with this one**: #37422 in `scripts/check-skills-token-ratchet.mjs`. Whichever lands second re-measures the `skills/objectstack-platform/SKILL.md` row. ## Verification First files to read, by risk: 1. `packages/plugins/knowledge-turso/src/plugin.ts`: `init()` / `start()` / `openFromSettings` (when the store opens, and what it answers before). 2. `packages/core/src/capability-composition.ts`: `resolveKnowledgeStore` (which store, with what argument). 3. `packages/services/service-knowledge/src/knowledge-service.ts`: `getAdapter` / `reportUnmountedAdapters` (the coded refusal). Two-minute check: `pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/plugin.test.ts`: expect 22/22, including "refuses a percent-encoded control character too" and "reads the settings at kernel:bootstrapped, never in init() or start()". <details><summary>Local runs (under scripts/pm/os-verify-lock.sh): the rework round on 806c55d, the token round on 664bd70, and what ran again on head c25cc1a</summary> - `pnpm install --frozen-lockfile`: exit 0. `pnpm turbo run build --concurrency=2 --filter='./packages/**' --filter='./examples/**'`: exit 0, 85/85 tasks. `gen:skill-refs` then `check:generated`: exit 0, tree clean. - `pnpm --filter @objectstack/knowledge-turso test`: exit 0, 3 files, 155/155. `typecheck`: exit 0. - `pnpm --filter @objectstack/core exec vitest run --maxWorkers=2 src/capability-composition.test.ts`: exit 0, 21/21. `pnpm --filter @objectstack/core typecheck`: exit 0. - `pnpm --filter @objectstack/verify exec vitest run --maxWorkers=2 src/harness.required-providers.test.ts`: exit 0, 15/15 (19.0 s of tests locally; the header's budget is re-derived to 28). `pnpm --filter @objectstack/verify typecheck`: exit 0. - `pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 src/utils/boot-preparation-parity.test.ts test/serve-capability-identity.test.ts src/commands/knowledge/knowledge.test.ts`: exit 0, 3 files, 143/143. `pnpm --filter @objectstack/cli typecheck`: exit 0. The rest of the cli suite is left to CI. - `pnpm --filter @objectstack/service-knowledge test`: exit 0, 14 files, 452/452. `pnpm --filter @objectstack/service-settings test`: exit 0, 77 files, 1521/1521 (after #37477's edits to the same manifest and locales). `scripts/platform-catalog.test.ts` (spec): exit 0, 20/20. - **The pgvector live cell**, as CI's step runs it: `OS_TEST_POSTGRES_URL=postgres://postgres:postgres@127.0.0.1:5432/postgres OS_EXPECT_LIVE_DIALECT_MATRIX=1 pnpm --filter @objectstack/knowledge-pgvector exec vitest run live-postgres`: exit 0, 5 files, 65/65, none skipped (4 files, 59/59 before the merge of `main` brought #37492's file). Server: PostgreSQL 16.15 with the `vector` extension 0.6.0 (the distribution's `postgresql-16-pgvector`), not CI's pinned pgvector 0.8.7 image. - **Ran again on the token commit 664bd70 (it touches `knowledge-turso`, one comment in the settings manifest, the docs page and the changeset):** `pnpm --filter @objectstack/knowledge-turso test`: exit 0, 3 files, 156/156 (`plugin.test.ts` 22/22); its `typecheck`: exit 0; `turbo run build` of `@objectstack/knowledge-turso` and `@objectstack/service-settings`: exit 0, 20/20 tasks. Everything above this line was run on 806c55d and not again. - **After the fourth merge (c25cc1a):** `pnpm install --frozen-lockfile`: exit 0. `pnpm --filter @objectstack/spec build`, `gen:skill-refs`, then `pnpm --filter @objectstack/spec check:generated`: exit 0, tree clean. `scripts/platform-catalog.test.ts`: exit 0, 20/20 (catalog ceiling 1735 unchanged). `node scripts/check-skills-token-ratchet.mjs`: exit 0, `skills/objectstack-platform/SKILL.md` 6151 / 6151. No package test was run again on this head. </details> <details><summary>Rework round: each new test turns red without its fix</summary> - **M1.** With the decoded read removed from `carriesControlCharacter` (the raw test alone, as on abf337b): `plugin.test.ts` 2 failed / 19 passed, "refuses a percent-encoded control character too" and "a saved URL with a NUL byte, or outside the data directory, never reaches the libSQL client". Restored (byte-identical to the committed file): 21/21. - **S2, S3, S4.** With `stateDir` and `optional: true` removed from core and core rebuilt: `harness.required-providers.test.ts` 3 failed / 12 passed. The file-database case answers `{ ok: false }` (the saved file under `OS_HOME` is outside the app's data directory); the missing-store case throws the "could not load it" boot error; the dependency pin reports `@objectstack/knowledge-turso` as not a dependency. Restored and rebuilt: 15/15. - **The auth token.** With the `acceptsAuthToken` check removed from `open()`: `plugin.test.ts` 1 failed / 21 passed, "an auth token with a control character never reaches the libSQL client, saved or given; the reason never quotes it". Restored with `git checkout` (the committed file): 22/22. </details> <details><summary>Fix round: reverse verification of the settings read (one-off, no file kept)</summary> A throwaway `@objectstack/verify` case booted a real kernel with `KnowledgeServicePlugin`, `KnowledgeTursoPlugin({ urlFromSettings: true })` and a plugin that saves `knowledge.turso_url` from its `kernel:ready` handler (ordered after the settings bind). - This head: the read in `start()` answers `source: 'default'`; after the boot the store is healthy on the saved file and `knowledge.db` was never made. Probe 1/1 green. - `plugin.ts` restored to 969b372 (the pre-fix file), `knowledge-turso` rebuilt (dist marker absent): the probe is red, the saved file was never made and the default `knowledge.db` was opened; `plugin.test.ts` 3 failed / 16 passed (the two saved-URL cases and the new phase case). - Restored from `HEAD` (blob hash equal, `git diff HEAD` empty), rebuilt (dist marker present): probe green again. </details> <details><summary>The first build of #37099 on a real kernel, after the second merge (one-off, no file kept)</summary> A throwaway `@objectstack/verify` case booted a real kernel with `KnowledgeServicePlugin`, `KnowledgeTursoPlugin({ urlFromSettings: true })` and an app plugin that registers an embedder, a source on `turso`, a source naming the unmounted `pgvector`, and saves `knowledge.turso_url` from its `kernel:ready` handler. 1/1 green; readings after the boot: - the `turso` source: `buildRecord` is `{ trigger: 'boot', status: 'done', result: { ok: true, failed: 0 } }`, then `readIndexState` answers `current` ("same fingerprint, same recipe hash"). The store is healthy on the saved file and the default `knowledge.db` was never made. - the `pgvector` source: no build record; `readIndexState` answers `{ state: 'unreadable', due: false }` with the coded refusal's text ("adapter 'pgvector' is not mounted (mounted: turso)"). Boot log: one `ERROR` line from the reading of unmounted adapters, one `WARN` line "is not built at boot" from the build pass. </details> <details><summary>Derived gates (node scripts/pm/dispatch-gates.mjs --commands, 166 commands)</summary> - On this head (c25cc1a, after the fourth merge and the re-pinned row): the 37 derived commands that read skills, the ratchet, the catalog, generated artifacts, docs or the changeset ran again, 37/37 exit 0 (among them `check-skills-token-ratchet.mjs` and its self-test, `check:skill-docs`, `check:skill-examples`, `check:skill-refs`, `check:skill-identifier-liveness`, `check:skill-links`, `check:skill-top-level-keys`, `check:ratchet-remedy-authority`). The other 129 were not run again locally on this head; CI runs them on the merge. - `overlap-check` before the push: `origin/main` (758e145) merges cleanly; exit 1 only for open PR #37422 (conflict in `scripts/check-skills-token-ratchet.mjs`). - Earlier rounds, for the record: 166/166 on the token commit 664bd70; 166/166 on 806c55d (the rework round); 166/166 on 63eba5b before the first merges; the 56 commands a merge can reach, 56/56, at 64075a7 and at abf337b. </details> ## Remaining - The ceiling-tier contract review owed by `Clause-②: yes`, then the maintainer's approval (Tier H). - The pgvector live cell has not run in CI on this PR (it cannot: see Tests); the merge queue is its first CI run, and a red there ejects the entry. Locally it passed against pgvector 0.6.0, not CI's 0.8.7. - The seat re-scopes #37479 before this lands; the re-pinned ratchet row (S5) is re-checked by the same contract reviewer. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CYE8s5v1UX96GEfkcR --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d92684a commit 87af66e

38 files changed

Lines changed: 1614 additions & 93 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/core': minor
4+
'@objectstack/cli': minor
5+
'@objectstack/verify': minor
6+
'@objectstack/service-knowledge': minor
7+
'@objectstack/knowledge-turso': minor
8+
'@objectstack/service-settings': patch
9+
---
10+
11+
feat(core): `requires: ['knowledge']` mounts the knowledge service and one vector store
12+
13+
Clause-②: yes
14+
Metadata-protocol: added
15+
Skills-docs: follow-up #37310
16+
17+
ADR-0161, #37102.
18+
19+
- **New capability token `knowledge`** (`PLATFORM_CAPABILITY_TOKENS`, provider `@objectstack/service-knowledge`, edition `open`). `os serve` and `@objectstack/verify` mount `KnowledgeServicePlugin` plus exactly one store, picked from the primary database: PostgreSQL gets `KnowledgePgvectorPlugin` (adapter `pgvector`, on the same database URL); any other database gets `KnowledgeTursoPlugin` (adapter `turso`) on a local libSQL file, `knowledge.db` in the directory of the default database: `.objectstack/data/`, or `<OS_HOME>/data/` when `OS_HOME` is set (`os start --home` sets it). An in-memory database gets an in-memory turso store. The in-memory adapter (`knowledge-memory`) is never mounted by the token.
20+
- No token: no knowledge service and no knowledge settings page, as before. A host that mounts `KnowledgeServicePlugin` itself keeps its own and gets no store from the runtime; a host that mounts only the store the token would choose keeps that store and gets the service.
21+
- New core exports: `resolveCapabilityExtras`, `resolveKnowledgeStore`, `KNOWLEDGE_STORE_PROVIDERS` and the `CapabilityDatabase` / `CapabilityExtra` / `KnowledgeStoreSpec` types. `constructServedProviders` (`@objectstack/verify`) takes an optional `database` (default: in-memory SQLite).
22+
- `os serve` now warns when a capability's extra plugin cannot be imported or constructed, instead of skipping it silently.
23+
- **A source whose adapter is not mounted** no longer fails silently. The service still mounts and boot does not fail; after boot the service logs one `error` per such source naming the mounted adapters, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same message. A search across several sources names the refused one beside the hits of the others. Before, indexing threw an uncoded error and search skipped the source with a warning.
24+
- **The turso store reads its URL from settings under the token.** `KnowledgeTursoPlugin` gains `urlFromSettings`: with no `url` option it reads the saved `knowledge.turso_url` / `turso_auth_token`. It reads them when the boot completes (`kernel:bootstrapped`), the first moment the settings service answers a saved value; the adapter is mounted from `start()` and answers `SERVICE_UNAVAILABLE` until the store has opened. A saved `file:` URL must resolve, after symlinks, inside that data directory; a URL that leaves it, names the platform database, or carries a NUL byte or another control character, written out or percent-encoded (`%00`, `%0a`), is refused before the libSQL client sees it (the client decodes the path, and a NUL byte in it kills the process inside the native library). New option `stateDir` (the token passes `OS_HOME`); new exports: `resolveSettingsStoreUrl`, `dataDirectoryOf`. `resolveStoreUrl` refuses control characters too, in both spellings. An auth token carrying a control character (a pasted line break, a NUL byte), saved or given as the `authToken` option, is refused the same way, read as written: the store answers `SERVICE_UNAVAILABLE` with a reason that never quotes the token.
25+
- **`@objectstack/knowledge-turso` is an optional dependency of `@objectstack/cli` and `@objectstack/verify`**, not a hard one: its libSQL client is a native module with an `os` / `cpu` list, and a hard dependency would refuse the whole install outside that list. Where it is absent `os serve` warns that the store was not mounted and boots on, `@objectstack/verify` does the same, and a source naming `turso` answers `SERVICE_UNAVAILABLE`. `KNOWLEDGE_STORE_PROVIDERS.turso` and the extra `resolveCapabilityExtras` answers for it carry `optional: true`.
26+
- The `turso_url` setting's example path now reads `file:./.objectstack/data/knowledge.db` in every locale.

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

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,35 @@ ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable bac
1212
**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@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

15-
## Wiring
15+
## Turning it on: `requires: ['knowledge']`
16+
17+
Add `knowledge` to your app's `requires`, and `os dev`, `os serve` and `os start` mount the knowledge service and one vector store for you — and in an app's tests, `bootStack` from `@objectstack/verify` mounts the same:
18+
19+
```ts
20+
export default defineStack({
21+
// …
22+
requires: ['knowledge'],
23+
});
24+
```
25+
26+
Which store is mounted depends on the platform database:
27+
28+
| Platform database | Store | Adapter id | Where the vectors live |
29+
|:--|:--|:--|:--|
30+
| PostgreSQL | `@objectstack/knowledge-pgvector` | `pgvector` | the platform database, schema `os_knowledge` ([below](#self-hosted-vector-store-postgresql--pgvector)) |
31+
| anything else (SQLite under `os dev`, libSQL, MySQL, MongoDB) | `@objectstack/knowledge-turso` | `turso` | `knowledge.db` in the directory of the default database and never its file: `.objectstack/data/`, or `<OS_HOME>/data/` when `OS_HOME` is set ([below](#local-vector-store-a-libsql-file)) |
32+
33+
- **Sources are still written in code**: register them on the `knowledge` service from your own plugin, and name the adapter of the store your database gets (`adapter: 'turso'` or `adapter: 'pgvector'`).
34+
- **A source naming a store that is not mounted** does not stop the boot: the server logs one error naming the source and the stores that are mounted, and indexing or searching that source answers `SERVICE_UNAVAILABLE` (503) with the same choices; `search_knowledge` lists it in `refused`.
35+
- **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)).
36+
- **Another libSQL store** for the `turso` case: save its URL as `turso_url` (and `turso_auth_token` for a managed `libsql://` database) in Settings → Knowledge, then restart. A `file:` URL saved there must name a file inside that same data directory, and a URL carrying a NUL byte or another control character, written out or percent-encoded (`%00`), is refused, as is a token carrying one (a pasted line break counts); either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on.
37+
- **Where the file is**: `os start --home` and `OS_HOME` move it with the default database, so on a container put `OS_HOME` on a volume and the index survives a redeploy. A database named by URL (`OS_DATABASE_URL`) does not move it.
38+
- **More than one replica** on MySQL, MongoDB or a remote libSQL database: each replica keeps its own local `knowledge.db` and indexes only the record writes that replica itself handles, so replicas answer from indexes that differ. Give them one store: save a shared `libsql://` URL in `turso_url`, or run on PostgreSQL, where the vectors live in the one database.
39+
- **An install without the libSQL client**: `@objectstack/knowledge-turso` is an optional dependency of the CLI, because its client is a native module. Where it could not be installed the server warns at boot that the store was not mounted, and sources naming `turso` answer `SERVICE_UNAVAILABLE`.
40+
- **Without the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you.
41+
- **Mounting it yourself** still works: an app whose `plugins` already hold `KnowledgeServicePlugin` keeps its own, and the runtime adds neither a second service nor a store.
42+
43+
## Wiring by hand
1644

1745
```ts
1846
import { ObjectKernel } from '@objectstack/core';
@@ -275,7 +303,7 @@ Details — the tables, an approximate index as an operator's step, rebuilds —
275303

276304
## Local vector store: a libSQL file
277305

278-
`@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'`:
306+
`@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. `requires: ['knowledge']` mounts it on any database but PostgreSQL; to wire it by hand, register `KnowledgeTursoPlugin` beside the knowledge service. Point a source at it with `adapter: 'turso'`:
279307

280308
```ts
281309
new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL

‎packages/cli/package.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@
122122
"@objectstack/driver-sql": "workspace:*",
123123
"@objectstack/driver-sqlite-wasm": "workspace:*",
124124
"@objectstack/formula": "workspace:*",
125+
"@objectstack/knowledge-pgvector": "workspace:*",
125126
"@objectstack/lint": "workspace:*",
126127
"@objectstack/mcp": "workspace:*",
127128
"@objectstack/metadata": "workspace:*",
@@ -146,6 +147,7 @@
146147
"@objectstack/service-cache": "workspace:*",
147148
"@objectstack/service-datasource": "workspace:*",
148149
"@objectstack/service-job": "workspace:*",
150+
"@objectstack/service-knowledge": "workspace:*",
149151
"@objectstack/service-mailbox": "workspace:*",
150152
"@objectstack/service-messaging": "workspace:*",
151153
"@objectstack/service-package": "workspace:*",
@@ -184,6 +186,7 @@
184186
}
185187
},
186188
"optionalDependencies": {
189+
"@objectstack/knowledge-turso": "workspace:*",
187190
"better-sqlite3": "^13.0.3"
188191
},
189192
"devDependencies": {

‎packages/cli/src/commands/serve.ts‎

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ import {
4646
providesCapability,
4747
resolveServedCapabilities,
4848
resolveCapabilityArgument,
49+
resolveCapabilityExtras,
50+
type CapabilityDatabase,
4951
materializeStackPlugin,
5052
STACK_TIER_PRESETS,
5153
CAPABILITY_TO_TIER as SHARED_CAPABILITY_TO_TIER,
@@ -2765,6 +2767,10 @@ export default class Serve extends Command {
27652767
// multi-replica local-database refusal before step 2 reads the runtime's
27662768
// own resolution of it. Unset on the legacy route.
27672769
let standaloneDatabaseInput: StandaloneStackConfig | undefined;
2770+
// The platform database this command's own `OS_DATABASE_URL` fallback
2771+
// declared (step 2), for the `knowledge` store choice in the capability
2772+
// resolver (`resolveCapabilityExtras`). Unset on every other route.
2773+
let fallbackPrimaryDatabase: CapabilityDatabase | undefined;
27682774

27692775
// Resolve the kernel logger level up front. It decides more than the
27702776
// logger's own threshold: it decides whether the boot-quiet window below
@@ -3600,6 +3606,7 @@ export default class Serve extends Command {
36003606
resolvedDriverLabel = resolution.label;
36013607
resolvedDatabaseUrl = resolution.displayUrl;
36023608
servedSqliteFilePath = resolution.sqliteFilePath;
3609+
fallbackPrimaryDatabase = { driver: resolution.driverId, url: databaseUrl };
36033610

36043611
// ADR-0057 §3.6 (#2834 ②): the dedicated `telemetry` datasource
36053612
// next to an explicit SQLite primary (`sqliteFilePath`, unset for
@@ -5474,6 +5481,22 @@ export default class Serve extends Command {
54745481
// token's own required/best-effort semantics — under the next.
54755482
const resolverMounted: unknown[] = [];
54765483

5484+
// The platform database, as the token rows whose providers depend on it
5485+
// read it (today the `knowledge` store: pgvector on PostgreSQL, else a
5486+
// libSQL file of its own). The one each route resolved for itself: this
5487+
// command's fallback (step 2), else the standalone stack's own
5488+
// resolution over the input it was composed from. Neither ⇒ a host
5489+
// whose own plugin provides the driver, and the rule reads the
5490+
// environment (`resolveKnowledgeStore`).
5491+
let capabilityDatabase: CapabilityDatabase | undefined = fallbackPrimaryDatabase;
5492+
if (!capabilityDatabase && standaloneDatabaseInput !== undefined) {
5493+
try {
5494+
const { resolveStandaloneDatabase } = await import('@objectstack/runtime');
5495+
const primary = resolveStandaloneDatabase(standaloneDatabaseInput);
5496+
capabilityDatabase = { driver: primary.driver, url: primary.url };
5497+
} catch { /* the stack's own boot reports a database it cannot resolve */ }
5498+
}
5499+
54775500
// Exact identity comparison, NOT substring containment — a consumer named
54785501
// after the capability it consumes must never be mistaken for its
54795502
// provider (#7652). See Serve.providesCapability.
@@ -5601,21 +5624,34 @@ export default class Serve extends Command {
56015624
resolverMounted.push(provider);
56025625
trackPlugin(spec.export);
56035626

5604-
if (spec.extras) {
5605-
for (const ex of spec.extras) {
5606-
if (hasPluginMatching(ex.identities)) continue;
5607-
try {
5608-
const exMod: any = await import(/* webpackIgnore: true */ ex.pkg);
5609-
const ExCtor = exMod[ex.export];
5610-
if (ExCtor) {
5611-
const extra = new ExCtor();
5612-
await kernel.use(extra);
5613-
resolverMounted.push(extra);
5614-
trackPlugin(ex.export);
5615-
}
5616-
} catch {
5617-
// optional extra — silently skip
5627+
// A row's extras, or for `knowledge` the one store the platform
5628+
// database chooses, each with its own argument — the rule the
5629+
// handle reads too (`resolveCapabilityExtras`, `@objectstack/core`).
5630+
const extras = resolveCapabilityExtras(cap, {
5631+
stack: config,
5632+
packageRoot: path.dirname(absolutePath),
5633+
env: process.env,
5634+
database: capabilityDatabase,
5635+
});
5636+
for (const ex of extras) {
5637+
if (hasPluginMatching(ex.identities)) continue;
5638+
try {
5639+
const exMod: any = await import(/* webpackIgnore: true */ ex.pkg);
5640+
const ExCtor = exMod[ex.export];
5641+
if (ExCtor) {
5642+
const extra = ex.argument !== undefined ? new ExCtor(ex.argument) : new ExCtor();
5643+
await kernel.use(extra);
5644+
resolverMounted.push(extra);
5645+
trackPlugin(ex.export);
5646+
} else {
5647+
console.warn(chalk.yellow(` ⚠ Capability "${cap}": ${ex.pkg} did not export ${ex.export}; it was not mounted`));
56185648
}
5649+
} catch (exErr: unknown) {
5650+
// The main provider is mounted; an extra that cannot load is
5651+
// said once, never skipped in silence (a `knowledge` source
5652+
// naming the store then answers why at its first use).
5653+
const exMsg = exErr instanceof Error ? exErr.message : String(exErr);
5654+
console.warn(chalk.yellow(` ⚠ Capability "${cap}": ${ex.export} (${ex.pkg}) was not mounted: ${exMsg}`));
56195655
}
56205656
}
56215657
} catch (err: unknown) {

‎packages/cli/src/utils/boot-preparation-parity.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,15 @@ import {
7878
} from './stack-collections.js';
7979
import { provisionTelemetryDatasource, standaloneTelemetryPrimary } from './telemetry-datasource.js';
8080

81+
// Paid at collection, not inside a clocked case: what the step modules imported
82+
// above reach through dynamic `import()`s (`check:test-source-alias`).
83+
import '@objectstack/service-datasource';
84+
import '@objectstack/driver-turso';
85+
import '@objectstack/driver-sql';
86+
import '@objectstack/platform-objects/plugin';
87+
import '@objectstack/plugin-security';
88+
import '@objectstack/rest';
89+
8190
/** …/packages/cli/src/utils */
8291
const HERE = dirname(fileURLToPath(import.meta.url));
8392
/** …/packages/cli/src — this package's own source tree. */
@@ -178,6 +187,12 @@ const SERVE_ONLY: Record<string, string> = {
178187
+ 'the storage root; [#22301], shared with @objectstack/verify\'s bootStack): the declaration boot constructs '
179188
+ 'each provider for its declarations only, with a measured posture per token '
180189
+ '(DECLARATION_PROVIDER_POSTURES), and runs no start() that would read a configuration',
190+
resolveCapabilityExtras:
191+
'which further providers serve mounts after a token\'s main one, and what each is built with — a row\'s '
192+
+ 'extras, and for knowledge the one vector store the platform database chooses (shared with '
193+
+ '@objectstack/verify\'s bootStack): the declaration boot reads a row\'s extras itself (composeServedPlatform) '
194+
+ 'and composes no knowledge store, whose init() declares nothing — its tables are its own, in a libSQL file '
195+
+ 'or a PostgreSQL schema of its own, made in the start() this boot does not run',
181196
findSqlDriverForKernel:
182197
'the artifact boot migration gate, a kernel:ready hook over a booted kernel — a serving-boot policy that '
183198
+ 'runs after preparation, not a step that shapes what is prepared',

‎packages/cli/test/serve-capability-identity.test.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import { describe, expect, it } from 'vitest';
3232
import { readFileSync } from 'node:fs';
3333
import { resolve } from 'node:path';
3434
import { fileURLToPath } from 'node:url';
35-
import { CAPABILITY_PROVIDERS, providesCapability } from '@objectstack/core';
35+
import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS, providesCapability } from '@objectstack/core';
3636
import Serve from '../src/commands/serve.js';
3737

3838
// Pay the first transform of these dist-resolved workspace deps at MODULE LOAD:
@@ -148,6 +148,7 @@ const EXPECTED_PROVIDER_NAME: Record<string, string> = {
148148
settings: 'com.objectstack.service.settings',
149149
webhooks: 'com.objectstack.plugin-webhook-outbox',
150150
'record-context': 'com.objectstack.service.record-context',
151+
knowledge: 'com.objectstack.service.knowledge',
151152
};
152153

153154
describe('#7652: every registered provider is still recognised (the other direction)', () => {
@@ -222,7 +223,12 @@ describe('#7652: declared identities match what the provider packages register',
222223
const entries = Object.entries(CAPABILITY_PROVIDERS).flatMap(([cap, spec]) => [
223224
{ cap, pkg: spec.pkg, export: spec.export, identities: spec.identities },
224225
...(spec.extras ?? []).map((ex) => ({ cap: `${cap}:${ex.export}`, pkg: ex.pkg, export: ex.export, identities: ex.identities })),
225-
]);
226+
]).concat(
227+
// The stores the `knowledge` token chooses between (`resolveCapabilityExtras`).
228+
Object.values(KNOWLEDGE_STORE_PROVIDERS).map((store) => ({
229+
cap: `knowledge:${store.export}`, pkg: store.pkg, export: store.export, identities: store.identities,
230+
})),
231+
);
226232

227233
/**
228234
* The consumer side of the pin. `@objectstack/connector-mcp` is not a
@@ -341,6 +347,12 @@ const IDENTITY_SOURCES: IdentitySource[] = [
341347
identities: ex.identities,
342348
})),
343349
]),
350+
...Object.entries(KNOWLEDGE_STORE_PROVIDERS).map(([id, store]) => ({
351+
label: `KNOWLEDGE_STORE_PROVIDERS.${id}`,
352+
pkg: store.pkg,
353+
export: store.export,
354+
identities: store.identities,
355+
})),
344356
...Object.entries(IDENTITY_LISTS).map(([name, entry]) => ({
345357
label: `Serve.${name}`,
346358
pkg: entry.pkg,

0 commit comments

Comments
 (0)