From 95ecb292a307be90b1329b2a43b1c1a739d021ae Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:00:02 +0000 Subject: [PATCH 1/8] wip(knowledge): requires knowledge mounts the knowledge service and one store Claude-Session: https://claude.ai/code/session_01JQwxbWZjh7mWMsJZHnGWwZ Co-authored-by: Claude --- content/docs/ai/knowledge-rag.mdx | 29 ++- packages/cli/package.json | 3 + packages/cli/src/commands/serve.ts | 64 +++++-- .../test/serve-capability-identity.test.ts | 16 +- .../core/src/capability-composition.test.ts | 94 ++++++++- packages/core/src/capability-composition.ts | 100 +++++++++- packages/core/src/capability-providers.ts | 50 +++++ .../capability-mount.live-postgres.test.ts | 85 +++++++++ .../src/__tests__/plugin.test.ts | 147 +++++++++++++- packages/plugins/knowledge-turso/src/index.ts | 2 + .../plugins/knowledge-turso/src/plugin.ts | 180 +++++++++++++++++- .../src/__tests__/knowledge-service.test.ts | 84 +++++++- .../src/knowledge-service-plugin.ts | 5 + .../src/knowledge-service.ts | 49 ++++- .../src/manifests/knowledge.manifest.ts | 10 +- .../service-settings/src/translations/ar.ts | 2 +- .../service-settings/src/translations/de.ts | 2 +- .../service-settings/src/translations/en.ts | 2 +- .../src/translations/es-ES.ts | 2 +- .../service-settings/src/translations/fr.ts | 2 +- .../src/translations/ja-JP.ts | 2 +- .../service-settings/src/translations/ko.ts | 2 +- .../src/translations/pt-BR.ts | 2 +- .../service-settings/src/translations/ru.ts | 2 +- .../src/translations/zh-CN.ts | 2 +- .../src/translations/zh-Hant.ts | 2 +- .../spec/src/kernel/platform-capabilities.ts | 6 + packages/verify/package.json | 3 + .../src/harness.required-providers.test.ts | 126 +++++++++++- packages/verify/src/required-providers.ts | 30 ++- pnpm-lock.yaml | 18 ++ 31 files changed, 1066 insertions(+), 57 deletions(-) create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index d74e41dc18c..d8252d554f4 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -12,7 +12,32 @@ ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable bac **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 +## Turning it on: `requires: ['knowledge']` + +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: + +```ts +export default defineStack({ + // … + requires: ['knowledge'], +}); +``` + +Which store is mounted depends on the platform database: + +| Platform database | Store | Adapter id | Where the vectors live | +|:--|:--|:--|:--| +| PostgreSQL | `@objectstack/knowledge-pgvector` | `pgvector` | the platform database, schema `os_knowledge` ([below](#self-hosted-vector-store-postgresql--pgvector)) | +| anything else (SQLite under `os dev`, libSQL, MySQL, MongoDB) | `@objectstack/knowledge-turso` | `turso` | `.objectstack/data/knowledge.db`, beside the dev database and never its file ([below](#local-vector-store-a-libsql-file)) | + +- **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'`). +- **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`. +- **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)). +- **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 the project's `.objectstack/data/` directory, and a URL carrying a NUL byte is refused; either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on. +- **Without the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you. +- **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. + +## Wiring by hand ```ts import { ObjectKernel } from '@objectstack/core'; @@ -237,7 +262,7 @@ Details — the tables, an approximate index as an operator's step, rebuilds — ## 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'`: +`@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'`: ```ts new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL diff --git a/packages/cli/package.json b/packages/cli/package.json index 0bb12925cd6..dc307d98fb0 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -119,6 +119,8 @@ "@objectstack/driver-sql": "workspace:*", "@objectstack/driver-sqlite-wasm": "workspace:*", "@objectstack/formula": "workspace:*", + "@objectstack/knowledge-pgvector": "workspace:*", + "@objectstack/knowledge-turso": "workspace:*", "@objectstack/lint": "workspace:*", "@objectstack/mcp": "workspace:*", "@objectstack/metadata": "workspace:*", @@ -143,6 +145,7 @@ "@objectstack/service-cache": "workspace:*", "@objectstack/service-datasource": "workspace:*", "@objectstack/service-job": "workspace:*", + "@objectstack/service-knowledge": "workspace:*", "@objectstack/service-mailbox": "workspace:*", "@objectstack/service-messaging": "workspace:*", "@objectstack/service-package": "workspace:*", diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index c3f757b9739..88369974528 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -46,6 +46,8 @@ import { providesCapability, resolveServedCapabilities, resolveCapabilityArgument, + resolveCapabilityExtras, + type CapabilityDatabase, materializeStackPlugin, STACK_TIER_PRESETS, CAPABILITY_TO_TIER as SHARED_CAPABILITY_TO_TIER, @@ -2765,6 +2767,10 @@ export default class Serve extends Command { // multi-replica local-database refusal before step 2 reads the runtime's // own resolution of it. Unset on the legacy route. let standaloneDatabaseInput: StandaloneStackConfig | undefined; + // The platform database this command's own `OS_DATABASE_URL` fallback + // declared (step 2), for the `knowledge` store choice in the capability + // resolver (`resolveCapabilityExtras`). Unset on every other route. + let fallbackPrimaryDatabase: CapabilityDatabase | undefined; // Resolve the kernel logger level up front. It decides more than the // logger's own threshold: it decides whether the boot-quiet window below @@ -3600,6 +3606,7 @@ export default class Serve extends Command { resolvedDriverLabel = resolution.label; resolvedDatabaseUrl = resolution.displayUrl; servedSqliteFilePath = resolution.sqliteFilePath; + fallbackPrimaryDatabase = { driver: resolution.driverId, url: databaseUrl }; // ADR-0057 §3.6 (#2834 ②): the dedicated `telemetry` datasource // next to an explicit SQLite primary (`sqliteFilePath`, unset for @@ -5474,6 +5481,22 @@ export default class Serve extends Command { // token's own required/best-effort semantics — under the next. const resolverMounted: unknown[] = []; + // The platform database, as the token rows whose providers depend on it + // read it (today the `knowledge` store: pgvector on PostgreSQL, else a + // libSQL file of its own). The one each route resolved for itself: this + // command's fallback (step 2), else the standalone stack's own + // resolution over the input it was composed from. Neither ⇒ a host + // whose own plugin provides the driver, and the rule reads the + // environment (`resolveKnowledgeStore`). + let capabilityDatabase: CapabilityDatabase | undefined = fallbackPrimaryDatabase; + if (!capabilityDatabase && standaloneDatabaseInput !== undefined) { + try { + const { resolveStandaloneDatabase } = await import('@objectstack/runtime'); + const primary = resolveStandaloneDatabase(standaloneDatabaseInput); + capabilityDatabase = { driver: primary.driver, url: primary.url }; + } catch { /* the stack's own boot reports a database it cannot resolve */ } + } + // Exact identity comparison, NOT substring containment — a consumer named // after the capability it consumes must never be mistaken for its // provider (#7652). See Serve.providesCapability. @@ -5601,21 +5624,34 @@ export default class Serve extends Command { resolverMounted.push(provider); trackPlugin(spec.export); - if (spec.extras) { - for (const ex of spec.extras) { - if (hasPluginMatching(ex.identities)) continue; - try { - const exMod: any = await import(/* webpackIgnore: true */ ex.pkg); - const ExCtor = exMod[ex.export]; - if (ExCtor) { - const extra = new ExCtor(); - await kernel.use(extra); - resolverMounted.push(extra); - trackPlugin(ex.export); - } - } catch { - // optional extra — silently skip + // A row's extras, or for `knowledge` the one store the platform + // database chooses, each with its own argument — the rule the + // handle reads too (`resolveCapabilityExtras`, `@objectstack/core`). + const extras = resolveCapabilityExtras(cap, { + stack: config, + packageRoot: path.dirname(absolutePath), + env: process.env, + database: capabilityDatabase, + }); + for (const ex of extras) { + if (hasPluginMatching(ex.identities)) continue; + try { + const exMod: any = await import(/* webpackIgnore: true */ ex.pkg); + const ExCtor = exMod[ex.export]; + if (ExCtor) { + const extra = ex.argument !== undefined ? new ExCtor(ex.argument) : new ExCtor(); + await kernel.use(extra); + resolverMounted.push(extra); + trackPlugin(ex.export); + } else { + console.warn(chalk.yellow(` ⚠ Capability "${cap}": ${ex.pkg} did not export ${ex.export}; it was not mounted`)); } + } catch (exErr: unknown) { + // The main provider is mounted; an extra that cannot load is + // said once, never skipped in silence (a `knowledge` source + // naming the store then answers why at its first use). + const exMsg = exErr instanceof Error ? exErr.message : String(exErr); + console.warn(chalk.yellow(` ⚠ Capability "${cap}": ${ex.export} (${ex.pkg}) was not mounted: ${exMsg}`)); } } } catch (err: unknown) { diff --git a/packages/cli/test/serve-capability-identity.test.ts b/packages/cli/test/serve-capability-identity.test.ts index 643658e195f..4995383504b 100644 --- a/packages/cli/test/serve-capability-identity.test.ts +++ b/packages/cli/test/serve-capability-identity.test.ts @@ -32,7 +32,7 @@ import { describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { CAPABILITY_PROVIDERS, providesCapability } from '@objectstack/core'; +import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS, providesCapability } from '@objectstack/core'; import Serve from '../src/commands/serve.js'; // Pay the first transform of these dist-resolved workspace deps at MODULE LOAD: @@ -148,6 +148,7 @@ const EXPECTED_PROVIDER_NAME: Record = { settings: 'com.objectstack.service.settings', webhooks: 'com.objectstack.plugin-webhook-outbox', 'record-context': 'com.objectstack.service.record-context', + knowledge: 'com.objectstack.service.knowledge', }; 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', const entries = Object.entries(CAPABILITY_PROVIDERS).flatMap(([cap, spec]) => [ { cap, pkg: spec.pkg, export: spec.export, identities: spec.identities }, ...(spec.extras ?? []).map((ex) => ({ cap: `${cap}:${ex.export}`, pkg: ex.pkg, export: ex.export, identities: ex.identities })), - ]); + ]).concat( + // The stores the `knowledge` token chooses between (`resolveCapabilityExtras`). + Object.values(KNOWLEDGE_STORE_PROVIDERS).map((store) => ({ + cap: `knowledge:${store.export}`, pkg: store.pkg, export: store.export, identities: store.identities, + })), + ); /** * The consumer side of the pin. `@objectstack/connector-mcp` is not a @@ -341,6 +347,12 @@ const IDENTITY_SOURCES: IdentitySource[] = [ identities: ex.identities, })), ]), + ...Object.entries(KNOWLEDGE_STORE_PROVIDERS).map(([id, store]) => ({ + label: `KNOWLEDGE_STORE_PROVIDERS.${id}`, + pkg: store.pkg, + export: store.export, + identities: store.identities, + })), ...Object.entries(IDENTITY_LISTS).map(([name, entry]) => ({ label: `Serve.${name}`, pkg: entry.pkg, diff --git a/packages/core/src/capability-composition.test.ts b/packages/core/src/capability-composition.test.ts index c8b22fc8ba5..03be709a467 100644 --- a/packages/core/src/capability-composition.test.ts +++ b/packages/core/src/capability-composition.test.ts @@ -11,7 +11,13 @@ import { afterEach, describe, expect, it } from 'vitest'; import { composeStacks, defineStack } from '@objectstack/spec'; import { PLATFORM_ALWAYS_ON_CAPABILITIES } from '@objectstack/spec/kernel'; -import { resolveCapabilityArgument, resolveServedCapabilities } from './capability-composition.js'; +import { + resolveCapabilityArgument, + resolveCapabilityExtras, + resolveKnowledgeStore, + resolveServedCapabilities, +} from './capability-composition.js'; +import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js'; import { stackDeclaredCapabilities } from './stack-collections.js'; const SLATE = [...PLATFORM_ALWAYS_ON_CAPABILITIES]; @@ -210,3 +216,89 @@ describe('resolveCapabilityArgument — what each provider is constructed with', } }); }); + +/** + * ADR-0161 — `requires: ['knowledge']` mounts the knowledge service and ONE + * vector store, chosen by the platform database. One case per arm, each + * against the answer that arm changes. + */ +describe('resolveKnowledgeStore — which store the knowledge token mounts', () => { + const root = '/srv/app'; + const PG = 'postgres://u:p@db:5432/app'; + + it('PostgreSQL by the resolved driver or URL: pgvector, handed the platform URL', () => { + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database: { driver: 'postgres', url: PG } })).toEqual({ + store: KNOWLEDGE_STORE_PROVIDERS.pgvector, + argument: { url: PG }, + }); + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database: { url: 'postgresql://db/app' } }).store.adapterId).toBe('pgvector'); + // A driver id alone, with a URL the store cannot read: the store reads its own env. + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database: { driver: 'postgres', url: 'pg://db/app' } })).toEqual({ + store: KNOWLEDGE_STORE_PROVIDERS.pgvector, + argument: {}, + }); + }); + + it('any other database: turso on a file under the app root, its URL configurable in settings', () => { + for (const database of [ + { driver: 'sqlite', url: 'file:/srv/app/.objectstack/data/objectstack.db' }, + { driver: 'turso', url: 'libsql://x.turso.io' }, + { driver: 'mysql', url: 'mysql://db/app' }, + { driver: 'mongodb', url: 'mongodb://db/app' }, + ]) { + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database })).toEqual({ + store: KNOWLEDGE_STORE_PROVIDERS.turso, + argument: { projectRoot: root, urlFromSettings: true }, + }); + } + }); + + it('an in-memory platform database: an in-memory store', () => { + for (const database of [{ driver: 'sqlite-wasm', url: ':memory:' }, { driver: 'memory' }]) { + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database })).toEqual({ + store: KNOWLEDGE_STORE_PROVIDERS.turso, + argument: { url: ':memory:' }, + }); + } + }); + + it('no resolved database: OS_DATABASE_URL, else DATABASE_URL, decides', () => { + const pick = (env: Record) => + resolveKnowledgeStore({ stack: {}, packageRoot: root, env }).store.adapterId; + expect(pick({ OS_DATABASE_URL: PG })).toBe('pgvector'); + expect(pick({ DATABASE_URL: PG })).toBe('pgvector'); + expect(pick({ OS_DATABASE_URL: 'file:./x.db', DATABASE_URL: PG })).toBe('turso'); + expect(pick({})).toBe('turso'); + // A resolved database wins over the environment. + expect( + resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_DATABASE_URL: PG }, database: { driver: 'sqlite' } }).store.adapterId, + ).toBe('turso'); + }); +}); + +describe('resolveCapabilityExtras — what a boot mounts after a main provider', () => { + it('knowledge: exactly one store, with its argument; never the in-memory one', () => { + const extras = resolveCapabilityExtras('knowledge', { stack: {}, packageRoot: '/a', database: { driver: 'postgres', url: 'postgres://h/d' } }); + expect(extras).toEqual([ + { + pkg: '@objectstack/knowledge-pgvector', + export: 'KnowledgePgvectorPlugin', + identities: ['com.objectstack.plugin.knowledge-pgvector', 'KnowledgePgvectorPlugin'], + argument: { url: 'postgres://h/d' }, + }, + ]); + expect(Object.values(KNOWLEDGE_STORE_PROVIDERS).map((s) => s.pkg)).not.toContain('@objectstack/knowledge-memory'); + }); + + it("any other token: its row's extras, each with no argument", () => { + const extras = resolveCapabilityExtras('triggers', { stack: {}, packageRoot: '/a' }); + expect(extras.map((e) => e.export)).toEqual((CAPABILITY_PROVIDERS.triggers.extras ?? []).map((e) => e.export)); + expect(extras.every((e) => e.argument === undefined)).toBe(true); + expect(resolveCapabilityExtras('cache', { stack: {}, packageRoot: '/a' })).toEqual([]); + }); + + it('the knowledge row names the service, never a store: the store is the database\'s choice', () => { + expect(CAPABILITY_PROVIDERS.knowledge).toMatchObject({ pkg: '@objectstack/service-knowledge', export: 'KnowledgeServicePlugin' }); + expect(CAPABILITY_PROVIDERS.knowledge.extras).toBeUndefined(); + }); +}); diff --git a/packages/core/src/capability-composition.ts b/packages/core/src/capability-composition.ts index d7e841dfacf..cafb9b5669c 100644 --- a/packages/core/src/capability-composition.ts +++ b/packages/core/src/capability-composition.ts @@ -59,7 +59,8 @@ import { PLATFORM_ALWAYS_ON_CAPABILITIES } from '@objectstack/spec/kernel'; import { readEnvWithDeprecation } from '@objectstack/types'; -import { CAPABILITY_PROVIDERS } from './capability-providers.js'; +import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js'; +import type { CapabilityIdentities, KnowledgeStoreSpec } from './capability-providers.js'; import { resolveStackCollection } from './stack-collections.js'; type Bag = Record; @@ -153,6 +154,19 @@ export interface CapabilityArgumentInput { readonly providerModule?: Readonly>; /** The environment the mail and SMS readers read. Defaults to `process.env`. */ readonly env?: Readonly>; + /** + * The platform database this boot resolved, when it resolved one itself: + * its driver kind (`postgres`, `sqlite`, `turso`, …) and URL. Read by the + * `knowledge` store choice ({@link resolveKnowledgeStore}); absent, the + * choice reads `OS_DATABASE_URL`, else `DATABASE_URL`, from `env`. + */ + readonly database?: CapabilityDatabase; +} + +/** The platform database a boot resolved, as {@link CapabilityArgumentInput.database} carries it. */ +export interface CapabilityDatabase { + readonly driver?: string; + readonly url?: string; } /** One provider's constructor argument. */ @@ -242,6 +256,90 @@ export function resolveCapabilityArgument(token: string, input: CapabilityArgume return { argument: undefined }; } +// ── extras ──────────────────────────────────────────────────────────────── + +/** One extra provider a served boot mounts after a token's main provider, and what it is built with. */ +export interface CapabilityExtra { + readonly pkg: string; + readonly export: string; + readonly identities: CapabilityIdentities; + /** Construct the provider with this, or with no argument when `undefined`. */ + readonly argument?: unknown; +} + +/** + * The extra providers a served boot mounts for `token` after its main + * provider, each with its constructor argument — the rule `os serve` and the + * handle both read in place of a row's `extras`. + * + * - `knowledge`: the one vector store {@link resolveKnowledgeStore} chooses + * for the platform database. + * - any other token: its row's `extras`, each with no argument. + * + * Each boot skips an extra it already holds (`providesCapability`), as it + * does for a row's `extras`. + */ +export function resolveCapabilityExtras(token: string, input: CapabilityArgumentInput): CapabilityExtra[] { + if (token === 'knowledge') { + const { store, argument } = resolveKnowledgeStore(input); + return [{ pkg: store.pkg, export: store.export, identities: store.identities, argument }]; + } + return (CAPABILITY_PROVIDERS[token]?.extras ?? []).map((extra) => ({ ...extra })); +} + +// ── knowledge ───────────────────────────────────────────────────────────── + +/** A PostgreSQL URL, as the pgvector store reads one. */ +const POSTGRES_URL = /^postgres(ql)?:\/\//i; + +/** + * The vector store `requires: ['knowledge']` mounts beside the knowledge + * service, and what it is constructed with (ADR-0161): + * + * - the platform database is PostgreSQL — its resolved driver is `postgres`, + * or its URL is a `postgres://` / `postgresql://` one — ⇒ `pgvector` + * (`@objectstack/knowledge-pgvector`), handed that URL, so the store's + * tables live in the platform's own database, in a schema of their own; + * - any other database ⇒ `turso` (`@objectstack/knowledge-turso`), a libSQL + * file of its own: `knowledge.db` under the app's `.objectstack/data/`, + * beside the dev database and never its file. The operator can name + * another store in the `knowledge.turso_url` setting, which the store holds + * to that data directory and refuses when it carries a NUL byte, before it + * reaches the libSQL client. An in-memory platform database (`:memory:`, + * or the `memory` driver) gets an in-memory store (`:memory:`). + * + * The database is the one the boot resolved ({@link CapabilityArgumentInput.database}); + * a boot that resolved none (a host whose own plugin provides the driver) + * is judged by `OS_DATABASE_URL`, else `DATABASE_URL` — the variables the + * pgvector store reads its URL from. + */ +export function resolveKnowledgeStore(input: CapabilityArgumentInput): { + store: KnowledgeStoreSpec; + argument: Record; +} { + const env = input.env ?? (typeof process !== 'undefined' ? process.env : {}); + const url = input.database + ? input.database.url?.trim() + : (env.OS_DATABASE_URL?.trim() || env.DATABASE_URL?.trim() || undefined); + const postgres = input.database?.driver === 'postgres' || (url !== undefined && POSTGRES_URL.test(url)); + if (postgres) { + return { + store: KNOWLEDGE_STORE_PROVIDERS.pgvector, + argument: url !== undefined && POSTGRES_URL.test(url) ? { url } : {}, + }; + } + // An in-memory platform database keeps nothing past the process, and its + // store keeps nothing either: a file beside it would outlive every row it + // indexes (the verification handle boots an in-memory SQLite). + if (url === ':memory:' || input.database?.driver === 'memory') { + return { store: KNOWLEDGE_STORE_PROVIDERS.turso, argument: { url: ':memory:' } }; + } + return { + store: KNOWLEDGE_STORE_PROVIDERS.turso, + argument: { projectRoot: input.packageRoot, urlFromSettings: true }, + }; +} + // ── storage ─────────────────────────────────────────────────────────────── // Moved here from `@objectstack/cli`'s `serve.ts` (#22301), which re-exports // both names, so every boot that composes what `serve` composes reads one root. diff --git a/packages/core/src/capability-providers.ts b/packages/core/src/capability-providers.ts index 13b7b4b9dc9..c41f91a6898 100644 --- a/packages/core/src/capability-providers.ts +++ b/packages/core/src/capability-providers.ts @@ -244,6 +244,56 @@ export const CAPABILITY_PROVIDERS: Readonly> = { export: 'RecordContextServicePlugin', identities: ['com.objectstack.service.record-context', 'RecordContextServicePlugin'], }, + // ADR-0161: the `knowledge` service, its settings page and its embedder. + // Requested, never always-on: without the token no service, no store and no + // Knowledge settings page. The token mounts ONE vector store beside it, + // chosen by the platform database — see KNOWLEDGE_STORE_PROVIDERS below and + // `resolveCapabilityExtras`, which every boot reads in place of `extras` for + // this row. A host that mounts the service in `plugins[]` keeps its own and + // gets no store from the runtime. + knowledge: { + pkg: '@objectstack/service-knowledge', + export: 'KnowledgeServicePlugin', + identities: ['com.objectstack.service.knowledge', 'KnowledgeServicePlugin'], + }, +}; + +/** One vector store the `knowledge` token can mount beside the service. */ +export type KnowledgeStoreSpec = { + pkg: string; + export: string; + identities: CapabilityIdentities; + /** The adapter id the store registers: the value a `KnowledgeSource.adapter` names. */ + adapterId: string; +}; + +/** + * The vector stores the `knowledge` token chooses between, keyed by the + * adapter id each registers (ADR-0161; the choice is + * `resolveKnowledgeStore` in `capability-composition.ts`): + * + * - `pgvector` when the platform database is PostgreSQL — the store's tables + * live in that database, in a schema of their own; + * - `turso` on any other database (SQLite under `os dev`, libSQL, MySQL, + * MongoDB) — a libSQL file of its own, `knowledge.db` under the project's + * `.objectstack/data/`, never the platform's database file. + * + * `knowledge-memory` is never mounted by the runtime: its index is gone at + * every restart. A host that wants it mounts it itself. + */ +export const KNOWLEDGE_STORE_PROVIDERS: Readonly> = { + pgvector: { + pkg: '@objectstack/knowledge-pgvector', + export: 'KnowledgePgvectorPlugin', + identities: ['com.objectstack.plugin.knowledge-pgvector', 'KnowledgePgvectorPlugin'], + adapterId: 'pgvector', + }, + turso: { + pkg: '@objectstack/knowledge-turso', + export: 'KnowledgeTursoPlugin', + identities: ['com.objectstack.plugin.knowledge-turso', 'KnowledgeTursoPlugin'], + adapterId: 'turso', + }, }; /** diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts new file mode 100644 index 00000000000..bcebce1fc54 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/capability-mount.live-postgres.test.ts @@ -0,0 +1,85 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0161 — `requires: ['knowledge']` on a PostgreSQL platform database, on + * the LIVE PostgreSQL: the token's rule (`resolveCapabilityExtras`, + * `@objectstack/core`, which `os serve` and `@objectstack/verify` both read) + * chooses this store and hands it the platform URL; mounted beside the + * token's main provider, a record write is indexed into the platform database + * and `search_knowledge` (the executor the MCP doors call) finds it. The + * SQLite half of the rule boots in `@objectstack/verify` + * (`harness.required-providers.test.ts`). + */ + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { CAPABILITY_PROVIDERS, LiteKernel, resolveCapabilityExtras } from '@objectstack/core'; +import { KnowledgeService, KnowledgeServicePlugin } from '@objectstack/service-knowledge'; +import { EMBEDDER_SERVICE } from '@objectstack/spec/contracts'; +import { KnowledgePgvectorPlugin } from '../index.js'; +import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector mounted by the knowledge capability'); + +const store = liveStore('kpg_mount'); + +describe.skipIf(!PG_URL)('requires knowledge on PostgreSQL — the token mounts pgvector on the platform database', { timeout: 60_000 }, () => { + let kernel: LiteKernel; + let svc: KnowledgeService; + const schema = store.schema(); + + beforeAll(async () => { + const extras = resolveCapabilityExtras('knowledge', { + stack: {}, + packageRoot: process.cwd(), + env: {}, + database: { driver: 'postgres', url: PG_URL }, + }); + expect(CAPABILITY_PROVIDERS.knowledge.export).toBe('KnowledgeServicePlugin'); + expect(extras).toHaveLength(1); + const [extra] = extras; + expect(extra).toMatchObject({ pkg: '@objectstack/knowledge-pgvector', export: 'KnowledgePgvectorPlugin', argument: { url: PG_URL } }); + + kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + kernel.use({ + name: 'test.embedder', + init: async (ctx: { registerService(n: string, s: unknown): void }) => ctx.registerService(EMBEDDER_SERVICE, new FakeEmbedder()), + } as never); + kernel.use( + new KnowledgeServicePlugin({ + enableEventSync: false, + sources: [{ id: 'kpg_notes', label: 'Notes', adapter: 'pgvector', source: { kind: 'object', object: 'kpg_note', contentFields: ['body'] } }], + }), + ); + // The store as the rule builds it — its argument — in a schema of this file's own. + kernel.use(new KnowledgePgvectorPlugin({ ...(extra.argument as object), schema })); + await kernel.bootstrap(); + svc = kernel.getService('knowledge'); + }); + + afterAll(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + await store.dropAll(); + }); + + it('the store is mounted, ready, on the platform database', async () => { + expect(svc.listAdapters()).toEqual(['pgvector']); + expect(await svc.getAdapter('pgvector').healthCheck!()).toMatchObject({ ok: true }); + expect(svc.reportUnmountedAdapters()).toEqual([]); + }); + + it('a record write is indexed there, and search_knowledge finds it', async () => { + await svc.handleRecordUpsert('kpg_note', { id: 'n1', body: 'granite quarry near the river' }); + const { rows } = await store.pool().query( + `SELECT count(*)::int AS n FROM information_schema.tables WHERE table_schema = $1`, + [schema], + ); + expect(rows[0].n).toBeGreaterThan(0); + const answer = await svc.knowledgeTools().searchKnowledge( + { query: 'granite quarry' }, + { isSystem: true, userId: 'system', roles: [], permissions: [] } as never, + ); + expect(answer.refused).toBeUndefined(); + expect(answer.hits.map((h) => h.sourceId)).toEqual(['kpg_notes']); + expect(JSON.stringify(answer.hits[0])).toContain('granite'); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 411bf6675de..646ef2b9c5a 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -7,14 +7,22 @@ * never a failed boot. */ -import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, 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 { + DEFAULT_REQUEST_TIMEOUT_MS, + KnowledgeTursoPlugin, + dataDirectoryOf, + defaultStoreUrl, + requestBoundFor, + resolveSettingsStoreUrl, + 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. */ @@ -173,3 +181,138 @@ describe('KnowledgeTursoPlugin', () => { expect(adapter.embedding).toEqual({ dimensions: 32, model: 'late-model' }); }); }); + +/** + * A store URL read from the `knowledge.turso_url` setting: written by an + * operator through the settings page, so held to the project's data directory, + * and refused when it carries a NUL byte before it reaches the libSQL client + * (whose native library ends the process on one). + */ +describe('resolveSettingsStoreUrl', () => { + const NUL = String.fromCharCode(0); + + it('refuses a NUL byte or another control character, in a setting and in the plugin option alike', () => { + const root = tempDir(); + const inside = `file:${join(dataDirectoryOf(root), 'k.db')}`; + for (const url of [`${inside}${NUL}`, `file:${dataDirectoryOf(root)}/k${NUL}.db`, `${inside}\n`, `libsql://db${NUL}.turso.io`, `:memory:${NUL}`]) { + expect(resolveSettingsStoreUrl(url, { projectRoot: root, env: {} })).toMatchObject({ + reason: expect.stringContaining('NUL byte'), + }); + expect(resolveStoreUrl({ url, projectRoot: root, env: {} })).toMatchObject({ reason: expect.stringContaining('NUL byte') }); + } + }); + + it('takes a file inside the data directory, and :memory: or a remote URL as they are', () => { + const root = tempDir(); + const file = join(dataDirectoryOf(root), 'search', 'k.db'); + expect(resolveSettingsStoreUrl(`file:${file}`, { projectRoot: root, env: {} })).toEqual({ + url: `file:${file}`, + from: 'the knowledge setting `turso_url`', + }); + expect(resolveSettingsStoreUrl(':memory:', { projectRoot: root, env: {} })).toMatchObject({ url: ':memory:' }); + expect(resolveSettingsStoreUrl('libsql://db.example.turso.io', { projectRoot: root, env: {} })).toMatchObject({ + url: 'libsql://db.example.turso.io', + }); + }); + + it('refuses a file outside the data directory: elsewhere, by .., by a link, or the directory itself', () => { + const root = tempDir(); + const data = dataDirectoryOf(root); + mkdirSync(data, { recursive: true }); + const outside = tempDir(); + symlinkSync(outside, join(data, 'escape')); + for (const url of [ + `file:${join(outside, 'k.db')}`, + `file:${data}/../k.db`, + `file:${join(root, '.objectstack', 'knowledge.db')}`, + `file:${join(data, 'escape', 'k.db')}`, + `file:${data}`, + ]) { + expect(resolveSettingsStoreUrl(url, { projectRoot: root, env: {} })).toMatchObject({ + reason: expect.stringContaining('outside the data directory'), + }); + } + }); + + it("still refuses the platform's own database file inside the data directory", () => { + const root = tempDir(); + expect( + resolveSettingsStoreUrl(`file:${join(dataDirectoryOf(root), 'objectstack.db')}`, { projectRoot: root, env: {} }), + ).toMatchObject({ reason: expect.stringContaining("platform's own database file") }); + }); +}); + +/** A settings service answering saved `knowledge` values, as `SettingsService.get` resolves them. */ +function settingsOf(saved: Record, failure?: Error) { + return { + get: async (namespace: string, key: string) => { + if (failure) throw failure; + if (namespace !== 'knowledge') throw Object.assign(new Error('unknown'), { code: 'SETTINGS_UNKNOWN_NAMESPACE' }); + const value = saved[key]; + return value === undefined ? { value: undefined, source: 'default' } : { value, source: 'global' }; + }, + }; +} + +describe('KnowledgeTursoPlugin — the store URL from settings (urlFromSettings)', () => { + it('opens the file a saved setting names inside the data directory', async () => { + const root = tempDir(); + const file = join(dataDirectoryOf(root), 'saved.db'); + const { ctx, adapters } = contextOf({ settings: settingsOf({ turso_url: `file:${file}` }) }); + const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }); + await plugin.start(ctx); + expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: true }); + expect(existsSync(file)).toBe(true); + expect(existsSync(join(dataDirectoryOf(root), 'knowledge.db'))).toBe(false); + await plugin.destroy(); + }); + + it('nothing saved, no knowledge namespace or no settings service: the default file', async () => { + for (const services of [{ settings: settingsOf({}) }, { settings: { get: async () => { throw Object.assign(new Error('x'), { code: 'SETTINGS_UNKNOWN_NAMESPACE' }); } } }, {}]) { + const root = tempDir(); + const { ctx, adapters } = contextOf(services); + const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }); + await plugin.start(ctx); + expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: true }); + expect(existsSync(join(dataDirectoryOf(root), 'knowledge.db'))).toBe(true); + await plugin.destroy(); + } + }); + + it('a saved URL with a NUL byte, or outside the data directory, never reaches the libSQL client', async () => { + const createClient = vi.fn(); + vi.doMock('@libsql/client', () => ({ createClient })); + vi.resetModules(); + const { KnowledgeTursoPlugin: Fresh } = await import('../plugin.js'); + const root = tempDir(); + for (const [url, reason] of [ + [`file:${join(dataDirectoryOf(root), 'k.db')}${String.fromCharCode(0)}x`, 'NUL byte'], + [`file:${join(tempDir(), 'k.db')}`, 'outside the data directory'], + ] as const) { + const { ctx, adapters, logs } = contextOf({ settings: settingsOf({ turso_url: url }) }); + await new Fresh({ projectRoot: root, env: {}, urlFromSettings: true }).start(ctx); + expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); + expect(logs.some(([level, m]) => level === 'warn' && m.includes(reason))).toBe(true); + } + expect(createClient).not.toHaveBeenCalled(); + }); + + it('a settings read that fails opens nothing: the store says why', async () => { + const root = tempDir(); + const { ctx, adapters, logs } = contextOf({ settings: settingsOf({}, new Error('database is locked')) }); + await new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }).start(ctx); + expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); + expect(logs.some(([level, m]) => level === 'warn' && m.includes('database is locked'))).toBe(true); + expect(existsSync(join(dataDirectoryOf(root), 'knowledge.db'))).toBe(false); + }); + + it('the plugin option `url` wins, and without urlFromSettings the settings are not read', async () => { + const root = tempDir(); + const read = vi.fn(async () => ({ value: `file:${join(dataDirectoryOf(root), 'saved.db')}`, source: 'global' })); + const { ctx, adapters } = contextOf({ settings: { get: read } }); + await new KnowledgeTursoPlugin({ url: ':memory:', env: {}, urlFromSettings: true, projectRoot: root }).start(ctx); + await new KnowledgeTursoPlugin({ projectRoot: root, env: {} }).start(ctx); + expect(read).not.toHaveBeenCalled(); + expect(adapters.get('turso')).toBeDefined(); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/index.ts b/packages/plugins/knowledge-turso/src/index.ts index 29b41d7bdf7..e96da0c8b11 100644 --- a/packages/plugins/knowledge-turso/src/index.ts +++ b/packages/plugins/knowledge-turso/src/index.ts @@ -10,8 +10,10 @@ export { DEFAULT_REQUEST_TIMEOUT_MS, KnowledgeTursoPlugin, PLATFORM_DATABASE_FILES, + dataDirectoryOf, defaultStoreUrl, requestBoundFor, + resolveSettingsStoreUrl, resolveStoreUrl, type KnowledgeTursoPluginOptions, } from './plugin.js'; diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index 953c9777303..744610b6011 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -1,7 +1,7 @@ // 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 { basename, dirname, isAbsolute, relative as relativePath, resolve as resolvePath } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { Client } from '@libsql/client'; import type { Plugin, PluginContext } from '@objectstack/core'; @@ -55,7 +55,15 @@ export interface KnowledgeTursoPluginOptions { 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() */ + /** + * Read the store's URL and auth token from the `knowledge` settings + * (`turso_url`, `turso_auth_token`) when neither `url` nor `client` is + * given. A URL read from there is held to the data directory + * ({@link resolveSettingsStoreUrl}). The runtime's `knowledge` capability + * mount sets it. @default false + */ + urlFromSettings?: boolean; + /** The project directory the default file and the data directory are under. @default process.cwd() */ projectRoot?: string; /** The environment the platform's database URL is read from. @default process.env */ env?: Record; @@ -66,6 +74,19 @@ export function defaultStoreUrl(projectRoot: string = process.cwd()): string { return `file:${resolvePath(projectRoot, '.objectstack', 'data', DEFAULT_KNOWLEDGE_FILE)}`; } +/** The project's data directory: `/.objectstack/data`, where the default file is. */ +export function dataDirectoryOf(projectRoot: string = process.cwd()): string { + return resolvePath(projectRoot, '.objectstack', 'data'); +} + +/** + * A control character (U+0000 to U+001F, U+007F) anywhere in a URL. The libSQL + * client hands a `file:` URL to its native library, which ends the process on + * a NUL byte inside the path rather than answering an error; no URL with a + * control character in it names a store, so none reaches the client. + */ +const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/; + /** The bound on one request to a remote database (`requestTimeoutMs`). */ export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; @@ -132,6 +153,9 @@ export function resolveStoreUrl( 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 (CONTROL_CHARACTER.test(url)) { + return { reason: 'its `url` option carries a NUL byte or another control character, which names no file or database.' }; + } if (!/^(file:|libsql:\/\/|https?:\/\/|wss?:\/\/)/i.test(url) && url !== ':memory:') { return { reason: 'its `url` option is not a file:, :memory: or libsql:// URL.' }; } @@ -160,6 +184,128 @@ export function resolveStoreUrl( return { url, from }; } +/** + * A path as it is on disk: the real path of its nearest existing ancestor with + * the rest appended, so a link anywhere above it is followed and a file not + * yet created is still placed. + */ +function realPathAllowingMissing(path: string): string { + const rest: string[] = []; + let current = resolvePath(path); + for (;;) { + try { + return resolvePath(realpathSync(current), ...rest); + } catch { + const parent = dirname(current); + if (parent === current) return resolvePath(path); + rest.unshift(basename(current)); + current = parent; + } + } +} + +/** + * The libSQL URL a store takes from the `knowledge.turso_url` setting, or why + * it does not take it. + * + * A setting is written through the settings page and the settings API, by an + * operator who never touches the server's disk, so what it may name is held + * tighter than a URL written in code: + * + * - a control character (a NUL byte above all) is refused before anything + * else, so it never reaches the native client; + * - a `file:` URL must name a file inside the project's data directory + * (`.objectstack/data/`, {@link dataDirectoryOf}), compared as the file it + * resolves to, so neither `..` nor a link leads out of it. A relative path is + * read from the process's working directory, as libSQL opens it; + * - `:memory:` and a remote `libsql://`, `https://` or `wss://` URL open no + * local file and are taken as they are. + * + * Every rule {@link resolveStoreUrl} applies holds after these: the platform's + * own database file is refused there too. + */ +export function resolveSettingsStoreUrl( + url: string, + opts: Pick = {}, +): { url: string; from: string } | { url?: undefined; reason: string } { + const from = 'the knowledge setting `turso_url`'; + if (CONTROL_CHARACTER.test(url)) { + return { + reason: + `${from} carries a NUL byte or another control character, which names no file or database. ` + + 'Save the URL again without it.', + }; + } + const trimmed = url.trim(); + if (/^file:/i.test(trimmed)) { + const file = fileOf(trimmed); + if (file === undefined) { + return { reason: `${from} is not a valid file: URL.` }; + } + const dataDir = realPathAllowingMissing(dataDirectoryOf(opts.projectRoot)); + const inside = relativePath(dataDir, realPathAllowingMissing(file)); + if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) { + return { + reason: + `${from} names a file outside the data directory (${dataDir}). A store file named in settings must be ` + + `inside it, such as file:${resolvePath(dataDir, DEFAULT_KNOWLEDGE_FILE)}; a file elsewhere is named in the ` + + "plugin's own `url` option.", + }; + } + } + const target = resolveStoreUrl({ url: trimmed, projectRoot: opts.projectRoot, env: opts.env }); + return target.url === undefined ? { reason: target.reason.replace('its `url` option', from) } : { url: target.url, from }; +} + +/** A settings service as this plugin reads it: one key's resolved value and the layer it came from. */ +interface StoreSettingsReader { + get(namespace: string, key: string): Promise<{ value?: unknown; source?: string } | undefined>; +} + +/** The settings service's code for a namespace or key nothing declares: nothing is saved there. */ +const UNDECLARED_SETTING = new Set(['SETTINGS_UNKNOWN_NAMESPACE', 'SETTINGS_UNKNOWN_KEY']); + +/** + * The `knowledge.turso_url` and `knowledge.turso_auth_token` an operator + * saved (any layer but the manifest's default, an `OS_*` override included). + * Nothing saved, no settings service, or no `knowledge` namespace: `{}`. A + * read that fails otherwise is a reason: a store must not open a file other + * than the one an operator may have named. + */ +async function readStoreSettings( + ctx: PluginContext, +): Promise<{ url?: string; authToken?: string } | { reason: string }> { + let settings: StoreSettingsReader | undefined; + try { + settings = ctx.getService('settings') ?? undefined; + } catch { + return {}; + } + if (typeof settings?.get !== 'function') return {}; + const saved = async (key: string): Promise => { + let resolved: { value?: unknown; source?: string } | undefined; + try { + resolved = await settings.get('knowledge', key); + } catch (err) { + const code = (err as { code?: unknown } | null)?.code; + if (typeof code === 'string' && UNDECLARED_SETTING.has(code)) return undefined; + throw err; + } + if (!resolved || (resolved.source ?? 'default') === 'default') return undefined; + const { value } = resolved; + return typeof value === 'string' && value.trim() !== '' ? value : undefined; + }; + try { + const url = await saved('turso_url'); + const authToken = url === undefined ? undefined : await saved('turso_auth_token'); + return { ...(url === undefined ? {} : { url }), ...(authToken === undefined ? {} : { authToken }) }; + } catch (err) { + return { + reason: `the knowledge settings could not be read (${err instanceof Error ? err.message : String(err)}).`, + }; + } +} + /** * `KnowledgeTursoPlugin` — registers a {@link TursoKnowledgeAdapter} with the * host's `IKnowledgeService` during `start()`. @@ -176,6 +322,17 @@ export class KnowledgeTursoPlugin implements Plugin { name = 'com.objectstack.plugin.knowledge-turso'; version = '0.1.0'; type = 'standard' as const; + /** + * Order-if-present (ADR-0116): start() registers with the knowledge service + * and, under `urlFromSettings`, reads the `knowledge` settings, which the + * settings service answers from the data engine. Literal ids: the boot-order + * gates read this array statically. + */ + optionalDependencies = [ + 'com.objectstack.service.knowledge', + 'com.objectstack.service.settings', + 'com.objectstack.engine.objectql', + ]; private readonly opts: KnowledgeTursoPluginOptions; private owned?: Client; @@ -201,12 +358,27 @@ export class KnowledgeTursoPlugin implements Plugin { let unavailable: string | undefined; let requestTimeoutMs = this.opts.requestTimeoutMs; if (!client) { - const target = resolveStoreUrl(this.opts); + let target: ReturnType = { reason: '' }; + let authToken = this.opts.authToken; + const given = this.opts.url?.trim(); + if (this.opts.urlFromSettings && (given === undefined || given === '')) { + const saved = await readStoreSettings(ctx); + if ('reason' in saved) { + target = { reason: saved.reason }; + } else if (saved.url !== undefined) { + target = resolveSettingsStoreUrl(saved.url, this.opts); + authToken = saved.authToken; + } else { + target = resolveStoreUrl(this.opts); + } + } else { + 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); + const opened = await openClient(target.url, { ...this.opts, authToken }); if ('client' in opened) client = this.owned = opened.client; else unavailable = opened.reason; } diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 271434ea6fc..fea22aa8cc1 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -68,7 +68,7 @@ describe('KnowledgeService — adapter & source registry', () => { svc.registerAdapter('memory', a); expect(svc.getAdapter('memory')).toBe(a); expect(svc.listAdapters()).toEqual(['memory']); - expect(() => svc.getAdapter('nope')).toThrow(/unknown adapter/); + expect(() => svc.getAdapter('nope')).toThrow(/adapter 'nope' is not mounted/); }); it('registerSource / listSources / getSource / unregister', () => { @@ -2383,3 +2383,85 @@ describe('KnowledgeService — record-level search (granularity, groupBy, freshn expect(hit.headingPath).toEqual(['Leave', 'Annual']); }); }); + +/** + * ADR-0161 — a source whose named adapter is not mounted (the runtime mounts + * one store per database, so a source naming the other is the common case): + * the service mounts, the boot says so once at `error`, and indexing and + * searching that source answer `SERVICE_UNAVAILABLE` naming the adapters that + * are mounted. Never an empty answer that reads as "nothing matched". + */ +describe('KnowledgeService — a source naming an adapter that is not mounted', () => { + function serviceWith() { + const logs: Array<[string, string]> = []; + const logger = { + info: () => undefined, + debug: () => undefined, + warn: (m: string) => logs.push(['warn', m]), + error: (m: string) => logs.push(['error', m]), + }; + const svc = new KnowledgeService({ logger }); + const turso = makeAdapter('turso', [{ id: 'd1', sourceId: 'notes', content: 'x', score: 1 } as KnowledgeHit]); + svc.registerAdapter('turso', turso); + svc.registerSource(objectSource('notes', 'task', 'turso')); + svc.registerSource(objectSource('docs', 'doc', 'pgvector')); + return { svc, logs, turso }; + } + + it('the boot reading names each such source once, at error, with the mounted choices', () => { + const { svc, logs } = serviceWith(); + expect(svc.reportUnmountedAdapters()).toEqual(['docs']); + const errors = logs.filter(([level]) => level === 'error').map(([, m]) => m); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("source 'docs' names adapter 'pgvector', which is not mounted (mounted: turso)"); + }); + + it('indexing it answers SERVICE_UNAVAILABLE naming the choices', async () => { + const { svc } = serviceWith(); + const err = await svc.indexDocument('docs', { id: 'a', content: 'x' } as KnowledgeDocument).catch((e: unknown) => e); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect((err as Error).message).toContain("adapter 'pgvector' is not mounted (mounted: turso)"); + }); + + it('searching it alone is refused whole; beside a mounted source it is named as refused', async () => { + const { svc, logs } = serviceWith(); + const alone = await svc.search('q', { sourceIds: ['docs'] }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect((alone as { refused: unknown }).refused).toEqual([ + expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 }), + ]); + const both = await svc.searchWithRefusals('q', {}); + expect(both.hits.map((h) => h.sourceId)).toEqual(['notes']); + expect(both.refused).toEqual([expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE' })]); + // Said once at boot, never a line per search. + expect(logs.filter(([, m]) => m.includes("'docs'"))).toEqual([]); + }); + + it('the plugin takes the reading at kernel:bootstrapped, after every store has registered; boot goes on', async () => { + const reading = vi.spyOn(KnowledgeService.prototype, 'reportUnmountedAdapters'); + try { + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + const late: Plugin = { + name: 'test.late-store', + init: async () => undefined, + start: async (ctx: PluginContext) => { + ctx.getService('knowledge').registerAdapter('turso', makeAdapter('turso')); + }, + }; + kernel.use( + new KnowledgeServicePlugin({ + sources: [objectSource('notes', 'task', 'turso'), objectSource('docs', 'doc', 'pgvector')], + enableEventSync: false, + }), + ); + kernel.use(late); + await kernel.bootstrap(); + // Taken once, after the store that started last registered: only 'docs' is named. + expect(reading).toHaveBeenCalledTimes(1); + expect(reading.mock.results[0]?.value).toEqual(['docs']); + await kernel.shutdown(); + } finally { + reading.mockRestore(); + } + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 119c4be6f64..fa6f1b6fe41 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -517,6 +517,11 @@ export class KnowledgeServicePlugin implements Plugin { ctx.hook('kernel:bootstrapped', async () => { await this.provideEmbedder(ctx); }); + // Every store registers its adapter in its own start(), so the reading of + // which sources name an unmounted one is taken once all have started. + ctx.hook('kernel:bootstrapped', () => { + this.service?.reportUnmountedAdapters(); + }); if (this.options.enableEventSync === false) return; const service = this.service; diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index f6725d153a3..a9c7d21400a 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -165,12 +165,28 @@ export class KnowledgeService implements IKnowledgeService { getAdapter(id: string): IKnowledgeAdapter { const adapter = this.adapters.get(id); - if (!adapter) { - throw new Error( - `[knowledge] unknown adapter '${id}'. Registered: [${[...this.adapters.keys()].join(', ')}]`, + if (!adapter) throw unmountedAdapterError(id, this.listAdapters()); + return adapter; + } + + /** + * Say once, at `error`, which registered sources name an adapter nothing + * registered — the boot's reading, taken by the plugin at + * `kernel:bootstrapped`, once every plugin has started and registered its + * store. Indexing and searching such a source answer the same refusal + * ({@link getAdapter}); the boot itself goes on. Answers the sources named. + */ + reportUnmountedAdapters(): string[] { + const mounted = this.listAdapters(); + const unmounted = this.listSources().filter((source) => !this.adapters.has(source.adapter)); + for (const source of unmounted) { + this.options.logger?.error?.( + `[knowledge] source '${source.id}' names adapter '${source.adapter}', which is not mounted ` + + `(mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). Indexing and searching it answer ` + + `${UNMOUNTED_ADAPTER_CODE} until its adapter is one of those, or the '${source.adapter}' store is mounted.`, ); } - return adapter; + return unmounted.map((source) => source.id); } listAdapters(): string[] { @@ -1213,9 +1229,11 @@ export class KnowledgeService implements IKnowledgeService { for (const { source, organizationIds, fingerprint, scope } of sources) { const adapter = this.adapters.get(source.adapter); if (!adapter) { - this.options.logger?.warn?.( - `[knowledge] source '${source.id}' references unknown adapter '${source.adapter}'; skipping.`, - ); + // Refused like an adapter that cannot serve: the caller is told which + // source was not searched and why; the boot said so at `error` + // (`reportUnmountedAdapters`), so no line per search. + const coded = codedRefusalOf(unmountedAdapterError(source.adapter, this.listAdapters())); + if (coded !== undefined) refused.push({ sourceId: source.id, ...coded }); continue; } try { @@ -1842,6 +1860,23 @@ interface SearchTarget { } /** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ +/** The code an index or search of a source whose adapter is not mounted answers. */ +const UNMOUNTED_ADAPTER_CODE = 'SERVICE_UNAVAILABLE'; + +/** + * The refusal of a source whose adapter is not mounted: ADR-0112 + * `SERVICE_UNAVAILABLE` (503), naming the adapter and the ones that are. + */ +function unmountedAdapterError(id: string, mounted: readonly string[]): Error { + return Object.assign( + new Error( + `[knowledge] adapter '${id}' is not mounted (mounted: ${mounted.length === 0 ? 'none' : mounted.join(', ')}). ` + + `Name one of those as the source's adapter, or mount the '${id}' store.`, + ), + { code: UNMOUNTED_ADAPTER_CODE, status: 503 }, + ); +} + function codedRefusalOf(err: unknown): Omit | undefined { if (err === null || typeof err !== 'object') return undefined; const { code, status } = err as { code?: unknown; status?: unknown }; diff --git a/packages/services/service-settings/src/manifests/knowledge.manifest.ts b/packages/services/service-settings/src/manifests/knowledge.manifest.ts index 55961c5213f..06bbe1bea9e 100644 --- a/packages/services/service-settings/src/manifests/knowledge.manifest.ts +++ b/packages/services/service-settings/src/manifests/knowledge.manifest.ts @@ -19,8 +19,12 @@ import type { SettingsActionHandler } from '../settings-service.types.js'; * 6.x releases came from the * ObjectOS Cloud monorepo) * - * None of them reads this namespace yet: a deployment registers the plugin - * beside the knowledge service itself. + * Only `turso` reads this namespace, and only `turso_url` and + * `turso_auth_token`, when the runtime mounts it for `requires: + * ['knowledge']` (#37102): a `file:` URL saved there is held to the project's + * `.objectstack/data/` directory and a URL with a NUL byte is refused, before + * it reaches the libSQL client. Every other adapter is registered by the + * deployment 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 @@ -80,7 +84,7 @@ const manifest = { 'or in-memory (:memory:). In a cloud deployment with a database per organization, leave blank to ' + 'reuse that organization\'s own database connection.' }, { type: 'text', key: 'turso_url', label: 'Connection URL', required: false, - description: 'Examples: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + description: 'Examples: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', visible: "${data.adapter === 'turso'}" }, { type: 'password', key: 'turso_auth_token', label: 'Auth token', required: false, encrypted: true, diff --git a/packages/services/service-settings/src/translations/ar.ts b/packages/services/service-settings/src/translations/ar.ts index b5372dc794b..2388fe56697 100644 --- a/packages/services/service-settings/src/translations/ar.ts +++ b/packages/services/service-settings/src/translations/ar.ts @@ -671,7 +671,7 @@ export const ar: PlatformTranslationData = { }, turso_url: { label: 'عنوان URL للاتصال', - help: 'أمثلة: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + help: 'أمثلة: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', }, turso_auth_token: { label: 'رمز المصادقة', help: 'مطلوب فقط لعناوين Turso المُدارة.' }, ragflow_base_url: { label: 'Base URL', help: 'مثال: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/de.ts b/packages/services/service-settings/src/translations/de.ts index f2106121196..3a06d080bc1 100644 --- a/packages/services/service-settings/src/translations/de.ts +++ b/packages/services/service-settings/src/translations/de.ts @@ -713,7 +713,7 @@ export const de: PlatformTranslationData = { }, turso_url: { label: 'Verbindungs-URL', - help: 'Beispiele: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + help: 'Beispiele: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', }, turso_auth_token: { label: 'Auth-Token', help: 'Nur für verwaltete Turso-URLs erforderlich.' }, ragflow_base_url: { label: 'Base URL', help: 'Beispiel: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/en.ts b/packages/services/service-settings/src/translations/en.ts index 0ce8f3d095d..ff5ca42a7d8 100644 --- a/packages/services/service-settings/src/translations/en.ts +++ b/packages/services/service-settings/src/translations/en.ts @@ -405,7 +405,7 @@ export const en: PlatformTranslationData = { }, }, turso_url: { label: 'Connection URL', - help: 'Examples: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:' }, + help: 'Examples: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:' }, turso_auth_token: { label: 'Auth token', help: 'Only required for managed Turso URLs.' }, ragflow_base_url: { label: 'Base URL', help: 'Example: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/es-ES.ts b/packages/services/service-settings/src/translations/es-ES.ts index c84cf5090a9..7558811df8a 100644 --- a/packages/services/service-settings/src/translations/es-ES.ts +++ b/packages/services/service-settings/src/translations/es-ES.ts @@ -571,7 +571,7 @@ export const esES: PlatformTranslationData = { }, }, turso_url: { label: 'URL de conexión', - help: 'Ejemplos: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:' }, + help: 'Ejemplos: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:' }, turso_auth_token: { label: 'Token de autenticación', help: 'Solo se requiere para URLs de Turso gestionado.' }, ragflow_base_url: { label: 'Base URL', help: 'Ejemplo: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/fr.ts b/packages/services/service-settings/src/translations/fr.ts index 37f540ab7fe..b08eacdb183 100644 --- a/packages/services/service-settings/src/translations/fr.ts +++ b/packages/services/service-settings/src/translations/fr.ts @@ -719,7 +719,7 @@ export const fr: PlatformTranslationData = { }, turso_url: { label: 'URL de connexion', - help: 'Exemples : libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + help: 'Exemples : libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', }, turso_auth_token: { label: 'Jeton d’authentification', diff --git a/packages/services/service-settings/src/translations/ja-JP.ts b/packages/services/service-settings/src/translations/ja-JP.ts index 3bae4ac7e49..d8090b8de80 100644 --- a/packages/services/service-settings/src/translations/ja-JP.ts +++ b/packages/services/service-settings/src/translations/ja-JP.ts @@ -570,7 +570,7 @@ export const jaJP: PlatformTranslationData = { }, }, turso_url: { label: '接続 URL', - help: '例: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:' }, + help: '例: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:' }, turso_auth_token: { label: '認証トークン', help: 'マネージド Turso URL の場合のみ必要です。' }, ragflow_base_url: { label: 'Base URL', help: '例: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/ko.ts b/packages/services/service-settings/src/translations/ko.ts index 55db5a4a8e6..ebc93ed65f7 100644 --- a/packages/services/service-settings/src/translations/ko.ts +++ b/packages/services/service-settings/src/translations/ko.ts @@ -540,7 +540,7 @@ export const ko: PlatformTranslationData = { }, turso_url: { label: '연결 URL', - help: '예: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + help: '예: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', }, turso_auth_token: { label: '인증 토큰', help: '관리형 Turso URL에만 필요합니다.' }, ragflow_base_url: { label: 'Base URL', help: '예: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/pt-BR.ts b/packages/services/service-settings/src/translations/pt-BR.ts index 07fb6be448c..952551b9db8 100644 --- a/packages/services/service-settings/src/translations/pt-BR.ts +++ b/packages/services/service-settings/src/translations/pt-BR.ts @@ -706,7 +706,7 @@ export const ptBR: PlatformTranslationData = { }, turso_url: { label: 'URL de conexão', - help: 'Exemplos: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + help: 'Exemplos: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', }, turso_auth_token: { label: 'Token de autenticação', help: 'Necessário apenas para URLs do Turso gerenciado.' }, ragflow_base_url: { label: 'Base URL', help: 'Exemplo: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/ru.ts b/packages/services/service-settings/src/translations/ru.ts index 2866bd258c3..34e2fb88a50 100644 --- a/packages/services/service-settings/src/translations/ru.ts +++ b/packages/services/service-settings/src/translations/ru.ts @@ -716,7 +716,7 @@ export const ru: PlatformTranslationData = { }, turso_url: { label: 'URL подключения', - help: 'Примеры: libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + help: 'Примеры: libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', }, turso_auth_token: { label: 'Токен авторизации', help: 'Нужен только для URL управляемого Turso.' }, ragflow_base_url: { label: 'Base URL', help: 'Пример: http://localhost:9380' }, diff --git a/packages/services/service-settings/src/translations/zh-CN.ts b/packages/services/service-settings/src/translations/zh-CN.ts index c7c39d0de89..3022ad188fa 100644 --- a/packages/services/service-settings/src/translations/zh-CN.ts +++ b/packages/services/service-settings/src/translations/zh-CN.ts @@ -596,7 +596,7 @@ export const zhCN: PlatformTranslationData = { ragflow: 'RAGFlow(外部)', }, }, - turso_url: { label: '连接 URL', help: '示例:libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:' }, + turso_url: { label: '连接 URL', help: '示例:libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:' }, turso_auth_token: { label: 'Auth Token', help: '仅托管 Turso URL 需要。' }, ragflow_base_url: { label: 'Base URL', help: '示例:http://localhost:9380' }, ragflow_api_key: { label: 'API Key' }, diff --git a/packages/services/service-settings/src/translations/zh-Hant.ts b/packages/services/service-settings/src/translations/zh-Hant.ts index 0a069e1c569..f0d05a8d5f5 100644 --- a/packages/services/service-settings/src/translations/zh-Hant.ts +++ b/packages/services/service-settings/src/translations/zh-Hant.ts @@ -479,7 +479,7 @@ export const zhHant: PlatformTranslationData = { }, turso_url: { label: '連線 URL', - help: '範例:libsql://your-tenant.turso.io · file:./.objectstack/knowledge.db · :memory:', + help: '範例:libsql://your-tenant.turso.io · file:./.objectstack/data/knowledge.db · :memory:', }, turso_auth_token: { label: '驗證權杖', help: '僅託管 Turso URL 需要。' }, ragflow_base_url: { label: 'Base URL', help: '範例:http://localhost:9380' }, diff --git a/packages/spec/src/kernel/platform-capabilities.ts b/packages/spec/src/kernel/platform-capabilities.ts index a37cc532904..d1f0b1bd64b 100644 --- a/packages/spec/src/kernel/platform-capabilities.ts +++ b/packages/spec/src/kernel/platform-capabilities.ts @@ -79,6 +79,11 @@ export const PLATFORM_CAPABILITY_TOKENS: readonly string[] = Object.freeze([ // Requested, never always-on: whether an app exposes a read tool is the // app's own declaration, not a side effect of shipping packs. 'record-context', + // Knowledge (ADR-0161): the `knowledge` service and one vector store, chosen + // by the platform database — pgvector on PostgreSQL, otherwise a libSQL file + // of its own. Requested, never always-on: without the token no knowledge + // service, no store and no Knowledge settings page. + 'knowledge', // Enterprise / cloud-runtime capabilities (no open-edition provider: // `hierarchy-security` ships in @objectstack/security-enterprise via // `plugins[]`; `ai-seat` / `governance` / `audit-compliance` / @@ -233,6 +238,7 @@ export const PLATFORM_CAPABILITY_PROVIDERS: Readonly const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { dependencies: Record; }; - const packages = Object.values(CAPABILITY_PROVIDERS).flatMap((spec) => [ - spec.pkg, - ...(spec.extras ?? []).map((extra) => extra.pkg), - ]); + const packages = [ + ...Object.values(CAPABILITY_PROVIDERS).flatMap((spec) => [spec.pkg, ...(spec.extras ?? []).map((extra) => extra.pkg)]), + // The stores the `knowledge` token chooses between (`resolveCapabilityExtras`). + ...Object.values(KNOWLEDGE_STORE_PROVIDERS).map((store) => store.pkg), + ]; expect(packages.length).toBeGreaterThan(0); expect(packages.filter((pkg) => !(pkg in manifest.dependencies))).toEqual([]); }); @@ -245,3 +246,118 @@ describe("requires: ['record-context'] — get_record_context over MCP", () => { expect(await stack.kernel.getServiceAsync(RECORD_CONTEXT_SERVICE)).toBe(marker); }, 120_000); }); + +/** + * ADR-0161 — `requires: ['knowledge']` mounts `KnowledgeServicePlugin` and ONE + * vector store, chosen by the platform database. This boot's database is an + * in-memory SQLite, so the store is `turso` on an in-memory libSQL database + * (`resolveKnowledgeStore`); `serve` over SQLite gets `turso` on + * `.objectstack/data/knowledge.db`, and over PostgreSQL `pgvector` — that + * branch runs on the live PostgreSQL, in `@objectstack/knowledge-pgvector`. + * Sources are still written in app code: a plugin registers one here. + */ +describe("requires: ['knowledge'] — the knowledge service and one store", () => { + const KNOWLEDGE = 'com.objectstack.service.knowledge'; + const TURSO = 'com.objectstack.plugin.knowledge-turso'; + const PGVECTOR = 'com.objectstack.plugin.knowledge-pgvector'; + const article = { + name: 'rqp_article', label: 'Article', pluralLabel: 'Articles', sharingModel: 'public_read_write', + fields: { + title: { name: 'title', type: 'text', label: 'Title', required: true }, + body: { name: 'body', type: 'textarea', label: 'Body' }, + }, + }; + const app = (extra: Bag = {}): Bag => + defineStack({ manifest: appManifest, objects: [article], ...extra } as never) as unknown as Bag; + + /** A deterministic bag-of-words embedder: shared words, close vectors. */ + class WordEmbedder { + readonly id = 'rqp-words'; + readonly dimensions = 16; + readonly model = 'rqp-words'; + async embed(texts: string[]): Promise { + return texts.map((text) => { + const v = new Array(this.dimensions).fill(0); + for (const word of text.toLowerCase().split(/\W+/).filter(Boolean)) { + let h = 0; + for (const ch of word) h = (h * 31 + ch.charCodeAt(0)) >>> 0; + v[h % this.dimensions] += 1; + } + const n = Math.hypot(...v) || 1; + return v.map((x) => x / n); + }); + } + } + + /** The app's own code: an embedder, a source on the mounted store, and one naming the other store. */ + class AppKnowledge { + readonly name = 'com.example.rqp.knowledge'; + readonly version = '0.0.0'; + readonly type = 'standard'; + async init(ctx: { registerService(name: string, service: unknown): void }): Promise { + ctx.registerService('embedder', new WordEmbedder()); + } + async start(ctx: { getService(name: string): T }): Promise { + const svc = ctx.getService<{ registerSource(s: unknown): void }>('knowledge'); + svc.registerSource({ id: 'rqp_articles', label: 'Articles', adapter: 'turso', source: { kind: 'object', object: 'rqp_article', contentFields: ['title', 'body'] } }); + svc.registerSource({ id: 'rqp_elsewhere', label: 'Elsewhere', adapter: 'pgvector', source: { kind: 'object', object: 'rqp_article', contentFields: ['body'] } }); + } + } + + it('the token: the service and the turso store; a record write is indexed and found, a source naming pgvector is refused', async () => { + stack = await bootStack(app({ requires: ['realtime', 'knowledge'] }), { extraPlugins: [new AppKnowledge()] }); + expect(stack.kernel.hasPlugin(KNOWLEDGE)).toBe(true); + expect(stack.kernel.hasPlugin(TURSO)).toBe(true); + expect(stack.kernel.hasPlugin(PGVECTOR)).toBe(false); + const knowledge = await stack.kernel.getServiceAsync('knowledge'); + expect(knowledge.listAdapters()).toEqual(['turso']); + + const ql = await stack.kernel.getServiceAsync('objectql'); + await ql.insert('rqp_article', { title: 'Granite quarry RQP', body: 'basalt and granite slabs' }, { context: { isSystem: true } }); + const ec = { isSystem: true, userId: 'system', roles: [], permissions: [] }; + let hits: Array<{ sourceId: string; content: string }> = []; + for (let i = 0; i < 50 && hits.length === 0; i++) { + hits = (await knowledge.searchWithRefusals('granite quarry', { executionContext: ec, sourceIds: ['rqp_articles'] })).hits; + if (hits.length === 0) await new Promise((r) => setTimeout(r, 50)); + } + expect(hits.map((h) => h.sourceId)).toEqual(['rqp_articles']); + expect(hits[0]?.content).toContain('granite'); + + const refused = await knowledge.search('granite', { executionContext: ec, sourceIds: ['rqp_elsewhere'] }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(String((refused as Error).message)).toContain("adapter 'pgvector' is not mounted (mounted: turso)"); + }, 120_000); + + it('control — no token: no knowledge service, no store, no Knowledge settings page', async () => { + stack = await bootStack(app({ requires: ['realtime'] })); + expect(stack.kernel.hasPlugin(KNOWLEDGE)).toBe(false); + expect(stack.kernel.hasPlugin(TURSO)).toBe(false); + await expect(stack.kernel.getServiceAsync('knowledge')).rejects.toThrow(); + const settings = await stack.kernel.getServiceAsync('settings'); + await expect(settings.getNamespace('knowledge')).rejects.toMatchObject({ code: 'SETTINGS_UNKNOWN_NAMESPACE' }); + }, 120_000); + + it('a host that mounts the service itself keeps its own, and the runtime adds no store', async () => { + class HostKnowledge { + readonly name = KNOWLEDGE; + readonly version = '0.0.0'; + readonly type = 'standard'; + async init(): Promise {} + } + const constructed = await constructServedProviders({ + config: app({ requires: ['knowledge'] }), + held: [new HostKnowledge()], + packageRoot: process.cwd(), + }); + const names = constructed.map((p) => (p as { name?: string }).name); + expect(names).not.toContain(KNOWLEDGE); + expect(names).not.toContain(TURSO); + expect(names).not.toContain(PGVECTOR); + // The control: without the host's instance both are constructed. + const served = ( + await constructServedProviders({ config: app({ requires: ['knowledge'] }), held: [], packageRoot: process.cwd() }) + ).map((p) => (p as { name?: string }).name); + expect(served).toEqual(expect.arrayContaining([KNOWLEDGE, TURSO])); + expect(served).not.toContain(PGVECTOR); + }); +}); diff --git a/packages/verify/src/required-providers.ts b/packages/verify/src/required-providers.ts index 8eccca5b473..2a62a9686a8 100644 --- a/packages/verify/src/required-providers.ts +++ b/packages/verify/src/required-providers.ts @@ -23,8 +23,10 @@ // tokens that schedule background work. No preset: `bootStack` takes none, // so the slate is always mounted, as on a `serve` with no `--preset`. // · WHICH provider: `CAPABILITY_PROVIDERS`, the table -// `Serve.CAPABILITY_PROVIDERS` is a handle over — main provider, then its -// `extras`. +// `Serve.CAPABILITY_PROVIDERS` is a handle over — main provider, then +// `resolveCapabilityExtras` (its `extras`; for `knowledge` the one vector +// store the database chooses — an in-memory one here, as this boot's +// database is in memory). // · WITH WHAT: `resolveCapabilityArgument` — `automation` the app's root // (`hostRoot` here), `analytics` the app's cubes, `email` / `sms` the // deployment's mail and SMS configuration (from the configuration and the @@ -62,6 +64,8 @@ import { CAPABILITY_PROVIDERS, providesCapability, resolveCapabilityArgument, + resolveCapabilityExtras, + type CapabilityDatabase, resolveServedCapabilities, stackDeclaredCapabilities, } from '@objectstack/core'; @@ -134,6 +138,12 @@ export async function constructServedProviders(opts: { config: unknown; held: readonly unknown[]; packageRoot: string; + /** + * The database this boot serves, for the providers chosen by it (the + * `knowledge` store). The harness boots an in-memory SQLite, so the store + * is an in-memory one too. @default `{ driver: 'sqlite-wasm', url: ':memory:' }` + */ + database?: CapabilityDatabase; }): Promise { const { tokens, declared } = resolveServedCapabilities(stackDeclaredCapabilities(opts.config)); const constructed: unknown[] = []; @@ -157,9 +167,21 @@ export async function constructServedProviders(opts: { }).argument, }), ); - for (const extra of spec.extras ?? []) { + const extras = resolveCapabilityExtras(token, { + stack: opts.config, + packageRoot: opts.packageRoot, + database: opts.database ?? { driver: 'sqlite-wasm', url: ':memory:' }, + }); + for (const extra of extras) { if (providesCapability(all(), extra.identities)) continue; - constructed.push(await constructProvider({ reason, pkg: extra.pkg, exportName: extra.export })); + constructed.push( + await constructProvider({ + reason, + pkg: extra.pkg, + exportName: extra.export, + ...(extra.argument === undefined ? {} : { argumentFor: () => extra.argument }), + }), + ); } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0f3012c670a..e9e61fdbef2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -616,6 +616,12 @@ importers: '@objectstack/formula': specifier: workspace:* version: link:../formula + '@objectstack/knowledge-pgvector': + specifier: workspace:* + version: link:../plugins/knowledge-pgvector + '@objectstack/knowledge-turso': + specifier: workspace:* + version: link:../plugins/knowledge-turso '@objectstack/lint': specifier: workspace:* version: link:../lint @@ -688,6 +694,9 @@ importers: '@objectstack/service-job': specifier: workspace:* version: link:../services/service-job + '@objectstack/service-knowledge': + specifier: workspace:* + version: link:../services/service-knowledge '@objectstack/service-mailbox': specifier: workspace:* version: link:../services/service-mailbox @@ -3768,6 +3777,12 @@ importers: '@objectstack/core': specifier: workspace:* version: link:../core + '@objectstack/knowledge-pgvector': + specifier: workspace:* + version: link:../plugins/knowledge-pgvector + '@objectstack/knowledge-turso': + specifier: workspace:* + version: link:../plugins/knowledge-turso '@objectstack/mcp': specifier: workspace:* version: link:../mcp @@ -3828,6 +3843,9 @@ importers: '@objectstack/service-job': specifier: workspace:* version: link:../services/service-job + '@objectstack/service-knowledge': + specifier: workspace:* + version: link:../services/service-knowledge '@objectstack/service-mailbox': specifier: workspace:* version: link:../services/service-mailbox From 969b372a6e8b03b6bf32a9a72cff866460f7710c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:30:40 +0000 Subject: [PATCH 2/8] feat(core): requires knowledge mounts the knowledge service and one vector store PostgreSQL gets pgvector on the same database; any other database gets turso on .objectstack/data/knowledge.db. A store URL saved in settings is held to the data directory and refused on a NUL byte before libSQL. A source naming an unmounted adapter: boot ok, index/search answer 503. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01JQwxbWZjh7mWMsJZHnGWwZ --- .../37102-knowledge-capability-token.md | 25 +++++++++++++++++++ .../src/__tests__/plugin.test.ts | 2 +- .../src/__tests__/knowledge-service.test.ts | 7 +++--- packages/spec/scripts/lib/platform-catalog.ts | 1 + .../src/harness.required-providers.test.ts | 6 ++--- .../references/platform-catalog.md | 1 + 6 files changed, 35 insertions(+), 7 deletions(-) create mode 100644 .changeset/37102-knowledge-capability-token.md diff --git a/.changeset/37102-knowledge-capability-token.md b/.changeset/37102-knowledge-capability-token.md new file mode 100644 index 00000000000..3c368e0af95 --- /dev/null +++ b/.changeset/37102-knowledge-capability-token.md @@ -0,0 +1,25 @@ +--- +'@objectstack/spec': minor +'@objectstack/core': minor +'@objectstack/cli': minor +'@objectstack/verify': minor +'@objectstack/service-knowledge': minor +'@objectstack/knowledge-turso': minor +'@objectstack/service-settings': patch +--- + +feat(core): `requires: ['knowledge']` mounts the knowledge service and one vector store + +Clause-②: yes +Metadata-protocol: added +Skills-docs: follow-up #37310 + +ADR-0161, #37102. + +- **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, `.objectstack/data/knowledge.db` by default. An in-memory database gets an in-memory turso store. The in-memory adapter (`knowledge-memory`) is never mounted by the token. +- No token: no knowledge service and no knowledge settings page, as before. A host that mounts `KnowledgeServicePlugin` (or a store) itself keeps its own: the token adds only what is not already mounted. +- 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). +- `os serve` now warns when a capability's extra plugin cannot be imported or constructed, instead of skipping it silently. +- **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. +- **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`. A saved `file:` URL must resolve, after symlinks, inside the project's `.objectstack/data/` directory; a URL that leaves it, names the platform database, or carries a NUL byte or another control character is refused before the libSQL client sees it (a NUL byte in a file URL kills the process inside the native client). New exports: `resolveSettingsStoreUrl`, `dataDirectoryOf`. `resolveStoreUrl` refuses control characters too. +- The `turso_url` setting's example path now reads `file:./.objectstack/data/knowledge.db` in every locale. diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 646ef2b9c5a..072a99472bc 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -194,7 +194,7 @@ describe('resolveSettingsStoreUrl', () => { it('refuses a NUL byte or another control character, in a setting and in the plugin option alike', () => { const root = tempDir(); const inside = `file:${join(dataDirectoryOf(root), 'k.db')}`; - for (const url of [`${inside}${NUL}`, `file:${dataDirectoryOf(root)}/k${NUL}.db`, `${inside}\n`, `libsql://db${NUL}.turso.io`, `:memory:${NUL}`]) { + for (const url of [`${inside}${NUL}`, `file:${dataDirectoryOf(root)}/k${NUL}.db`, `file:${dataDirectoryOf(root)}/k\t.db`, `libsql://db${NUL}.turso.io`, `:memory:${NUL}`]) { expect(resolveSettingsStoreUrl(url, { projectRoot: root, env: {} })).toMatchObject({ reason: expect.stringContaining('NUL byte'), }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index fea22aa8cc1..61e92af1776 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -2401,7 +2401,7 @@ describe('KnowledgeService — a source naming an adapter that is not mounted', error: (m: string) => logs.push(['error', m]), }; const svc = new KnowledgeService({ logger }); - const turso = makeAdapter('turso', [{ id: 'd1', sourceId: 'notes', content: 'x', score: 1 } as KnowledgeHit]); + const turso = makeAdapter('turso', [{ chunkId: 'c1', documentId: 'd1', sourceId: 'notes', snippet: 'x', score: 1 }]); svc.registerAdapter('turso', turso); svc.registerSource(objectSource('notes', 'task', 'turso')); svc.registerSource(objectSource('docs', 'doc', 'pgvector')); @@ -2425,12 +2425,13 @@ describe('KnowledgeService — a source naming an adapter that is not mounted', it('searching it alone is refused whole; beside a mounted source it is named as refused', async () => { const { svc, logs } = serviceWith(); - const alone = await svc.search('q', { sourceIds: ['docs'] }).catch((e: unknown) => e); + const system = { isSystem: true } as never; + const alone = await svc.search('q', { sourceIds: ['docs'], executionContext: system }).catch((e: unknown) => e); expect(alone).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); expect((alone as { refused: unknown }).refused).toEqual([ expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 }), ]); - const both = await svc.searchWithRefusals('q', {}); + const both = await svc.searchWithRefusals('q', { executionContext: system }); expect(both.hits.map((h) => h.sourceId)).toEqual(['notes']); expect(both.refused).toEqual([expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE' })]); // Said once at boot, never a line per search. diff --git a/packages/spec/scripts/lib/platform-catalog.ts b/packages/spec/scripts/lib/platform-catalog.ts index 290595387d9..da26ed8db18 100644 --- a/packages/spec/scripts/lib/platform-catalog.ts +++ b/packages/spec/scripts/lib/platform-catalog.ts @@ -192,6 +192,7 @@ export const CAPABILITY_ROWS: Readonly> = Object.freeze({ settings: 'the settings store', webhooks: 'outbound webhooks', 'record-context': 'get_record_context over MCP', + knowledge: 'knowledge search: the service and one vector store', 'hierarchy-security': 'hierarchy-relative permission scopes', 'ai-seat': 'the AI-seat tier', governance: 'the governance tier', diff --git a/packages/verify/src/harness.required-providers.test.ts b/packages/verify/src/harness.required-providers.test.ts index 2c8606ac9a9..669b1b0a734 100644 --- a/packages/verify/src/harness.required-providers.test.ts +++ b/packages/verify/src/harness.required-providers.test.ts @@ -1,5 +1,5 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// test-budget: 20 — spawns the real producer once per single-cause fixture: nine in-process bootStack boots, no two the same configuration (a top-level requires, a package body's, the top level over the bodies, the control, an explicit instance, triggers with its hard dependencies, record-context with mcp, its no-token control, a host-mounted record-context), each its case's subject; 5.9 s in a local run for the first six, 10.0 s with the three record-context boots (local, verbose reporter); slowest CI reading 11.4 s (scheduled full-battery run 41199450735, Test Core shard log) x 1.25, rounded up, read before the record-context boots — the first CI reading after them re-measures it +// test-budget: 22 — spawns the real producer once per single-cause fixture: eleven in-process bootStack boots, no two the same configuration (a top-level requires, a package body's, the top level over the bodies, the control, an explicit instance, triggers with its hard dependencies, record-context with mcp, its no-token control, a host-mounted record-context, knowledge with realtime, its no-token control), each its case's subject; 5.9 s in a local run for the first six, 10.0 s with the three record-context boots, 14.8 s with the two knowledge boots (local, verbose reporter); slowest CI reading 11.4 s (scheduled full-battery run 41199450735, Test Core shard log) read before the record-context boots, scaled by the local ratio to 16.9 s, x 1.25, rounded up — the first CI reading after the knowledge boots re-measures it /** * #22301 item 1 — `bootStack` mounts the providers an app's `requires` names, @@ -315,13 +315,13 @@ describe("requires: ['knowledge'] — the knowledge service and one store", () = const ql = await stack.kernel.getServiceAsync('objectql'); await ql.insert('rqp_article', { title: 'Granite quarry RQP', body: 'basalt and granite slabs' }, { context: { isSystem: true } }); const ec = { isSystem: true, userId: 'system', roles: [], permissions: [] }; - let hits: Array<{ sourceId: string; content: string }> = []; + let hits: Array<{ sourceId: string; snippet: string }> = []; for (let i = 0; i < 50 && hits.length === 0; i++) { hits = (await knowledge.searchWithRefusals('granite quarry', { executionContext: ec, sourceIds: ['rqp_articles'] })).hits; if (hits.length === 0) await new Promise((r) => setTimeout(r, 50)); } expect(hits.map((h) => h.sourceId)).toEqual(['rqp_articles']); - expect(hits[0]?.content).toContain('granite'); + expect(hits[0]?.snippet).toContain('granite'); const refused = await knowledge.search('granite', { executionContext: ec, sourceIds: ['rqp_elsewhere'] }).catch((e: unknown) => e); expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); diff --git a/skills/objectstack-project/references/platform-catalog.md b/skills/objectstack-project/references/platform-catalog.md index 86e232d0080..b5100865787 100644 --- a/skills/objectstack-project/references/platform-catalog.md +++ b/skills/objectstack-project/references/platform-catalog.md @@ -134,6 +134,7 @@ whether or not the stack lists it. Declare what the app uses | `settings` | the settings store | open | every boot | | `webhooks` | outbound webhooks | open | on `requires` | | `record-context` | get_record_context over MCP | open | on `requires` | +| `knowledge` | knowledge search: the service and one vector store | open | on `requires` | | `hierarchy-security` | hierarchy-relative permission scopes | enterprise | on `requires` | | `ai-seat` | the AI-seat tier | cloud | on `requires` | | `governance` | the governance tier | cloud | on `requires` | From af91dc14afbe88b947764a3930daa64e06f11f80 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:29:40 +0000 Subject: [PATCH 3/8] wip(knowledge-turso): the store URL setting is read at kernel:bootstrapped Claude-Session: https://claude.ai/code/session_01Utp6CYE8s5v1UX96GEfkcR Co-authored-by: Claude --- .../src/__tests__/plugin.test.ts | 107 ++++++++--- .../plugins/knowledge-turso/src/plugin.ts | 168 +++++++++++++----- packages/spec/scripts/lib/platform-catalog.ts | 2 +- 3 files changed, 206 insertions(+), 71 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 072a99472bc..20375f6e913 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -34,11 +34,19 @@ function contextOf(services: Record = {}) { const all = services; if (!(KNOWLEDGE_SERVICE in all)) all[KNOWLEDGE_SERVICE] = svc; if (!(EMBEDDER_SERVICE in all)) all[EMBEDDER_SERVICE] = new FakeEmbedder(); + const hooks = new Map unknown>>(); + /** Fire a hook as the kernel does: its handlers in registration order, each awaited. */ + const fire = async (name: string): Promise => { + for (const handler of hooks.get(name) ?? []) await handler(); + }; const ctx = { getService: (name: string) => { if (!(name in all) || all[name] === undefined) throw new Error(`no service ${name}`); return all[name]; }, + hook: (name: string, handler: () => unknown) => { + hooks.set(name, [...(hooks.get(name) ?? []), handler]); + }, logger: { info: (m: string) => logs.push(['info', m]), warn: (m: string) => logs.push(['warn', m]), @@ -46,7 +54,7 @@ function contextOf(services: Record = {}) { error: () => undefined, }, } as unknown as PluginContext; - return { ctx, adapters, logs }; + return { ctx, adapters, logs, fire }; } const dirs: string[] = []; @@ -242,38 +250,93 @@ describe('resolveSettingsStoreUrl', () => { }); }); -/** A settings service answering saved `knowledge` values, as `SettingsService.get` resolves them. */ +/** + * A settings service answering saved `knowledge` values as `SettingsService.get` + * resolves them — and, as the real one does, only once its data engine is + * bound: until `bound` is set a saved value reads as the manifest default. + */ function settingsOf(saved: Record, failure?: Error) { - return { + const settings = { + bound: false, + reads: 0, get: async (namespace: string, key: string) => { + settings.reads += 1; if (failure) throw failure; if (namespace !== 'knowledge') throw Object.assign(new Error('unknown'), { code: 'SETTINGS_UNKNOWN_NAMESPACE' }); - const value = saved[key]; + const value = settings.bound ? saved[key] : undefined; return value === undefined ? { value: undefined, source: 'default' } : { value, source: 'global' }; }, }; + return settings; +} + +/** + * A boot as the kernel runs one: init(), start(), then the settings service's + * own `kernel:ready` bind, then `kernel:bootstrapped`. + */ +async function boot( + plugin: { init(ctx: PluginContext): Promise; start(ctx: PluginContext): Promise }, + { ctx, fire }: { ctx: PluginContext; fire: (name: string) => Promise }, + settings?: { bound: boolean }, +): Promise { + await plugin.init(ctx); + await plugin.start(ctx); + if (settings) settings.bound = true; + await fire('kernel:bootstrapped'); } describe('KnowledgeTursoPlugin — the store URL from settings (urlFromSettings)', () => { it('opens the file a saved setting names inside the data directory', async () => { const root = tempDir(); const file = join(dataDirectoryOf(root), 'saved.db'); - const { ctx, adapters } = contextOf({ settings: settingsOf({ turso_url: `file:${file}` }) }); + const settings = settingsOf({ turso_url: `file:${file}` }); + const host = contextOf({ settings }); const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }); + await boot(plugin, host, settings); + expect(await host.adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: true }); + expect(existsSync(file)).toBe(true); + expect(existsSync(join(dataDirectoryOf(root), 'knowledge.db'))).toBe(false); + await plugin.destroy(); + }); + + it('reads the settings at kernel:bootstrapped, never in init() or start(): mounted from start(), open once the boot completes', async () => { + const root = tempDir(); + const file = join(dataDirectoryOf(root), 'saved.db'); + const settings = settingsOf({ turso_url: `file:${file}` }); + const { ctx, adapters, logs, fire } = contextOf({ settings }); + const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }); + await plugin.init(ctx); await plugin.start(ctx); + // The settings service has not bound its data engine yet: nothing is read, + // nothing is opened, and the adapter is mounted and says it is not ready. + expect(settings.reads).toBe(0); + expect(existsSync(dataDirectoryOf(root))).toBe(false); + const pending = adapters.get('turso')!; + expect(pending).toBeDefined(); + const err = await pending + .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).toEqual([]); + + settings.bound = true; + await fire('kernel:bootstrapped'); + expect(settings.reads).toBeGreaterThan(0); expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: true }); expect(existsSync(file)).toBe(true); expect(existsSync(join(dataDirectoryOf(root), 'knowledge.db'))).toBe(false); + expect(logs.filter(([level]) => level === 'warn')).toEqual([]); await plugin.destroy(); }); it('nothing saved, no knowledge namespace or no settings service: the default file', async () => { - for (const services of [{ settings: settingsOf({}) }, { settings: { get: async () => { throw Object.assign(new Error('x'), { code: 'SETTINGS_UNKNOWN_NAMESPACE' }); } } }, {}]) { + const unknown = { bound: false, get: async () => { throw Object.assign(new Error('x'), { code: 'SETTINGS_UNKNOWN_NAMESPACE' }); } }; + for (const settings of [settingsOf({}), unknown, undefined]) { const root = tempDir(); - const { ctx, adapters } = contextOf(services); + const host = contextOf(settings === undefined ? {} : { settings }); const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }); - await plugin.start(ctx); - expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: true }); + await boot(plugin, host, settings); + expect(await host.adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: true }); expect(existsSync(join(dataDirectoryOf(root), 'knowledge.db'))).toBe(true); await plugin.destroy(); } @@ -289,30 +352,32 @@ describe('KnowledgeTursoPlugin — the store URL from settings (urlFromSettings) [`file:${join(dataDirectoryOf(root), 'k.db')}${String.fromCharCode(0)}x`, 'NUL byte'], [`file:${join(tempDir(), 'k.db')}`, 'outside the data directory'], ] as const) { - const { ctx, adapters, logs } = contextOf({ settings: settingsOf({ turso_url: url }) }); - await new Fresh({ projectRoot: root, env: {}, urlFromSettings: true }).start(ctx); - expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); - expect(logs.some(([level, m]) => level === 'warn' && m.includes(reason))).toBe(true); + const settings = settingsOf({ turso_url: url }); + const host = contextOf({ settings }); + await boot(new Fresh({ projectRoot: root, env: {}, urlFromSettings: true }), host, settings); + expect(await host.adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); + expect(host.logs.some(([level, m]) => level === 'warn' && m.includes(reason))).toBe(true); } expect(createClient).not.toHaveBeenCalled(); }); it('a settings read that fails opens nothing: the store says why', async () => { const root = tempDir(); - const { ctx, adapters, logs } = contextOf({ settings: settingsOf({}, new Error('database is locked')) }); - await new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }).start(ctx); - expect(await adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); - expect(logs.some(([level, m]) => level === 'warn' && m.includes('database is locked'))).toBe(true); + const settings = settingsOf({}, new Error('database is locked')); + const host = contextOf({ settings }); + await boot(new KnowledgeTursoPlugin({ projectRoot: root, env: {}, urlFromSettings: true }), host, settings); + expect(await host.adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); + expect(host.logs.some(([level, m]) => level === 'warn' && m.includes('database is locked'))).toBe(true); expect(existsSync(join(dataDirectoryOf(root), 'knowledge.db'))).toBe(false); }); it('the plugin option `url` wins, and without urlFromSettings the settings are not read', async () => { const root = tempDir(); const read = vi.fn(async () => ({ value: `file:${join(dataDirectoryOf(root), 'saved.db')}`, source: 'global' })); - const { ctx, adapters } = contextOf({ settings: { get: read } }); - await new KnowledgeTursoPlugin({ url: ':memory:', env: {}, urlFromSettings: true, projectRoot: root }).start(ctx); - await new KnowledgeTursoPlugin({ projectRoot: root, env: {} }).start(ctx); + const host = contextOf({ settings: { get: read } }); + await boot(new KnowledgeTursoPlugin({ url: ':memory:', env: {}, urlFromSettings: true, projectRoot: root }), host); + await boot(new KnowledgeTursoPlugin({ projectRoot: root, env: {} }), host); expect(read).not.toHaveBeenCalled(); - expect(adapters.get('turso')).toBeDefined(); + expect(host.adapters.get('turso')).toBeDefined(); }); }); diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index 744610b6011..5448b7aee80 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -59,8 +59,9 @@ export interface KnowledgeTursoPluginOptions { * Read the store's URL and auth token from the `knowledge` settings * (`turso_url`, `turso_auth_token`) when neither `url` nor `client` is * given. A URL read from there is held to the data directory - * ({@link resolveSettingsStoreUrl}). The runtime's `knowledge` capability - * mount sets it. @default false + * ({@link resolveSettingsStoreUrl}). They are read when the boot completes + * (`kernel:bootstrapped`), and the store opens then. The runtime's + * `knowledge` capability mount sets it. @default false */ urlFromSettings?: boolean; /** The project directory the default file and the data directory are under. @default process.cwd() */ @@ -257,6 +258,14 @@ export function resolveSettingsStoreUrl( return target.url === undefined ? { reason: target.reason.replace('its `url` option', from) } : { url: target.url, from }; } +/** + * What a store whose URL is the operator's setting says between its start() + * and `kernel:bootstrapped`, when it opens: every call answers + * `SERVICE_UNAVAILABLE` with this. + */ +const SETTINGS_NOT_READ_YET = + 'Its URL is read from the knowledge settings (`turso_url`) once the boot has completed; until then it opens no database.'; + /** A settings service as this plugin reads it: one key's resolved value and the layer it came from. */ interface StoreSettingsReader { get(namespace: string, key: string): Promise<{ value?: unknown; source?: string } | undefined>; @@ -310,6 +319,11 @@ async function readStoreSettings( * `KnowledgeTursoPlugin` — registers a {@link TursoKnowledgeAdapter} with the * host's `IKnowledgeService` during `start()`. * + * Under `urlFromSettings` the adapter registered in `start()` has no database + * yet: the saved `knowledge.turso_url` is read, and the database opened, at + * `kernel:bootstrapped`, the first moment the settings service answers a + * saved value. Until then its calls answer `SERVICE_UNAVAILABLE`. + * * 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 @@ -323,16 +337,13 @@ export class KnowledgeTursoPlugin implements Plugin { version = '0.1.0'; type = 'standard' as const; /** - * Order-if-present (ADR-0116): start() registers with the knowledge service - * and, under `urlFromSettings`, reads the `knowledge` settings, which the - * settings service answers from the data engine. Literal ids: the boot-order - * gates read this array statically. + * Order-if-present (ADR-0116): start() registers with the knowledge service. + * No edge to the settings service: under `urlFromSettings` the settings are + * read at `kernel:bootstrapped`, and no ordering moves a read in start() + * past the settings service's bind (see init()). A literal id: the + * boot-order gates read this array statically. */ - optionalDependencies = [ - 'com.objectstack.service.knowledge', - 'com.objectstack.service.settings', - 'com.objectstack.engine.objectql', - ]; + optionalDependencies = ['com.objectstack.service.knowledge']; private readonly opts: KnowledgeTursoPluginOptions; private owned?: Client; @@ -341,49 +352,100 @@ export class KnowledgeTursoPlugin implements Plugin { this.opts = opts; } - async init(_ctx: PluginContext): Promise { - // No-op: registration happens in start() once IKnowledgeService is up. + async init(ctx: PluginContext): Promise { + // The adapter registers in start(), once IKnowledgeService is up. A store + // whose URL is the operator's setting opens later still: the settings + // service answers a saved value only once its data engine is bound, in its + // own `kernel:ready` hook, so a read in init() or start() sees the default + // while a saved row sits unread (`pnpm check:settings-bind-window`). The + // hook is registered here, in init(), so it runs ahead of every + // `kernel:bootstrapped` handler a plugin registers in its start(): the + // knowledge service's own (its embedder, its reading of unmounted + // adapters, a first build) then find the store open. + if (!this.opensFromSettings()) return; + ctx.hook('kernel:bootstrapped', async () => { + await this.openFromSettings(ctx); + }); } async start(ctx: PluginContext): Promise { - let svc: IKnowledgeService | undefined; - try { - svc = ctx.getService(KNOWLEDGE_SERVICE); - } catch { + const svc = this.knowledgeService(ctx); + if (!svc) { ctx.logger.warn?.('KnowledgeTursoPlugin: IKnowledgeService not registered — install KnowledgeServicePlugin first.'); return; } + if (this.opts.client) { + await this.register(ctx, svc, { client: this.opts.client, requestTimeoutMs: this.opts.requestTimeoutMs }); + return; + } + if (this.opensFromSettings()) { + // Mounted from here on, so a source naming it is never read as naming an + // unmounted adapter; it has no database until the boot completes. + svc.registerAdapter(this.opts.id ?? 'turso', this.adapterOver(ctx, { unavailable: SETTINGS_NOT_READ_YET })); + return; + } + await this.open(ctx, svc, resolveStoreUrl(this.opts), this.opts.authToken); + } - let client: Client | undefined = this.opts.client; - let unavailable: string | undefined; - let requestTimeoutMs = this.opts.requestTimeoutMs; - if (!client) { - let target: ReturnType = { reason: '' }; - let authToken = this.opts.authToken; - const given = this.opts.url?.trim(); - if (this.opts.urlFromSettings && (given === undefined || given === '')) { - const saved = await readStoreSettings(ctx); - if ('reason' in saved) { - target = { reason: saved.reason }; - } else if (saved.url !== undefined) { - target = resolveSettingsStoreUrl(saved.url, this.opts); - authToken = saved.authToken; - } else { - target = resolveStoreUrl(this.opts); - } - } else { - 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, authToken }); - if ('client' in opened) client = this.owned = opened.client; - else unavailable = opened.reason; - } + /** The store's URL is the operator's setting: `urlFromSettings`, and neither `client` nor `url` given. */ + private opensFromSettings(): boolean { + const given = this.opts.url?.trim(); + return this.opts.urlFromSettings === true && !this.opts.client && (given === undefined || given === ''); + } + + private knowledgeService(ctx: PluginContext): IKnowledgeService | undefined { + try { + return ctx.getService(KNOWLEDGE_SERVICE) ?? undefined; + } catch { + return undefined; } + } + /** + * At `kernel:bootstrapped`: read the saved `knowledge.turso_url` and + * `turso_auth_token`, open that database (or the default file when nothing + * is saved) and register the adapter over the one start() registered. + */ + private async openFromSettings(ctx: PluginContext): Promise { + const svc = this.knowledgeService(ctx); + if (!svc) return; // start() said so + const saved = await readStoreSettings(ctx); + if ('reason' in saved) { + await this.open(ctx, svc, { reason: saved.reason }, undefined); + } else if (saved.url !== undefined) { + await this.open(ctx, svc, resolveSettingsStoreUrl(saved.url, this.opts), saved.authToken); + } else { + await this.open(ctx, svc, resolveStoreUrl(this.opts), this.opts.authToken); + } + } + + /** Open the database `target` names and register the adapter on it, or one that says why there is none. */ + private async open( + ctx: PluginContext, + svc: IKnowledgeService, + target: ReturnType, + authToken: string | undefined, + ): Promise { + if (target.url === undefined) { + await this.register(ctx, svc, { unavailable: target.reason }); + return; + } + const opened = await openClient(target.url, { ...this.opts, authToken }); + if ('client' in opened) { + this.owned = opened.client; + await this.register(ctx, svc, { + client: opened.client, + requestTimeoutMs: requestBoundFor(target.url, this.opts.requestTimeoutMs), + }); + } else { + await this.register(ctx, svc, { unavailable: opened.reason }); + } + } + + private adapterOver( + ctx: PluginContext, + store: { client?: Client; unavailable?: string; requestTimeoutMs?: number }, + ): TursoKnowledgeAdapter { // 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 => { @@ -394,14 +456,22 @@ export class KnowledgeTursoPlugin implements Plugin { return undefined; } }; - - const adapter = new TursoKnowledgeAdapter({ + return new TursoKnowledgeAdapter({ id: this.opts.id, - ...(client ? { client } : { unavailable }), + ...(store.client ? { client: store.client } : { unavailable: store.unavailable }), embedder, queryPrefix: this.opts.queryPrefix, - ...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }), + ...(store.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: store.requestTimeoutMs }), }); + } + + /** Register the adapter over `store` and say whether it is ready. */ + private async register( + ctx: PluginContext, + svc: IKnowledgeService, + store: { client?: Client; unavailable?: string; requestTimeoutMs?: number }, + ): Promise { + const adapter = this.adapterOver(ctx, store); svc.registerAdapter(adapter.id, adapter); const health = await adapter.healthCheck(); diff --git a/packages/spec/scripts/lib/platform-catalog.ts b/packages/spec/scripts/lib/platform-catalog.ts index da26ed8db18..f6cb7b3793a 100644 --- a/packages/spec/scripts/lib/platform-catalog.ts +++ b/packages/spec/scripts/lib/platform-catalog.ts @@ -192,7 +192,7 @@ export const CAPABILITY_ROWS: Readonly> = Object.freeze({ settings: 'the settings store', webhooks: 'outbound webhooks', 'record-context': 'get_record_context over MCP', - knowledge: 'knowledge search: the service and one vector store', + knowledge: 'knowledge search and its vector store', 'hierarchy-security': 'hierarchy-relative permission scopes', 'ai-seat': 'the AI-seat tier', governance: 'the governance tier', From cdb4a53ab267458b7640c65b677293cee78be0ea Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:32:46 +0000 Subject: [PATCH 4/8] wip(knowledge): the knowledge enumeration rows, both ceilings by the measured delta, the serve-only step entry Claude-Session: https://claude.ai/code/session_01Utp6CYE8s5v1UX96GEfkcR Co-authored-by: Claude --- .changeset/37102-knowledge-capability-token.md | 2 +- .../cli/src/utils/boot-preparation-parity.test.ts | 6 ++++++ packages/spec/scripts/platform-catalog.test.ts | 5 ++++- scripts/check-skills-token-ratchet.mjs | 12 +++++++++++- skills/objectstack-platform/SKILL.md | 2 +- 5 files changed, 23 insertions(+), 4 deletions(-) diff --git a/.changeset/37102-knowledge-capability-token.md b/.changeset/37102-knowledge-capability-token.md index 3c368e0af95..adbdb2faa2d 100644 --- a/.changeset/37102-knowledge-capability-token.md +++ b/.changeset/37102-knowledge-capability-token.md @@ -21,5 +21,5 @@ ADR-0161, #37102. - 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). - `os serve` now warns when a capability's extra plugin cannot be imported or constructed, instead of skipping it silently. - **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. -- **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`. A saved `file:` URL must resolve, after symlinks, inside the project's `.objectstack/data/` directory; a URL that leaves it, names the platform database, or carries a NUL byte or another control character is refused before the libSQL client sees it (a NUL byte in a file URL kills the process inside the native client). New exports: `resolveSettingsStoreUrl`, `dataDirectoryOf`. `resolveStoreUrl` refuses control characters too. +- **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 the project's `.objectstack/data/` directory; a URL that leaves it, names the platform database, or carries a NUL byte or another control character is refused before the libSQL client sees it (a NUL byte in a file URL kills the process inside the native client). New exports: `resolveSettingsStoreUrl`, `dataDirectoryOf`. `resolveStoreUrl` refuses control characters too. - The `turso_url` setting's example path now reads `file:./.objectstack/data/knowledge.db` in every locale. diff --git a/packages/cli/src/utils/boot-preparation-parity.test.ts b/packages/cli/src/utils/boot-preparation-parity.test.ts index 2d4cb5145c6..a97dfaa21d8 100644 --- a/packages/cli/src/utils/boot-preparation-parity.test.ts +++ b/packages/cli/src/utils/boot-preparation-parity.test.ts @@ -178,6 +178,12 @@ const SERVE_ONLY: Record = { + 'the storage root; [#22301], shared with @objectstack/verify\'s bootStack): the declaration boot constructs ' + 'each provider for its declarations only, with a measured posture per token ' + '(DECLARATION_PROVIDER_POSTURES), and runs no start() that would read a configuration', + resolveCapabilityExtras: + 'which further providers serve mounts after a token\'s main one, and what each is built with — a row\'s ' + + 'extras, and for knowledge the one vector store the platform database chooses (shared with ' + + '@objectstack/verify\'s bootStack): the declaration boot reads a row\'s extras itself (composeServedPlatform) ' + + 'and composes no knowledge store, whose init() declares nothing — its tables are its own, in a libSQL file ' + + 'or a PostgreSQL schema of its own, made in the start() this boot does not run', findSqlDriverForKernel: 'the artifact boot migration gate, a kernel:ready hook over a booted kernel — a serving-boot policy that ' + 'runs after preparation, not a step that shapes what is prepared', diff --git a/packages/spec/scripts/platform-catalog.test.ts b/packages/spec/scripts/platform-catalog.test.ts index f2e33757114..3d845e8b208 100644 --- a/packages/spec/scripts/platform-catalog.test.ts +++ b/packages/spec/scripts/platform-catalog.test.ts @@ -191,7 +191,10 @@ describe('pricing — the hand-written text is ratcheted, shrink-only', () => { // and by no more, nothing else cut, under the standing enumeration-row case of the skills // ratchet — ruling A on #32584, record 6819475461, made standing by #32673 letter A, // record 6840575378) - const HAND_WRITTEN_CEILING_TOKENS = 1726; + // 6939 bytes -> ceil(6939 / 4) = 1735 (the PR that adds the `knowledge` token: its one + // CAPABILITY_ROWS line, 37 bytes, at zero headroom; raised by that row's measured delta + // and by no more, nothing else cut, under the same standing enumeration-row case) + const HAND_WRITTEN_CEILING_TOKENS = 1735; it('measures every hand-written string the page carries and nothing derived', () => { const page = renderPlatformCatalog(); diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 58e34b3d88c..d373b57b085 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -870,7 +870,17 @@ export const CEILINGS = new Map([ // are absorbed and the ceiling moves 6148 -> 6149 (+1). Pinned AT the // measurement. // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 20) / 4) == ceil(24594 / 4) - ['skills/objectstack-platform/SKILL.md', 6149], + // 6149 -> 6152 (card #37102): the enumeration row for the new `knowledge` + // capability token, in the same cell of the same `requires:` table and under + // the same standing enumeration-row case (ruling A on #32584, record + // 6819475461; #32673 letter A, record 6840575378). Raised by the row's own + // measured delta and by no more; nothing else in the file is cut and nothing + // rides along. Arithmetic in priced bytes (stamp line excluded): on the base + // the text was 24593 bytes (6149 tokens, headroom 0); the row adds 12 bytes, + // so the LANDED priced text is 24605 bytes -> 6152 tokens (+3). Pinned AT the + // measurement. + // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 20) / 4) == ceil(24605 / 4) + ['skills/objectstack-platform/SKILL.md', 6152], // `skills/objectstack-pm-dispatch/SKILL.md` (9708) and its // `rules/dev-template.md` (1838) left this table on 2026-09-10 with the files: // the maintainer deleted the published PM skill whole (verbatim: diff --git a/skills/objectstack-platform/SKILL.md b/skills/objectstack-platform/SKILL.md index e2c0cc2be43..4d9ced5838a 100644 --- a/skills/objectstack-platform/SKILL.md +++ b/skills/objectstack-platform/SKILL.md @@ -301,7 +301,7 @@ token through the `CAPABILITY_PROVIDERS` registry in | Token | Provider package | |:--|:--| | `automation` | `@objectstack/service-automation` — flows, and any declarative `connectors:` entry | -| `analytics`° `cache`° `storage`° `queue`° `job`° `messaging`° `realtime` `settings`° `sms`° `push` `record-context` | `@objectstack/service-` + the token ([the `push` block](./references/operations.md#mobile-push)) | +| `analytics`° `cache`° `storage`° `queue`° `job`° `messaging`° `realtime` `settings`° `sms`° `push` `record-context` `knowledge` | `@objectstack/service-` + the token ([the `push` block](./references/operations.md#mobile-push)) | | `mailbox` | `@objectstack/service-mailbox` — inbound mail | | `marketplace` `package-registry`° | `@objectstack/service-package` | | `audit` `email`° `sharing`° `approvals` `webhooks` | `@objectstack/plugin-` + the token | From 7389e7c975525fb5307061008c3e3282deb324d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:38:22 +0000 Subject: [PATCH 5/8] wip(skills): regenerate the platform catalog row Claude-Session: https://claude.ai/code/session_01Utp6CYE8s5v1UX96GEfkcR Co-authored-by: Claude --- skills/objectstack-project/references/platform-catalog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/objectstack-project/references/platform-catalog.md b/skills/objectstack-project/references/platform-catalog.md index b5100865787..541919ad7a0 100644 --- a/skills/objectstack-project/references/platform-catalog.md +++ b/skills/objectstack-project/references/platform-catalog.md @@ -134,7 +134,7 @@ whether or not the stack lists it. Declare what the app uses | `settings` | the settings store | open | every boot | | `webhooks` | outbound webhooks | open | on `requires` | | `record-context` | get_record_context over MCP | open | on `requires` | -| `knowledge` | knowledge search: the service and one vector store | open | on `requires` | +| `knowledge` | knowledge search and its vector store | open | on `requires` | | `hierarchy-security` | hierarchy-relative permission scopes | enterprise | on `requires` | | `ai-seat` | the AI-seat tier | cloud | on `requires` | | `governance` | the governance tier | cloud | on `requires` | From 63eba5b52bec9d7e31f72aa4efcda4fffd36bbc0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:36:19 +0000 Subject: [PATCH 6/8] test(cli): the parity pin pays its step modules' dynamic imports at collection Claude-Session: https://claude.ai/code/session_01Utp6CYE8s5v1UX96GEfkcR Co-authored-by: Claude --- packages/cli/src/utils/boot-preparation-parity.test.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/cli/src/utils/boot-preparation-parity.test.ts b/packages/cli/src/utils/boot-preparation-parity.test.ts index a97dfaa21d8..dd7cb63c97f 100644 --- a/packages/cli/src/utils/boot-preparation-parity.test.ts +++ b/packages/cli/src/utils/boot-preparation-parity.test.ts @@ -78,6 +78,15 @@ import { } from './stack-collections.js'; import { provisionTelemetryDatasource, standaloneTelemetryPrimary } from './telemetry-datasource.js'; +// Paid at collection, not inside a clocked case: what the step modules imported +// above reach through dynamic `import()`s (`check:test-source-alias`). +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; +import '@objectstack/driver-sql'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; + /** …/packages/cli/src/utils */ const HERE = dirname(fileURLToPath(import.meta.url)); /** …/packages/cli/src — this package's own source tree. */ From 215cebf6658e373b81c1aaebaace6b3e9424dd01 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:44:00 +0000 Subject: [PATCH 7/8] fix(knowledge): an encoded control character in the store URL is refused; the store follows OS_HOME; the libSQL store is an optional dependency Rework after the contract review of abf337bd0 (record 7187791236). - M1: resolveStoreUrl and resolveSettingsStoreUrl refuse a control character behind a percent escape too. libSQL decodes the path it opens, so a saved file:.../k%00.db reached the native client as a NUL byte and ended the process at every boot. - S2: one real-kernel case for the file-database arm: the store opens the file the operator saved and a record write is found by search. - S3: @objectstack/knowledge-turso is an optional dependency of the CLI and of @objectstack/verify. The store's row and extra carry optional: true; verify warns and goes on where it cannot be imported, as serve does. - S4: the store's data directory follows OS_HOME (os start --home), the directory the default platform database is kept in. New option stateDir. - Docs: where the file is, more than one replica, an install without the libSQL client. Claude-Session: https://claude.ai/code/session_01Utp6CYE8s5v1UX96GEfkcR Co-authored-by: Claude --- .../37102-knowledge-capability-token.md | 7 +- content/docs/ai/knowledge-rag.mdx | 7 +- packages/cli/package.json | 2 +- .../core/src/capability-composition.test.ts | 18 ++- packages/core/src/capability-composition.ts | 28 +++-- packages/core/src/capability-providers.ts | 11 ++ .../src/__tests__/plugin.test.ts | 46 ++++++- .../plugins/knowledge-turso/src/plugin.ts | 79 +++++++++--- packages/verify/package.json | 4 +- .../src/harness.required-providers.test.ts | 114 +++++++++++++++++- packages/verify/src/required-providers.ts | 19 ++- pnpm-lock.yaml | 13 +- 12 files changed, 299 insertions(+), 49 deletions(-) diff --git a/.changeset/37102-knowledge-capability-token.md b/.changeset/37102-knowledge-capability-token.md index adbdb2faa2d..07460ec5a05 100644 --- a/.changeset/37102-knowledge-capability-token.md +++ b/.changeset/37102-knowledge-capability-token.md @@ -16,10 +16,11 @@ Skills-docs: follow-up #37310 ADR-0161, #37102. -- **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, `.objectstack/data/knowledge.db` by default. An in-memory database gets an in-memory turso store. The in-memory adapter (`knowledge-memory`) is never mounted by the token. -- No token: no knowledge service and no knowledge settings page, as before. A host that mounts `KnowledgeServicePlugin` (or a store) itself keeps its own: the token adds only what is not already mounted. +- **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 `/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. +- 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. - 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). - `os serve` now warns when a capability's extra plugin cannot be imported or constructed, instead of skipping it silently. - **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. -- **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 the project's `.objectstack/data/` directory; a URL that leaves it, names the platform database, or carries a NUL byte or another control character is refused before the libSQL client sees it (a NUL byte in a file URL kills the process inside the native client). New exports: `resolveSettingsStoreUrl`, `dataDirectoryOf`. `resolveStoreUrl` refuses control characters too. +- **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. +- **`@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`. - The `turso_url` setting's example path now reads `file:./.objectstack/data/knowledge.db` in every locale. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 18ae74cb76d..66546ee7757 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -28,12 +28,15 @@ Which store is mounted depends on the platform database: | Platform database | Store | Adapter id | Where the vectors live | |:--|:--|:--|:--| | PostgreSQL | `@objectstack/knowledge-pgvector` | `pgvector` | the platform database, schema `os_knowledge` ([below](#self-hosted-vector-store-postgresql--pgvector)) | -| anything else (SQLite under `os dev`, libSQL, MySQL, MongoDB) | `@objectstack/knowledge-turso` | `turso` | `.objectstack/data/knowledge.db`, beside the dev database and never its file ([below](#local-vector-store-a-libsql-file)) | +| 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 `/data/` when `OS_HOME` is set ([below](#local-vector-store-a-libsql-file)) | - **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'`). - **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`. - **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)). -- **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 the project's `.objectstack/data/` directory, and a URL carrying a NUL byte is refused; either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on. +- **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; either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on. +- **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. +- **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. +- **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`. - **Without the token** nothing is mounted: no knowledge service, no store and no Knowledge settings page. `knowledge-memory` is never mounted for you. - **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. diff --git a/packages/cli/package.json b/packages/cli/package.json index 581122c39ce..0de11dde873 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -123,7 +123,6 @@ "@objectstack/driver-sqlite-wasm": "workspace:*", "@objectstack/formula": "workspace:*", "@objectstack/knowledge-pgvector": "workspace:*", - "@objectstack/knowledge-turso": "workspace:*", "@objectstack/lint": "workspace:*", "@objectstack/mcp": "workspace:*", "@objectstack/metadata": "workspace:*", @@ -187,6 +186,7 @@ } }, "optionalDependencies": { + "@objectstack/knowledge-turso": "workspace:*", "better-sqlite3": "^13.0.3" }, "devDependencies": { diff --git a/packages/core/src/capability-composition.test.ts b/packages/core/src/capability-composition.test.ts index 03be709a467..ca55146b91a 100644 --- a/packages/core/src/capability-composition.test.ts +++ b/packages/core/src/capability-composition.test.ts @@ -246,13 +246,29 @@ describe('resolveKnowledgeStore — which store the knowledge token mounts', () { driver: 'mysql', url: 'mysql://db/app' }, { driver: 'mongodb', url: 'mongodb://db/app' }, ]) { - expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database })).toEqual({ + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: {}, database })).toEqual({ store: KNOWLEDGE_STORE_PROVIDERS.turso, argument: { projectRoot: root, urlFromSettings: true }, }); } }); + it('OS_HOME moves the store with the platform database: the store is handed the state directory', () => { + // `os start --home` sets OS_HOME; the default database is `/data/objectstack.db`. + const database = { driver: 'sqlite', url: 'file:/var/lib/os/data/objectstack.db' }; + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_HOME: ' /var/lib/os ' }, database })).toEqual({ + store: KNOWLEDGE_STORE_PROVIDERS.turso, + argument: { projectRoot: root, stateDir: '/var/lib/os', urlFromSettings: true }, + }); + // Unset or empty: the app's own `.objectstack/`, as before. + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_HOME: ' ' }, database }).argument).toEqual({ + projectRoot: root, + urlFromSettings: true, + }); + // The other two arms take no directory. + expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_HOME: '/h' }, database: { url: ':memory:' } }).argument).toEqual({ url: ':memory:' }); + }); + it('an in-memory platform database: an in-memory store', () => { for (const database of [{ driver: 'sqlite-wasm', url: ':memory:' }, { driver: 'memory' }]) { expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database })).toEqual({ diff --git a/packages/core/src/capability-composition.ts b/packages/core/src/capability-composition.ts index cafb9b5669c..9ab2d2eb723 100644 --- a/packages/core/src/capability-composition.ts +++ b/packages/core/src/capability-composition.ts @@ -265,6 +265,12 @@ export interface CapabilityExtra { readonly identities: CapabilityIdentities; /** Construct the provider with this, or with no argument when `undefined`. */ readonly argument?: unknown; + /** + * The package is an optional dependency of the boots that mount it: one + * that cannot import it warns and goes on without it, on `os serve` and on + * the verification handle alike. + */ + readonly optional?: boolean; } /** @@ -282,7 +288,9 @@ export interface CapabilityExtra { export function resolveCapabilityExtras(token: string, input: CapabilityArgumentInput): CapabilityExtra[] { if (token === 'knowledge') { const { store, argument } = resolveKnowledgeStore(input); - return [{ pkg: store.pkg, export: store.export, identities: store.identities, argument }]; + return [ + { pkg: store.pkg, export: store.export, identities: store.identities, argument, ...(store.optional ? { optional: true } : {}) }, + ]; } return (CAPABILITY_PROVIDERS[token]?.extras ?? []).map((extra) => ({ ...extra })); } @@ -301,12 +309,15 @@ const POSTGRES_URL = /^postgres(ql)?:\/\//i; * (`@objectstack/knowledge-pgvector`), handed that URL, so the store's * tables live in the platform's own database, in a schema of their own; * - any other database ⇒ `turso` (`@objectstack/knowledge-turso`), a libSQL - * file of its own: `knowledge.db` under the app's `.objectstack/data/`, - * beside the dev database and never its file. The operator can name - * another store in the `knowledge.turso_url` setting, which the store holds - * to that data directory and refuses when it carries a NUL byte, before it - * reaches the libSQL client. An in-memory platform database (`:memory:`, - * or the `memory` driver) gets an in-memory store (`:memory:`). + * file of its own: `knowledge.db` in the directory the boot keeps the + * default platform database in, and never that database's file — + * `/data/` when `OS_HOME` is set (`os start --home` sets it), + * else the app's `.objectstack/data/`. A database named by URL does not + * move it. The operator can name another store in the `knowledge.turso_url` + * setting, which the store holds to that data directory and refuses when + * it carries a NUL byte, written out or percent-encoded, before it reaches + * the libSQL client. An in-memory platform database (`:memory:`, or the + * `memory` driver) gets an in-memory store (`:memory:`). * * The database is the one the boot resolved ({@link CapabilityArgumentInput.database}); * a boot that resolved none (a host whose own plugin provides the driver) @@ -334,9 +345,10 @@ export function resolveKnowledgeStore(input: CapabilityArgumentInput): { if (url === ':memory:' || input.database?.driver === 'memory') { return { store: KNOWLEDGE_STORE_PROVIDERS.turso, argument: { url: ':memory:' } }; } + const home = env.OS_HOME?.trim(); return { store: KNOWLEDGE_STORE_PROVIDERS.turso, - argument: { projectRoot: input.packageRoot, urlFromSettings: true }, + argument: { projectRoot: input.packageRoot, ...(home ? { stateDir: home } : {}), urlFromSettings: true }, }; } diff --git a/packages/core/src/capability-providers.ts b/packages/core/src/capability-providers.ts index c41f91a6898..ff4f6a7d927 100644 --- a/packages/core/src/capability-providers.ts +++ b/packages/core/src/capability-providers.ts @@ -265,6 +265,13 @@ export type KnowledgeStoreSpec = { identities: CapabilityIdentities; /** The adapter id the store registers: the value a `KnowledgeSource.adapter` names. */ adapterId: string; + /** + * The package is an optional dependency of the CLI and of the verification + * handle, so an install may not have it: a boot that cannot import it says + * so once and goes on with the service alone, and a source naming the store + * answers `SERVICE_UNAVAILABLE`. + */ + optional?: boolean; }; /** @@ -293,6 +300,10 @@ export const KNOWLEDGE_STORE_PROVIDERS: Readonly { expect(defaultStoreUrl('/srv/app')).toBe('file:/srv/app/.objectstack/data/knowledge.db'); }); + it('a state directory (OS_HOME, os start --home) moves the data directory with the platform database', () => { + expect(dataDirectoryOf('/srv/app', '/var/lib/os')).toBe('/var/lib/os/data'); + expect(dataDirectoryOf('/srv/app', '~/os-home')).toBe(join(homedir(), 'os-home', 'data')); + expect(dataDirectoryOf('/srv/app', ' ')).toBe('/srv/app/.objectstack/data'); + expect(resolveStoreUrl({ projectRoot: '/srv/app', stateDir: '/var/lib/os', env: {} })).toEqual({ + url: 'file:/var/lib/os/data/knowledge.db', + from: 'the default location', + }); + // A settings URL is held to that directory, and the app's own is outside it. + const home = tempDir(); + const app = tempDir(); + expect(resolveSettingsStoreUrl(`file:${join(home, 'data', 'saved.db')}`, { projectRoot: app, stateDir: home, env: {} })).toMatchObject({ + url: `file:${join(home, 'data', 'saved.db')}`, + }); + expect( + resolveSettingsStoreUrl(`file:${join(dataDirectoryOf(app), 'saved.db')}`, { projectRoot: app, stateDir: home, env: {} }), + ).toMatchObject({ reason: expect.stringContaining('outside the data directory') }); + }); + 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") }); @@ -210,6 +229,29 @@ describe('resolveSettingsStoreUrl', () => { } }); + it('refuses a percent-encoded control character too: libSQL decodes the path it opens', () => { + const root = tempDir(); + const data = dataDirectoryOf(root); + for (const url of [ + `file:${data}/k%00.db`, + `file:${data}/k%0a.db`, + `file:${data}/k%0A.db`, + `file:${data}/k.db%7f`, + `file://${data}/k%00.db`, + 'libsql://db.turso.io/%00', + ]) { + expect(resolveSettingsStoreUrl(url, { projectRoot: root, env: {} })).toMatchObject({ + reason: expect.stringContaining('percent-encoded'), + }); + expect(resolveStoreUrl({ url, projectRoot: root, env: {} })).toMatchObject({ reason: expect.stringContaining('percent-encoded') }); + } + // The control: an escape that decodes to an ordinary character names a file, and one + // encoded twice is the text `%00`, which libSQL decodes once and opens as a name. + for (const name of ['k%20v.db', 'k%2500.db']) { + expect(resolveSettingsStoreUrl(`file:${data}/${name}`, { projectRoot: root, env: {} })).toMatchObject({ url: `file:${data}/${name}` }); + } + }); + it('takes a file inside the data directory, and :memory: or a remote URL as they are', () => { const root = tempDir(); const file = join(dataDirectoryOf(root), 'search', 'k.db'); @@ -350,6 +392,8 @@ describe('KnowledgeTursoPlugin — the store URL from settings (urlFromSettings) const root = tempDir(); for (const [url, reason] of [ [`file:${join(dataDirectoryOf(root), 'k.db')}${String.fromCharCode(0)}x`, 'NUL byte'], + [`file:${join(dataDirectoryOf(root), 'k%00.db')}`, 'percent-encoded'], + [`file:${join(dataDirectoryOf(root), 'k%0a.db')}`, 'percent-encoded'], [`file:${join(tempDir(), 'k.db')}`, 'outside the data directory'], ] as const) { const settings = settingsOf({ turso_url: url }); diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index 5448b7aee80..6cf741e0c7a 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -1,6 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { mkdirSync, realpathSync } from 'node:fs'; +import { homedir } from 'node:os'; import { basename, dirname, isAbsolute, relative as relativePath, resolve as resolvePath } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { Client } from '@libsql/client'; @@ -66,18 +67,35 @@ export interface KnowledgeTursoPluginOptions { urlFromSettings?: boolean; /** The project directory the default file and the data directory are under. @default process.cwd() */ projectRoot?: string; + /** + * The platform's state directory (`OS_HOME`, `os start --home`), where the + * boot keeps the platform database: the data directory is then + * `/data`, so the store's file moves with the database's. A leading + * `~` is the user's home. The runtime's `knowledge` capability mount passes + * `OS_HOME`. @default `/.objectstack` + */ + stateDir?: 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 store's default URL: `file:` + `knowledge.db` in the data directory ({@link dataDirectoryOf}). */ +export function defaultStoreUrl(projectRoot: string = process.cwd(), stateDir?: string): string { + return `file:${resolvePath(dataDirectoryOf(projectRoot, stateDir), DEFAULT_KNOWLEDGE_FILE)}`; } -/** The project's data directory: `/.objectstack/data`, where the default file is. */ -export function dataDirectoryOf(projectRoot: string = process.cwd()): string { - return resolvePath(projectRoot, '.objectstack', 'data'); +/** + * The data directory, where the default file is and where a settings URL must + * stay: `/data` when a state directory is given (the order the boot + * resolves the platform database's own directory in: `--home`, `OS_HOME`, then + * the project), else `/.objectstack/data`. + */ +export function dataDirectoryOf(projectRoot: string = process.cwd(), stateDir?: string): string { + const state = stateDir?.trim(); + if (state === undefined || state === '') return resolvePath(projectRoot, '.objectstack', 'data'); + return state.startsWith('~') + ? resolvePath(homedir(), state.slice(1).replace(/^[/\\]/, ''), 'data') + : resolvePath(state, 'data'); } /** @@ -88,6 +106,21 @@ export function dataDirectoryOf(projectRoot: string = process.cwd()): string { */ const CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/; +/** One percent escape (`%00`, `%0a`), read byte by byte: a malformed one is left as written. */ +const PERCENT_ESCAPE = /%([0-9a-f]{2})/gi; + +/** + * Whether `url` carries a control character, as written or behind a percent + * escape. libSQL percent-decodes the path it opens, so `k%00.db` reaches its + * native library as the NUL byte itself, and ends the process the same way. + */ +function carriesControlCharacter(url: string): boolean { + return ( + CONTROL_CHARACTER.test(url) || + CONTROL_CHARACTER.test(url.replace(PERCENT_ESCAPE, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)))) + ); +} + /** The bound on one request to a remote database (`requestTimeoutMs`). */ export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; @@ -149,13 +182,17 @@ function platformFileOf(url: string): string | undefined { /** The libSQL URL the store opens, and where it was read from — or why there is none. */ export function resolveStoreUrl( - opts: Pick, + 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 url = given === undefined || given === '' ? defaultStoreUrl(opts.projectRoot, opts.stateDir) : given; const from = given === undefined || given === '' ? 'the default location' : 'the plugin option `url`'; - if (CONTROL_CHARACTER.test(url)) { - return { reason: 'its `url` option carries a NUL byte or another control character, which names no file or database.' }; + if (carriesControlCharacter(url)) { + return { + reason: + 'its `url` option carries a NUL byte or another control character, written out or percent-encoded, ' + + 'which names no file or database.', + }; } if (!/^(file:|libsql:\/\/|https?:\/\/|wss?:\/\/)/i.test(url) && url !== ':memory:') { return { reason: 'its `url` option is not a file:, :memory: or libsql:// URL.' }; @@ -213,10 +250,12 @@ function realPathAllowingMissing(path: string): string { * operator who never touches the server's disk, so what it may name is held * tighter than a URL written in code: * - * - a control character (a NUL byte above all) is refused before anything - * else, so it never reaches the native client; - * - a `file:` URL must name a file inside the project's data directory - * (`.objectstack/data/`, {@link dataDirectoryOf}), compared as the file it + * - a control character (a NUL byte above all), written out or + * percent-encoded, is refused before anything else, so it never reaches the + * native client; + * - a `file:` URL must name a file inside the data directory + * (`.objectstack/data/` of the project, or `data/` of the state directory: + * {@link dataDirectoryOf}), compared as the file it * resolves to, so neither `..` nor a link leads out of it. A relative path is * read from the process's working directory, as libSQL opens it; * - `:memory:` and a remote `libsql://`, `https://` or `wss://` URL open no @@ -227,14 +266,14 @@ function realPathAllowingMissing(path: string): string { */ export function resolveSettingsStoreUrl( url: string, - opts: Pick = {}, + opts: Pick = {}, ): { url: string; from: string } | { url?: undefined; reason: string } { const from = 'the knowledge setting `turso_url`'; - if (CONTROL_CHARACTER.test(url)) { + if (carriesControlCharacter(url)) { return { reason: - `${from} carries a NUL byte or another control character, which names no file or database. ` + - 'Save the URL again without it.', + `${from} carries a NUL byte or another control character, written out or percent-encoded, which names ` + + 'no file or database. Save the URL again without it.', }; } const trimmed = url.trim(); @@ -243,7 +282,7 @@ export function resolveSettingsStoreUrl( if (file === undefined) { return { reason: `${from} is not a valid file: URL.` }; } - const dataDir = realPathAllowingMissing(dataDirectoryOf(opts.projectRoot)); + const dataDir = realPathAllowingMissing(dataDirectoryOf(opts.projectRoot, opts.stateDir)); const inside = relativePath(dataDir, realPathAllowingMissing(file)); if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) { return { @@ -254,7 +293,7 @@ export function resolveSettingsStoreUrl( }; } } - const target = resolveStoreUrl({ url: trimmed, projectRoot: opts.projectRoot, env: opts.env }); + const target = resolveStoreUrl({ url: trimmed, projectRoot: opts.projectRoot, stateDir: opts.stateDir, env: opts.env }); return target.url === undefined ? { reason: target.reason.replace('its `url` option', from) } : { url: target.url, from }; } diff --git a/packages/verify/package.json b/packages/verify/package.json index a8ecda0d202..544bdb39a62 100644 --- a/packages/verify/package.json +++ b/packages/verify/package.json @@ -29,7 +29,6 @@ "dependencies": { "@objectstack/core": "workspace:*", "@objectstack/knowledge-pgvector": "workspace:*", - "@objectstack/knowledge-turso": "workspace:*", "@objectstack/mcp": "workspace:*", "@objectstack/metadata": "workspace:*", "@objectstack/objectql": "workspace:*", @@ -67,6 +66,9 @@ "@objectstack/trigger-schedule": "workspace:*", "@objectstack/types": "workspace:*" }, + "optionalDependencies": { + "@objectstack/knowledge-turso": "workspace:*" + }, "devDependencies": { "@types/node": "^26.6.5", "typescript": "^6.0.3", diff --git a/packages/verify/src/harness.required-providers.test.ts b/packages/verify/src/harness.required-providers.test.ts index 669b1b0a734..462351c51e3 100644 --- a/packages/verify/src/harness.required-providers.test.ts +++ b/packages/verify/src/harness.required-providers.test.ts @@ -1,5 +1,5 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// test-budget: 22 — spawns the real producer once per single-cause fixture: eleven in-process bootStack boots, no two the same configuration (a top-level requires, a package body's, the top level over the bodies, the control, an explicit instance, triggers with its hard dependencies, record-context with mcp, its no-token control, a host-mounted record-context, knowledge with realtime, its no-token control), each its case's subject; 5.9 s in a local run for the first six, 10.0 s with the three record-context boots, 14.8 s with the two knowledge boots (local, verbose reporter); slowest CI reading 11.4 s (scheduled full-battery run 41199450735, Test Core shard log) read before the record-context boots, scaled by the local ratio to 16.9 s, x 1.25, rounded up — the first CI reading after the knowledge boots re-measures it +// test-budget: 28 — spawns the real producer once per single-cause fixture: twelve in-process bootStack boots, no two the same configuration (a top-level requires, a package body's, the top level over the bodies, the control, an explicit instance, triggers with its hard dependencies, record-context with mcp, its no-token control, a host-mounted record-context, knowledge with realtime, its no-token control, knowledge on a file database under OS_HOME), each its case's subject; 5.9 s in a local run for the first six, 10.0 s with the three record-context boots, 14.8 s with the two knowledge boots, 19.0 s with the file-database knowledge boot (local, verbose reporter); slowest CI reading 11.4 s (scheduled full-battery run 41199450735, Test Core shard log) read before the record-context boots, scaled by the local ratio to 21.7 s, x 1.25, rounded up — the first CI reading after the knowledge boots re-measures it /** * #22301 item 1 — `bootStack` mounts the providers an app's `requires` names, @@ -25,8 +25,10 @@ * of the slate. */ -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, it } from 'vitest'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from '@objectstack/core'; import { composeStacks, defineStack } from '@objectstack/spec'; import { bootStack, type VerifyStack } from './harness.js'; @@ -145,14 +147,21 @@ describe('every provider the table names is a dependency of this package', () => it('so a declared token never fails to import from @objectstack/verify', () => { const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { dependencies: Record; + optionalDependencies?: Record; }; + const stores = Object.values(KNOWLEDGE_STORE_PROVIDERS); const packages = [ ...Object.values(CAPABILITY_PROVIDERS).flatMap((spec) => [spec.pkg, ...(spec.extras ?? []).map((extra) => extra.pkg)]), - // The stores the `knowledge` token chooses between (`resolveCapabilityExtras`). - ...Object.values(KNOWLEDGE_STORE_PROVIDERS).map((store) => store.pkg), + // The stores the `knowledge` token chooses between (`resolveCapabilityExtras`), bar the optional one. + ...stores.filter((store) => !store.optional).map((store) => store.pkg), ]; expect(packages.length).toBeGreaterThan(0); expect(packages.filter((pkg) => !(pkg in manifest.dependencies))).toEqual([]); + // A store the table marks optional is an OPTIONAL dependency, and only that: as a hard one its + // native client would refuse this package's install on a platform outside its os / cpu list. + const optional = stores.filter((store) => store.optional).map((store) => store.pkg); + expect(optional).toEqual(['@objectstack/knowledge-turso']); + expect(optional.filter((pkg) => !(pkg in (manifest.optionalDependencies ?? {})) || pkg in manifest.dependencies)).toEqual([]); }); }); @@ -360,4 +369,99 @@ describe("requires: ['knowledge'] — the knowledge service and one store", () = expect(served).toEqual(expect.arrayContaining([KNOWLEDGE, TURSO])); expect(served).not.toContain(PGVECTOR); }); + + // The arm `os dev` and `os serve` mount on SQLite: a FILE database, so the + // store is a libSQL file whose URL the operator may save in Settings. On a + // real kernel, because what is under test is the kernel's own order: the + // settings service binds in `kernel:ready`, the saved value is written + // after that, and the store opens at `kernel:bootstrapped`. + it('a file database: the store opens the file the operator saved, in the directory OS_HOME names, and indexes into it', async () => { + const root = mkdtempSync(join(tmpdir(), 'rqp-knowledge-')); + const home = join(root, 'home'); + const saved = join(home, 'data', 'saved.db'); + const previousHome = process.env.OS_HOME; + process.env.OS_HOME = home; + try { + const served = await constructServedProviders({ + config: app({ requires: ['knowledge'] }), + held: [], + packageRoot: join(root, 'app'), + database: { driver: 'sqlite', url: `file:${join(home, 'data', 'objectstack.db')}` }, + }); + const mounted = served.filter((p) => [KNOWLEDGE, TURSO, PGVECTOR].includes((p as { name: string }).name)); + expect(mounted.map((p) => (p as { name: string }).name)).toEqual([KNOWLEDGE, TURSO]); + + /** The operator's save: after the settings service has bound, before the boot completes. */ + class SavesStoreUrl { + readonly name = 'com.example.rqp.saves-store-url'; + readonly version = '0.0.0'; + readonly type = 'standard'; + readonly optionalDependencies = ['com.objectstack.service.settings']; + outcome: unknown; + async init(): Promise {} + async start(ctx: { getService(name: string): T; hook(name: string, handler: () => Promise): void }): Promise { + const settings = ctx.getService<{ set(ns: string, key: string, value: unknown, ec: unknown): Promise }>('settings'); + ctx.hook('kernel:ready', async () => { + this.outcome = await settings.set('knowledge', 'turso_url', `file:${saved}`, { isSystem: true }).then( + () => 'saved', + (e: unknown) => e, + ); + }); + } + } + const saver = new SavesStoreUrl(); + // The two providers the file arm constructed are this boot's own: held, so the boot adds no second pair. + stack = await bootStack(app({ requires: ['realtime', 'knowledge'] }), { + extraPlugins: [...mounted, new AppKnowledge(), saver], + } as never); + expect(saver.outcome).toBe('saved'); + + const knowledge = await stack.kernel.getServiceAsync('knowledge'); + expect(await knowledge.getAdapter('turso').healthCheck()).toMatchObject({ ok: true }); + expect(existsSync(saved)).toBe(true); + // Neither default was made: not the one under OS_HOME, and nothing under the app's own directory. + expect(existsSync(join(home, 'data', 'knowledge.db'))).toBe(false); + expect(existsSync(join(root, 'app', '.objectstack'))).toBe(false); + + const ql = await stack.kernel.getServiceAsync('objectql'); + await ql.insert('rqp_article', { title: 'Slate quarry RQP', body: 'slate and shale tiles' }, { context: { isSystem: true } }); + const ec = { isSystem: true, userId: 'system', roles: [], permissions: [] }; + let hits: Array<{ sourceId: string }> = []; + for (let i = 0; i < 50 && hits.length === 0; i++) { + hits = (await knowledge.searchWithRefusals('slate quarry', { executionContext: ec, sourceIds: ['rqp_articles'] })).hits; + if (hits.length === 0) await new Promise((r) => setTimeout(r, 50)); + } + expect(hits.map((h) => h.sourceId)).toEqual(['rqp_articles']); + } finally { + await stack?.stop(); + stack = undefined; + if (previousHome === undefined) delete process.env.OS_HOME; + else process.env.OS_HOME = previousHome; + rmSync(root, { recursive: true, force: true }); + } + }, 120_000); + + // LAST in the file: it clears the module cache to make the store's package unimportable. + it('an install without the optional libSQL store: the service is constructed, the store is not, and the boot says so once', async () => { + vi.resetModules(); + vi.doMock('@objectstack/knowledge-turso', () => { + throw new Error("Cannot find module '@objectstack/knowledge-turso'"); + }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const served = ( + await constructServedProviders({ config: app({ requires: ['knowledge'] }), held: [], packageRoot: process.cwd() }) + ).map((p) => (p as { name?: string }).name); + expect(served).toContain(KNOWLEDGE); + expect(served).not.toContain(TURSO); + const said = warn.mock.calls.map(([m]) => String(m)).filter((m) => m.includes('@objectstack/knowledge-turso')); + expect(said).toHaveLength(1); + expect(said[0]).toContain("requires: ['knowledge'] mounts KnowledgeTursoPlugin"); + expect(said[0]).toContain('an optional dependency this install does not have'); + } finally { + warn.mockRestore(); + vi.doUnmock('@objectstack/knowledge-turso'); + vi.resetModules(); + } + }); }); diff --git a/packages/verify/src/required-providers.ts b/packages/verify/src/required-providers.ts index 2a62a9686a8..ccf9b40c3d7 100644 --- a/packages/verify/src/required-providers.ts +++ b/packages/verify/src/required-providers.ts @@ -58,7 +58,11 @@ // without it would pass green on a composition production does not run. // Every package in the table is a dependency of `@objectstack/verify` // (pinned), so an import failure is a broken install; a configuration the -// mail or SMS reader refuses names its own remedy. +// mail or SMS reader refuses names its own remedy. The one exception is an +// extra the table marks `optional` (the `knowledge` token's libSQL store, +// an optional dependency here and of the CLI, since its client is a native +// module): where it cannot be imported this boot warns once and goes on +// without it, which is the composition `serve` runs on that install. import { CAPABILITY_PROVIDERS, @@ -174,6 +178,19 @@ export async function constructServedProviders(opts: { }); for (const extra of extras) { if (providesCapability(all(), extra.identities)) continue; + if (extra.optional) { + const missing = await import(/* webpackIgnore: true */ extra.pkg).then( + () => undefined, + (e: unknown) => (e instanceof Error ? e.message : String(e)), + ); + if (missing !== undefined) { + console.warn( + `verify: ${reason} mounts ${extra.export} (${extra.pkg}), an optional dependency this install does not ` + + `have: ${missing}. It was not mounted, as objectstack serve does not mount it on this install.`, + ); + continue; + } + } constructed.push( await constructProvider({ reason, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e9e61fdbef2..ef512a3c556 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -619,9 +619,6 @@ importers: '@objectstack/knowledge-pgvector': specifier: workspace:* version: link:../plugins/knowledge-pgvector - '@objectstack/knowledge-turso': - specifier: workspace:* - version: link:../plugins/knowledge-turso '@objectstack/lint': specifier: workspace:* version: link:../lint @@ -807,6 +804,9 @@ 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)) optionalDependencies: + '@objectstack/knowledge-turso': + specifier: workspace:* + version: link:../plugins/knowledge-turso better-sqlite3: specifier: ^13.0.3 version: 13.0.3 @@ -3780,9 +3780,6 @@ importers: '@objectstack/knowledge-pgvector': specifier: workspace:* version: link:../plugins/knowledge-pgvector - '@objectstack/knowledge-turso': - specifier: workspace:* - version: link:../plugins/knowledge-turso '@objectstack/mcp': specifier: workspace:* version: link:../mcp @@ -3901,6 +3898,10 @@ importers: 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)) + optionalDependencies: + '@objectstack/knowledge-turso': + specifier: workspace:* + version: link:../plugins/knowledge-turso ui: devDependencies: From 664bd7025c947534e22040d6caccb70646491868 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:47:49 +0000 Subject: [PATCH 8/8] fix(knowledge-turso): refuse a control character in the store's auth token The auth token is the second settings value handed to the libSQL client. One with a NUL byte, a line break or another control character is now refused in the plugin's open path, for the saved setting and the plugin option alike, before the client is created; the reason never quotes the token. It is read as written: the client percent-decodes a URL, never this option. Also corrects the knowledge settings manifest jsdoc (the data directory follows the state directory; the percent-encoded spelling is refused). Claude-Session: https://claude.ai/code/session_01Utp6CYE8s5v1UX96GEfkcR Co-authored-by: Claude --- .../37102-knowledge-capability-token.md | 2 +- content/docs/ai/knowledge-rag.mdx | 2 +- .../src/__tests__/plugin.test.ts | 43 +++++++++++++++++++ .../plugins/knowledge-turso/src/plugin.ts | 26 ++++++++++- .../src/manifests/knowledge.manifest.ts | 8 ++-- 5 files changed, 75 insertions(+), 6 deletions(-) diff --git a/.changeset/37102-knowledge-capability-token.md b/.changeset/37102-knowledge-capability-token.md index 07460ec5a05..ece1c93690e 100644 --- a/.changeset/37102-knowledge-capability-token.md +++ b/.changeset/37102-knowledge-capability-token.md @@ -21,6 +21,6 @@ ADR-0161, #37102. - 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). - `os serve` now warns when a capability's extra plugin cannot be imported or constructed, instead of skipping it silently. - **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. -- **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. +- **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. - **`@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`. - The `turso_url` setting's example path now reads `file:./.objectstack/data/knowledge.db` in every locale. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index c4b7cb5d231..b9ca288c181 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -33,7 +33,7 @@ Which store is mounted depends on the platform database: - **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'`). - **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`. - **The embedder** comes from Settings → AI & Embedder ([below](#configuring-the-embedder-from-settings)). -- **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; either way the store answers `SERVICE_UNAVAILABLE` saying why, and the boot goes on. +- **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. - **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. - **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. - **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`. diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 49c0ca2a8f9..6ea15777010 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -405,6 +405,49 @@ describe('KnowledgeTursoPlugin — the store URL from settings (urlFromSettings) expect(createClient).not.toHaveBeenCalled(); }); + it('an auth token with a control character never reaches the libSQL client, saved or given; the reason never quotes it', async () => { + const createClient = vi.fn((): never => { + throw new Error('refused by the double'); + }); + vi.doMock('@libsql/client', () => ({ createClient })); + vi.resetModules(); + const { KnowledgeTursoPlugin: Fresh, acceptsAuthToken } = await import('../plugin.js'); + const root = tempDir(); + const inside = `file:${join(dataDirectoryOf(root), 'k.db')}`; + const refused = [`secret${String.fromCharCode(0)}tail`, 'secret-tail\n', 'secret\r\ntail', `secret${String.fromCharCode(0x7f)}tail`]; + for (const token of refused) { + expect(acceptsAuthToken(token)).toBe(false); + // The settings door, on a remote URL and on a file; then the plugin option. + for (const url of ['libsql://tenant.example.turso.io', inside]) { + const settings = settingsOf({ turso_url: url, turso_auth_token: token }); + const host = contextOf({ settings }); + await boot(new Fresh({ projectRoot: root, env: {}, urlFromSettings: true }), host, settings); + expect(await host.adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); + expect(host.logs.some(([level, m]) => level === 'warn' && m.includes('auth token') && m.includes('control character'))).toBe(true); + expect(host.logs.some(([, m]) => m.includes('secret'))).toBe(false); + } + const host = contextOf(); + await boot(new Fresh({ url: 'libsql://tenant.example.turso.io', authToken: token, env: {} }), host); + expect(await host.adapters.get('turso')!.healthCheck!()).toMatchObject({ ok: false }); + expect(host.logs.some(([level, m]) => level === 'warn' && m.includes('auth token'))).toBe(true); + } + expect(createClient).not.toHaveBeenCalled(); + expect(existsSync(dataDirectoryOf(root))).toBe(false); + + // Controls: a token as tokens are, and one with a percent escape (the + // client never decodes this option, so `%00` is three characters), reach + // the client as written. + for (const token of ['eyJhbGciOiJFZERTQSJ9.e30.c2ln', 'a%00b']) { + expect(acceptsAuthToken(token)).toBe(true); + const settings = settingsOf({ turso_url: 'libsql://tenant.example.turso.io', turso_auth_token: token }); + const host = contextOf({ settings }); + await boot(new Fresh({ projectRoot: root, env: {}, urlFromSettings: true }), host, settings); + expect(createClient).toHaveBeenLastCalledWith(expect.objectContaining({ authToken: token })); + } + expect(createClient).toHaveBeenCalledTimes(2); + expect(acceptsAuthToken(undefined)).toBe(true); + }); + it('a settings read that fails opens nothing: the store says why', async () => { const root = tempDir(); const settings = settingsOf({}, new Error('database is locked')); diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index 6cf741e0c7a..22384363bee 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -31,7 +31,10 @@ export interface KnowledgeTursoPluginOptions { * project's `.objectstack/data/`. Never the platform's own database file. */ url?: string; - /** The auth token of a `libsql://` URL. */ + /** + * The auth token of a `libsql://` URL. One with a control character in it + * (a pasted line break, a NUL byte) is refused before it reaches the client. + */ authToken?: string; /** * A libSQL client the store uses as it is (the plugin neither configures nor @@ -121,6 +124,23 @@ function carriesControlCharacter(url: string): boolean { ); } +/** + * Why a store whose auth token carries a control character has no database. + * The token is the second value an operator's settings hand the libSQL client + * (a `file:` URL passes it into the native open, a remote one into a request + * header), and no token has a control character in it: a pasted line break is + * the usual one. It is read as written: the client percent-decodes a URL, + * never this option. The token is a secret, so the reason never quotes it. + */ +const AUTH_TOKEN_CONTROL_CHARACTER = + 'its auth token (the knowledge setting `turso_auth_token`, or the plugin option `authToken`) carries a NUL ' + + 'byte, a line break or another control character, which no token has. Save the token again without it.'; + +/** Whether `authToken` is one the libSQL client may be handed: absent, or free of control characters. */ +export function acceptsAuthToken(authToken: string | undefined): boolean { + return authToken === undefined || !CONTROL_CHARACTER.test(authToken); +} + /** The bound on one request to a remote database (`requestTimeoutMs`). */ export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; @@ -469,6 +489,10 @@ export class KnowledgeTursoPlugin implements Plugin { await this.register(ctx, svc, { unavailable: target.reason }); return; } + if (!acceptsAuthToken(authToken)) { + await this.register(ctx, svc, { unavailable: AUTH_TOKEN_CONTROL_CHARACTER }); + return; + } const opened = await openClient(target.url, { ...this.opts, authToken }); if ('client' in opened) { this.owned = opened.client; diff --git a/packages/services/service-settings/src/manifests/knowledge.manifest.ts b/packages/services/service-settings/src/manifests/knowledge.manifest.ts index 2420829f3f0..2969f66d076 100644 --- a/packages/services/service-settings/src/manifests/knowledge.manifest.ts +++ b/packages/services/service-settings/src/manifests/knowledge.manifest.ts @@ -20,9 +20,11 @@ import type { SettingsActionHandler } from '../settings-service.types.js'; * * Only `turso` reads this namespace, and only `turso_url` and * `turso_auth_token`, when the runtime mounts it for `requires: - * ['knowledge']` (#37102): a `file:` URL saved there is held to the project's - * `.objectstack/data/` directory and a URL with a NUL byte is refused, before - * it reaches the libSQL client. Every other adapter is registered by the + * ['knowledge']` (#37102): a `file:` URL saved there is held to the data + * directory of the platform's state directory (`/data/`, else the + * project's `.objectstack/data/`), and a URL with a control character in it, + * written out or percent-encoded, or a token with one, is refused before it + * reaches the libSQL client. Every other adapter is registered by the * deployment beside the knowledge service itself. * * As with the AI manifest, the real adapter wiring happens in the