From 0c4179078cbbfd3919f21a3bcafe4fbce82f832b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 11:04:57 +0000 Subject: [PATCH 01/17] wip(knowledge): adapter optional, deployment's store mark, item mounts the service Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- packages/cli/src/commands/serve.ts | 14 +- packages/core/src/capability-composition.ts | 48 +++- packages/core/src/capability-providers.ts | 13 +- .../src/knowledge-build-actions.ts | 11 +- .../src/knowledge-reap-guard.ts | 4 +- .../src/knowledge-service-plugin.ts | 12 + .../src/knowledge-service.ts | 208 +++++++++++++++--- packages/spec/src/ai/knowledge-source.test.ts | 10 + packages/spec/src/ai/knowledge-source.zod.ts | 12 +- .../spec/src/kernel/platform-capabilities.ts | 21 +- packages/spec/src/stack.zod.ts | 2 +- packages/verify/src/required-providers.ts | 23 +- 12 files changed, 327 insertions(+), 51 deletions(-) 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/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/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 6fb6037659f..25fcfb37e7f 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -351,6 +351,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; } /** @@ -447,6 +458,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 7cccdc9fb0d..3713a693a6d 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -95,6 +95,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 @@ -215,6 +229,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 @@ -224,15 +292,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[] { @@ -266,6 +347,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( @@ -278,7 +360,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(); } @@ -291,9 +373,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(); @@ -360,20 +443,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 { @@ -436,6 +526,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); @@ -623,7 +720,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) { @@ -1082,7 +1179,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') { @@ -1836,7 +1933,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; @@ -1873,12 +1971,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; } @@ -1900,12 +2003,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) { @@ -1920,7 +2023,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}`, ); } } @@ -1971,14 +2074,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.', @@ -2066,7 +2174,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) { @@ -2180,7 +2288,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?.( @@ -2371,6 +2479,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'); @@ -2665,6 +2781,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 0acb02d6a0c..49009716f4a 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -55,6 +55,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 52cc3af61ae..ef7a525c810 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -245,10 +245,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..0fd39ba27c1 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; readonly type: string }; } /** @@ -238,7 +248,12 @@ export const PLATFORM_CAPABILITY_PROVIDERS: Readonly): 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; From df7ace763bb1f214bd5a7ef155c13395b99d0c31 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 11:26:17 +0000 Subject: [PATCH 02/17] test(knowledge): pin the deployment's-store placement and the item mount Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../core/src/capability-composition.test.ts | 52 +++++++- .../src/__tests__/knowledge-service.test.ts | 115 ++++++++++++++++++ 2 files changed, 166 insertions(+), 1 deletion(-) diff --git a/packages/core/src/capability-composition.test.ts b/packages/core/src/capability-composition.test.ts index ca55146b91a..3a26fece949 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', type: 'knowledge_source' } })]]); + }); + + 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/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(); + } + }); +}); From 9fcd153f8115ff2609533ed1ec28267d88d30c4b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 11:30:26 +0000 Subject: [PATCH 03/17] feat(objectql): the first knowledge_source saved with no service is told so; the boot line names the token Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../src/knowledge-source-unserved.test.ts | 77 +++++++++++++++++++ .../objectql/src/knowledge-source-unserved.ts | 75 +++++++++++++++++- packages/objectql/src/plugin.ts | 6 +- 3 files changed, 155 insertions(+), 3 deletions(-) diff --git a/packages/objectql/src/knowledge-source-unserved.test.ts b/packages/objectql/src/knowledge-source-unserved.test.ts index fc722ca8890..88e94735924 100644 --- a/packages/objectql/src/knowledge-source-unserved.test.ts +++ b/packages/objectql/src/knowledge-source-unserved.test.ts @@ -4,7 +4,9 @@ import { describe, expect, it, vi } from 'vitest'; import { UNSERVED_KNOWLEDGE_SOURCES_NAMED, announceUnservedKnowledgeSources, + describeSavedUnservedKnowledgeSource, describeUnservedKnowledgeSources, + watchSavedUnservedKnowledgeSources, } from './knowledge-source-unserved.js'; describe('describeUnservedKnowledgeSources — items with no knowledge service (ADR-0161 K4, ADR-0078)', () => { @@ -20,6 +22,8 @@ describe('describeUnservedKnowledgeSources — items with no knowledge service ( expect(line).toContain('it is loaded, indexed or searched'); expect(line).toContain('@objectstack/service-knowledge'); expect(line).toContain('or remove the item.'); + // [ADR-0161 K8 item 12] The stack's own items mount the service, so the remedy for these is the token. + expect(line).toContain("Declare requires: ['knowledge'] in the stack and restart"); }); it(`names at most ${UNSERVED_KNOWLEDGE_SOURCES_NAMED} items, counts the rest, and says a name two packages hold once`, () => { @@ -81,3 +85,76 @@ describe('announceUnservedKnowledgeSources — once, at warn, never a refusal', expect(h.warn).toHaveBeenCalledTimes(1); }); }); + +/** + * [ADR-0161 row 3b, item 4] The first `knowledge_source` saved at run time on a + * deployment that mounted no knowledge service at boot: no service is mounted + * while the process runs, so the item is kept and not served, and its save is + * told so once, naming what serves it — `requires: ['knowledge']` and a + * restart. + */ +describe('watchSavedUnservedKnowledgeSources — the first item saved at run time with no service', () => { + type Listener = (evt: { type?: string; name?: string; state?: string }) => void; + const host = (services: Record) => { + const warn = vi.fn(); + return { + warn, + host: { + getService: (name: string) => { + if (name in services) return services[name]; + throw new Error(`no service ${name}`); + }, + logger: { warn }, + }, + }; + }; + const signal = () => { + const listeners: Listener[] = []; + const unsubscribe = vi.fn(); + return { + listeners, + unsubscribe, + protocol: { + onMetadataMutation: vi.fn((l: Listener) => { + listeners.push(l); + return unsubscribe; + }), + }, + emit: (evt: { type?: string; name?: string; state?: string }) => listeners.forEach((l) => l(evt)), + }; + }; + + it('a saved source is said once, at warn: kept, not served, and what serves it after a restart', () => { + const s = signal(); + const h = host({ protocol: s.protocol }); + const unwatch = watchSavedUnservedKnowledgeSources(h.host); + s.emit({ type: 'knowledge_source', name: 'faq', state: 'active' }); + s.emit({ type: 'knowledge_source', name: 'faq', state: 'active' }); + expect(h.warn).toHaveBeenCalledTimes(1); + const line = String(h.warn.mock.calls[0][0]); + expect(line).toBe(describeSavedUnservedKnowledgeSource('faq')); + expect(line).toContain("knowledge_source 'faq' was saved"); + expect(line).toContain('it is kept and is not loaded, indexed or searched'); + expect(line).toContain("Declare requires: ['knowledge'] in the stack and restart"); + expect(line).toContain('the next boot then loads and builds it'); + unwatch?.(); + expect(s.unsubscribe).toHaveBeenCalledOnce(); + }); + + it('says nothing for a draft, a delete or another type', () => { + const s = signal(); + const h = host({ protocol: s.protocol }); + watchSavedUnservedKnowledgeSources(h.host); + s.emit({ type: 'knowledge_source', name: 'faq', state: 'draft' }); + s.emit({ type: 'knowledge_source', name: 'faq', state: 'deleted' }); + s.emit({ type: 'object', name: 'faq', state: 'active' }); + expect(h.warn).not.toHaveBeenCalled(); + }); + + it('a deployment with a knowledge service watches nothing: the service loads the item itself', () => { + const s = signal(); + const h = host({ protocol: s.protocol, knowledge: {} }); + expect(watchSavedUnservedKnowledgeSources(h.host)).toBeUndefined(); + expect(s.protocol.onMetadataMutation).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/objectql/src/knowledge-source-unserved.ts b/packages/objectql/src/knowledge-source-unserved.ts index 073c6142ba0..d8521329012 100644 --- a/packages/objectql/src/knowledge-source-unserved.ts +++ b/packages/objectql/src/knowledge-source-unserved.ts @@ -16,6 +16,20 @@ * A statement at `warn`, never a boot refusal: a package may ship a source to * a deployment that chose not to run retrieval, and its objects, pages and * flows must keep serving there. + * + * [ADR-0161 K8 item 12] Since a `knowledge_source` the stack ships mounts the + * service by itself, the items this line names are the ones the stack does + * not ship: saved at run time (Studio, the metadata API, MCP) or installed in + * a package after the boot composed its services. A kernel takes no plugin + * once it has booted, and the composition is decided before the metadata + * store is read, so such an item is not served — not now, and not by a plain + * restart either — until the stack asks for the service: + * `requires: ['knowledge']`, then a restart. That is what happens to the + * FIRST item saved at run time on a deployment with no knowledge service + * (ADR-0161 row 3b, item 4): it is kept, and said once at its save, in the + * words {@link describeSavedUnservedKnowledgeSource} gives + * ({@link watchSavedUnservedKnowledgeSources}); every later boot says it again + * here. */ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; @@ -40,12 +54,69 @@ export function describeUnservedKnowledgeSources(names: readonly string[], servi return ( `[ObjectQLPlugin] this deployment holds ${count} knowledge_source ${count === 1 ? 'item' : 'items'} ` + `(${shown}${rest > 0 ? `, and ${rest} more` : ''}), but no '${KNOWLEDGE_SERVICE}' service is registered, so ` + - `${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. Add KnowledgeServicePlugin ` + - '(@objectstack/service-knowledge) and a knowledge adapter to the composition, or remove the ' + + `${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. ${UNSERVED_REMEDY} or remove the ` + `${count === 1 ? 'item' : 'items'}.` ); } +/** + * What mounts the service for an item the stack does not ship. A source the + * stack ships in `knowledgeSources` mounts it by itself, so the remedy is the + * token (or the plugin, for a host that composes its own kernel). + */ +const UNSERVED_REMEDY = + "Declare requires: ['knowledge'] in the stack and restart — the service and the deployment's store are mounted " + + 'at boot, never while the process runs — or, on a host that composes its own kernel, add KnowledgeServicePlugin ' + + '(@objectstack/service-knowledge) and a knowledge store;'; + +/** + * The statement for one `knowledge_source` saved while no knowledge service is + * mounted (ADR-0161 row 3b, item 4): the item is kept, it is not served, and + * what serves it. + */ +export function describeSavedUnservedKnowledgeSource(name: string): string { + return ( + `[ObjectQLPlugin] knowledge_source '${name}' was saved, and no '${KNOWLEDGE_SERVICE}' service is registered on ` + + 'this deployment, so it is kept and is not loaded, indexed or searched: a knowledge_source mounts the service ' + + `only when the stack ships it. ${UNSERVED_REMEDY} the next boot then loads and builds it.` + ); +} + +/** The slice of the metadata protocol {@link watchSavedUnservedKnowledgeSources} reads. */ +interface MutationSignal { + onMetadataMutation?(listener: (evt: { type?: string; name?: string; state?: string } | undefined) => void): unknown; +} + +/** + * Say {@link describeSavedUnservedKnowledgeSource} at `warn` when a + * `knowledge_source` is saved (not a draft, not a delete) while no knowledge + * service is registered — once per item name for the life of the process. + * Armed at `kernel:bootstrapped`, beside the boot line: every plugin has + * registered its services, and none registers one later. Answers the + * unsubscribe, or `undefined` when there is no protocol or no mutation signal. + */ +export function watchSavedUnservedKnowledgeSources(host: UnservedKnowledgeSourcesHost): (() => void) | undefined { + const service = (name: string): unknown => { + try { + return host.getService(name) ?? undefined; + } catch { + return undefined; + } + }; + if (service(KNOWLEDGE_SERVICE) !== undefined) return undefined; + const protocol = service('protocol') as MutationSignal | undefined; + if (typeof protocol?.onMetadataMutation !== 'function') return undefined; + const said = new Set(); + const unsubscribe = protocol.onMetadataMutation((evt) => { + if (evt?.type !== KNOWLEDGE_SOURCE_TYPE || evt.state === 'draft' || evt.state === 'deleted') return; + const name = typeof evt.name === 'string' && evt.name !== '' ? evt.name : undefined; + if (name === undefined || said.has(name)) return; + said.add(name); + host.logger?.warn?.(describeSavedUnservedKnowledgeSource(name)); + }); + return typeof unsubscribe === 'function' ? (unsubscribe as () => void) : undefined; +} + /** What {@link announceUnservedKnowledgeSources} reads of its host. */ export interface UnservedKnowledgeSourcesHost { /** Resolve a kernel service by name; throws or answers nothing when none is registered. */ diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index c8717fa8063..9ec254a0111 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -45,7 +45,7 @@ import { RecordCurrencyFollowRefusedError } from './record-currency-aggregate-do // [#22070] The builtin audit stamps are wrapped like a bound hook but registered in code. import { wrapDeclarativeHook } from './hook-wrappers.js'; import { announceStoredExpressionHoles } from './stored-expression-backfill.js'; -import { announceUnservedKnowledgeSources } from './knowledge-source-unserved.js'; +import { announceUnservedKnowledgeSources, watchSavedUnservedKnowledgeSources } from './knowledge-source-unserved.js'; import { announceSummaryHoles } from './summary-hole-announce.js'; import { LifecycleService } from './lifecycle/lifecycle-service.js'; import { WORK_CALENDAR_OBJECT, WorkCalendarService, installWorkCalendarHooks } from './work-calendar-service.js'; @@ -1485,6 +1485,10 @@ export class ObjectQLPlugin implements Plugin { // service to load them are valid and inert: said once, at warn, never // a boot refusal (`knowledge-source-unserved.ts`). await announceUnservedKnowledgeSources({ getService: (name) => ctx.getService(name), logger: ctx.logger }); + // [ADR-0161 row 3b, item 4] And the first one saved while the process + // runs: no service is mounted after boot, so the save is told so. + const unwatch = watchSavedUnservedKnowledgeSources({ getService: (name) => ctx.getService(name), logger: ctx.logger }); + if (unwatch) this.metadataUnsubscribes.push(unwatch); }); ctx.hook('metadata:reloaded', async (payload?: unknown) => { await this.resyncAuthoredHooks(ctx); From bae10e6b64133aaef1f785430d8d0c456bc06e80 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 11:34:07 +0000 Subject: [PATCH 04/17] test(verify): a knowledge_source item with no adapter and no token mounts the service and the deployment's store Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../src/harness.required-providers.test.ts | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/packages/verify/src/harness.required-providers.test.ts b/packages/verify/src/harness.required-providers.test.ts index 53f1199ae46..60e52a70bf6 100644 --- a/packages/verify/src/harness.required-providers.test.ts +++ b/packages/verify/src/harness.required-providers.test.ts @@ -444,6 +444,80 @@ describe("requires: ['knowledge'] — the knowledge service and one store", () = } }, 120_000); + // [ADR-0161 K4 ◆, K8 item 12] The epic's finish line (a), on this boot's + // database: a source written as metadata — the stack's `knowledgeSources` — + // with no `adapter` and no `requires: ['knowledge']`. The item mounts the + // service and the deployment's store, and the source binds to that store + // although application code registered a second adapter beside it. + it("an item, no adapter, no token: the item mounts the service and the deployment's store, which builds and searches Chinese text", async () => { + /** 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(); From 8e2613a6961c0df06330a3c17943dda59c01be2e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 11:52:00 +0000 Subject: [PATCH 05/17] docs(knowledge): a source needs no adapter and no requires entry Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- content/docs/ai/knowledge-rag.mdx | 20 ++++++++------ content/docs/protocol/knowledge.mdx | 43 +++++++++++++++++++++++------ 2 files changed, 46 insertions(+), 17 deletions(-) diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 8f9e1ff7e9e..5465f40425d 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,22 +30,25 @@ 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. - **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 (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. +- **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, else the deployment's, 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. +- **The first source saved at run time on a deployment with neither** (in Studio, the metadata API or MCP) is kept and not served: the service is mounted when the server starts, never while it runs, and it is the app's own sources that mount it. The save is logged once at `warn`, and every boot after says it again, naming the fix: add `requires: ['knowledge']` and restart — the next boot loads and builds the source. - **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 +57,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 +68,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 +78,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 613349abc3f..281433c380e 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,15 @@ 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. 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. **The first one saved at run time** on such a deployment is kept and +not served: the service is mounted at boot, never while the process runs, and +the boot composes its services before it reads the metadata store, so a plain +restart does not mount it either. Its save is said once at `warn`, naming the +fix — `requires: ['knowledge']` (or, on a host that composes its own kernel, +`KnowledgeServicePlugin` and a store), then a restart; the next boot loads and +builds it. #### Who may author one @@ -606,8 +633,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 From 910e50557640f777666a3d7664e980726e1579b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 11:53:34 +0000 Subject: [PATCH 06/17] chore(changeset): knowledge source adapter optional, item mounts the service Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- ...37306-knowledge-source-adapter-optional.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .changeset/37306-knowledge-source-adapter-optional.md diff --git a/.changeset/37306-knowledge-source-adapter-optional.md b/.changeset/37306-knowledge-source-adapter-optional.md new file mode 100644 index 00000000000..3fb3e5990d4 --- /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/objectql': minor +--- + +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, type }`, set on the `knowledge` row of `PLATFORM_CAPABILITY_PROVIDERS` (`knowledgeSources`, `knowledge_source`): 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). +- **`@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/objectql`.** The first `knowledge_source` saved at run time on a deployment that mounted no knowledge service is kept and not served: no service is mounted while the process runs, and the boot composes its services before it reads the metadata store. Its save is now said once at `warn`, naming the fix (`requires: ['knowledge']`, then a restart), and the boot line for such items names the same fix. + +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. + +What to do: nothing. 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. From df2ed0c3a2d69b84883e90ef37aca8f444d1da52 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:52:06 +0000 Subject: [PATCH 07/17] docs(spec): regenerate references for the optional knowledge source adapter Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- content/docs/references/ai/knowledge-source.mdx | 2 +- content/docs/references/api/package-api-assembled.mdx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 6307d5b9684..d189891c55a 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. 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. 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. 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 | From fa2b5387b3528294edf875705eac0ae7359986df Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:43:19 +0000 Subject: [PATCH 08/17] test(verify): budget the thirteenth required-providers boot Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- packages/verify/src/harness.required-providers.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/verify/src/harness.required-providers.test.ts b/packages/verify/src/harness.required-providers.test.ts index 60e52a70bf6..eecf2874ddb 100644 --- a/packages/verify/src/harness.required-providers.test.ts +++ b/packages/verify/src/harness.required-providers.test.ts @@ -1,5 +1,5 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// test-budget: 70 — spawns the real producer once per single-cause fixture: twelve in-process bootStack boots, no two the same configuration (a top-level requires, a package body's, the top level over the bodies, the control, an explicit instance, triggers with its hard dependencies, record-context with mcp, its no-token control, a host-mounted record-context, knowledge with realtime, its no-token control, knowledge on a file database under OS_HOME), each its case's subject; 5.9 s in a local run for the first six, 10.0 s with the three record-context boots, 14.8 s with the two knowledge boots, 19.0 s with the file-database knowledge boot (local, verbose reporter); slowest CI reading 53.7 s (scheduled CI run 45914939800, job Test Core (10/10) 140232535871, head 80519b5991, after PR #37708), x 1.25 = 67.1 s, rounded up to the next 10 s +// test-budget: 80 — spawns the real producer once per single-cause fixture: thirteen in-process bootStack boots, no two the same configuration (a top-level requires, a package body's, the top level over the bodies, the control, an explicit instance, triggers with its hard dependencies, record-context with mcp, its no-token control, a host-mounted record-context, knowledge with realtime, its no-token control, knowledge on a file database under OS_HOME, a knowledge_source item with no adapter and no token), each its case's subject; 5.9 s in a local run for the first six, 10.0 s with the three record-context boots, 14.8 s with the two knowledge boots, 19.0 s with the file-database knowledge boot, 15.6 s for all thirteen on a shared box after the item boot was added (local, verbose reporter); slowest CI reading 53.7 s for the twelve (scheduled CI run 45914939800, job Test Core (10/10) 140232535871, head 80519b5991, after PR #37708), scaled by 13/12 = 58.2 s, x 1.25 = 72.7 s, rounded up to the next 10 s /** * #22301 item 1 — `bootStack` mounts the providers an app's `requires` names, From 9d419f712546a6a6100efe59222e947f8f5766db Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:04:29 +0000 Subject: [PATCH 09/17] revert(objectql): split item 4 (the first knowledge_source saved with no service) to its own card The save-time warn, the reworded boot line and their tests leave this change; row 3a's boot line and behaviour are main's again. The full state is kept on claude/area-o1C-37306-item4 (fa2b5387b3). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- ...37306-knowledge-source-adapter-optional.md | 4 +- content/docs/ai/knowledge-rag.mdx | 1 - content/docs/protocol/knowledge.mdx | 12 +-- .../src/knowledge-source-unserved.test.ts | 77 ------------------- .../objectql/src/knowledge-source-unserved.ts | 75 +----------------- packages/objectql/src/plugin.ts | 6 +- 6 files changed, 7 insertions(+), 168 deletions(-) diff --git a/.changeset/37306-knowledge-source-adapter-optional.md b/.changeset/37306-knowledge-source-adapter-optional.md index 3fb3e5990d4..4075290bc06 100644 --- a/.changeset/37306-knowledge-source-adapter-optional.md +++ b/.changeset/37306-knowledge-source-adapter-optional.md @@ -4,7 +4,6 @@ '@objectstack/service-knowledge': minor '@objectstack/cli': minor '@objectstack/verify': minor -'@objectstack/objectql': minor --- 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 @@ -19,8 +18,7 @@ A `knowledge_source` may leave out `adapter` (ADR-0161 K4), and a stack that shi - **`@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). - **`@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/objectql`.** The first `knowledge_source` saved at run time on a deployment that mounted no knowledge service is kept and not served: no service is mounted while the process runs, and the boot composes its services before it reads the metadata store. Its save is now said once at `warn`, naming the fix (`requires: ['knowledge']`, then a restart), and the boot line for such items names the same fix. -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. +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. 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 5465f40425d..733d3099aaf 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -40,7 +40,6 @@ Which store is mounted depends on the platform database: - **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 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. -- **The first source saved at run time on a deployment with neither** (in Studio, the metadata API or MCP) is kept and not served: the service is mounted when the server starts, never while it runs, and it is the app's own sources that mount it. The save is logged once at `warn`, and every boot after says it again, naming the fix: add `requires: ['knowledge']` and restart — the next boot loads and builds the source. - **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 diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 281433c380e..50e76860e1c 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -200,15 +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. 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. **The first one saved at run time** on such a deployment is kept and -not served: the service is mounted at boot, never while the process runs, and -the boot composes its services before it reads the metadata store, so a plain -restart does not mount it either. Its save is said once at `warn`, naming the -fix — `requires: ['knowledge']` (or, on a host that composes its own kernel, -`KnowledgeServicePlugin` and a store), then a restart; the next boot loads and -builds it. +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 diff --git a/packages/objectql/src/knowledge-source-unserved.test.ts b/packages/objectql/src/knowledge-source-unserved.test.ts index 88e94735924..fc722ca8890 100644 --- a/packages/objectql/src/knowledge-source-unserved.test.ts +++ b/packages/objectql/src/knowledge-source-unserved.test.ts @@ -4,9 +4,7 @@ import { describe, expect, it, vi } from 'vitest'; import { UNSERVED_KNOWLEDGE_SOURCES_NAMED, announceUnservedKnowledgeSources, - describeSavedUnservedKnowledgeSource, describeUnservedKnowledgeSources, - watchSavedUnservedKnowledgeSources, } from './knowledge-source-unserved.js'; describe('describeUnservedKnowledgeSources — items with no knowledge service (ADR-0161 K4, ADR-0078)', () => { @@ -22,8 +20,6 @@ describe('describeUnservedKnowledgeSources — items with no knowledge service ( expect(line).toContain('it is loaded, indexed or searched'); expect(line).toContain('@objectstack/service-knowledge'); expect(line).toContain('or remove the item.'); - // [ADR-0161 K8 item 12] The stack's own items mount the service, so the remedy for these is the token. - expect(line).toContain("Declare requires: ['knowledge'] in the stack and restart"); }); it(`names at most ${UNSERVED_KNOWLEDGE_SOURCES_NAMED} items, counts the rest, and says a name two packages hold once`, () => { @@ -85,76 +81,3 @@ describe('announceUnservedKnowledgeSources — once, at warn, never a refusal', expect(h.warn).toHaveBeenCalledTimes(1); }); }); - -/** - * [ADR-0161 row 3b, item 4] The first `knowledge_source` saved at run time on a - * deployment that mounted no knowledge service at boot: no service is mounted - * while the process runs, so the item is kept and not served, and its save is - * told so once, naming what serves it — `requires: ['knowledge']` and a - * restart. - */ -describe('watchSavedUnservedKnowledgeSources — the first item saved at run time with no service', () => { - type Listener = (evt: { type?: string; name?: string; state?: string }) => void; - const host = (services: Record) => { - const warn = vi.fn(); - return { - warn, - host: { - getService: (name: string) => { - if (name in services) return services[name]; - throw new Error(`no service ${name}`); - }, - logger: { warn }, - }, - }; - }; - const signal = () => { - const listeners: Listener[] = []; - const unsubscribe = vi.fn(); - return { - listeners, - unsubscribe, - protocol: { - onMetadataMutation: vi.fn((l: Listener) => { - listeners.push(l); - return unsubscribe; - }), - }, - emit: (evt: { type?: string; name?: string; state?: string }) => listeners.forEach((l) => l(evt)), - }; - }; - - it('a saved source is said once, at warn: kept, not served, and what serves it after a restart', () => { - const s = signal(); - const h = host({ protocol: s.protocol }); - const unwatch = watchSavedUnservedKnowledgeSources(h.host); - s.emit({ type: 'knowledge_source', name: 'faq', state: 'active' }); - s.emit({ type: 'knowledge_source', name: 'faq', state: 'active' }); - expect(h.warn).toHaveBeenCalledTimes(1); - const line = String(h.warn.mock.calls[0][0]); - expect(line).toBe(describeSavedUnservedKnowledgeSource('faq')); - expect(line).toContain("knowledge_source 'faq' was saved"); - expect(line).toContain('it is kept and is not loaded, indexed or searched'); - expect(line).toContain("Declare requires: ['knowledge'] in the stack and restart"); - expect(line).toContain('the next boot then loads and builds it'); - unwatch?.(); - expect(s.unsubscribe).toHaveBeenCalledOnce(); - }); - - it('says nothing for a draft, a delete or another type', () => { - const s = signal(); - const h = host({ protocol: s.protocol }); - watchSavedUnservedKnowledgeSources(h.host); - s.emit({ type: 'knowledge_source', name: 'faq', state: 'draft' }); - s.emit({ type: 'knowledge_source', name: 'faq', state: 'deleted' }); - s.emit({ type: 'object', name: 'faq', state: 'active' }); - expect(h.warn).not.toHaveBeenCalled(); - }); - - it('a deployment with a knowledge service watches nothing: the service loads the item itself', () => { - const s = signal(); - const h = host({ protocol: s.protocol, knowledge: {} }); - expect(watchSavedUnservedKnowledgeSources(h.host)).toBeUndefined(); - expect(s.protocol.onMetadataMutation).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/objectql/src/knowledge-source-unserved.ts b/packages/objectql/src/knowledge-source-unserved.ts index d8521329012..073c6142ba0 100644 --- a/packages/objectql/src/knowledge-source-unserved.ts +++ b/packages/objectql/src/knowledge-source-unserved.ts @@ -16,20 +16,6 @@ * A statement at `warn`, never a boot refusal: a package may ship a source to * a deployment that chose not to run retrieval, and its objects, pages and * flows must keep serving there. - * - * [ADR-0161 K8 item 12] Since a `knowledge_source` the stack ships mounts the - * service by itself, the items this line names are the ones the stack does - * not ship: saved at run time (Studio, the metadata API, MCP) or installed in - * a package after the boot composed its services. A kernel takes no plugin - * once it has booted, and the composition is decided before the metadata - * store is read, so such an item is not served — not now, and not by a plain - * restart either — until the stack asks for the service: - * `requires: ['knowledge']`, then a restart. That is what happens to the - * FIRST item saved at run time on a deployment with no knowledge service - * (ADR-0161 row 3b, item 4): it is kept, and said once at its save, in the - * words {@link describeSavedUnservedKnowledgeSource} gives - * ({@link watchSavedUnservedKnowledgeSources}); every later boot says it again - * here. */ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; @@ -54,69 +40,12 @@ export function describeUnservedKnowledgeSources(names: readonly string[], servi return ( `[ObjectQLPlugin] this deployment holds ${count} knowledge_source ${count === 1 ? 'item' : 'items'} ` + `(${shown}${rest > 0 ? `, and ${rest} more` : ''}), but no '${KNOWLEDGE_SERVICE}' service is registered, so ` + - `${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. ${UNSERVED_REMEDY} or remove the ` + + `${count === 1 ? 'it is' : 'none is'} loaded, indexed or searched. Add KnowledgeServicePlugin ` + + '(@objectstack/service-knowledge) and a knowledge adapter to the composition, or remove the ' + `${count === 1 ? 'item' : 'items'}.` ); } -/** - * What mounts the service for an item the stack does not ship. A source the - * stack ships in `knowledgeSources` mounts it by itself, so the remedy is the - * token (or the plugin, for a host that composes its own kernel). - */ -const UNSERVED_REMEDY = - "Declare requires: ['knowledge'] in the stack and restart — the service and the deployment's store are mounted " + - 'at boot, never while the process runs — or, on a host that composes its own kernel, add KnowledgeServicePlugin ' + - '(@objectstack/service-knowledge) and a knowledge store;'; - -/** - * The statement for one `knowledge_source` saved while no knowledge service is - * mounted (ADR-0161 row 3b, item 4): the item is kept, it is not served, and - * what serves it. - */ -export function describeSavedUnservedKnowledgeSource(name: string): string { - return ( - `[ObjectQLPlugin] knowledge_source '${name}' was saved, and no '${KNOWLEDGE_SERVICE}' service is registered on ` + - 'this deployment, so it is kept and is not loaded, indexed or searched: a knowledge_source mounts the service ' + - `only when the stack ships it. ${UNSERVED_REMEDY} the next boot then loads and builds it.` - ); -} - -/** The slice of the metadata protocol {@link watchSavedUnservedKnowledgeSources} reads. */ -interface MutationSignal { - onMetadataMutation?(listener: (evt: { type?: string; name?: string; state?: string } | undefined) => void): unknown; -} - -/** - * Say {@link describeSavedUnservedKnowledgeSource} at `warn` when a - * `knowledge_source` is saved (not a draft, not a delete) while no knowledge - * service is registered — once per item name for the life of the process. - * Armed at `kernel:bootstrapped`, beside the boot line: every plugin has - * registered its services, and none registers one later. Answers the - * unsubscribe, or `undefined` when there is no protocol or no mutation signal. - */ -export function watchSavedUnservedKnowledgeSources(host: UnservedKnowledgeSourcesHost): (() => void) | undefined { - const service = (name: string): unknown => { - try { - return host.getService(name) ?? undefined; - } catch { - return undefined; - } - }; - if (service(KNOWLEDGE_SERVICE) !== undefined) return undefined; - const protocol = service('protocol') as MutationSignal | undefined; - if (typeof protocol?.onMetadataMutation !== 'function') return undefined; - const said = new Set(); - const unsubscribe = protocol.onMetadataMutation((evt) => { - if (evt?.type !== KNOWLEDGE_SOURCE_TYPE || evt.state === 'draft' || evt.state === 'deleted') return; - const name = typeof evt.name === 'string' && evt.name !== '' ? evt.name : undefined; - if (name === undefined || said.has(name)) return; - said.add(name); - host.logger?.warn?.(describeSavedUnservedKnowledgeSource(name)); - }); - return typeof unsubscribe === 'function' ? (unsubscribe as () => void) : undefined; -} - /** What {@link announceUnservedKnowledgeSources} reads of its host. */ export interface UnservedKnowledgeSourcesHost { /** Resolve a kernel service by name; throws or answers nothing when none is registered. */ diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index 9ec254a0111..c8717fa8063 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -45,7 +45,7 @@ import { RecordCurrencyFollowRefusedError } from './record-currency-aggregate-do // [#22070] The builtin audit stamps are wrapped like a bound hook but registered in code. import { wrapDeclarativeHook } from './hook-wrappers.js'; import { announceStoredExpressionHoles } from './stored-expression-backfill.js'; -import { announceUnservedKnowledgeSources, watchSavedUnservedKnowledgeSources } from './knowledge-source-unserved.js'; +import { announceUnservedKnowledgeSources } from './knowledge-source-unserved.js'; import { announceSummaryHoles } from './summary-hole-announce.js'; import { LifecycleService } from './lifecycle/lifecycle-service.js'; import { WORK_CALENDAR_OBJECT, WorkCalendarService, installWorkCalendarHooks } from './work-calendar-service.js'; @@ -1485,10 +1485,6 @@ export class ObjectQLPlugin implements Plugin { // service to load them are valid and inert: said once, at warn, never // a boot refusal (`knowledge-source-unserved.ts`). await announceUnservedKnowledgeSources({ getService: (name) => ctx.getService(name), logger: ctx.logger }); - // [ADR-0161 row 3b, item 4] And the first one saved while the process - // runs: no service is mounted after boot, so the save is told so. - const unwatch = watchSavedUnservedKnowledgeSources({ getService: (name) => ctx.getService(name), logger: ctx.logger }); - if (unwatch) this.metadataUnsubscribes.push(unwatch); }); ctx.hook('metadata:reloaded', async (payload?: unknown) => { await this.resyncAuthoredHooks(ctx); From 205f667ec01ffd1d4b3dbb2b1c7080f04638c8a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:14:35 +0000 Subject: [PATCH 10/17] fix(knowledge): the boot build pass places a source that names no adapter main's boot pass (#37951) read the source's named adapter; a source that names none is now placed through boundAdapterId, and one that cannot be placed is left to the reading, as an unmounted named one is. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../src/__tests__/knowledge-build.test.ts | 23 +++++++++++++++++++ .../src/knowledge-service.ts | 8 +++++-- 2 files changed, 29 insertions(+), 2 deletions(-) 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 c89b617ec4d..35480021c34 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts @@ -400,6 +400,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(); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index ee13959bb08..f0a49ccf081 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -1485,8 +1485,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}`); From dc55de32ed8f8fffa9ab65c1f1ab2b6ae156deb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:01:28 +0000 Subject: [PATCH 11/17] =?UTF-8?q?docs(knowledge):=20leave=20the=20Settings?= =?UTF-8?q?=20=E2=86=92=20Knowledge=20bullet=20as=20main=20has=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- content/docs/ai/knowledge-rag.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 54ece8164b0..8534435290b 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -36,7 +36,7 @@ Which store is mounted depends on the platform database: - **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. - **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 (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, else the deployment's, and `os knowledge status` reports it per source. Every search re-checks each hit as the asking user, and no setting turns that off. +- **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 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. From aba523a3413298d11c6b2d54bf02b716f7581abb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 16:04:47 +0000 Subject: [PATCH 12/17] fix(runtime): the MCP draft door keeps a knowledge source refusal's own code A 400 VALIDATION_ERROR from admitAuthoredSource arrived over MCP as SERVICE_UNAVAILABLE with status 400; only a 403 is respelled now. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/37306-knowledge-source-adapter-optional.md | 2 ++ packages/runtime/src/domains/mcp-authoring.test.ts | 9 +++++++++ packages/runtime/src/domains/mcp-authoring.ts | 6 +++++- 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.changeset/37306-knowledge-source-adapter-optional.md b/.changeset/37306-knowledge-source-adapter-optional.md index 4075290bc06..f48a639a317 100644 --- a/.changeset/37306-knowledge-source-adapter-optional.md +++ b/.changeset/37306-knowledge-source-adapter-optional.md @@ -4,6 +4,7 @@ '@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 @@ -18,6 +19,7 @@ A `knowledge_source` may leave out `adapter` (ADR-0161 K4), and a stack that shi - **`@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). - **`@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. 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, }; From 9fb423fc5cd9db88c05328157c18d6bc584c1104 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:22:13 +0000 Subject: [PATCH 13/17] fix(spec): mountedBy carries only the collection its reader reads The type member had no reader (the spelling map already owns the collection-to-type mapping). The changeset names the one behaviour a next.1 stack shipping a source without requires sees. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/37306-knowledge-source-adapter-optional.md | 4 ++-- packages/core/src/capability-composition.test.ts | 2 +- packages/spec/src/kernel/platform-capabilities.ts | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.changeset/37306-knowledge-source-adapter-optional.md b/.changeset/37306-knowledge-source-adapter-optional.md index f48a639a317..105d6c66aec 100644 --- a/.changeset/37306-knowledge-source-adapter-optional.md +++ b/.changeset/37306-knowledge-source-adapter-optional.md @@ -15,7 +15,7 @@ Skills-docs: follow-up #37310 — `skills/**` teaches the optional `adapter` and 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, type }`, set on the `knowledge` row of `PLATFORM_CAPABILITY_PROVIDERS` (`knowledgeSources`, `knowledge_source`): a stack holding an item of that collection is served the capability as its token serves it. +- **`@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). - **`@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. @@ -23,4 +23,4 @@ A `knowledge_source` may leave out `adapter` (ADR-0161 K4), and a stack that shi 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. 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. +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/packages/core/src/capability-composition.test.ts b/packages/core/src/capability-composition.test.ts index 3a26fece949..c5df0f0e54b 100644 --- a/packages/core/src/capability-composition.test.ts +++ b/packages/core/src/capability-composition.test.ts @@ -341,7 +341,7 @@ describe("stackItemCapabilities — a stack's items mount their reader", () => { 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', type: 'knowledge_source' } })]]); + 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', () => { diff --git a/packages/spec/src/kernel/platform-capabilities.ts b/packages/spec/src/kernel/platform-capabilities.ts index 0fd39ba27c1..bfc1f8bff51 100644 --- a/packages/spec/src/kernel/platform-capabilities.ts +++ b/packages/spec/src/kernel/platform-capabilities.ts @@ -172,7 +172,7 @@ export interface PlatformCapabilityProvider { * 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; readonly type: string }; + readonly mountedBy?: { readonly collection: string }; } /** @@ -252,7 +252,7 @@ export const PLATFORM_CAPABILITY_PROVIDERS: Readonly Date: Fri, 27 Nov 2026 17:23:00 +0000 Subject: [PATCH 14/17] docs(spec): regenerate the knowledge_source reference on the merged tree Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- content/docs/references/ai/knowledge-source.mdx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index d189891c55a..08cd6efcb41 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -39,7 +39,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **onRecordChange** | `boolean` | optional (default: `true`) | Sync the index from record events (default true); false leaves the index to an external indexer | -| **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. 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. | +| **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. 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. | --- @@ -51,14 +51,14 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **name** | `string` | ✅ | Source machine name (snake_case) — what search_knowledge lists and its sourceIds argument names | -| **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. 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. | +| **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` | 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. 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. | +| **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. 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. | -| **vectorStore** | `never` | optional | [REMOVED] `knowledge_source.vectorStore` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was never read: no service and no adapter chose a store from it. Delete the key. The store is the adapter the deployment installs, named by `adapter`. 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. | +| **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. | +| **vectorStore** | `never` | optional | [REMOVED] `knowledge_source.vectorStore` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was never read: no service and no adapter chose a store from it. Delete the key. The store is the adapter the deployment installs, named by `adapter`. 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. | | **refresh** | `{ onRecordChange?: boolean }` | optional (default: `{}`) | Refresh / sync configuration; omitted parses to `{}` | | **aiExposed** | `boolean` | optional (default: `true`) | | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | @@ -76,7 +76,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **kind** | `Enum<'object'>` | ✅ | What the source indexes; `object` is the one kind | | **object** | `string` | ✅ | Short object name to index | | **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | -| **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. 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. | +| **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. 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. | | **metadataFields** | `string[]` | optional (default: `[]`) | | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | @@ -86,7 +86,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **onRecordChange** | `boolean` | optional (default: `true`) | Sync the index from record events (default true); false leaves the index to an external indexer | -| **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. 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. | +| **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. 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. | --- @@ -124,7 +124,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **kind** | `Enum<'object'>` | ✅ | What the source indexes; `object` is the one kind | | **object** | `string` | ✅ | Short object name to index | | **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | -| **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. 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. | +| **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. 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. | | **metadataFields** | `string[]` | optional (default: `[]`) | | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | From 633041b354f80892aa17fd53bbd9cf5bff2108ef Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:32:32 +0000 Subject: [PATCH 15/17] fix(cli): the migrate boot composes what a stack's items mount, as serve does stackItemCapabilities is a composition step of both boots: os migrate plan/apply now composes the knowledge service for a stack that ships a knowledge_source and lists no knowledge token, as os serve mounts it. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../src/utils/boot-preparation-parity.test.ts | 4 ++++ .../src/utils/schema-migration-plugins.test.ts | 16 ++++++++++++++++ .../cli/src/utils/schema-migration-plugins.ts | 7 +++++-- 3 files changed, 25 insertions(+), 2 deletions(-) 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..8c3e07e377a 100644 --- a/packages/cli/src/utils/schema-migration-plugins.test.ts +++ b/packages/cli/src/utils/schema-migration-plugins.test.ts @@ -934,6 +934,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. From af27454a77c7029e50b1a5cb214abf043afb310b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 19:04:51 +0000 Subject: [PATCH 16/17] test(cli): pay the migrate composition's dynamic imports at collection Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- packages/cli/src/utils/schema-migration-plugins.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/cli/src/utils/schema-migration-plugins.test.ts b/packages/cli/src/utils/schema-migration-plugins.test.ts index 8c3e07e377a..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, From 6881aa6f0b2d357a81c79e34f8b19f417c334c0b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 19:17:22 +0000 Subject: [PATCH 17/17] docs(changeset): name the migrate boot among the item-token readers Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/37306-knowledge-source-adapter-optional.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/37306-knowledge-source-adapter-optional.md b/.changeset/37306-knowledge-source-adapter-optional.md index 105d6c66aec..1b504f7e0d5 100644 --- a/.changeset/37306-knowledge-source-adapter-optional.md +++ b/.changeset/37306-knowledge-source-adapter-optional.md @@ -17,7 +17,7 @@ A `knowledge_source` may leave out `adapter` (ADR-0161 K4), and a stack that shi - **`@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). +- **`@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`.