diff --git a/.changeset/37306-knowledge-source-adapter-optional.md b/.changeset/37306-knowledge-source-adapter-optional.md new file mode 100644 index 00000000000..1b504f7e0d5 --- /dev/null +++ b/.changeset/37306-knowledge-source-adapter-optional.md @@ -0,0 +1,26 @@ +--- +'@objectstack/spec': minor +'@objectstack/core': minor +'@objectstack/service-knowledge': minor +'@objectstack/cli': minor +'@objectstack/verify': minor +'@objectstack/runtime': patch +--- + +feat(knowledge): a knowledge source needs no `adapter` and no `requires: ['knowledge']` — it binds to the deployment's store, and shipping one mounts the service + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: follow-up #37310 — `skills/**` teaches the optional `adapter` and the item mount after this lands + +A `knowledge_source` may leave out `adapter` (ADR-0161 K4), and a stack that ships one in `knowledgeSources` is served the knowledge service and one vector store without listing `knowledge` under `requires` (ADR-0161 K8, item 12). One source written as metadata now builds on SQLite under `os dev` (the `turso` store, a libSQL file), on PostgreSQL (`pgvector`) and on a host that mounts its own store, with no change to the source. + +- **`@objectstack/spec`.** `KnowledgeSourceSchema.adapter` is optional. Omitted, the source is held by the deployment's adapter: the store the runtime mounted beside the knowledge service, else the only adapter registered. A named adapter is kept as written. `PlatformCapabilityProvider` gains an optional `mountedBy: { collection }`, set on the `knowledge` row of `PLATFORM_CAPABILITY_PROVIDERS` (`knowledgeSources`): a stack holding an item of that collection is served the capability as its token serves it. +- **`@objectstack/core`.** `stackItemCapabilities(stack)` answers the tokens a stack's items mount (top level, then each package body), and `resolveServedCapabilities` takes them as `itemTokens`: appended after the declared tokens, read as declared (a provider that cannot be built fails the boot as for `requires`), and reported in a new `byItems` set. `resolveCapabilityArgument('knowledge', …)` now answers `{ deploymentAdapter }`, the adapter id of the store `resolveCapabilityExtras` mounts for the same database. +- **`@objectstack/cli` and `@objectstack/verify`.** `os serve` / `os dev` / `os start` and `bootStack` read the item tokens, and hand the knowledge service the deployment's store (`pgvector` on PostgreSQL, `turso` otherwise). `os migrate plan` / `apply` read them too, so an item-only stack's migrate run composes the knowledge service as `os serve` mounts it (init only: no store, build or embedder call). +- **`@objectstack/service-knowledge`.** `KnowledgeServicePlugin` and `KnowledgeService` take a `deploymentAdapter` option: the runtime's mark of the store it mounted. It is a service option, not an adapter-contract member, and `registerAdapter` is unchanged: an adapter application code registers is never the deployment's by registering. A source that names no adapter is placed where it is used (`adapterIdFor`, `adapterFor`), so one registered in code before its store started finds it. With several adapters registered and none the deployment's, such a source is refused at registration (both doors) and at its save, `400 VALIDATION_ERROR`, naming the adapters; registered first and left unplaceable by adapters that came later, it answers the same refusal at index and search, and the boot names it once at `error`. With no adapter registered it answers `503 SERVICE_UNAVAILABLE`, naming the deployment's store when one was marked. The `index_status` action reports the adapter a source is placed on. +- **`@objectstack/runtime`.** The MCP draft door (`save_metadata_draft`) carries the knowledge service's refusal code through: a source refused `400 VALIDATION_ERROR` arrived over MCP as `SERVICE_UNAVAILABLE` with status 400, and now arrives as `VALIDATION_ERROR`, as on the REST door. A `403` is still `PERMISSION_DENIED`. + +Unchanged: a source that names an adapter that is not mounted answers `SERVICE_UNAVAILABLE` as before; a host that mounts `KnowledgeServicePlugin` itself keeps its own, gets no store from the runtime and no deployment's mark; without a source or the token nothing is mounted; an item saved at run time on a deployment that mounted no knowledge service is reported at boot exactly as before. + +What to do: nothing to change, with one behaviour to know. A stack on 19.0.0-next.1 that ships a source without `requires: ['knowledge']` held it inert, with a boot warning; it is now indexed: the service mounts, the boot pass builds the source's index, and its content fields are sent to the configured embedder (ADR-0161 K5: embedding is egress). A source that names `adapter: 'turso'` or `adapter: 'pgvector'` keeps working; drop the key to let the deployment choose, and drop `knowledge` from `requires` in an app that ships its sources. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 499a52f7233..8534435290b 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -14,7 +14,7 @@ ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable bac ## 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: +Ship a knowledge source in your app ([below](#writing-a-source)), or add `knowledge` to its `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. A source in the app's `knowledgeSources` is enough on its own; the token is for an app that ships none and authors its sources at run time: ```ts export default defineStack({ @@ -30,7 +30,8 @@ Which store is mounted depends on the platform database: | 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` | `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 metadata**: list them under `knowledgeSources` ([below](#writing-a-source)), and name the adapter of the store your database gets (`adapter: 'turso'` or `adapter: 'pgvector'`). +- **Sources are metadata**: list them under `knowledgeSources` ([below](#writing-a-source)). A source needs no `adapter`: one left out is held by the store in this table — the deployment's store — so the same source builds on SQLite under `os dev`, on PostgreSQL and on a hosted environment. Name an adapter only to place a source on another store you mounted. +- **Two stores and none the deployment's** (a host that mounts the service and two adapters itself): a source that names no adapter is refused when it is registered or saved — `VALIDATION_ERROR` (400), naming the adapters to choose from. - **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, 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. @@ -38,14 +39,15 @@ Which store is mounted depends on the platform database: - **Settings → Knowledge** holds only what the service and its store read: `turso_url` and `turso_auth_token`, which `@objectstack/knowledge-turso` adds to the page where it is the store and reads them (on PostgreSQL the page shows neither), and `chunk_target`, the longest passage the splitter cuts. The page names no adapter: a source's store is the one its own `adapter` names, and `os knowledge status` reports it per source. Every search re-checks each hit as the asking user, and no setting turns that off. - **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. +- **Without a source or 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. ## Writing a source A knowledge source is a metadata item: a `*.knowledge-source.ts` file in your app, listed under `knowledgeSources`. It says which object's records to -index, which fields become searchable text, and which adapter holds the index. +index and which fields become searchable text; the deployment's store holds the +index unless the source names another. ```ts // src/ai/task-notes.knowledge-source.ts @@ -54,7 +56,7 @@ import type { KnowledgeSource } from '@objectstack/spec/ai'; export const TaskNotes: KnowledgeSource = { name: 'task_notes', label: 'Task notes', - adapter: 'turso', // 'pgvector' when the platform database is PostgreSQL + // No `adapter`: the deployment's store (turso, or pgvector on PostgreSQL). source: { kind: 'object', object: 'task', content: ['title', 'notes'] }, }; ``` @@ -65,8 +67,7 @@ import { defineStack } from '@objectstack/spec'; import { TaskNotes } from './src/ai/task-notes.knowledge-source.js'; export default defineStack({ - requires: ['knowledge'], - knowledgeSources: [TaskNotes], + knowledgeSources: [TaskNotes], // mounts the knowledge service: no `requires` entry // … }); ``` @@ -76,7 +77,7 @@ and keeps the index in step with the records. There is no registration call to write. - **`content` lists its fields by name.** What is listed is what leaves the row store: the text of those fields is sent to the embedder and kept in the index. `'*'` is refused, and a field added to the object later is not indexed until you add it here. -- **A source can also be created or changed at run time**, in Studio or through MCP, with no restart: a new source is loaded and built, a changed one is reloaded (and rebuilt when what it indexes changed), and a removed one has its index dropped. +- **A source can also be created or changed at run time**, in Studio or through MCP, with no restart where the knowledge service is mounted (above): a new source is loaded and built, a changed one is reloaded (and rebuilt when what it indexes changed), and a removed one has its index dropped. - **Authoring one needs `manage_knowledge_sources`** beside `manage_metadata` — platform administrators hold it by default — and the author must themselves be allowed to search the object and query every listed field and every field `where` reads, or the save is refused naming what they may not read. A write to a package that holds a source (publish its drafts, roll it back, duplicate, disable or delete it) needs the same capability. - **Two packages may each ship a source of the same name.** `search_knowledge` lists a package's source as `NAMESPACE-NAME` and takes that spelling in `sourceIds`. - **Registering in code still works**: `new KnowledgeServicePlugin({ sources: [TaskNotes] })` or `knowledge.registerSource(TaskNotes)` takes the same shape. A source registered in code and an item saved under the same name are one name: the second to arrive is refused. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index a1042f86659..612dc689253 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -109,7 +109,8 @@ any AI consumer.** ### 3.1 `KnowledgeSource` (the `knowledge_source` metadata type) A knowledge source says *which records* to index, *which of their fields* -become searchable text, and *which adapter* holds the index. It is a governed +become searchable text, and, when it is not the deployment's store, *which +adapter* holds the index. It is a governed metadata type, `knowledge_source` (ADR-0161 K4): a package ships it as a `*.knowledge-source.ts` (or `.yml`) file under the stack's `knowledgeSources` collection, and an administrator creates or changes one at run time in Studio @@ -122,7 +123,7 @@ import type { KnowledgeSource } from '@objectstack/spec/ai'; export const KbArticles: KnowledgeSource = { name: 'kb_articles', // snake_case; with its package, the source's identity label: 'Knowledge base', - adapter: 'pgvector', // the adapter id a plugin registered + // adapter: 'pgvector', // optional; omitted ⇒ the deployment's store source: { kind: 'object', // the one kind object: 'kb_article', @@ -133,7 +134,7 @@ export const KbArticles: KnowledgeSource = { }, }; -// objectstack.config.ts +// objectstack.config.ts — the source mounts the knowledge service: no `requires` entry defineStack({ knowledgeSources: [KbArticles], /* … */ }); ``` @@ -161,9 +162,27 @@ write instead, and `os migrate meta --from 18` converts the mechanical ones: | `refresh.cron` | removed: nothing scheduled it | | `source.kind: 'file'` / `'http'` with `prefix`, `mimeTypes`, `urls`, `userAgent` | removed: a source indexes an object's records | -Every source binds to a named **adapter id** (e.g. `'pgvector'`, `'turso'`, +A source binds to an **adapter id** (e.g. `'pgvector'`, `'turso'`, `'memory'`), resolved at run time to the plugin that registered itself under -that name. +that name (ADR-0161 K4): + +- **Named** — that adapter. One that is not mounted is refused at index and + search, `SERVICE_UNAVAILABLE` (503), naming the adapters that are. +- **Omitted** — the deployment's adapter: the store the runtime mounted beside + the service (`pgvector` on PostgreSQL, `turso` otherwise; the runtime passes + `KnowledgeServicePlugin` its `deploymentAdapter` option when it mounts both), + else the only adapter registered. An adapter application code registers is + never the deployment's by registering. With several registered and none the + deployment's, the source is refused at registration and at its save, + `VALIDATION_ERROR` (400), naming them. The adapter is placed where it is + used, so a source registered before its store started finds it. + +**What mounts the service.** A stack that ships a `knowledge_source` — any +item in its `knowledgeSources`, at the top level or in a package — is served +the knowledge service and the deployment's store, exactly as +`requires: ['knowledge']` serves them (the `mountedBy` of the `knowledge` row +in `PLATFORM_CAPABILITY_PROVIDERS`). A host that mounts +`KnowledgeServicePlugin` itself keeps its own, and the runtime adds no store. #### How a source is loaded @@ -181,7 +200,9 @@ starts and follows the type from then on, with no restart: A deployment that holds a `knowledge_source` item but mounts no knowledge service says so once at boot, naming the items: nothing loads, indexes or -searches them until `KnowledgeServicePlugin` and an adapter are mounted. +searches them until `KnowledgeServicePlugin` and an adapter are mounted. Such +an item is one the stack does not ship — saved at run time or installed in a +package after the boot — since a shipped one mounts the service. #### Who may author one @@ -606,8 +627,8 @@ Each plugin: 3. Owns its own dependencies (SDK, fetch client, embedder). 4. Owns its own lifecycle / health checks. -Multiple adapters can co-exist; sources pick which one to use via the -`adapter` field. +Multiple adapters can co-exist; a source picks one with its `adapter` field, +or leaves it out for the deployment's store (§3.1). ### 4.1 `knowledge-pgvector` — the open vector store on PostgreSQL diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 9f00bafbdf2..08cd6efcb41 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -54,7 +54,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **id** | `never` | optional | [REMOVED] `knowledge_source.id` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — a knowledge source is a metadata item, and an item is identified by `name`; use `name`. Rename the key; the value is unchanged, so the source's index is found again and is not rebuilt. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **label** | `string` | ✅ | | | **description** | `string` | optional | | -| **adapter** | `string` | ✅ | Adapter id | +| **adapter** | `string` | optional | Adapter id; omitted means the deployment's store (pgvector on PostgreSQL, turso otherwise), else the only adapter registered | | **adapterConfig** | `never` | optional | [REMOVED] `knowledge_source.adapterConfig` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — no adapter read it: its one reader was the retired RAGFlow adapter. Delete the key. An adapter takes its settings as options of the plugin that mounts it. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **source** | `{ kind: Enum<'object'>; object: string; content: string[]; metadataFields?: string[]; … }` | ✅ | | | **embedding** | `never` | optional | [REMOVED] `knowledge_source.embedding` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was never read: no service and no adapter chose a model from it. Delete the key. The embedder is configured once for the deployment, and every source is embedded by it. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | diff --git a/content/docs/references/api/package-api-assembled.mdx b/content/docs/references/api/package-api-assembled.mdx index 4a5f6a8ad8f..6c86b555faa 100644 --- a/content/docs/references/api/package-api-assembled.mdx +++ b/content/docs/references/api/package-api-assembled.mdx @@ -139,7 +139,7 @@ Installed package row whose manifest is the assembled package body | **tools** | `{ name: string; label: string; description: string; parameters: Record; … }[]` | optional | AI Tool metadata records — optional refinement layer, never required: the default path is skills referencing platform tools or materialised action_`` tools (ADR-0109) | | **skills** | `{ name: string; label: string; description?: string; surface?: Enum<'ask' \| 'build' \| 'both'>; … }[]` | optional | AI Skills (reusable capability bundles — the third-party AI extension primitive, ADR-0063) | | **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160). A host serves that tool only when it mounts the record-context service: the CLI mounts it where `requires` includes `record-context`, and a host that composes its own kernel lists `RecordContextServicePlugin` in `plugins` | -| **knowledgeSources** | `{ name: string; label: string; description?: string; adapter: string; … }[]` | optional | Knowledge sources — which object's records the knowledge service indexes, which fields are sent to the embedder as content, and which adapter holds the index (ADR-0161 K4). A host indexes them only when it mounts the knowledge service: the CLI mounts it where `requires` includes `knowledge`, and a host that composes its own kernel lists `KnowledgeServicePlugin` in `plugins` | +| **knowledgeSources** | `{ name: string; label: string; description?: string; adapter?: string; … }[]` | optional | Knowledge sources — which object's records the knowledge service indexes, which fields are sent to the embedder as content, and which adapter holds the index (ADR-0161 K4). A host indexes them only when it mounts the knowledge service: the CLI mounts it, with the deployment's store, where the stack holds a source or `requires` includes `knowledge`, and a host that composes its own kernel lists `KnowledgeServicePlugin` in `plugins` | | **hooks** | `{ name: string; label?: string; object: string \| string[]; events: Enum<'beforeFind' \| 'afterFind' \| 'beforeInsert' \| 'afterInsert' \| 'beforeUpdate' \| …>[]; … }[]` | optional | Object Lifecycle Hooks, as a JSON document carries them | | **mappings** | `{ name: string; label?: string; sourceFormat?: Enum<'csv' \| 'json' \| 'xml' \| 'sql'>; targetObject: string; … }[]` | optional | Data Import/Export Mappings | | **analyticsCubes** | `{ name: string; title?: string; description?: string; sql: string; … }[]` | optional | Analytics Semantic Layer Cubes | @@ -392,7 +392,7 @@ This schema accepts one of the following structures: | **tools** | `{ name: string; label: string; description: string; parameters: Record; … }[]` | optional | AI Tool metadata records — optional refinement layer, never required: the default path is skills referencing platform tools or materialised action_`` tools (ADR-0109) | | **skills** | `{ name: string; label: string; description?: string; surface?: Enum<'ask' \| 'build' \| 'both'>; … }[]` | optional | AI Skills (reusable capability bundles — the third-party AI extension primitive, ADR-0063) | | **aiContexts** | `{ name: string; label: string; object: string; fields?: string[]; … }[]` | optional | AI context packs — the material of one record handed to a model, read as the caller by get_record_context (ADR-0160). A host serves that tool only when it mounts the record-context service: the CLI mounts it where `requires` includes `record-context`, and a host that composes its own kernel lists `RecordContextServicePlugin` in `plugins` | -| **knowledgeSources** | `{ name: string; label: string; description?: string; adapter: string; … }[]` | optional | Knowledge sources — which object's records the knowledge service indexes, which fields are sent to the embedder as content, and which adapter holds the index (ADR-0161 K4). A host indexes them only when it mounts the knowledge service: the CLI mounts it where `requires` includes `knowledge`, and a host that composes its own kernel lists `KnowledgeServicePlugin` in `plugins` | +| **knowledgeSources** | `{ name: string; label: string; description?: string; adapter?: string; … }[]` | optional | Knowledge sources — which object's records the knowledge service indexes, which fields are sent to the embedder as content, and which adapter holds the index (ADR-0161 K4). A host indexes them only when it mounts the knowledge service: the CLI mounts it, with the deployment's store, where the stack holds a source or `requires` includes `knowledge`, and a host that composes its own kernel lists `KnowledgeServicePlugin` in `plugins` | | **hooks** | `{ name: string; label?: string; object: string \| string[]; events: Enum<'beforeFind' \| 'afterFind' \| 'beforeInsert' \| 'afterInsert' \| 'beforeUpdate' \| …>[]; … }[]` | optional | Object Lifecycle Hooks, as a JSON document carries them | | **mappings** | `{ name: string; label?: string; sourceFormat?: Enum<'csv' \| 'json' \| 'xml' \| 'sql'>; targetObject: string; … }[]` | optional | Data Import/Export Mappings | | **analyticsCubes** | `{ name: string; title?: string; description?: string; sql: string; … }[]` | optional | Analytics Semantic Layer Cubes | diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 88369974528..b0da5637d08 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -47,6 +47,7 @@ import { resolveServedCapabilities, resolveCapabilityArgument, resolveCapabilityExtras, + stackItemCapabilities, type CapabilityDatabase, materializeStackPlugin, STACK_TIER_PRESETS, @@ -3129,7 +3130,14 @@ export default class Serve extends Command { const hostDefaults: string[] = []; if (isMcpServerEnabled()) hostDefaults.push('mcp'); if (stampSearchPinyinEnabled((config as any).i18n)) hostDefaults.push('pinyin-search'); - const served = resolveServedCapabilities(stackDeclaredCapabilities(config), { preset: presetName, hostDefaults }); + // [ADR-0161 K8 item 12] A stack that ships a `knowledge_source` is + // served the knowledge service and the deployment's store as if it + // listed `requires: ['knowledge']` (`stackItemCapabilities`). + const served = resolveServedCapabilities(stackDeclaredCapabilities(config), { + preset: presetName, + hostDefaults, + itemTokens: stackItemCapabilities(config), + }); const requires: string[] = [...served.tokens]; const declaredRequires: ReadonlySet = served.declared; // Capability → tier: any capability that is gated by a tier @@ -5588,11 +5596,15 @@ export default class Serve extends Command { // transport can deliver through (#5087, #5132, #5713) — the catch // below turns that into the boot failure / loud error it should be, // never a log transport substituted behind the operator's back. + // `database` too: the `knowledge` service is told which store is the + // deployment's (`deploymentAdapter`), by the choice the extras below + // read, so the two agree (ADR-0161 K4). const resolved = resolveCapabilityArgument(cap, { stack: config, packageRoot: path.dirname(absolutePath), providerModule: mod, env: process.env, + database: capabilityDatabase, }); const arg: any = resolved.argument; if (resolved.localStorageRoot && !isDev) { diff --git a/packages/cli/src/utils/boot-preparation-parity.test.ts b/packages/cli/src/utils/boot-preparation-parity.test.ts index dd7cb63c97f..2dc0be29529 100644 --- a/packages/cli/src/utils/boot-preparation-parity.test.ts +++ b/packages/cli/src/utils/boot-preparation-parity.test.ts @@ -63,6 +63,7 @@ import { resolvePlatformAuthComposition, resolveServedCapabilities, resolveStackTiers, + stackItemCapabilities, } from '@objectstack/core'; import { createStandaloneStack } from '@objectstack/runtime'; import { stampSearchPinyinEnabled } from '@objectstack/types'; @@ -123,6 +124,9 @@ const STEPS: readonly Step[] = [ // [#22301] Which tokens get a provider — the declared ones, `email` for // `auth`, the always-on slate, `job` / `queue` ahead — read by both boots. resolveServedCapabilities, + // [ADR-0161 K8 item 12] The tokens a stack's items mount (a shipped + // `knowledge_source` mounts `knowledge`), read by both boots off the config. + stackItemCapabilities, stampSearchPinyinEnabled, providesCapability, ], diff --git a/packages/cli/src/utils/schema-migration-plugins.test.ts b/packages/cli/src/utils/schema-migration-plugins.test.ts index 038fa12000f..b9ad04f2eba 100644 --- a/packages/cli/src/utils/schema-migration-plugins.test.ts +++ b/packages/cli/src/utils/schema-migration-plugins.test.ts @@ -7,6 +7,12 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { SqlDriver } from '@objectstack/driver-sql'; import { SchemaRegistry } from '@objectstack/objectql'; +// Paid at collection, not in a case's clocked window: the modules the source +// under test loads with `await import(…)` (check:test-source-alias). +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/runtime'; import { findHostConfig, composeForDeclarations, @@ -934,6 +940,22 @@ describe('servedPlatform (#22506)', () => { expect(out.plugins.map((p: any) => p?.name)).toContain('com.objectstack.rest.api'); }, 60_000); + it('[ADR-0161 K8 item 12] a stack that ships a knowledge_source and lists no `knowledge` composes the knowledge service, as `serve` mounts it; without one it does not', async () => { + const withSource = project([ + 'export default {', + " manifest: { id: 'com.example.os37306unit', name: 'item mount', version: '0.0.0', type: 'app' },", + " objects: [{ name: 'os37306_note', fields: { title: { type: 'text' } } }],", + " knowledgeSources: [{ name: 'notes', label: 'Notes', source: { kind: 'object', object: 'os37306_note', content: ['title'] } }],", + '};', + '', + ].join('\n')); + const out = await buildSchemaMigrationPlugins({ basePlugins: [], cwd: withSource, servedPlatform: {} }); + expect(out.plugins.map((p: any) => p?.constructor?.name)).toContain('KnowledgeServicePlugin'); + + const control = await buildSchemaMigrationPlugins({ basePlugins: [], cwd: project(APP), servedPlatform: {} }); + expect(control.plugins.map((p: any) => p?.constructor?.name)).not.toContain('KnowledgeServicePlugin'); + }, 60_000); + it('a provider the host already supplies wins, as under `serve` — never a second instance', async () => { process.env.OS_AUTH_SECRET = SECRET; const dir = project([ diff --git a/packages/cli/src/utils/schema-migration-plugins.ts b/packages/cli/src/utils/schema-migration-plugins.ts index 3de228231d1..bd65292c0c8 100644 --- a/packages/cli/src/utils/schema-migration-plugins.ts +++ b/packages/cli/src/utils/schema-migration-plugins.ts @@ -1964,7 +1964,7 @@ async function composeServedPlatform(input: { */ serveFlags?: { readonly dev?: boolean; readonly preset?: string }; }): Promise<{ authFamily: unknown[]; plugins: unknown[]; notes: string[] }> { - const { CAPABILITY_PROVIDERS, providesCapability, resolveServedCapabilities } = await import('@objectstack/core'); + const { CAPABILITY_PROVIDERS, providesCapability, resolveServedCapabilities, stackItemCapabilities } = await import('@objectstack/core'); const config = input.config ?? {}; // `serve`'s `requires` — the rule {@link composeAuthGatedSecurity} states. const requires = !isHostConfig(config) && Array.isArray(input.artifactRequires) @@ -2038,7 +2038,10 @@ async function composeServedPlatform(input: { } return composeProviderForDeclarations(new Ctor() as object); }; - for (const token of resolveServedCapabilities(requires).tokens) { + // [ADR-0161 K8 item 12] The tokens the stack's items mount (a shipped + // `knowledge_source` mounts `knowledge`), read off the same config `serve` + // reads them from (`stackItemCapabilities`), so both boots compose one set. + for (const token of resolveServedCapabilities(requires, { itemTokens: stackItemCapabilities(config) }).tokens) { const spec = CAPABILITY_PROVIDERS[token]; // A tier token (`auth`, `ui`, `i18n`, `ai`) or one no open package // provides mounts nothing in `serve`'s resolver either. diff --git a/packages/core/src/capability-composition.test.ts b/packages/core/src/capability-composition.test.ts index ca55146b91a..c5df0f0e54b 100644 --- a/packages/core/src/capability-composition.test.ts +++ b/packages/core/src/capability-composition.test.ts @@ -10,12 +10,13 @@ import { afterEach, describe, expect, it } from 'vitest'; import { composeStacks, defineStack } from '@objectstack/spec'; -import { PLATFORM_ALWAYS_ON_CAPABILITIES } from '@objectstack/spec/kernel'; +import { PLATFORM_ALWAYS_ON_CAPABILITIES, PLATFORM_CAPABILITY_PROVIDERS } from '@objectstack/spec/kernel'; import { resolveCapabilityArgument, resolveCapabilityExtras, resolveKnowledgeStore, resolveServedCapabilities, + stackItemCapabilities, } from './capability-composition.js'; import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js'; import { stackDeclaredCapabilities } from './stack-collections.js'; @@ -318,3 +319,52 @@ describe('resolveCapabilityExtras — what a boot mounts after a main provider', expect(CAPABILITY_PROVIDERS.knowledge.extras).toBeUndefined(); }); }); + +/** + * [ADR-0161 K8 item 12] A `knowledge_source` item mounts the knowledge + * service and the deployment's store, through the token's own provider row; + * and [K4 ◆] the service is told which store is the deployment's. + */ +describe("stackItemCapabilities — a stack's items mount their reader", () => { + const SOURCE = { name: 'ccp_notes', label: 'Notes', source: { kind: 'object', object: 'ccp_note', content: ['name'] } }; + + it('a stack holding a knowledge source mounts `knowledge`, at the top level or in a package body; none, nothing', () => { + expect(stackItemCapabilities({ knowledgeSources: [SOURCE] })).toEqual(['knowledge']); + const multi = twoPackages({ knowledgeSources: [SOURCE] }); + // Anti-vacuity: the producer really left the source out of the top level. + expect(multi.knowledgeSources).toBeUndefined(); + expect(stackItemCapabilities(multi)).toEqual(['knowledge']); + expect(stackItemCapabilities(twoPackages({}))).toEqual([]); + expect(stackItemCapabilities({ knowledgeSources: [] })).toEqual([]); + expect(stackItemCapabilities({})).toEqual([]); + }); + + it('is read off the spec provider row — one row today, the knowledge one', () => { + const rows = Object.entries(PLATFORM_CAPABILITY_PROVIDERS).filter(([, row]) => row.mountedBy !== undefined); + expect(rows).toEqual([['knowledge', expect.objectContaining({ mountedBy: { collection: 'knowledgeSources' } })]]); + }); + + it('an item token is declared (required), mounted after the declared ones, and reported as the items\' own', () => { + const served = resolveServedCapabilities(['automation'], { itemTokens: ['knowledge'] }); + expect(served.tokens.slice(0, 2)).toEqual(['automation', 'knowledge']); + expect(served.declared.has('knowledge')).toBe(true); + expect([...served.byItems]).toEqual(['knowledge']); + // Listed under `requires` as well: the requirement is the author's, not the items'. + const both = resolveServedCapabilities(['knowledge'], { itemTokens: ['knowledge'] }); + expect(both.tokens.filter((token) => token === 'knowledge')).toEqual(['knowledge']); + expect([...both.byItems]).toEqual([]); + }); + + it("the knowledge service is constructed with the deployment's store: the adapter id of the store the extras mount", () => { + const pg = { stack: {}, packageRoot: '/app', database: { driver: 'postgres', url: 'postgres://db/app' } }; + const file = { stack: {}, packageRoot: '/app', database: { driver: 'sqlite', url: 'file:/app/.objectstack/data/objectstack.db' } }; + for (const input of [pg, file]) { + const { argument } = resolveCapabilityArgument('knowledge', input); + const [store] = resolveCapabilityExtras('knowledge', input); + expect(argument).toEqual({ deploymentAdapter: resolveKnowledgeStore(input).store.adapterId }); + expect(store?.pkg).toBe(resolveKnowledgeStore(input).store.pkg); + } + expect(resolveCapabilityArgument('knowledge', pg).argument).toEqual({ deploymentAdapter: 'pgvector' }); + expect(resolveCapabilityArgument('knowledge', file).argument).toEqual({ deploymentAdapter: 'turso' }); + }); +}); diff --git a/packages/core/src/capability-composition.ts b/packages/core/src/capability-composition.ts index 9ab2d2eb723..d7580ee8bfb 100644 --- a/packages/core/src/capability-composition.ts +++ b/packages/core/src/capability-composition.ts @@ -57,7 +57,7 @@ * readers: importing this module loads nothing. */ -import { PLATFORM_ALWAYS_ON_CAPABILITIES } from '@objectstack/spec/kernel'; +import { PLATFORM_ALWAYS_ON_CAPABILITIES, PLATFORM_CAPABILITY_PROVIDERS } from '@objectstack/spec/kernel'; import { readEnvWithDeprecation } from '@objectstack/types'; import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js'; import type { CapabilityIdentities, KnowledgeStoreSpec } from './capability-providers.js'; @@ -76,8 +76,31 @@ export interface ServedCapabilities { * The tokens the stack itself declares — the "required" intent * (#1597): under `serve` a declared token whose provider cannot be provided * is a hard boot error, where a token the platform appended is best-effort. + * A token the stack's items mount ({@link stackItemCapabilities}) is + * declared too: the items ask for their reader as `requires` would. */ readonly declared: ReadonlySet; + /** The declared tokens the stack's items mount and its `requires` does not list. */ + readonly byItems: ReadonlySet; +} + +/** + * [ADR-0161 K8, item 12] The capability tokens the stack's ITEMS mount: each + * token whose provider row in `PLATFORM_CAPABILITY_PROVIDERS` + * (`@objectstack/spec`) names a `mountedBy` collection the stack holds an item + * of — the top level, then each package body (`resolveStackCollection`). Today + * one row: `knowledge`, by `knowledgeSources`, so a stack shipping a + * `knowledge_source` is served the knowledge service and the deployment's + * store without `requires: ['knowledge']`. Through the same provider entry as + * the token: the item adds the token, and the token's row mounts the provider. + */ +export function stackItemCapabilities(stack: unknown): string[] { + const tokens: string[] = []; + for (const [token, row] of Object.entries(PLATFORM_CAPABILITY_PROVIDERS)) { + const collection = row.mountedBy?.collection; + if (collection !== undefined && resolveStackCollection(stack, collection).length > 0) tokens.push(token); + } + return tokens; } /** @@ -120,9 +143,20 @@ export function resolveServedCapabilities( readonly preset?: string; /** The host's process-level default tokens, appended before the slate. */ readonly hostDefaults?: readonly string[]; + /** + * The tokens the stack's items mount ({@link stackItemCapabilities}), + * appended after the declared ones and read as declared. + */ + readonly itemTokens?: readonly string[]; } = {}, ): ServedCapabilities { const tokens = [...new Set(declaredTokens)]; + const byItems = new Set(); + for (const token of opts.itemTokens ?? []) { + if (tokens.includes(token)) continue; + tokens.push(token); + byItems.add(token); + } const declared: ReadonlySet = new Set(tokens); if (tokens.includes('auth') && !tokens.includes('email')) tokens.push('email'); for (const token of opts.hostDefaults ?? []) { @@ -137,7 +171,7 @@ export function resolveServedCapabilities( if (!tokens.includes('queue')) tokens.unshift('queue'); if (!tokens.includes('job')) tokens.unshift('job'); } - return { tokens, declared }; + return { tokens, declared, byItems }; } /** What {@link resolveCapabilityArgument} reads to build one provider's argument. */ @@ -222,6 +256,13 @@ function providerReader( * and on a configuration the schema refuses, an inline secret included. * - `storage`: the local adapter at {@link resolveStorageLocalRootEnv}'s root, * else `.objectstack/data/uploads` ({@link resolveStorageCapabilityArg}). + * - `knowledge`: `{ deploymentAdapter }`, the adapter id of the store + * {@link resolveKnowledgeStore} chooses and {@link resolveCapabilityExtras} + * mounts beside the service — the deployment's-store mark (ADR-0161 K4): a + * source that names no adapter binds to it. A service option, not an + * adapter-contract member; the store itself is told nothing. Read from the + * same {@link CapabilityArgumentInput.database} as the store's choice, so + * the two agree. * - any other token: no argument. * * A throw is the boot's to report: whether it fails the boot or is logged is @@ -253,6 +294,9 @@ export function resolveCapabilityArgument(token: string, input: CapabilityArgume const storage = resolveStorageCapabilityArg(resolveStorageLocalRootEnv()); return { argument: storage.options, localStorageRoot: storage.localRoot }; } + if (token === 'knowledge') { + return { argument: { deploymentAdapter: resolveKnowledgeStore(input).store.adapterId } }; + } return { argument: undefined }; } diff --git a/packages/core/src/capability-providers.ts b/packages/core/src/capability-providers.ts index ff4f6a7d927..c2ce6b48376 100644 --- a/packages/core/src/capability-providers.ts +++ b/packages/core/src/capability-providers.ts @@ -245,8 +245,10 @@ export const CAPABILITY_PROVIDERS: Readonly> = { 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, + // Requested, never always-on: the token mounts it, and so does a + // `knowledge_source` item in the stack (K8 item 12: `mountedBy` on the spec + // row, read by `stackItemCapabilities`); without either, 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 @@ -263,7 +265,12 @@ export type KnowledgeStoreSpec = { pkg: string; export: string; identities: CapabilityIdentities; - /** The adapter id the store registers: the value a `KnowledgeSource.adapter` names. */ + /** + * The adapter id the store registers: the value a `KnowledgeSource.adapter` + * names, and the one the service is handed as the deployment's + * (`deploymentAdapter`, `resolveCapabilityArgument`), so a source that + * names no adapter binds to this store (ADR-0161 K4). + */ adapterId: string; /** * The package is an optional dependency of the CLI and of the verification diff --git a/packages/runtime/src/domains/mcp-authoring.test.ts b/packages/runtime/src/domains/mcp-authoring.test.ts index add1ea37bb0..0e566776fb7 100644 --- a/packages/runtime/src/domains/mcp-authoring.test.ts +++ b/packages/runtime/src/domains/mcp-authoring.test.ts @@ -1035,6 +1035,15 @@ describe('[ADR-0161 K4] save_metadata_draft asks the knowledge service to admit expect(caller).toMatchObject({ userId: 'u1', isSystem: false, systemPermissions: BOTH }); }); + it('[ADR-0161 K4] a source refused 400 VALIDATION_ERROR keeps its code and status, and nothing is written', async () => { + const message = "The knowledge source 'faq' was not saved: it names no adapter, and 2 adapters are registered (a, b) with none the deployment's store."; + const admitAuthoredSource = vi.fn(async () => ({ admitted: false, status: 400, code: 'VALIDATION_ERROR', message })); + const { authoring, served } = await authorThroughDomain({ systemPermissions: BOTH, knowledge: { admitAuthoredSource } }); + const refused = await save(authoring); + expect(refused.body.error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400, message }); + expect(served.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]); + }); + it('fails closed: a verdict that throws is 503 SERVICE_UNAVAILABLE, and nothing is written', async () => { const knowledge = { admitAuthoredSource: async () => { throw new Error('registry unavailable'); } }; const { authoring, served } = await authorThroughDomain({ systemPermissions: BOTH, knowledge }); diff --git a/packages/runtime/src/domains/mcp-authoring.ts b/packages/runtime/src/domains/mcp-authoring.ts index 5fcfc5885f5..5517fc51955 100644 --- a/packages/runtime/src/domains/mcp-authoring.ts +++ b/packages/runtime/src/domains/mcp-authoring.ts @@ -680,7 +680,11 @@ function openWriter( }); if (!refused) return undefined; return { - code: refused.status === 403 ? PERMISSION_DENIED : SERVICE_UNAVAILABLE, + // A 403 is spelled in this door's vocabulary; any other verdict + // keeps its own ADR-0112 code, so a `400 VALIDATION_ERROR` (a + // source that names no adapter where none can hold it, + // ADR-0161 K4) arrives as one, as on the REST door. + code: refused.status === 403 ? PERMISSION_DENIED : (refused.code as ErrorCode), message: refused.message, status: refused.status, }; diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts index 4a167259a2f..e227a70d345 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts @@ -412,6 +412,29 @@ describe('buildSourcesAtBoot — the first build', () => { expect(service.buildRecord('kb')).toMatchObject({ status: 'done' }); }); + it('[ADR-0161 K4] a source that names no adapter is built at boot on the one it is placed on; one that cannot be placed is left to the reading', async () => { + const db = makeEngine(ROWS); + const { adapter, calls } = makeAdapter(); + const { service } = makeService(db.engine, adapter); + const { adapter: other } = makeAdapter(); + const { adapter: unnamed } = makeAdapter(); + service.registerSource(source({ adapter: undefined })); + + await service.buildSourcesAtBoot(); + expect(service.adapterIdFor(service.describeSources()[0]!.source)).toBe('memory'); + expect(service.buildRecord('kb')).toMatchObject({ trigger: 'boot', status: 'done', result: { ok: true, indexed: 3 } }); + expect(calls.upserted).toBe(3); + + // A second node where two adapters arrived after the source and none is the deployment's: + // the pass builds nothing for it, and the reading names it. + const second = makeService(db.engine, other); + second.service.registerSource(source({ adapter: undefined })); + second.service.registerAdapter('app_store', unnamed); + await second.service.buildSourcesAtBoot(); + expect(second.service.buildRecord('kb')).toBeUndefined(); + expect(second.service.reportUnmountedAdapters()).toEqual(['kb']); + }); + it('a source with refresh.onRecordChange: false is left to its external indexer', async () => { const db = makeEngine(ROWS); const { adapter, calls } = makeAdapter(); @@ -601,6 +624,23 @@ describe('reconcileSources — which sources the reconcile walks (ADR-0161 K1)', expect(said[0]).toContain('os knowledge rebuild'); }); + it('[ADR-0161 K4] reads the store a source that names no adapter is placed on: one that lists no documents is left, one that does is walked', async () => { + const db = makeEngine(ROWS); + const { adapter, calls } = makeAdapter({ omit: ['listDocuments'] }); + const { service } = makeService(db.engine, adapter); + service.registerSource(source({ adapter: undefined })); + const report = await service.reconcileSources(); + expect(report.sources[0]).toMatchObject({ sourceId: 'kb', left: expect.stringContaining('no listDocuments') }); + expect(calls).toMatchObject({ beginBuild: 0, upserted: 0 }); + + const listing = makeAdapter(); + const walked = makeService(db.engine, listing.adapter); + walked.service.registerSource(source({ adapter: undefined })); + await walked.service.reconcileSources(); + expect(walked.service.buildRecord('kb')).toMatchObject({ trigger: 'reconcile', status: 'done' }); + expect(listing.calls.upserted).toBe(3); + }); + it('leaves a source with refresh.onRecordChange: false to its external indexer', async () => { const db = makeEngine(ROWS); const { adapter, calls } = makeAdapter(); 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 eacf94daee9..c1a0c5a8c60 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -2323,3 +2323,118 @@ describe('KnowledgeService — a source naming an adapter that is not mounted', } }); }); + +/** + * [ADR-0161 K4 ◆] A source that names no `adapter` binds to the deployment's + * adapter — the store the runtime marked when it mounted it + * (`deploymentAdapter`) — else to the only adapter registered. Several + * registered and none the deployment's: refused at registration, naming them. + */ +describe('KnowledgeService — a source that names no adapter (the deployment\'s store)', () => { + const ec = { positions: [], permissions: [], isSystem: true }; + /** `objectSource` with its `adapter` left out, as an author may now write it. */ + function unnamed(id: string, object = 'task'): KnowledgeSource { + const { adapter: _omitted, ...source } = objectSource(id, object); + return source as KnowledgeSource; + } + + it('binds to the deployment\'s store when the runtime marked one, beside an adapter application code registered', async () => { + const deployment = makeAdapter('turso'); + const app = makeAdapter('memory'); + const svc = new KnowledgeService({ deploymentAdapter: 'turso' }); + svc.registerAdapter('memory', app); + svc.registerAdapter('turso', deployment); + svc.registerSource(unnamed('s1')); + expect(svc.adapterIdFor(svc.getSource('s1')!)).toBe('turso'); + await svc.search('q', { sourceIds: ['s1'], executionContext: ec }); + expect(deployment.searchSpy).toHaveBeenCalledOnce(); + expect(app.searchSpy).not.toHaveBeenCalled(); + await svc.handleRecordUpsert('task', { id: 'r1', title: 'T', notes: 'N' }); + expect(deployment.upsertSpy).toHaveBeenCalledOnce(); + expect(app.upsertSpy).not.toHaveBeenCalled(); + }); + + it('a named adapter is kept as named, whatever the deployment\'s store is', async () => { + const deployment = makeAdapter('turso'); + const app = makeAdapter('memory'); + const svc = new KnowledgeService({ deploymentAdapter: 'turso' }); + svc.registerAdapter('turso', deployment); + svc.registerAdapter('memory', app); + svc.registerSource(objectSource('s1', 'task', 'memory')); + await svc.search('q', { sourceIds: ['s1'], executionContext: ec }); + expect(app.searchSpy).toHaveBeenCalledOnce(); + expect(deployment.searchSpy).not.toHaveBeenCalled(); + }); + + it('with no mark, binds to the only adapter registered — placed where it is used, so a store registering after the source is found', async () => { + const svc = new KnowledgeService(); + // A source registered in code at init(), before any store's start(). + svc.registerSource(unnamed('s1')); + const only = makeAdapter('memory'); + svc.registerAdapter('memory', only); + await svc.search('q', { sourceIds: ['s1'], executionContext: ec }); + expect(only.searchSpy).toHaveBeenCalledOnce(); + }); + + it('two adapters registered by application code and none the deployment\'s: refused at registration, naming both', () => { + const svc = new KnowledgeService(); + svc.registerAdapter('memory', makeAdapter('memory')); + svc.registerAdapter('pgvector', makeAdapter('pgvector')); + let refused: unknown; + try { + svc.registerSource(unnamed('s1')); + } catch (err) { + refused = err; + } + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("source 's1' names no adapter, and 2 adapters are registered (memory, pgvector)"); + expect(svc.getSource('s1')).toBeUndefined(); + // The metadata door refuses the same way. + expect(() => svc.registerMetadataSource(unnamed('s2'))).toThrow(/Name one of 'memory', 'pgvector'/); + expect(svc.getSource('s2')).toBeUndefined(); + }); + + it('two adapters registered after the source, none the deployment\'s: the search refuses it with the same code, naming both', async () => { + const svc = new KnowledgeService(); + svc.registerSource(unnamed('s1')); + svc.registerAdapter('memory', makeAdapter('memory')); + svc.registerAdapter('pgvector', makeAdapter('pgvector')); + // The only source asked for cannot be searched, so the search answers its refusal. + const refused = await svc.search('q', { sourceIds: ['s1'], executionContext: ec }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain('2 adapters are registered (memory, pgvector)'); + expect(svc.reportUnmountedAdapters()).toEqual(['s1']); + }); + + it('the deployment\'s store marked but not mounted, and nothing else: SERVICE_UNAVAILABLE naming the store', async () => { + const svc = new KnowledgeService({ deploymentAdapter: 'turso' }); + svc.registerSource(unnamed('s1')); + expect(() => svc.adapterFor(svc.getSource('s1')!)).toThrow(/the deployment's store 'turso' is not mounted/); + const refused = await svc.search('q', { sourceIds: ['s1'], executionContext: ec }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + }); + + it('the save of an unplaceable source is refused to its author, naming the adapters', async () => { + const svc = new KnowledgeService({ dataEngine: {} as IDataEngine }); + svc.registerAdapter('memory', makeAdapter('memory')); + svc.registerAdapter('pgvector', makeAdapter('pgvector')); + const verdict = await svc.admitAuthoredSource(unnamed('s1'), { userId: 'u1', positions: [], permissions: [] } as never); + expect(verdict).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 }); + expect((verdict as { message: string }).message).toContain("Name one of 'memory', 'pgvector'"); + }); + + it('KnowledgeServicePlugin hands its `deploymentAdapter` option to the service', async () => { + const kernel = new LiteKernel(); + await kernel.use(new KnowledgeServicePlugin({ deploymentAdapter: 'turso', enableEventSync: false, buildAtBoot: false })); + await kernel.bootstrap(); + try { + const svc = kernel.getService('knowledge'); + svc.registerAdapter('memory', makeAdapter('memory')); + svc.registerAdapter('turso', makeAdapter('turso')); + svc.registerSource(unnamed('s1')); + expect(svc.adapterIdFor(svc.getSource('s1')!)).toBe('turso'); + } finally { + await kernel.shutdown(); + } + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-build-actions.ts b/packages/services/service-knowledge/src/knowledge-build-actions.ts index 58b3bdfe893..fc3db121691 100644 --- a/packages/services/service-knowledge/src/knowledge-build-actions.ts +++ b/packages/services/service-knowledge/src/knowledge-build-actions.ts @@ -40,7 +40,7 @@ export const KNOWLEDGE_INDEX_STATUS_ACTION = 'index_status'; /** The part of `KnowledgeService` the two actions use. */ export type KnowledgeBuildActionsService = Pick< KnowledgeService, - 'describeSources' | 'describeSource' | 'readIndexState' | 'rebuildSource' | 'buildRecord' + 'describeSources' | 'describeSource' | 'readIndexState' | 'rebuildSource' | 'buildRecord' | 'boundAdapterId' >; /** One source in an `index_status` answer. */ @@ -48,7 +48,11 @@ export interface KnowledgeIndexStatusEntry { /** The source, as `search_knowledge` lists it: `NAMESPACE-NAME` for a package's source, the bare name otherwise. */ id: string; label: string; - adapter: string; + /** + * The adapter the source binds to: the one it names, else the deployment's + * (ADR-0161 K4). Absent when it names none and none can be placed. + */ + adapter?: string; /** The package that holds the source; absent for a source no package holds. */ packageId?: string; /** What the adapter holds against what the service expects. */ @@ -155,10 +159,11 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions } const sources: KnowledgeIndexStatusEntry[] = []; for (const source of targets) { + const adapter = service.boundAdapterId(source.source); sources.push({ id: source.id, label: source.source.label, - adapter: source.source.adapter, + ...(adapter === undefined ? {} : { adapter }), ...(source.packageId === undefined ? {} : { packageId: source.packageId }), index: await service.readIndexState(source.id), build: service.buildRecord(source.id) ?? null, diff --git a/packages/services/service-knowledge/src/knowledge-reap-guard.ts b/packages/services/service-knowledge/src/knowledge-reap-guard.ts index 2aa93eeccd0..cfdfdae64f3 100644 --- a/packages/services/service-knowledge/src/knowledge-reap-guard.ts +++ b/packages/services/service-knowledge/src/knowledge-reap-guard.ts @@ -25,7 +25,7 @@ type ReapGuard = ( * each source as its adapter is handed it — `name` is its index key — which * is what a document id is built from and what the adapter's context carries. */ -type KnowledgeReapGuardService = Pick; +type KnowledgeReapGuardService = Pick; /** * Reap guard that DE-INDEXES a row before the platform lifecycle sweep deletes @@ -84,7 +84,7 @@ export function createKnowledgeReapGuard( let deIndexed = true; for (const source of targets) { try { - const adapter = service.getAdapter(source.adapter); + const adapter = service.adapterFor(source); await adapter.delete([documentIdFor(source.name, recordId)], { source, // Declared free-form diagnostics tag on the EXISTING diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 2be6d530304..735f14e926d 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -369,6 +369,17 @@ export interface KnowledgeServicePluginOptions { * @default true */ buildAtBoot?: boolean; + /** + * [ADR-0161 K4 ◆] The deployment's adapter: the id of the store the runtime + * mounts beside this plugin for the `knowledge` capability. Set by the + * runtime's capability composition (`resolveCapabilityArgument` in + * `@objectstack/core`, read by `os serve` and `@objectstack/verify`), which + * constructs this plugin and the store together; a host that mounts the + * plugin itself leaves it unset. A source that names no `adapter` binds to + * it (`KnowledgeServiceOptions.deploymentAdapter`). A service option, never + * an adapter-contract member. + */ + deploymentAdapter?: string; /** * The reconcile (ADR-0161 K1: "a reconcile pass keeps it correct"; * `KnowledgeService.reconcileSources`): one job on the platform's job @@ -498,6 +509,7 @@ export class KnowledgeServicePlugin implements Plugin { dataEngine: engine, logger, defaultTopK: this.options.defaultTopK, + ...(this.options.deploymentAdapter === undefined ? {} : { deploymentAdapter: this.options.deploymentAdapter }), // The field gate's `security` service, resolved per search so plugin // order is free (plugin-security registers it in its own start()). // Only a GENUINE absence reads as "no security service" (the contract's diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index d6cff267157..3fb05548b72 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -100,6 +100,20 @@ export interface KnowledgeServiceOptions { dataEngine?: IDataEngine; /** Optional structured logger. */ logger?: KnowledgeLogger; + /** + * [ADR-0161 K4 ◆] The deployment's adapter: the id of the store the + * runtime mounted beside this service for the `knowledge` capability + * (`pgvector` on PostgreSQL, `turso` otherwise — `resolveCapabilityArgument` + * in `@objectstack/core` sets it on the plugin it constructs). A source + * that names no `adapter` binds to it while an adapter of that id is + * registered. Only the runtime that mounts the store sets it: an adapter + * application code registers is never the deployment's by registering + * (`registerAdapter` takes no such mark). A service option, not an + * adapter-contract member (ADR-0161 K8, "What counts as a member"). + * Omitted (a host that mounts the service itself), a source that names + * no adapter binds to the only adapter registered. + */ + deploymentAdapter?: string; /** * The `security` service, resolved at search time, for the field gate * (`knowledge-source-admission.ts`). Answers `undefined` when the host @@ -226,6 +240,60 @@ export class KnowledgeService implements IKnowledgeService { return adapter; } + /** + * The id of the adapter `source` binds to, read now (ADR-0161 K4 ◆): + * + * 1. the `adapter` the source names — mounted or not: a named adapter that + * is not mounted is {@link getAdapter}'s refusal; + * 2. else the deployment's adapter ({@link KnowledgeServiceOptions.deploymentAdapter}), + * while an adapter of that id is registered; + * 3. else the only adapter registered. + * + * With none registered, throws `503 SERVICE_UNAVAILABLE`; with several and + * none the deployment's, `400 VALIDATION_ERROR` naming them, as the source's + * registration is refused ({@link refuseUnplacedSource}). Never cached: + * adapters register in their plugins' `start()`, after a source registered + * in code at `init()`, so the answer is taken where it is used. + */ + adapterIdFor(source: KnowledgeSource): string { + if (source.adapter !== undefined) return source.adapter; + const deployment = this.options.deploymentAdapter; + if (deployment !== undefined && this.adapters.has(deployment)) return deployment; + const registered = this.listAdapters(); + if (registered.length === 1) return registered[0]!; + if (registered.length === 0) throw noAdapterMountedError(this.label(source), deployment); + throw unplacedSourceError(this.label(source), registered); + } + + /** The adapter `source` binds to ({@link adapterIdFor}), registered; throws the coded refusal otherwise. */ + adapterFor(source: KnowledgeSource): IKnowledgeAdapter { + return this.getAdapter(this.adapterIdFor(source)); + } + + /** {@link adapterIdFor}, or `undefined` where it refuses: for a log line or a status answer. */ + boundAdapterId(source: KnowledgeSource): string | undefined { + try { + return this.adapterIdFor(source); + } catch { + return undefined; + } + } + + /** + * Refuse, at registration, a source that names no adapter where the answer + * cannot become one: several adapters are registered and the runtime marked + * none the deployment's (ADR-0161 K4 ◆). With a mark, or with one adapter + * or none registered yet, the source is taken and placed where it is used: + * a store registers in its own `start()`, after a source registered at + * `init()`, so "none yet" is no verdict (AGENTS.md, startup registry reads). + */ + private refuseUnplacedSource(source: KnowledgeSource, door: string): void { + if (source.adapter !== undefined || this.options.deploymentAdapter !== undefined) return; + const registered = this.listAdapters(); + if (registered.length < 2) return; + throw unplacedSourceError(source.name, registered, ` ${door} did not register it.`); + } + /** * Say once, at `error`, which registered sources name an adapter nothing * registered — the boot's reading, taken by the plugin at @@ -235,15 +303,28 @@ export class KnowledgeService implements IKnowledgeService { */ reportUnmountedAdapters(): string[] { const mounted = this.listAdapters(); - const unmounted = this.describeSources().filter(({ source }) => !this.adapters.has(source.adapter)); - for (const { id, source } of unmounted) { + const named: string[] = []; + for (const { id, source } of this.describeSources()) { + if (source.adapter === undefined) { + // [ADR-0161 K4 ◆] A source that names no adapter, which this boot + // cannot place: no adapter at all, or several and none the deployment's. + try { + this.adapterIdFor(source); + } catch (err) { + this.options.logger?.error?.(`${errorText(err)} Indexing and searching it answer that refusal.`); + named.push(id); + } + continue; + } + if (this.adapters.has(source.adapter)) continue; this.options.logger?.error?.( `[knowledge] 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.`, ); + named.push(id); } - return unmounted.map(({ id }) => id); + return named; } listAdapters(): string[] { @@ -277,6 +358,7 @@ export class KnowledgeService implements IKnowledgeService { `[knowledge] registerSource refused the source${describeName(source)}: ${parsed.message}`, ); } + this.refuseUnplacedSource(parsed.source, 'registerSource'); const packageId = packageIdOfItem(parsed.source); if (packageId !== undefined) { throw codedError( @@ -289,7 +371,7 @@ export class KnowledgeService implements IKnowledgeService { } const { entry, replaced } = this.registry.register(parsed.source, 'code'); if (replaced) this.options.logger?.warn?.(`[knowledge] source overwritten: ${entry.face}`); - this.options.logger?.info?.(`[knowledge] source registered: ${entry.face} (adapter=${entry.authored.adapter})`); + this.options.logger?.info?.(`[knowledge] source registered: ${entry.face} (adapter=${this.adapterLabel(entry.authored)})`); this.sourcesChanged(); } @@ -302,9 +384,10 @@ export class KnowledgeService implements IKnowledgeService { * caller holding `IKnowledgeService`. */ registerMetadataSource(source: KnowledgeSource, holder: KnowledgeSourceHolder = {}): KnowledgeSourceEntry { + this.refuseUnplacedSource(source, 'The knowledge_source loader'); const { entry, replaced } = this.registry.register(source, 'metadata', holder); this.options.logger?.info?.( - `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${entry.authored.adapter}` + + `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + `${entry.packageId === undefined ? '' : `, package=${entry.packageId}`})`, ); this.sourcesChanged(); @@ -371,20 +454,27 @@ export class KnowledgeService implements IKnowledgeService { async dropMetadataSource(key: string): Promise { const entry = this.registry.byIndexKey(key); if (!entry || entry.door !== 'metadata') return undefined; + // Placed before the entry is forgotten: an unnamed adapter is placed + // among the adapters registered now, as every other use places it. + const adapterId = this.boundAdapterId(entry.handed); this.forget(entry); const kept = (why: string): void => { this.options.logger?.warn?.( `[knowledge] source '${entry.face}' was removed, and its index was not dropped: ${why} ` + - `What adapter '${entry.authored.adapter}' holds under the key '${entry.key}' stays until it is removed there.`, + `What adapter '${adapterId ?? this.adapterLabel(entry.authored)}' holds under the key '${entry.key}' stays until it is removed there.`, ); }; - const adapter = this.adapters.get(entry.authored.adapter); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); if (!adapter) { - kept(`adapter '${entry.authored.adapter}' is not mounted.`); + kept( + adapterId === undefined + ? 'it names no adapter, and none could be placed for it.' + : `adapter '${adapterId}' is not mounted.`, + ); return entry; } if (typeof adapter.dropSource !== 'function') { - kept(`adapter '${entry.authored.adapter}' has no dropSource.`); + kept(`adapter '${adapterId}' has no dropSource.`); return entry; } try { @@ -449,6 +539,13 @@ export class KnowledgeService implements IKnowledgeService { return this.registry.entries().map((entry) => entry.handed); } + /** How a log line names a source's adapter: the one it names, else the one it is placed on now. */ + private adapterLabel(source: KnowledgeSource): string { + if (source.adapter !== undefined) return source.adapter; + const placed = this.boundAdapterId(source); + return placed === undefined ? "the deployment's, not placed yet" : `${placed}, the deployment's`; + } + /** How a log line or an answer names a handed source: its face. */ private label(source: KnowledgeSource): string { return this.faceOfKey(source.name); @@ -636,7 +733,7 @@ export class KnowledgeService implements IKnowledgeService { progress?: (step: KnowledgeBuildProgress) => void, fence?: KnowledgeBuildFence, ): Promise { - const adapter = this.getAdapter(source.adapter); + const adapter = this.adapterFor(source); const engine = this.options.dataEngine; if (!engine) { @@ -1095,7 +1192,7 @@ export class KnowledgeService implements IKnowledgeService { return reading('not-built-here', false, 'no data engine is bound, so the source cannot be walked.'); } try { - const adapter = this.getAdapter(source.adapter); + const adapter = this.adapterFor(source); const plan = await this.planIndex(source, adapter); const ctx = plan.context('reindex'); if (typeof adapter.indexStatus === 'function') { @@ -1402,8 +1499,12 @@ export class KnowledgeService implements IKnowledgeService { // A source whose adapter is not mounted is named once at boot, at // `error`, by the boot's reading (`reportUnmountedAdapters`); the pass // adds no second line for it. On reload no reading runs, so the line - // below is the one that names it. - if (trigger === 'boot' && !this.adapters.has(entry.handed.adapter)) return; + // below is the one that names it. A source that names no adapter and + // cannot be placed is named by the same reading. + if (trigger === 'boot') { + const adapterId = this.boundAdapterId(entry.handed); + if (adapterId === undefined || !this.adapters.has(adapterId)) return; + } const reading = await this.readIndexStateOf(entry); if (reading.due) { logger?.info?.(`[knowledge] source '${entry.face}' is built now: ${reading.detail}`); @@ -1565,7 +1666,8 @@ export class KnowledgeService implements IKnowledgeService { if (!this.options.dataEngine) { return { text: 'no data engine is bound, so the source cannot be walked.', unlisted: false }; } - const adapter = this.adapters.get(entry.authored.adapter); + const adapterId = this.boundAdapterId(entry.handed); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); if (adapter && typeof adapter.listDocuments !== 'function') { return { text: @@ -2072,7 +2174,8 @@ export class KnowledgeService implements IKnowledgeService { let target: Promise | undefined; const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); for (const entry of admitted) { - const adapter = this.adapters.get(entry.source.adapter); + const adapterId = this.boundAdapterId(entry.source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); if (!adapter) { out.push(entry); continue; @@ -2109,12 +2212,17 @@ export class KnowledgeService implements IKnowledgeService { ): Promise> { const out = new Map(); for (const { source, organizationIds, fingerprint, scope } of sources) { - const adapter = this.adapters.get(source.adapter); - if (!adapter) { - // 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())); + // 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. A source that + // names no adapter is placed here, as everywhere (`adapterIdFor`). + let adapterId: string; + let adapter: IKnowledgeAdapter; + try { + adapterId = this.adapterIdFor(source); + adapter = this.getAdapter(adapterId); + } catch (err) { + const coded = codedRefusalOf(err); if (coded !== undefined) refused.push({ sourceId: source.name, ...coded }); continue; } @@ -2136,12 +2244,12 @@ export class KnowledgeService implements IKnowledgeService { const foreign = hits.length - served.length; if (foreign > 0) { this.options.logger?.warn?.( - `[knowledge] adapter '${source.adapter}' answered ${foreign} hit(s) for source '${this.label(source)}' that name ` + + `[knowledge] adapter '${adapterId}' answered ${foreign} hit(s) for source '${this.label(source)}' that name ` + 'another source; dropped — a hit is served only as the source it was searched for.', ); } out.set(source.name, { - hits: scope === undefined ? served : this.checkScope(served, scope, source), + hits: scope === undefined ? served : this.checkScope(served, scope, source, adapterId), answered: hits.length, }); } catch (err) { @@ -2156,7 +2264,7 @@ export class KnowledgeService implements IKnowledgeService { continue; } this.options.logger?.error?.( - `[knowledge] adapter '${source.adapter}' search failed for source '${this.label(source)}': ${(err as Error).message}`, + `[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`, ); } } @@ -2207,14 +2315,19 @@ export class KnowledgeService implements IKnowledgeService { * the rest are dropped, and the first time an adapter's answer loses a hit * here it is reported once, at `warn` ({@link searchRound}). */ - private checkScope(hits: KnowledgeHit[], terms: readonly AdapterScopeTerm[], source: KnowledgeSource): KnowledgeHit[] { + private checkScope( + hits: KnowledgeHit[], + terms: readonly AdapterScopeTerm[], + source: KnowledgeSource, + adapterId: string, + ): KnowledgeHit[] { const inScope = scopeCheck(terms); const kept = hits.filter(inScope); const dropped = hits.length - kept.length; - if (dropped > 0 && !this.scopeIgnoredReported.has(source.adapter)) { - this.scopeIgnoredReported.add(source.adapter); + if (dropped > 0 && !this.scopeIgnoredReported.has(adapterId)) { + this.scopeIgnoredReported.add(adapterId); this.options.logger?.warn?.( - `[knowledge] adapter '${source.adapter}' answered ${dropped} hit(s) for source '${this.label(source)}' outside the ` + + `[knowledge] adapter '${adapterId}' answered ${dropped} hit(s) for source '${this.label(source)}' outside the ` + "search's scope; dropped. The adapter does not apply AdapterSearchOptions.scope before ranking, or answers " + "hits without the document's metadata, so its scoped searches may answer fewer than topK. " + 'Reported once for this adapter.', @@ -2302,7 +2415,7 @@ export class KnowledgeService implements IKnowledgeService { ): Promise { const objSource = source.source; try { - const adapter = this.getAdapter(source.adapter); + const adapter = this.adapterFor(source); const engine = this.options.dataEngine; if (!engine) { if (objSource.where !== undefined) { @@ -2416,7 +2529,7 @@ export class KnowledgeService implements IKnowledgeService { const docId = documentIdFor(source.name, recordId); await this.serializeRecordSync(docId, async () => { try { - const adapter = this.getAdapter(source.adapter); + const adapter = this.adapterFor(source); await adapter.delete([docId], (await this.planIndex(source, adapter)).context('event-sync')); } catch (err) { this.options.logger?.warn?.( @@ -2607,6 +2720,14 @@ export class KnowledgeService implements IKnowledgeService { 'allowed to search what their source indexes. Nothing was written; try again.', ); if (!ctx) return refuse(403, 'PERMISSION_DENIED', `${named}: the save carries no identity, and a missing identity is not a grant of authority.`); + // [ADR-0161 K4 ◆] A source that names no adapter where this deployment + // cannot place one is refused at its save as at its registration, so the + // author hears it: several adapters registered, none the deployment's. + const authoredAdapter = (item as { adapter?: unknown } | null | undefined)?.adapter; + const registeredAdapters = this.listAdapters(); + if (authoredAdapter === undefined && this.options.deploymentAdapter === undefined && registeredAdapters.length > 1) { + return refuse(400, 'VALIDATION_ERROR', `${named}: it ${unplacedSourceText(registeredAdapters)}`); + } const engine = this.options.dataEngine; if (!engine) return unavailable('the knowledge service has no data engine'); @@ -2901,6 +3022,44 @@ function unmountedAdapterError(id: string, mounted: readonly string[]): Error { ); } +/** + * [ADR-0161 K4 ◆] The refusal of a source that names no adapter where no + * adapter is registered: ADR-0112 `SERVICE_UNAVAILABLE` (503), as for a named + * adapter that is not mounted. Names the deployment's store when the runtime + * marked one. + */ +function noAdapterMountedError(source: string, deployment: string | undefined): Error { + return Object.assign( + new Error( + `[knowledge] source '${source}' names no adapter, and no adapter is mounted` + + `${deployment === undefined ? '' : ` (the deployment's store '${deployment}' is not mounted)`}. ` + + "Mount a knowledge store — `requires: ['knowledge']` mounts the deployment's — or name the source's adapter.", + ), + { code: UNMOUNTED_ADAPTER_CODE, status: 503 }, + ); +} + +/** + * [ADR-0161 K4 ◆] The refusal of a source that names no adapter where several + * are registered and none is the deployment's: ADR-0112 `VALIDATION_ERROR` + * (400), naming the choices. The source must say which store holds it. + */ +function unplacedSourceError(source: string, registered: readonly string[], tail = ''): Error { + return Object.assign(new Error(`[knowledge] source '${source}' ${unplacedSourceText(registered)}${tail}`), { + code: 'VALIDATION_ERROR', + status: 400, + }); +} + +/** Why a source that names no adapter cannot be placed among `registered`, and what to write. */ +function unplacedSourceText(registered: readonly string[]): string { + return ( + `names no adapter, and ${registered.length} adapters are registered (${registered.join(', ')}) with none the ` + + "deployment's store, so which one holds its index cannot be told. Name one of " + + `${registered.map((id) => `'${id}'`).join(', ')} as the source's \`adapter\`.` + ); +} + 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/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index 56ebce2f5d4..596140688b3 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -76,6 +76,16 @@ describe('KnowledgeSourceSchema — the one schema of the knowledge_source type' }); }); + it('[ADR-0161 K4 ◆] `adapter` may be omitted — the deployment\'s adapter — and a named one is kept as written', () => { + const { adapter: _named, ...unnamed } = SOURCE; + const parsed = KnowledgeSourceSchema.parse(unnamed); + expect('adapter' in parsed).toBe(false); + expect(parsed.name).toBe('kb_articles'); + expect(KnowledgeSourceSchema.parse(SOURCE).adapter).toBe('memory'); + // Not every value: a non-string adapter is still refused. + expect(issuesOf({ ...SOURCE, adapter: 42 }).map(([code, path]) => [code, path])).toEqual([['invalid_type', 'adapter']]); + }); + it('is the schema the metadata-type registry maps `knowledge_source` to — no second schema', () => { expect(getMetadataTypeSchema('knowledge_source')).toBe(KnowledgeSourceSchema); }); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 0d433e77468..2cde523e7f3 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -261,10 +261,16 @@ export const KnowledgeSourceSchema = lazySchema(() => strictObject( /** Optional description. */ description: z.string().optional(), /** - * Adapter id this source binds to (e.g. `'pgvector'`, `'memory'`). - * Resolved at runtime by `IKnowledgeService.registerAdapter`. + * [ADR-0161 K4] Adapter id this source binds to (e.g. `'pgvector'`, + * `'memory'`), as an adapter registered it + * (`IKnowledgeService.registerAdapter`). Omitted ⇒ the deployment's + * adapter: the store the runtime mounted beside the knowledge service + * (`pgvector` on PostgreSQL, `turso` otherwise), else the only adapter + * registered. With several registered and none the deployment's, an + * omitted adapter is refused, naming the ones registered. */ - adapter: z.string().describe('Adapter id'), + adapter: z.string().optional() + .describe("Adapter id; omitted means the deployment's store (pgvector on PostgreSQL, turso otherwise), else the only adapter registered"), /** * [ADR-0161 K4, K6] Retired: no adapter reads per-source configuration. */ diff --git a/packages/spec/src/kernel/platform-capabilities.ts b/packages/spec/src/kernel/platform-capabilities.ts index d1f0b1bd64b..bfc1f8bff51 100644 --- a/packages/spec/src/kernel/platform-capabilities.ts +++ b/packages/spec/src/kernel/platform-capabilities.ts @@ -81,8 +81,10 @@ export const PLATFORM_CAPABILITY_TOKENS: readonly string[] = Object.freeze([ '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. + // of its own. Requested, never always-on: the token mounts it, and so does a + // `knowledge_source` item in the stack (K8 item 12; the provider row's + // `mountedBy`). Without either, 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 @@ -163,6 +165,14 @@ export interface PlatformCapabilityProvider { * preflight / boot error so the message carries its own context. */ readonly note?: string; + /** + * The stack collection whose items mount this capability as its token + * does: a stack holding one item of it is served as if it listed the token + * under `requires`. Set only where the provider is the items' one reader, + * so an item with no provider would be inert (ADR-0078). Today + * `knowledge`, by `knowledgeSources` (ADR-0161 K8, item 12). + */ + readonly mountedBy?: { readonly collection: string }; } /** @@ -238,7 +248,12 @@ export const PLATFORM_CAPABILITY_PROVIDERS: Readonly { + /** Character bigrams: Chinese text has no spaces to split words on. */ + class BigramEmbedder { + readonly id = 'rqp-bigrams'; + readonly dimensions = 64; + readonly model = 'rqp-bigrams'; + async embed(texts: string[]): Promise { + return texts.map((text) => { + const v = new Array(this.dimensions).fill(0); + const chars = [...text.replace(/\s+/g, '')]; + for (let i = 0; i + 1 < chars.length; i++) { + let h = 0; + for (const ch of chars[i]! + chars[i + 1]!) h = (h * 31 + ch.codePointAt(0)!) >>> 0; + v[h % this.dimensions] += 1; + } + const n = Math.hypot(...v) || 1; + return v.map((x) => x / n); + }); + } + } + /** Application code: the embedder, and an adapter of its own — never the deployment's by registering. */ + class AppStore { + readonly name = 'com.example.rqp.app-store'; + readonly version = '0.0.0'; + readonly type = 'standard'; + readonly searched: string[] = []; + async init(ctx: { registerService(name: string, service: unknown): void }): Promise { + ctx.registerService('embedder', new BigramEmbedder()); + } + async start(ctx: { getService(name: string): T }): Promise { + const searched = this.searched; + ctx.getService<{ registerAdapter(id: string, a: unknown): void }>('knowledge').registerAdapter('rqp_app_store', { + id: 'rqp_app_store', + upsert: async () => undefined, + delete: async () => undefined, + search: async (q: string) => { + searched.push(q); + return []; + }, + }); + } + } + const appStore = new AppStore(); + const source = { name: 'rqp_policies', label: '制度', source: { kind: 'object', object: 'rqp_article', content: ['title', 'body'] } }; + stack = await bootStack(app({ requires: ['realtime'], knowledgeSources: [source] }), { extraPlugins: [appStore] }); + 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().sort()).toEqual(['rqp_app_store', 'turso']); + const [described] = knowledge.describeSources(); + expect(described?.source.adapter).toBeUndefined(); + expect(knowledge.adapterIdFor(described.source)).toBe('turso'); + + const ql = await stack.kernel.getServiceAsync('objectql'); + await ql.insert('rqp_article', { title: '差旅报销制度', body: '出差住宿标准每晚不超过五百元,报销需附发票。' }, { context: { isSystem: true } }); + await ql.insert('rqp_article', { title: '信息安全制度', body: '密码至少十二位,每季度更换一次。' }, { context: { isSystem: true } }); + const ec = { isSystem: true, userId: 'system', roles: [], permissions: [] }; + let hits: Array<{ sourceId: string; snippet: string }> = []; + for (let i = 0; i < 50 && hits.length === 0; i++) { + hits = (await knowledge.searchWithRefusals('住宿标准 报销', { executionContext: ec, sourceIds: [described.id], topK: 1 })).hits; + if (hits.length === 0) await new Promise((r) => setTimeout(r, 50)); + } + expect(hits.map((h) => h.sourceId)).toEqual([described.id]); + expect(hits[0]?.snippet).toContain('住宿标准'); + // The application's adapter was never asked: the source is the deployment's store's. + expect(appStore.searched).toEqual([]); + }, 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(); diff --git a/packages/verify/src/required-providers.ts b/packages/verify/src/required-providers.ts index ccf9b40c3d7..9e2f7521ed0 100644 --- a/packages/verify/src/required-providers.ts +++ b/packages/verify/src/required-providers.ts @@ -17,7 +17,9 @@ // // · WHICH tokens: `resolveServedCapabilities` over the tokens the app // declares as `stackDeclaredCapabilities` reads them (the top-level -// `requires` when the stack carries one, otherwise each package body's) — +// `requires` when the stack carries one, otherwise each package body's) +// and the tokens its items mount (`stackItemCapabilities`: a +// `knowledge_source` mounts `knowledge`) — // `email` for a declared `auth`, the always-on slate // (`PLATFORM_ALWAYS_ON_CAPABILITIES`), and `job` / `queue` ahead of the // tokens that schedule background work. No preset: `bootStack` takes none, @@ -72,11 +74,13 @@ import { type CapabilityDatabase, resolveServedCapabilities, stackDeclaredCapabilities, + stackItemCapabilities, } from '@objectstack/core'; /** Why this boot constructs a provider, as a refusal names it. */ -function reasonFor(token: string, declared: ReadonlySet): string { - return declared.has(token) +function reasonFor(token: string, served: { declared: ReadonlySet; byItems: ReadonlySet }): string { + if (served.byItems.has(token)) return `the stack's items, which mount the '${token}' capability as requires: ['${token}'] does`; + return served.declared.has(token) ? `requires: ['${token}']` : `the always-on '${token}' capability (objectstack serve mounts it for every app)`; } @@ -149,7 +153,13 @@ export async function constructServedProviders(opts: { */ database?: CapabilityDatabase; }): Promise { - const { tokens, declared } = resolveServedCapabilities(stackDeclaredCapabilities(opts.config)); + // [ADR-0161 K8 item 12] A stack that ships a `knowledge_source` mounts the + // knowledge service and the store as `serve` mounts them (`stackItemCapabilities`). + const served = resolveServedCapabilities(stackDeclaredCapabilities(opts.config), { + itemTokens: stackItemCapabilities(opts.config), + }); + const { tokens } = served; + const database = opts.database ?? { driver: 'sqlite-wasm', url: ':memory:' }; const constructed: unknown[] = []; const all = (): unknown[] => [...opts.held, ...constructed]; @@ -157,7 +167,7 @@ export async function constructServedProviders(opts: { const spec = CAPABILITY_PROVIDERS[token]; if (!spec) continue; if (providesCapability(all(), spec.identities)) continue; - const reason = reasonFor(token, declared); + const reason = reasonFor(token, served); constructed.push( await constructProvider({ reason, @@ -168,13 +178,14 @@ export async function constructServedProviders(opts: { stack: opts.config, packageRoot: opts.packageRoot, providerModule: mod, + database, }).argument, }), ); const extras = resolveCapabilityExtras(token, { stack: opts.config, packageRoot: opts.packageRoot, - database: opts.database ?? { driver: 'sqlite-wasm', url: ':memory:' }, + database, }); for (const extra of extras) { if (providesCapability(all(), extra.identities)) continue;