diff --git a/.changeset/38369-knowledge-held-without-embedder-or-store.md b/.changeset/38369-knowledge-held-without-embedder-or-store.md new file mode 100644 index 00000000000..8b776b1b964 --- /dev/null +++ b/.changeset/38369-knowledge-held-without-embedder-or-store.md @@ -0,0 +1,28 @@ +--- +'@objectstack/service-knowledge': minor +'@objectstack/core': patch +'@objectstack/mcp': patch +'@objectstack/spec': patch +--- + +feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a self-hosted deployment whose knowledge service the runtime mounts (the stack declares `requires: ['knowledge']` or ships a `knowledgeSources` entry) and which, at boot, has no embedder or no deployment knowledge store mounted. Such a deployment used to start its boot build, record sync and reconcile job, list `search_knowledge` on MCP, and answer every build and search with an error from a stand-in embedder; a source on a store the application registered was built and searched with no embedder saved. Mounted is not enabled now (ADR-0161 K8, the dated note on item 12): the service is enabled by configuration, read once at `kernel:bootstrapped`, and without both halves every source is held, whichever store it names. + +- **`@objectstack/service-knowledge`.** `KnowledgeServicePlugin` takes `runtimeComposed: { declared }`. When set, the plugin reads the embedder and the deployment store at `kernel:bootstrapped`; without both, `KnowledgeService` holds every source: loaded and listed, never built, synced, reconciled or searched. It hands out no `search_knowledge` definition while the reading is pending or held; `search`, `rebuildSource` and `reindexSource` answer `503` with code `SERVICE_UNAVAILABLE` and a message naming the missing half and the fix; a dropped source keeps its index and no store is called. No lifecycle reap guard registers until the reading is enabled, so a retention sweep deletes rows on time. The boot logs one line: info when only a shipped source mounted the service and nothing was saved, warn when the stack declares `requires: ['knowledge']`, a saved embedder provider builds nothing (a provider saved without its key), or the store is missing. Never a boot refusal. +- **`@objectstack/core`.** The capability composition passes `runtimeComposed: { declared }` with the knowledge service's deployment adapter; `declared` is true only when the stack lists `knowledge` in `requires`. +- **`@objectstack/mcp`.** The stdio transport registers `search_knowledge` at `kernel:listening`, after the reading, only when the service hands out its definition; clients are told by `notifications/tools/list_changed`. A held service is never listed on either transport. +- **`@objectstack/spec`.** The upgrade guide carries the `knowledge-service-held-without-embedder-or-store` entry. + +Unchanged: a knowledge service a host mounts itself (`KnowledgeServicePlugin` in `plugins[]`, no `runtimeComposed`) boots, builds and serves as before; a deployment with both halves builds, syncs and serves as before; stored sources are not rewritten or refused. + +## FROM → TO + +- A deployment with knowledge sources and no embedder → save an embedder provider on the AI settings page (or register an `embedder` service from a plugin), then restart. +- A deployment whose boot says its knowledge store is not mounted → mount that store, then restart. +- An application whose own store embeds without the kernel's embedder → mount `KnowledgeServicePlugin` itself in `plugins[]`. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index d6809c20960..9b10839fd2c 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -34,6 +34,7 @@ Which store is mounted depends on the platform database: - **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** (a retired store such as `ragflow`, or a typo) is refused when it is saved in Studio, over `PUT /meta/knowledge_source` or through MCP: `VALIDATION_ERROR` (400), naming the source, the adapter and the stores that are mounted. A source that leaves `adapter` out is not refused for it. That save check does not reach a package install, a source registered in code or `os validate`; such a source 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)). +- **Mounted is not enabled.** A service the runtime mounts this way is enabled by configuration, read once when the server starts: an embedder (one a plugin registered, or a provider saved in Settings → AI & Embedder that builds one) and the deployment's store mounted. Without both, every source is **held**, whichever store it names: it is listed to administrators and never built, synced, reconciled or searched; `search_knowledge` is not listed on MCP (HTTP or stdio); a search or a rebuild answers `SERVICE_UNAVAILABLE` (503) naming what is missing; no reap guard is registered and no store is called, so a retention sweep deletes rows on time. The boot says it once: at `info` when only a shipped source mounted the service and nothing was saved, at `warn` when the stack declares `requires: ['knowledge']`, a saved provider builds no embedder (one saved without its key) or the store is not mounted. The server always starts. To enable it, save an embedder provider (or mount the store the log names), then restart. A service you mount yourself (below) is not held. - **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. - **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, with the "Test connection" check of those two fields (on PostgreSQL the page shows none of the three), 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. A PostgreSQL deployment that saved the two Turso keys before the group left the page keeps their rows; the settings service never deletes a stored row. To tidy it up, delete the `knowledge` rows named `turso_url` and `turso_auth_token`, and the `sys_secret` row the `turso_auth_token` row's handle names: without the store no API door clears that key, and the row is a decryptable copy of the token. Nothing requires it. @@ -195,7 +196,7 @@ An adapter that reads the scope filters before it ranks, so the `topK` hits all ## The `search_knowledge` tool -An AI client searches through one tool, `search_knowledge`, defined once by the knowledge service. The MCP door (HTTP and stdio) and the in-product agent serve that one definition unchanged, so every client is offered the same arguments and gets the same answer. It searches only sources whose `aiExposed` is not `false`, and reads as the person asking. +An AI client searches through one tool, `search_knowledge`, defined once by the knowledge service. The MCP door (HTTP and stdio) and the in-product agent serve that one definition unchanged, so every client is offered the same arguments and gets the same answer. It searches only sources whose `aiExposed` is not `false`, and reads as the person asking. Where the knowledge service is held (no embedder or no store, [above](#turning-it-on-requires-knowledge)), the tool is not listed at all; on stdio it is registered after the boot reads the service as enabled, and a connected client is told by `notifications/tools/list_changed`. | Argument | What it does | |:--|:--| @@ -230,7 +231,7 @@ When `KnowledgeServicePlugin` is mounted beside the settings service, Settings - **A provider is saved and complete** → an `@objectstack/embedder-openai` embedder for that provider. The saved Base URL applies only to the custom and Azure providers; other providers use their preset endpoint. The boot line names the endpoint host. "Complete" is what the **Test embedder** button checks: a provider, an API key (Ollama excepted) and, for a custom or Azure endpoint, a Base URL. - **Dimensions and batch size are positive integers**, saved as numbers or set as text through an `OS_*` override (`OS_AI_EMBEDDER_DIMENSIONS=256`). A value that is not a positive integer is refused, with a `warn` at boot and the error below on every use — never silently ignored. - **The batch size is passed only when you saved it.** Left unsaved (the form shows 64), the embedder sends as many inputs per request as the model's documented cap allows — 10 for DashScope `text-embedding-v3`, 2048 for OpenAI `text-embedding-3-*` — and 10 for a model it does not know. A saved batch size is held to the saved model's documented cap (`documentedMaxBatchSize(model)` from `@objectstack/embedder-openai`): a saved 64 on `text-embedding-v3` sends 10. For a model without a documented cap the saved size is sent as saved. -- **Nothing is configured** — no provider saved, `none` saved, or the saved settings incomplete → the server still boots, and every use of the embedder answers an error naming the missing settings: an adapter that embeds refuses indexing and search with it, and nothing is sent anywhere. Nothing is sent to a provider until you have saved one, and the API key is never logged or put in an error. +- **Nothing is configured** — no provider saved, `none` saved, or the saved settings incomplete → the server still boots, and every use of the embedder answers an error naming the missing settings: an adapter that embeds refuses indexing and search with it, and nothing is sent anywhere. Where the runtime mounted the service (`requires: ['knowledge']` or a shipped source), its sources are held instead ([above](#turning-it-on-requires-knowledge)): nothing is built or searched, and `search_knowledge` is not listed. Nothing is sent to a provider until you have saved one, and the API key is never logged or put in an error. **A saved change takes effect after a restart** — the page says so under the provider field. There is no hot replacement. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index ae52bbcea19..41676f7ed75 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -188,6 +188,18 @@ the knowledge service and the deployment's store, exactly as in `PLATFORM_CAPABILITY_PROVIDERS`). A host that mounts `KnowledgeServicePlugin` itself keeps its own, and the runtime adds no store. +**Mounted is not enabled** (ADR-0161 K8, the dated note on item 12). A service +the runtime mounted (`runtimeComposed` on the plugin) reads once, at +`kernel:bootstrapped`, whether an embedder is available and whether the +deployment's store is mounted. Without both, every source is held, whichever +store it names: loaded and listed, never built, synced, reconciled or searched; +no `search_knowledge` definition is handed out; `search`, `rebuildSource` and +`reindexSource` answer `503 SERVICE_UNAVAILABLE` naming the missing half; a +removed source keeps its index, and no store is called. The boot logs one line, +`info` when only a shipped source mounted the service and nothing was saved, +`warn` otherwise, and never refuses to start. A change takes effect at the next +restart. A host-mounted service is not read this way and serves from the start. + #### How a source is loaded The knowledge service reads the published `knowledge_source` items when it @@ -1270,7 +1282,9 @@ handled at the source rather than after the fact For every object a source projects, the plugin registers an ADR-0057 **reap guard** with the lifecycle service. The sweep hands the guard the candidate rows before deleting them; the guard deletes each row's document and -returns the ids it confirms. Rows it does not confirm stay put. The guarded +returns the ids it confirms. Rows it does not confirm stay put. A service the runtime mounted registers +no guard until the boot reads it as enabled (above): a held service guards +nothing and calls no store, so the sweep deletes its rows on time. The guarded set follows the sources: a source added after boot for an object with no guard gets one when it is loaded, so a reaped row of that object is de-indexed too. diff --git a/packages/core/src/capability-composition.test.ts b/packages/core/src/capability-composition.test.ts index c5df0f0e54b..8878e160ffa 100644 --- a/packages/core/src/capability-composition.test.ts +++ b/packages/core/src/capability-composition.test.ts @@ -361,10 +361,30 @@ describe("stackItemCapabilities — a stack's items mount their reader", () => { 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(argument).toEqual({ + deploymentAdapter: resolveKnowledgeStore(input).store.adapterId, + runtimeComposed: { declared: false }, + }); expect(store?.pkg).toBe(resolveKnowledgeStore(input).store.pkg); } - expect(resolveCapabilityArgument('knowledge', pg).argument).toEqual({ deploymentAdapter: 'pgvector' }); - expect(resolveCapabilityArgument('knowledge', file).argument).toEqual({ deploymentAdapter: 'turso' }); + expect(resolveCapabilityArgument('knowledge', pg).argument).toEqual({ + deploymentAdapter: 'pgvector', + runtimeComposed: { declared: false }, + }); + expect(resolveCapabilityArgument('knowledge', file).argument).toEqual({ + deploymentAdapter: 'turso', + runtimeComposed: { declared: false }, + }); + }); + + it('[ADR-0161 K8, note on item 12] marks the service runtime-composed, declared only when the stack lists the token', () => { + const database = { driver: 'sqlite', url: 'file:/app/.objectstack/data/objectstack.db' }; + const argumentOf = (stack: unknown) => + resolveCapabilityArgument('knowledge', { stack, packageRoot: '/app', database }).argument as { + runtimeComposed: { declared: boolean }; + }; + // A shipped `knowledge_source` mounts the service (an item token), and is no request for it. + expect(argumentOf({ knowledgeSources: [{ name: 'faq' }] }).runtimeComposed).toEqual({ declared: false }); + expect(argumentOf({ requires: ['knowledge'] }).runtimeComposed).toEqual({ declared: true }); }); }); diff --git a/packages/core/src/capability-composition.ts b/packages/core/src/capability-composition.ts index d7580ee8bfb..16bdec734d8 100644 --- a/packages/core/src/capability-composition.ts +++ b/packages/core/src/capability-composition.ts @@ -61,7 +61,7 @@ import { PLATFORM_ALWAYS_ON_CAPABILITIES, PLATFORM_CAPABILITY_PROVIDERS } from ' import { readEnvWithDeprecation } from '@objectstack/types'; import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js'; import type { CapabilityIdentities, KnowledgeStoreSpec } from './capability-providers.js'; -import { resolveStackCollection } from './stack-collections.js'; +import { resolveStackCollection, stackDeclaredCapabilities } from './stack-collections.js'; type Bag = Record; @@ -256,13 +256,21 @@ 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 + * - `knowledge`: `{ deploymentAdapter, runtimeComposed }` — 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. + * the two agree. Beside it, `runtimeComposed: { declared }`: the service + * was composed by this rule, not mounted by a host, so it is enabled by + * configuration (ADR-0161 K8, the dated note on item 12): at + * `kernel:bootstrapped` it serves only with an embedder and the + * deployment's store, and holds its sources otherwise. `declared` is + * whether the stack lists `requires: ['knowledge']` + * (`stackDeclaredCapabilities`), which raises the not-enabled boot line from + * `info` to `warn`; a stack that mounts the service only by shipping a + * `knowledge_source` leaves it `false`. * - any other token: no argument. * * A throw is the boot's to report: whether it fails the boot or is logged is @@ -295,7 +303,12 @@ export function resolveCapabilityArgument(token: string, input: CapabilityArgume return { argument: storage.options, localStorageRoot: storage.localRoot }; } if (token === 'knowledge') { - return { argument: { deploymentAdapter: resolveKnowledgeStore(input).store.adapterId } }; + return { + argument: { + deploymentAdapter: resolveKnowledgeStore(input).store.adapterId, + runtimeComposed: { declared: stackDeclaredCapabilities(input.stack).includes('knowledge') }, + }, + }; } return { argument: undefined }; } diff --git a/packages/mcp/src/mcp-knowledge-tools.test.ts b/packages/mcp/src/mcp-knowledge-tools.test.ts index dcf7229a999..8569adf8289 100644 --- a/packages/mcp/src/mcp-knowledge-tools.test.ts +++ b/packages/mcp/src/mcp-knowledge-tools.test.ts @@ -24,15 +24,17 @@ * value, and only the scoped records' hits. */ -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, vi, afterEach } from 'vitest'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; -import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; +import { ToolListChangedNotificationSchema, type JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; import { MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE } from '@objectstack/spec/ai'; import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import { assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; import { KnowledgeService, getKnowledgeToolDefinitions, recordToDocument } from '@objectstack/service-knowledge'; import { MCPServerRuntime } from './mcp-server-runtime.js'; +import { MCPServerPlugin } from './plugin.js'; import { SEARCH_KNOWLEDGE_TOOL_NAME, type McpDataBridge } from './mcp-http-tools.js'; import type { McpSkillBridge } from './skill-prompts.js'; import { createStdioDataBridge, type StdioKnowledgeToolsService } from './stdio-data-bridge.js'; @@ -421,3 +423,163 @@ describe('[ADR-0161 K9] search_knowledge over the real definition — every tran expect(stdio.content[0].text).toBe(http.content[0].text); }); }); + +/** + * [ADR-0161 K8, the dated note on item 12] A knowledge service the runtime + * composed is enabled by configuration, read at `kernel:bootstrapped`. Until + * that reading, and while it says not enabled, the service hands out no + * definition, so neither transport lists `search_knowledge`; enabled, both + * do. The stdio transport registers its tools in the MCP plugin's `start()`, + * before the reading, so it registers this one at `kernel:listening`, once + * the reading said enabled — never listed and then withdrawn. A service a + * host mounts serves its definition from the start, as before. + */ +describe('[ADR-0161 K8, note on item 12] search_knowledge follows the enabled reading on both transports', () => { + const originalEnv = { ...process.env }; + afterEach(() => { + process.env = { ...originalEnv }; + vi.restoreAllMocks(); + }); + + const SOURCE: KnowledgeSource = { + name: 'faq', + label: 'FAQ', + source: { kind: 'object', object: 'faq', content: ['body'] } as ObjectKnowledgeSource, + }; + + function service(opts: { runtimeComposed: boolean }): KnowledgeService { + const svc = new KnowledgeService({ + logger: { warn: () => undefined, debug: () => undefined }, + deploymentAdapter: 'memory', + ...(opts.runtimeComposed ? { enabledByConfiguration: true } : {}), + }); + svc.registerAdapter('memory', { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] }); + svc.registerSource(SOURCE); + return svc; + } + + const bridgeOver = (svc: KnowledgeService) => + createStdioDataBridge({ + engine: {} as never, + metadataService: { list: async () => [], getObject: async () => undefined } as never, + resolvePrincipal: async () => ({ userId: 'u_key_owner', isSystem: false }) as never, + knowledgeTools: svc, + }); + + it('over HTTP: absent until the reading, absent when held, listed when enabled', async () => { + const held = service({ runtimeComposed: true }); + expect(knowledgeTool(await listTools(bridgeOver(held)))).toBeUndefined(); + held.settleEnablement({ embedder: 'no provider is saved' }); + expect(knowledgeTool(await listTools(bridgeOver(held)))).toBeUndefined(); + + const enabled = service({ runtimeComposed: true }); + enabled.settleEnablement(undefined); + expect(knowledgeTool(await listTools(bridgeOver(enabled)))).toBeDefined(); + + // A service a host mounts: listed from the start. + expect(knowledgeTool(await listTools(bridgeOver(service({ runtimeComposed: false }))))).toBeDefined(); + }); + + /** The MCP plugin's stdio wiring over a context holding `knowledge`; the boot hooks are fired by hand. */ + async function stdioPlugin(knowledge: KnowledgeService) { + process.env.OS_MCP_STDIO_API_KEY = 'osk_stdio_pin'; + delete process.env.OS_MCP_SERVER_TRANSPORT; + delete process.env.OS_MCP_STDIO_ENABLED; + const hooks = new Map Promise | void>>(); + const services = new Map([ + ['knowledge', knowledge], + ['metadata', { + listObjects: async () => [], getObject: async () => null, get: async () => null, list: async () => [], + exists: async () => false, getRegisteredTypes: async () => ['object'], register: () => undefined, unregister: () => undefined, + }], + ['objectql', { + find: async (object: string, query?: { where?: { id?: string } }) => { + if (object === 'sys_api_key') return [{ id: 'k1', user_id: 'usr_stdio', revoked: false }]; + if (object === 'sys_user') return query?.where?.id === 'usr_stdio' ? [{ id: 'usr_stdio' }] : []; + return []; + }, + findOne: async (object: string, query?: EngineFindOneQueryInput) => { assertEngineFindOnePredicate(object, query); return null; }, + count: async () => 0, + aggregate: async () => [], + }], + ]); + const ctx = { + registerService: (name: string, svc: unknown) => services.set(name, svc), + getService: (name: string) => { + if (!services.has(name)) throw new Error(`Service "${name}" not found`); + return services.get(name); + }, + replaceService: () => undefined, + getServices: () => services, + hook: (name: string, fn: () => Promise | void) => hooks.set(name, [...(hooks.get(name) ?? []), fn]), + trigger: async () => undefined, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + getKernel: () => ({}), + }; + const plugin = new MCPServerPlugin({ autoStart: true }); + await plugin.init(ctx as never); + const runtime = services.get('mcp') as MCPServerRuntime; + // Only the transport attach is stubbed: it would claim this process's stdin/stdout. + vi.spyOn(runtime, 'start').mockResolvedValue(undefined); + await plugin.start(ctx as never); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await runtime.server.connect(serverSide); + const client = new Client({ name: 't', version: '1.0.0' }); + let listChanged = 0; + client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + listChanged += 1; + }); + await client.connect(clientSide); + const fire = async (name: string) => { + for (const fn of hooks.get(name) ?? []) await fn(); + }; + const names = async () => (await client.listTools()).tools.map((t) => t.name); + return { client, fire, names, listChanged: () => listChanged, ctx }; + } + + it('over stdio, held: never listed — not before the reading, not after it', async () => { + const knowledge = service({ runtimeComposed: true }); + const { client, fire, names, listChanged } = await stdioPlugin(knowledge); + try { + expect(await names()).toContain('query_records'); + expect(await names()).not.toContain(SEARCH_KNOWLEDGE_TOOL_NAME); + knowledge.settleEnablement({ embedder: 'no provider is saved' }); + await fire('kernel:bootstrapped'); + await fire('kernel:listening'); + expect(await names()).not.toContain(SEARCH_KNOWLEDGE_TOOL_NAME); + expect(listChanged()).toBe(0); + } finally { + await client.close(); + } + }); + + it('over stdio, enabled: registered at kernel:listening, and a connected client is told the list changed', async () => { + const knowledge = service({ runtimeComposed: true }); + const { client, fire, names, listChanged } = await stdioPlugin(knowledge); + try { + expect(await names()).not.toContain(SEARCH_KNOWLEDGE_TOOL_NAME); + knowledge.settleEnablement(undefined); + await fire('kernel:bootstrapped'); + await fire('kernel:listening'); + expect(await names()).toContain(SEARCH_KNOWLEDGE_TOOL_NAME); + await vi.waitFor(() => expect(listChanged()).toBeGreaterThan(0)); + // The one definition the service hands out, as HTTP lists it. + const listed = (await client.listTools()).tools.find((t) => t.name === SEARCH_KNOWLEDGE_TOOL_NAME); + expect(listed?.description).toBe(getKnowledgeToolDefinitions()[0]!.description); + } finally { + await client.close(); + } + }); + + it('over stdio, a service a host mounts: registered with the other tools in start(), as before', async () => { + const { client, fire, names, listChanged } = await stdioPlugin(service({ runtimeComposed: false })); + try { + expect(await names()).toContain(SEARCH_KNOWLEDGE_TOOL_NAME); + await fire('kernel:listening'); + expect((await names()).filter((n) => n === SEARCH_KNOWLEDGE_TOOL_NAME)).toHaveLength(1); + expect(listChanged()).toBe(0); + } finally { + await client.close(); + } + }); +}); diff --git a/packages/mcp/src/plugin.ts b/packages/mcp/src/plugin.ts index 15eda623cb9..32d956fe095 100644 --- a/packages/mcp/src/plugin.ts +++ b/packages/mcp/src/plugin.ts @@ -59,7 +59,7 @@ import { type StdioProtocolObjectReads, type StoredHashDigest, } from './stdio-data-bridge.js'; -import type { McpDataBridge } from './mcp-http-tools.js'; +import { SEARCH_KNOWLEDGE_TOOL_NAME, knowledgeToolDefinition, registerKnowledgeTools, type McpDataBridge } from './mcp-http-tools.js'; import { CONNECT_AGENT_UI_BUNDLE } from './connect-ui.js'; import { configureReadFileExtraction } from './file-content.js'; @@ -968,7 +968,8 @@ export class MCPServerPlugin implements Plugin { // record argument only where this server registers `get_record_context`, // which it reads from the tools registered by then. if (dataBridge) { - this.runtime.bridgeDataTools(dataBridge); + const bridged = this.runtime.bridgeDataTools(dataBridge); + this.registerKnowledgeToolOnceSettled(ctx, dataBridge, bridged); } if (metadataService) { @@ -1038,6 +1039,45 @@ export class MCPServerPlugin implements Plugin { await ctx.trigger('mcp:ready', this.runtime); } + /** + * [ADR-0161 K8, the dated note on item 12] `search_knowledge` on the stdio + * transport, for a knowledge service the runtime composed. Such a service is + * enabled by configuration, read once at `kernel:bootstrapped`, and until + * then hands out no definition, so {@link MCPServerRuntime.bridgeDataTools}, + * which runs in this `start()`, registered none. The tool registers here, + * at `kernel:listening` — after every `kernel:bootstrapped` handler, the + * reading's among them — only when the service now hands out its + * definition (enabled). Not enabled, it stays absent: an unknown state reads + * as absent, never listed and then withdrawn. The server already declares + * the `tools` capability (the object tools registered it before the + * transport attached), so the SDK takes a tool after the transport has + * attached and tells a connected client with `notifications/tools/list_changed`. + * The skill prompts read the served tools at each listing, so a skill that + * binds the tool is listed from then on. + * + * A service a host mounted hands out its definition from the start, so its + * tool registered with the others and nothing is done here. + */ + private registerKnowledgeToolOnceSettled(ctx: PluginContext, bridge: McpDataBridge, bridged: readonly string[]): void { + if (bridged.includes(SEARCH_KNOWLEDGE_TOOL_NAME)) return; + if (typeof bridge.searchKnowledge !== 'function' || typeof bridge.knowledgeToolDefinitions !== 'function') return; + ctx.hook('kernel:listening', async () => { + const runtime = this.runtime; + if (!runtime || !knowledgeToolDefinition(bridge)) return; + try { + const registered = registerKnowledgeTools(runtime.server, bridge, { logger: ctx.logger }); + if (registered.length > 0) { + ctx.logger.info(`[MCP] stdio transport: ${registered.join(', ')} registered once the knowledge service was read as enabled`); + } + } catch (err) { + // A tool of that name the AI registry bridged keeps it (the SDK refuses a second registration). + ctx.logger.warn( + `[MCP] stdio transport: ${SEARCH_KNOWLEDGE_TOOL_NAME} was not registered (${err instanceof Error ? err.message : String(err)}).`, + ); + } + }); + } + async destroy(): Promise { if (this.runtime?.isStarted) { await this.runtime.stop(); diff --git a/packages/runtime/src/mcp-knowledge-tools-bridge.test.ts b/packages/runtime/src/mcp-knowledge-tools-bridge.test.ts index fd1a35053b6..1e83982e2bc 100644 --- a/packages/runtime/src/mcp-knowledge-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-knowledge-tools-bridge.test.ts @@ -19,6 +19,7 @@ import { describe, it, expect, vi } from 'vitest'; // Paid during collection, not inside a clocked case: the dispatcher reaches // `standalone-stack.ts`, whose function body `import()`s it (`scripts/check-test-source-alias.mjs`). import '@objectstack/metadata'; +import { KnowledgeService } from '@objectstack/service-knowledge'; import { HttpDispatcher } from './http-dispatcher.js'; import { buildMcpBridge, resolveMcpKnowledgeToolsService, type McpKnowledgeToolsService } from './domains/mcp.js'; @@ -73,6 +74,23 @@ describe('[ADR-0149 D2] the MCP bridge\'s knowledge members', () => { await bridge.searchKnowledge(input); expect(executor.searchKnowledge).toHaveBeenCalledWith(input, EC); }); + + it('[ADR-0161 K8, note on item 12] over a runtime-composed service: no definition until it is read enabled, none while held', () => { + const { ctx, deps } = harness(); + const serviceOf = () => + new KnowledgeService({ enabledByConfiguration: true, logger: { warn: () => undefined, debug: () => undefined } }); + const held = serviceOf(); + const bridge = buildMcpBridge(deps, ctx, { knowledgeTools: held }); + // Read at each listing: an unsettled service hands out none, a held one none either. + expect(bridge.knowledgeToolDefinitions()).toEqual([]); + held.settleEnablement({ store: 'turso' }); + expect(bridge.knowledgeToolDefinitions()).toEqual([]); + const enabled = serviceOf(); + enabled.settleEnablement(undefined); + expect(buildMcpBridge(deps, ctx, { knowledgeTools: enabled }).knowledgeToolDefinitions().map((d: { name: string }) => d.name)).toEqual([ + 'search_knowledge', + ]); + }); }); /** diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts index 619ed43468e..2baab52802c 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts @@ -759,3 +759,231 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb expect(requests).toHaveLength(0); }); }); + +/** + * [ADR-0161 K8, the dated note on item 12] A knowledge service the runtime + * composed (`runtimeComposed`, set by `resolveCapabilityArgument`) is enabled + * by configuration: at `kernel:bootstrapped` it serves only with an embedder + * and the deployment's store, and otherwise holds every source — listed, never + * built, synced or searched, no tool definition, no store called — said once, + * in one line. A plugin a host mounts itself is untouched. + */ +describe('[ADR-0161 K8, note on item 12] a runtime-composed knowledge service is enabled by configuration', () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + /** Every call the deployment's store is handed, by member. */ + type StoreCalls = string[]; + + /** The deployment's store (`id`), counting every call made to it. */ + class CountingStorePlugin implements Plugin { + name = 'test.knowledge.counting-store'; + version = '1.0.0'; + type = 'standard' as const; + dependencies = ['com.objectstack.service.knowledge']; + constructor(private readonly storeId: string, private readonly calls: StoreCalls) {} + async init(): Promise {} + async start(ctx: PluginContext): Promise { + const calls = this.calls; + const embedder = () => ctx.getService(EMBEDDER_SERVICE); + const adapter: IKnowledgeAdapter = { + id: this.storeId, + async upsert(docs) { + calls.push('upsert'); + await embedder().embed(docs.map((d) => d.content)); + }, + async search(query) { + calls.push('search'); + await embedder().embed([query]); + return []; + }, + async delete() { + calls.push('delete'); + }, + async dropSource() { + calls.push('dropSource'); + }, + }; + // Registered in start(), as a store plugin registers its adapter. + ctx.getService(KNOWLEDGE_SERVICE).registerAdapter(this.storeId, adapter); + } + } + + async function bootComposed(opts: { + runtimeComposed?: { declared: boolean }; + /** The deployment's store id the runtime marks. @default 'vec' */ + deploymentAdapter?: string; + /** Whether the deployment's store registers its adapter. @default true */ + storeMounted?: boolean; + saved?: Record; + host?: { embedder: IEmbedder; phase: 'init' | 'kernel:ready' }; + sources?: KnowledgeSource[]; + } = {}) { + const lines: LoggedLine[] = []; + const calls: StoreCalls = []; + const store = opts.deploymentAdapter ?? 'vec'; + const kernel = new LiteKernel(); + kernel.use(new LogRecorder(lines)); + if (opts.host) kernel.use(new HostEmbedderPlugin(opts.host.embedder, opts.host.phase)); + kernel.use(new KnowledgeServicePlugin({ + enableEventSync: false, + deploymentAdapter: store, + ...(opts.runtimeComposed ? { runtimeComposed: opts.runtimeComposed } : {}), + // A shipped source names no adapter: it binds to the deployment's store. + sources: opts.sources ?? [{ name: 'docs', label: 'Docs', source: { kind: 'object', object: 'doc', content: ['body'] } }], + })); + kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() })); + if (opts.storeMounted !== false) kernel.use(new CountingStorePlugin(store, calls)); + if (opts.saved) kernel.use(new SavedAiSettings(opts.saved)); + await kernel.bootstrap(); + // The boot build runs in the background: let it settle before counting. + await new Promise((resolve) => setTimeout(resolve, 20)); + const knowledge = kernel.getService(KNOWLEDGE_SERVICE); + /** The one line of the held state, if any. */ + const heldLines = () => lines.filter((l) => l.line.includes('the knowledge service is not enabled')); + return { kernel, lines, calls, knowledge, heldLines }; + } + + /** What the record sync's two triggers hand the service for one write and one delete. */ + async function writeAndDelete(knowledge: KnowledgeService): Promise { + await knowledge.handleRecordUpsert('doc', { id: 'd1', body: 'granite quarry' }); + await knowledge.handleRecordDelete('doc', 'd1'); + knowledge.enqueueRecordSync('doc', 'd1'); + await knowledge.reconcileSources(); + knowledge.requestReconcile('doc'); + } + + const hostEmbedder = (): IEmbedder => ({ id: 'host-own', dimensions: 2, embed: async (t) => t.map(() => [0.6, 0.8]) }); + + it('a shipped source and no embedder: mounted, held, zero store calls across boot and a record write, one line at info', async () => { + const requests = stubProvider(); + const { knowledge, calls, lines, heldLines } = await bootComposed({ runtimeComposed: { declared: false } }); + + // Mounted: the service and the deployment's store are both there. + expect(knowledge.listAdapters()).toEqual(['vec']); + expect(knowledge.describeSources().map((d) => d.id)).toEqual(['docs']); + expect(knowledge.heldReading()).toEqual({ embedder: expect.stringContaining('ai.embedder_provider') }); + + await writeAndDelete(knowledge); + expect(calls).toEqual([]); + expect(requests).toHaveLength(0); + + // Exactly one line says the state, at info, naming the remedy and the held source. + expect(heldLines()).toHaveLength(1); + expect(heldLines()[0]).toMatchObject({ level: 'info' }); + expect(heldLines()[0].line).toContain('save an embedder provider'); + expect(heldLines()[0].line).toContain('docs'); + // Folded into it: the embedder's own line and the unplaceable-source error, and no reconcile line. + expect(lines.filter((l) => l.line.includes('no embedder is configured (') && !l.line.includes('not enabled'))).toEqual([]); + expect(lines.filter((l) => l.level === 'error')).toEqual([]); + expect(lines.filter((l) => l.line.includes('reconcile'))).toEqual([]); + }); + + it('held: no tool definition, and a direct search is refused 503 naming the missing half, never answered empty', async () => { + const { knowledge } = await bootComposed({ runtimeComposed: { declared: false } }); + expect(knowledge.knowledgeTools().definitions).toEqual([]); + const refused = await knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect((refused as Error).message).toMatch(/^\[knowledge\] the knowledge service is not enabled on this deployment: no embedder is configured/); + expect((refused as Error).message).toContain('save an embedder provider'); + expect((refused as Error).message).not.toContain('knowledge store'); + const report = await knowledge.searchWithRefusals('granite', { executionContext: SYSTEM }).catch((e: unknown) => e); + expect(report).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + // An operator's rebuild calls no store either. + await expect(knowledge.rebuildSource('docs', { trigger: 'operator' })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + }); + + it("requires: ['knowledge'] and no embedder: the one line is warn; the boot succeeds", async () => { + const { knowledge, heldLines, calls } = await bootComposed({ runtimeComposed: { declared: true } }); + expect(knowledge.heldReading()).toBeDefined(); + expect(heldLines()).toHaveLength(1); + expect(heldLines()[0]).toMatchObject({ level: 'warn' }); + expect(calls).toEqual([]); + }); + + it('a provider saved without its key: the one line is warn and names the reason', async () => { + const requests = stubProvider(); + const { knowledge, heldLines } = await bootComposed({ runtimeComposed: { declared: false }, saved: { embedder_provider: 'siliconflow' } }); + expect(knowledge.heldReading()?.embedder).toContain('requires an API key'); + expect(heldLines()).toHaveLength(1); + expect(heldLines()[0]).toMatchObject({ level: 'warn' }); + expect(heldLines()[0].line).toContain('requires an API key'); + expect(requests).toHaveLength(0); + }); + + it("the deployment's store not mounted, an embedder there: held, warn, naming the store and that the boot log says why", async () => { + const { knowledge, heldLines } = await bootComposed({ + runtimeComposed: { declared: false }, + host: { embedder: hostEmbedder(), phase: 'init' }, + storeMounted: false, + deploymentAdapter: 'turso', + }); + expect(knowledge.heldReading()).toEqual({ store: 'turso' }); + expect(heldLines()).toHaveLength(1); + expect(heldLines()[0]).toMatchObject({ level: 'warn' }); + expect(heldLines()[0].line).toContain("knowledge store 'turso' is not mounted"); + expect(heldLines()[0].line).not.toContain('save an embedder provider'); + const refused = await knowledge.search('x', { executionContext: SYSTEM }).catch((e: unknown) => e); + expect((refused as Error).message).toContain("mount the deployment's knowledge store"); + }); + + it('both halves missing: the refusal names both', async () => { + const { knowledge } = await bootComposed({ runtimeComposed: { declared: false }, storeMounted: false, deploymentAdapter: 'turso' }); + expect(knowledge.heldReading()).toEqual({ embedder: expect.any(String), store: 'turso' }); + const refused = (await knowledge.search('x', { executionContext: SYSTEM }).catch((e: unknown) => e)) as Error; + expect(refused.message).toContain('save an embedder provider'); + expect(refused.message).toContain("mount the deployment's knowledge store"); + }); + + it('[point 2] a source on a store the application registered is held too: the state is the whole service\'s', async () => { + const { knowledge, calls } = await bootComposed({ + runtimeComposed: { declared: false }, + // The application's own store, named by the source; the deployment's is another id, unmounted. + deploymentAdapter: 'turso', + storeMounted: false, + sources: [{ name: 'docs', label: 'Docs', adapter: 'vec', source: { kind: 'object', object: 'doc', content: ['body'] } }], + }); + // Not mounted by the runtime: register the application's store by hand, as app code does. + const appCalls: string[] = []; + knowledge.registerAdapter('vec', { id: 'vec', upsert: async () => { appCalls.push('upsert'); }, search: async () => { appCalls.push('search'); return []; }, delete: async () => { appCalls.push('delete'); } }); + await writeAndDelete(knowledge); + expect(appCalls).toEqual([]); + expect(calls).toEqual([]); + expect(knowledge.knowledgeTools().definitions).toEqual([]); + }); + + it('control — an embedder registered by a plugin: enabled, the tool is handed out and a record write reaches the store', async () => { + const { knowledge, calls, heldLines, lines } = await bootComposed({ + runtimeComposed: { declared: true }, + host: { embedder: hostEmbedder(), phase: 'kernel:ready' }, + }); + expect(knowledge.heldReading()).toBeUndefined(); + expect(heldLines()).toEqual([]); + expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']); + expect(lines.filter((l) => l.line.includes('already registered') && l.line.includes('host-own'))).toHaveLength(1); + await knowledge.handleRecordUpsert('doc', { id: 'd1', body: 'granite quarry' }); + expect(calls).toContain('upsert'); + }); + + it('control — an embedder built from the saved settings: enabled', async () => { + stubProvider(); + const { knowledge, heldLines } = await bootComposed({ + runtimeComposed: { declared: false }, + saved: { embedder_provider: 'openai', embedder_api_key: API_KEY }, + }); + expect(knowledge.heldReading()).toBeUndefined(); + expect(heldLines()).toEqual([]); + expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']); + }); + + it('a plugin a host mounts itself, no embedder: as before — not held, the tool handed out, the stand-in refuses at the store', async () => { + const { knowledge, heldLines, lines, calls } = await bootComposed({}); + expect(knowledge.heldReading()).toBeUndefined(); + expect(heldLines()).toEqual([]); + expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']); + expect(lines.some((l) => l.level === 'info' && l.line.includes('no embedder is configured ('))).toBe(true); + await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]); + expect(calls).toContain('search'); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts b/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts index 5bc9adc2135..e0843a2a33e 100644 --- a/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts +++ b/packages/services/service-knowledge/src/__tests__/reap-guard.test.ts @@ -24,6 +24,7 @@ import { assertEngineDeleteDispatch, type LifecycleObjectLike, } from '@objectstack/objectql'; +import { LiteKernel, type Plugin, type PluginContext } from '@objectstack/core'; import type { KnowledgeSource } from '@objectstack/spec/ai'; import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; @@ -451,3 +452,78 @@ describe('ADR-0161 K3, item 2 — the guarded object set follows the sources', ( expect(registered).toEqual([]); }); }); + +/** + * [ADR-0161 K8, the dated note on item 12, point 3] A knowledge service the + * runtime composed registers no reap guard while it is not enabled, and calls + * no store: a retention sweep deletes the rows of a held source's object on + * time. The guard waits for the boot's enabled reading at + * `kernel:bootstrapped`: the lifecycle service has no unregister. Booted on a + * real kernel, so the reading runs where the boot runs it. + */ +describe('[ADR-0161 K8, note on item 12, point 3] no reap guard while a runtime-composed service is not enabled', () => { + async function bootComposed(withEmbedder: boolean) { + const { engine, deleted, idsLeft } = reapEngine({ + task: [ + { id: 'k1', deleted_at: OLD }, + { id: 'k2', deleted_at: OLD }, + ], + audit_log: [], + }); + const lifecycle = lifecycleOver(engine); + const registerReapGuard = vi.spyOn(lifecycle, 'registerReapGuard'); + const { adapter, deletedDocs } = fakeAdapter(); + const kernel = new LiteKernel(); + kernel.use({ + name: 'test.lifecycle', + version: '1.0.0', + async init(ctx: any) { + ctx.registerService('lifecycle', lifecycle); + if (withEmbedder) ctx.registerService('embedder', { id: 'own', dimensions: 2, embed: async (t: string[]) => t.map(() => [1, 0]) }); + }, + } as any); + kernel.use( + new KnowledgeServicePlugin({ + // A shipped source names no adapter: it binds to the deployment's store. + sources: [noteSource({ adapter: undefined })], + deploymentAdapter: 'fake', + runtimeComposed: { declared: false }, + }), + ); + kernel.use({ + name: 'test.deployment-store', + version: '1.0.0', + dependencies: ['com.objectstack.service.knowledge'], + async init() {}, + async start(ctx: PluginContext) { + ctx.getService('knowledge').registerAdapter('fake', adapter); + }, + } satisfies Plugin); + await kernel.bootstrap(); + const knowledge = kernel.getService('knowledge'); + return { lifecycle, registerReapGuard, deletedDocs, deleted, idsLeft, knowledge }; + } + + it('held: no guard registered, and a retention sweep deletes on time with zero store calls', async () => { + const { lifecycle, registerReapGuard, deletedDocs, deleted, idsLeft, knowledge } = await bootComposed(false); + expect(knowledge.heldReading()).toBeDefined(); + expect(registerReapGuard).not.toHaveBeenCalled(); + + await lifecycle.sweep(); + + expect(deleted.map((d) => d.id)).toEqual(['k1', 'k2']); + expect(idsLeft('task')).toEqual([]); + expect(deletedDocs).toEqual([]); + }); + + it('control — enabled: the guard is registered once the reading said so, and de-indexes before the delete', async () => { + const { lifecycle, registerReapGuard, deletedDocs, deleted, knowledge } = await bootComposed(true); + expect(knowledge.heldReading()).toBeUndefined(); + expect(registerReapGuard.mock.calls.map(([object]) => object)).toEqual(['task']); + + await lifecycle.sweep(); + + expect(deletedDocs).toEqual(['task_notes:k1', 'task_notes:k2']); + expect(deleted.map((d) => d.id)).toEqual(['k1', 'k2']); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index cb74a11b26f..2d6c3dfd738 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -22,8 +22,8 @@ import { import { aiTestEmbedderActionHandler } from '@objectstack/service-settings'; import { RECORD_RESTORED_EVENT } from '@objectstack/spec/data'; import { stripReadDecorations } from '@objectstack/spec/kernel'; -import { KnowledgeService } from './knowledge-service.js'; -import type { KnowledgeLogger } from './knowledge-service.js'; +import { KnowledgeService, heldSourcesText } from './knowledge-service.js'; +import type { KnowledgeHeldReading, KnowledgeLogger } from './knowledge-service.js'; import { RECONCILE_DEFAULT_CRON, RECONCILE_JOB, @@ -114,6 +114,22 @@ type EmbedderFromSettings = quiet: boolean; }; +/** + * What `KnowledgeServicePlugin.provideEmbedder` provided: whether an embedder + * is available now, and its boot line, said by the caller — not at all when + * the service is held, whose one line says it instead. + */ +interface EmbedderProvision { + /** An embedder another plugin registered, or one the saved settings built. */ + available: boolean; + /** Why none is available (`available: false`), as operator text. */ + reason?: string; + /** `available: false` only: nothing asked for an embedder (the line is `info`), or the saved settings build none (`warn`). */ + quiet?: boolean; + /** Log the provision's own boot line. */ + say: () => void; +} + /** * The `IEmbedder` registered when the settings configure none. Every use of it * — `embed()` with any input, or reading `dimensions` to size a vector column — @@ -424,6 +440,30 @@ export interface KnowledgeServicePluginOptions { * an adapter-contract member. */ deploymentAdapter?: string; + /** + * [ADR-0161 K8, the dated note on item 12] The runtime composed this plugin + * (`resolveCapabilityArgument` in `@objectstack/core`, beside + * {@link deploymentAdapter}), so the service is enabled by configuration: + * mounted is not enabled. At `kernel:bootstrapped` the boot reads, once, + * whether an embedder is available (another plugin registered one, or the + * saved `ai.embedder_*` settings build one) and whether the deployment's + * store is mounted (an adapter of {@link deploymentAdapter}'s id is + * registered). Both ⇒ the service serves, as one a host mounts always does. + * Either missing ⇒ every source is held, whichever store it names: loaded + * and listed to administrators, never built, synced, reconciled or searched; + * no tool definition is handed out; no lifecycle reap guard is registered + * and no store is called (`KnowledgeService.settleEnablement`). The state is + * said once, in one line: `info` when only a shipped `knowledge_source` + * mounted the service and nothing was saved; `warn` when `declared` (the + * stack lists `requires: ['knowledge']`), when the saved embedder settings + * do not build an embedder, or when the store is not mounted. Never a boot + * refusal (ADR-0078 §4). A change takes effect at the next restart. + * + * Left unset (a host that mounts the plugin itself), nothing of this + * applies: its adapters may embed on their own (K1), and the service serves + * from the start, as it always has. + */ + runtimeComposed?: { declared: boolean }; /** * The reconcile (ADR-0161 K1: "a reconcile pass keeps it correct"; * `KnowledgeService.reconcileSources`): one job on the platform's job @@ -528,8 +568,18 @@ export class KnowledgeServicePlugin implements Plugin { private syncQueue: IQueueService | undefined; /** Whether init() bound a data engine to the service: the queued sync's worker re-reads through it. */ private dataEngineBound = false; + /** + * Whether the lifecycle reap guard may be registered ({@link syncReapGuards}): + * from the start on a plugin a host mounted; on one the runtime composed, + * only once the boot read the service as enabled (ADR-0161 K8, the dated + * note on item 12, point 3: none while it is not). The lifecycle service has + * no unregister, so registration waits for that reading. + */ + private reapGuardsAllowed: boolean; - constructor(private readonly options: KnowledgeServicePluginOptions = {}) {} + constructor(private readonly options: KnowledgeServicePluginOptions = {}) { + this.reapGuardsAllowed = options.runtimeComposed === undefined; + } async init(ctx: PluginContext): Promise { let engine: IDataEngine | undefined; @@ -580,6 +630,7 @@ export class KnowledgeServicePlugin implements Plugin { ...(syncState === undefined ? {} : { syncState }), defaultTopK: this.options.defaultTopK, ...(this.options.deploymentAdapter === undefined ? {} : { deploymentAdapter: this.options.deploymentAdapter }), + ...(this.options.runtimeComposed === undefined ? {} : { enabledByConfiguration: true }), // 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 @@ -702,7 +753,17 @@ export class KnowledgeServicePlugin implements Plugin { await service.recordSources(); this.unsubscribes.push(service.onSourcesChanged(() => { void service.recordSources(); })); } - await this.provideEmbedder(ctx); + const embedder = await this.provideEmbedder(ctx); + // [ADR-0161 K8, the dated note on item 12] A service the runtime + // composed is enabled by configuration, read here once per boot: an + // embedder (just provided) and the deployment's store (registered in + // its own start()). Not enabled ⇒ held, said in one line, and nothing + // below runs for it. + if (this.options.runtimeComposed !== undefined && this.service) { + const held = this.settleEnablement(ctx, this.service, embedder); + if (held) return; + } + embedder.say(); // [ADR-0161 K7] The first build: every source a build is due for is // built once, in the background — after the embedder is provided, // since a build embeds, and never awaited, so the boot does not wait @@ -720,7 +781,9 @@ export class KnowledgeServicePlugin implements Plugin { }); // 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. + // Held, the one line of the held state names what is missing instead. ctx.hook('kernel:bootstrapped', () => { + if (this.service?.heldReading()) return; this.service?.reportUnmountedAdapters(); }); // [ADR-0161 K1] The daily reconcile. The job service may start after this @@ -915,6 +978,8 @@ export class KnowledgeServicePlugin implements Plugin { * not stale anywhere: `debug` only. */ private onPredicateWrite(ctx: PluginContext, service: KnowledgeService, object: string, type: string, matched: unknown): void { + // Held: nothing is synced or reconciled, which the boot line said once. + if (service.heldReading()) return; const count = typeof matched === 'number' ? matched : 'an unreported number of'; const head = `KnowledgeServicePlugin: '${object}' had a predicate write (${type}) affecting ${count} record(s). ` + @@ -971,7 +1036,8 @@ export class KnowledgeServicePlugin implements Plugin { */ private async scheduleReconcile(ctx: PluginContext): Promise { const service = this.service; - if (!service) return; + // Held (ADR-0161 K8, the dated note on item 12): no reconcile job. + if (!service || service.heldReading()) return; const option = this.options.reconcile; if (option === false) { ctx.logger.info?.( @@ -1040,7 +1106,7 @@ export class KnowledgeServicePlugin implements Plugin { * settings page says so). Nothing is sent to a provider until the operator * has saved one, and the API key is never logged. */ - private async provideEmbedder(ctx: PluginContext): Promise { + private async provideEmbedder(ctx: PluginContext): Promise { let registered = true; let existing: unknown; try { @@ -1050,32 +1116,80 @@ export class KnowledgeServicePlugin implements Plugin { } if (registered) { const id = (existing as { id?: unknown } | undefined)?.id; - ctx.logger.info?.( - `KnowledgeServicePlugin: an embedder is already registered as '${EMBEDDER_SERVICE}'` + - `${typeof id === 'string' ? ` (id=${id})` : ''} — kept; the ai.embedder_* settings are not applied.`, - ); - return; + return { + available: true, + say: () => + ctx.logger.info?.( + `KnowledgeServicePlugin: an embedder is already registered as '${EMBEDDER_SERVICE}'` + + `${typeof id === 'string' ? ` (id=${id})` : ''} — kept; the ai.embedder_* settings are not applied.`, + ), + }; } const outcome = await embedderFromSettings(ctx); if (outcome.kind === 'configured') { ctx.registerService(EMBEDDER_SERVICE, outcome.embedder); - ctx.logger.info?.( - `KnowledgeServicePlugin: registered '${EMBEDDER_SERVICE}' from the ai.embedder_* settings ` + - `(provider=${outcome.provider}, endpoint=${outcome.endpointHost}, model=${outcome.model ?? '(embedder default)'}, ` + - `batch size=${outcome.batchSize ?? "the model's own cap"}` + - `${outcome.savedBatchSize !== undefined ? ` — the saved ${outcome.savedBatchSize}, held to the model's documented cap` : ''}). ` + - 'A saved change takes effect on the next restart.', - ); - return; + return { + available: true, + say: () => + ctx.logger.info?.( + `KnowledgeServicePlugin: registered '${EMBEDDER_SERVICE}' from the ai.embedder_* settings ` + + `(provider=${outcome.provider}, endpoint=${outcome.endpointHost}, model=${outcome.model ?? '(embedder default)'}, ` + + `batch size=${outcome.batchSize ?? "the model's own cap"}` + + `${outcome.savedBatchSize !== undefined ? ` — the saved ${outcome.savedBatchSize}, held to the model's documented cap` : ''}). ` + + 'A saved change takes effect on the next restart.', + ), + }; } ctx.registerService(EMBEDDER_SERVICE, new UnconfiguredEmbedder(outcome.reason)); const line = `KnowledgeServicePlugin: no embedder is configured (${outcome.reason}). The knowledge service is mounted; ` + 'an adapter that embeds refuses indexing and search with this reason until an embedder is configured.'; - if (outcome.quiet) ctx.logger.info?.(line); + return { + available: false, + reason: outcome.reason, + quiet: outcome.quiet, + say: () => { + if (outcome.quiet) ctx.logger.info?.(line); + else ctx.logger.warn?.(line); + }, + }; + } + + /** + * [ADR-0161 K8, the dated note on item 12] Read, once per boot, whether the + * service the runtime composed is enabled, and settle it + * (`KnowledgeService.settleEnablement`). Enabled ⇒ the reap guard may now + * be registered, and the boot goes on as for a service a host mounts. + * Not enabled ⇒ the one line that says so, at the level the note rules, + * and the answer `true`: the caller builds nothing. + */ + private settleEnablement(ctx: PluginContext, service: KnowledgeService, embedder: EmbedderProvision): boolean { + const store = this.options.deploymentAdapter; + const storeMissing = store !== undefined && !service.listAdapters().includes(store); + if (embedder.available && !storeMissing) { + service.settleEnablement(undefined); + this.reapGuardsAllowed = true; + if (this.options.enableEventSync !== false) this.syncReapGuards(ctx, service); + return false; + } + const reading: KnowledgeHeldReading = { + ...(embedder.available ? {} : { embedder: embedder.reason }), + ...(storeMissing ? { store } : {}), + }; + service.settleEnablement(reading); + const held = service.describeSources().map(({ id }) => id); + const line = + `KnowledgeServicePlugin: ${heldSourcesText(reading).replace(/^\[knowledge\] /, '')} ` + + `${held.length} source(s) held${held.length > 0 ? `: ${held.join(', ')}` : ''}.`; + // `info` only where a shipped item alone mounted the service and nothing + // was saved; a request, saved settings that build nothing, or a missing + // store is `warn`. Never a boot refusal (ADR-0078 §4). + const quiet = this.options.runtimeComposed?.declared !== true && embedder.quiet !== false && !storeMissing; + if (quiet) ctx.logger.info?.(line); else ctx.logger.warn?.(line); + return true; } /** @@ -1188,6 +1302,7 @@ export class KnowledgeServicePlugin implements Plugin { * de-indexes nothing. */ private syncReapGuards(ctx: PluginContext, service: KnowledgeService): void { + if (!this.reapGuardsAllowed) return; const objects = guardedObjectsFor(service.indexedSources()).filter((object) => !this.guardedObjects.has(object)); if (objects.length === 0) return; diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index fc75b128ab2..274b7cd04be 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -122,6 +122,23 @@ export interface KnowledgeLogger { /** * Constructor options for `KnowledgeService`. */ +/** + * [ADR-0161 K8, the dated note on item 12] Why a knowledge service the + * runtime composed is not enabled at this boot: each half that is missing. + * At least one member is set. Read once per boot, at `kernel:bootstrapped`, + * by `KnowledgeServicePlugin`, and handed to {@link KnowledgeService.settleEnablement}. + */ +export interface KnowledgeHeldReading { + /** + * Set when no embedder is available — none registered by a plugin, and the + * saved `ai.embedder_*` settings build none: why, as operator text (the + * settings that are missing or do not build one). Never a key. + */ + readonly embedder?: string; + /** Set when the deployment's store is not mounted: the id of its adapter, which nothing registered. */ + readonly store?: string; +} + export interface KnowledgeServiceOptions { /** Data engine used for RLS re-checks and bulk reindex walks. Optional in tests. */ dataEngine?: IDataEngine; @@ -141,6 +158,16 @@ export interface KnowledgeServiceOptions { * no adapter binds to the only adapter registered. */ deploymentAdapter?: string; + /** + * [ADR-0161 K8, the dated note on item 12] The runtime composed this + * service, so it is enabled by configuration: until the boot's reading + * settles it ({@link KnowledgeService.settleEnablement}), the service hands + * out no tool definition, and once settled it either serves or holds its + * sources. `KnowledgeServicePlugin` sets it from its `runtimeComposed` + * option. Omitted (a host that mounts the service itself), the service + * serves from the start, as it always has. + */ + enabledByConfiguration?: boolean; /** * The `security` service, resolved at search time, for the field gate * (`knowledge-source-admission.ts`). Answers `undefined` when the host @@ -275,8 +302,54 @@ export class KnowledgeService implements IKnowledgeService { */ private recordSyncPublisher: ((message: KnowledgeRecordSyncMessage) => Promise) | undefined; + /** + * [ADR-0161 K8, the dated note on item 12] Set when the service the runtime + * composed is not enabled at this boot ({@link settleEnablement}); `undefined` + * while it serves, and always on a service a host mounted itself. + */ + private held: KnowledgeHeldReading | undefined; + /** + * `true` from construction until the boot's reading settles a service the + * runtime composed ({@link KnowledgeServiceOptions.enabledByConfiguration}); + * always `false` on a service a host mounted itself. + */ + private enablementPending: boolean; + constructor(private readonly options: KnowledgeServiceOptions = {}) { this.defaultTopK = options.defaultTopK ?? 10; + this.enablementPending = options.enabledByConfiguration === true; + } + + // ── Enablement (ADR-0161 K8, the dated note on item 12) ────────── + + /** + * Settle a service the runtime composed, once per boot, at + * `kernel:bootstrapped` (`KnowledgeServicePlugin`): `undefined` when the + * boot found an embedder and the deployment's store, so the service serves + * from now on, as a service a host mounts always does; else the reading of + * what is missing, and every source is held for the rest of this process. + * + * Held — mounted is not enabled. The sources stay + * registered and are listed to administrators ({@link describeSources}), + * and no member calls a store for them: no build (boot, reload, reconcile or + * an operator's), no record sync, no index drop. {@link knowledgeTools} + * hands out no definition, so no transport registers `search_knowledge`; + * {@link search} and {@link searchWithRefusals} answer the coded refusal + * that names the remedy ({@link heldSourcesError}), never an empty answer. + * The state is the whole service's, whichever store a source names (the + * note's point 2). Called once, by `KnowledgeServicePlugin`; a later boot + * reads the state again. + */ + settleEnablement(held: KnowledgeHeldReading | undefined): void { + this.enablementPending = false; + this.held = held; + if (!held) return; + for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); + } + + /** {@link settleEnablement}'s reading while the sources are held, else `undefined`. */ + heldReading(): KnowledgeHeldReading | undefined { + return this.held; } // ── Adapter registry ────────────────────────────────────────────── @@ -525,6 +598,10 @@ export class KnowledgeService implements IKnowledgeService { `What adapter '${adapterId ?? this.adapterLabel(entry.authored)}' holds under the key '${entry.key}' stays until it is removed there.`, ); }; + if (this.held) { + kept('the knowledge service is not enabled at this boot, so no store is called.'); + return entry; + } const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); if (!adapter) { kept( @@ -781,7 +858,9 @@ export class KnowledgeService implements IKnowledgeService { sourceId: string, opts: KnowledgeReindexOptions = {}, ): Promise { - return this.reindexWith(this.requireEntry(sourceId).handed, opts); + const entry = this.requireEntry(sourceId); + if (this.held) throw heldSourcesError(this.held); + return this.reindexWith(entry.handed, opts); } /** @@ -1368,7 +1447,9 @@ export class KnowledgeService implements IKnowledgeService { sourceId: string, opts: { trigger: KnowledgeBuildTrigger; onStarted?: (record: KnowledgeBuildRecord) => void }, ): Promise { - return this.rebuildOf(this.requireEntry(sourceId), opts); + const entry = this.requireEntry(sourceId); + if (this.held) throw heldSourcesError(this.held); + return this.rebuildOf(entry, opts); } /** @@ -1968,6 +2049,7 @@ export class KnowledgeService implements IKnowledgeService { * background by `KnowledgeServicePlugin`, so the boot never waits for it. */ async buildSourcesAtBoot(): Promise { + if (this.held) return; let entries: KnowledgeSourceEntry[]; try { entries = this.registry.entries(); @@ -1990,7 +2072,7 @@ export class KnowledgeService implements IKnowledgeService { */ async buildReloadedSource(key: string): Promise { const entry = this.registry.byIndexKey(key); - if (entry && !this.buildsStopped) await this.buildIfDue(entry, 'reload'); + if (entry && !this.buildsStopped && !this.held) await this.buildIfDue(entry, 'reload'); } /** One source of {@link buildSourcesAtBoot}. Never rejects. */ @@ -2082,8 +2164,11 @@ export class KnowledgeService implements IKnowledgeService { */ reconcileSources(opts: { sources?: string[] } = {}): Promise { const names = opts.sources; + // Held, the pass walks nothing: no store is called while not enabled. return this.enqueueReconcile(() => - names === undefined + this.held + ? [] + : names === undefined ? this.registry.entries() : names.map((name) => this.registry.resolve(name)).filter((e): e is KnowledgeSourceEntry => e !== undefined), ); @@ -2207,7 +2292,7 @@ export class KnowledgeService implements IKnowledgeService { */ requestReconcile(object: string): KnowledgeReconcileRequest { const request: KnowledgeReconcileRequest = { scheduled: [], unreconcilable: [] }; - if (this.buildsStopped) return request; + if (this.buildsStopped || this.held) return request; for (const entry of this.registry.entries()) { if (entry.handed.source.object !== object) continue; const why = this.reconcileExclusion(entry); @@ -2231,7 +2316,7 @@ export class KnowledgeService implements IKnowledgeService { const timer = setTimeout(() => { this.pendingReconciles.delete(key); const entry = this.registry.byIndexKey(key); - if (!entry || this.buildsStopped) return; + if (!entry || this.buildsStopped || this.held) return; // A build of the source running now may have read past the rows the // write changed: wait for it, then walk again. if (this.builds.get(key)?.status === 'running') { @@ -2264,7 +2349,15 @@ export class KnowledgeService implements IKnowledgeService { * tool only where a service carries it. */ knowledgeTools(): KnowledgeTools { - return createKnowledgeTools(this); + const tools = createKnowledgeTools(this); + // [ADR-0161 K8, the dated note on item 12] Held, or not yet settled, the + // service hands out no definition, so no transport registers one (K9 + // rule 1): an unknown state reads as absent. A transport that registers + // its tools before the boot settles registers this one once it has + // (`@objectstack/mcp`'s stdio host, at `kernel:listening`). The executor + // stays: a call that reaches it while held is refused by + // {@link searchWithRefusals}. + return this.held || this.enablementPending ? { ...tools, definitions: [] } : tools; } // ── Permission-aware search ─────────────────────────────────────── @@ -2369,6 +2462,9 @@ export class KnowledgeService implements IKnowledgeService { * `refused` lists them all. */ async searchWithRefusals(query: string, opts: KnowledgeSearchOptions = {}): Promise { + // [ADR-0161 K8, the dated note on item 12] Held: refused, never answered + // empty (K7 rule 5), naming the half that is missing. + if (this.held) throw heldSourcesError(this.held); const report = await this.searchByKey(query, opts); return { hits: report.hits.map((hit) => ({ ...hit, sourceId: this.faceOfKey(hit.sourceId) })), @@ -3250,7 +3346,7 @@ export class KnowledgeService implements IKnowledgeService { * {@link handleRecordUpsert} / {@link handleRecordDelete} instead. */ enqueueRecordSync(object: string, recordId: string | number, reason: KnowledgeRecordSyncReason = 'event'): void { - if (!isRecordId(recordId)) return; + if (!isRecordId(recordId) || this.held) return; const sources = this.sourcesForObject(object); if (sources.length === 0) return; this.publishRecordSyncs(sources, object, String(recordId), reason); @@ -3313,6 +3409,8 @@ export class KnowledgeService implements IKnowledgeService { ); return 'malformed'; } + // Held: completed without a sync, and no store is called. + if (this.held) return 'not-synced'; const source = this.handed(message.source); if (!source) { this.options.logger?.debug?.( @@ -3410,6 +3508,7 @@ export class KnowledgeService implements IKnowledgeService { * of the same document; the index still ends consistent. */ async handleRecordUpsert(object: string, record: Record): Promise { + if (this.held) return; const recordId = record.id; for (const source of this.sourcesForObject(object)) { const sync = (): Promise => this.syncRecord(source, object, recordId, record); @@ -3558,6 +3657,7 @@ export class KnowledgeService implements IKnowledgeService { * sync's re-read and its write. */ async handleRecordDelete(object: string, recordId: string): Promise { + if (this.held) return; const targets = this.sourcesForObject(object); for (const source of targets) { const docId = documentIdFor(source.name, recordId); @@ -4204,6 +4304,34 @@ function noAdapterMountedError(source: string, deployment: string | undefined): ); } +/** + * [ADR-0161 K8, the dated note on item 12] The refusal of a search, a build or + * a reindex while the service is not enabled: ADR-0112 `SERVICE_UNAVAILABLE` + * (503), naming each half that is missing and its remedy, as the refusal of + * an author's save names them. + */ +export function heldSourcesError(reading: KnowledgeHeldReading): Error { + return Object.assign(new Error(heldSourcesText(reading)), { code: UNMOUNTED_ADAPTER_CODE, status: 503 }); +} + +/** The sentence {@link heldSourcesError} answers, and the boot line names the same halves with. */ +export function heldSourcesText(reading: KnowledgeHeldReading): string { + const missing: string[] = []; + const remedy: string[] = []; + if (reading.embedder !== undefined) { + missing.push(`no embedder is configured (${reading.embedder})`); + remedy.push('save an embedder provider'); + } + if (reading.store !== undefined) { + missing.push(`the deployment's knowledge store '${reading.store}' is not mounted, for the reason the boot's log names`); + remedy.push("mount the deployment's knowledge store"); + } + return ( + `[knowledge] the knowledge service is not enabled on this deployment: ${missing.join(', and ')}. ` + + `Its sources are held: none is built, synced or searched. To enable it, ${remedy.join(' and ')}, then restart.` + ); +} + /** * [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` diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-service-held-without-embedder-or-store.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-service-held-without-embedder-or-store.ts new file mode 100644 index 00000000000..eebe6fd6890 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-service-held-without-embedder-or-store.ts @@ -0,0 +1,36 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the held state of a knowledge service the runtime +// composes (ADR-0161 K8, the dated note on item 12): mounted is not enabled. +// Notice only: the schema is unchanged, no key is removed and no D2 conversion +// exists, because the fix is the deployment's configuration, never the item. +export const entry: SemanticMigration = { + id: 'knowledge-service-held-without-embedder-or-store', + surface: + 'A self-hosted deployment whose knowledge service the runtime mounts (the stack declares ' + + '`requires: [\'knowledge\']` or ships a `knowledgeSources` entry, served by `os serve`, `os dev` or ' + + '`@objectstack/verify`) and which, at boot, has no embedder (none registered by a plugin, and the saved ' + + '`ai.embedder_*` settings build none) or no deployment knowledge store mounted', + replacement: + 'Save an embedder provider on the AI settings page (or register an `embedder` service from a plugin) and, ' + + 'where the boot log says the deployment\'s knowledge store is not mounted, mount it; then restart the server. ' + + 'An application whose own store embeds without the kernel\'s embedder mounts `KnowledgeServicePlugin` itself ' + + 'in `plugins[]`', + reason: + 'Such a deployment used to start its boot build, its record sync and its reconcile job, list ' + + '`search_knowledge` on MCP, and answer every build and search with an error from a stand-in embedder; a ' + + 'source on a store the application registered was built and searched with no embedder saved. The service ' + + 'is now enabled by configuration, read once at boot: without both halves every source is held, whichever ' + + 'store it names. The sources are loaded and listed to administrators; none is built, synced, reconciled or ' + + 'searched; no lifecycle reap guard is registered and no store is called, so a retention sweep deletes rows ' + + 'on time; neither MCP transport lists `search_knowledge`; a direct search answers 503 SERVICE_UNAVAILABLE ' + + 'naming what is missing, never an empty answer. The boot says it once, at info when only a shipped source ' + + 'mounted the service and nothing was saved, at warn otherwise, and never refuses to start. A knowledge ' + + 'service a host mounts itself is unchanged.', + acceptanceCriteria: + 'On a deployment that should search its knowledge sources, the boot logs no line saying the knowledge service ' + + 'is not enabled, `search_knowledge` is listed on MCP, and a search answers hits. On a deployment that should ' + + 'not, the boot logs that line once and the sources are listed and held.', +}; diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 41792ad5941..9eb06abce5d 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -156,6 +156,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/mcp/src/mcp-knowledge-tools.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/mcp/src/mcp-stdio-tools.test.ts", "verb": "delete",