diff --git a/.changeset/38692-knowledge-retrieval-mode-service.md b/.changeset/38692-knowledge-retrieval-mode-service.md new file mode 100644 index 00000000000..8630e1cd1c3 --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-service.md @@ -0,0 +1,28 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/spec': patch +--- + +feat(service-knowledge): the knowledge service reads a source's retrieval mode + +A search of a knowledge source now runs in its effective retrieval mode: the +mode the source declares (`source.retrieval.mode`), else its store's default +(`capabilities.retrieval.default`). The mode is handed to the store on every +search and logged at `debug` with where it came from; it is not in what a +search answers the caller. `index_status` carries each source's `retrieval` +(the mode, its origin, the store's modes, a refusal) and each mounted store's +modes. + +A source that declares a mode its store does not run is never searched +another way. It is refused at its save (`400 VALIDATION_ERROR`, listing the +modes the store runs), at registration in code (`registerSource`) when its +store is already registered, +once after boot at `error` (`reportUnsupportedRetrieval`), and on every search, +where it is listed in `refused` with `SERVICE_UNAVAILABLE` (503). It still +builds and syncs its index: a published item (a package install, the stack's +`knowledgeSources`) meets no save and is registered and indexed as usual, and +the boot's reading and every search refuse it. A store that reports no modes (knowledge-memory) +takes only a source that leaves the mode out. + +Clause-②: no +Metadata-protocol: none diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 80c896266a8..3bf79c03e44 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -182,12 +182,32 @@ that name (ADR-0161 K4): used, so a source registered before its store started finds it. **How a source is searched: `source.retrieval.mode`** (ADR-0161, the dated -note of 2026-11-30 under K8). `'vector'` ranks by meaning alone, `'keyword'` -by the question's words alone (the embedder is never called), `'hybrid'` runs +note of 2026-11-30 under K8). `'vector'` ranks by meaning alone, `'keyword'` by +the question's words alone (the embedder is never called), `'hybrid'` runs both and merges them; omitted (or `retrieval: {}`), the adapter's default -(`capabilities.retrieval.default`, `'hybrid'` on `turso` and `pgvector`). The -mode is read by search alone: it enters neither the index fingerprint nor the -recipe hash, so changing it rebuilds nothing. +(`capabilities.retrieval.default`, `'hybrid'` on `turso` and `pgvector`). +That is the effective mode, handed to the adapter on every search and logged +at `debug` with where it came from; it is not in what a search answers the +caller, and an administrator reads it in the source's `index_status`. A +source is never searched in a mode other than the one it declares, so a mode +its adapter does not list (an adapter that reports none, such as `memory`, +lists none) is refused at four points: + +1. its save (Studio, `/meta`, an MCP draft): `VALIDATION_ERROR` (400), + listing the modes the store runs; +2. its registration in code (`registerSource`), when its adapter is already + registered: the same refusal. A store registers in its own `start()`, + after a source registered at `init()`, so "not registered yet" is no + verdict. A published item (a package install, the stack's + `knowledgeSources`) meets no save and is not refused by the loader: it is + registered and indexed, and the next two points hold it; +3. once after boot, at `error`, naming the source and the modes; +4. every search: the source is listed in `refused`, `SERVICE_UNAVAILABLE` + (503), as a source whose adapter is not mounted is. + +The mode is read by search alone: it enters neither the index fingerprint nor +the recipe hash, so changing it rebuilds nothing, and a refused source still +builds and syncs its index. **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 @@ -260,7 +280,8 @@ and the MCP draft door: serve for `search`, a system object without `enable.aiReadable`, or a field the author may not query refuses the save `403`, naming the object or the field; an `adapter` naming no mounted store refuses it `400`, naming the - source, the adapter and the mounted ones. The fields judged are the ones the source serves (`content`, + source, the adapter and the mounted ones, and so does a + `source.retrieval.mode` the store does not run, listing the ones it does. The fields judged are the ones the source serves (`content`, `metadataFields`, the title field) and the ones its `where` reads. A verdict that cannot be reached, or a knowledge service that is registered and cannot be resolved, refuses `503`; nothing is written. diff --git a/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts new file mode 100644 index 00000000000..9d7d3ec7058 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/retrieval-mode-38692.test.ts @@ -0,0 +1,377 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38692 phase 1a] A source's retrieval mode (`source.retrieval.mode`) as the + * knowledge service reads it: the effective mode (the declaration, else the + * adapter's default), handed to the adapter on every search and logged at + * `debug`, never answered to the caller; and the four refusal points of a + * declared mode the adapter does not run (save, registration, the boot's + * reading, every search). Such a source is still indexed. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { + KnowledgeHit, + KnowledgeRetrievalMode, + KnowledgeSource, + ObjectKnowledgeSource, +} from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; +import { KnowledgeSourceLoader } from '../knowledge-source-loader.js'; +import { knowledgeIndexStatusActionHandler } from '../knowledge-build-actions.js'; +import { + RETRIEVAL_UNSUPPORTED_CODE, + readRetrieval, + resolveRetrievalMode, + retrievalRefusalText, +} from '../knowledge-retrieval-mode.js'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as never; +const ALL_MODES: KnowledgeRetrievalMode[] = ['vector', 'keyword', 'hybrid']; + +function adapterOf( + id: string, + retrieval?: { modes: KnowledgeRetrievalMode[]; default: KnowledgeRetrievalMode }, +): IKnowledgeAdapter & { searchSpy: ReturnType; upsertSpy: ReturnType } { + const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource }): Promise => [ + { chunkId: `${opts.source.name}#c1`, documentId: `${opts.source.name}:d1`, sourceId: opts.source.name, snippet: 'x', score: 1 }, + ]); + const upsertSpy = vi.fn(async () => undefined); + return { + id, + upsert: upsertSpy, + delete: vi.fn(async () => undefined), + search: searchSpy, + ...(retrieval === undefined ? {} : { capabilities: { retrieval } }), + searchSpy, + upsertSpy, + } as never; +} + +function source(name: string, adapter: string, mode?: KnowledgeRetrievalMode | 'empty'): KnowledgeSource { + return { + name, + label: name, + adapter, + source: { + kind: 'object', + object: 'task', + content: ['title', 'notes'], + ...(mode === undefined ? {} : { retrieval: mode === 'empty' ? {} : { mode } }), + } as ObjectKnowledgeSource, + }; +} + +function logged() { + const lines: Array<[string, string]> = []; + return { + lines, + logger: { + debug: (m: string) => lines.push(['debug', m]), + info: (m: string) => lines.push(['info', m]), + warn: (m: string) => lines.push(['warn', m]), + error: (m: string) => lines.push(['error', m]), + }, + }; +} + +describe('resolveRetrievalMode — the effective mode and where it came from', () => { + const hybridStore = adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' }); + const vectorOnly = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + const silent = adapterOf('memory'); + + it('the declaration wins; none declared (or `retrieval: {}`) takes the adapter default', () => { + for (const mode of ALL_MODES) { + expect(resolveRetrievalMode(source('s', 'turso', mode), hybridStore)).toEqual({ refused: false, mode, from: 'source' }); + } + expect(resolveRetrievalMode(source('s', 'turso'), hybridStore)).toEqual({ refused: false, mode: 'hybrid', from: 'adapter' }); + expect(resolveRetrievalMode(source('s', 'turso', 'empty'), hybridStore)).toEqual({ refused: false, mode: 'hybrid', from: 'adapter' }); + }); + + it('a mode the adapter does not list is refused, never run another way', () => { + expect(resolveRetrievalMode(source('s', 'vec', 'keyword'), vectorOnly)).toEqual({ + refused: true, + declared: 'keyword', + modes: ['vector'], + }); + }); + + it('an adapter that reports no modes is never told one: none declared searches as before, a declared one is refused', () => { + expect(resolveRetrievalMode(source('s', 'memory'), silent)).toEqual({ refused: false }); + expect(resolveRetrievalMode(source('s', 'memory', 'vector'), silent)).toEqual({ refused: true, declared: 'vector' }); + }); + + it('the refusal text names the declared mode, the modes the store runs and the remedies', () => { + expect(retrievalRefusalText('vec', 'keyword', vectorOnly)).toBe( + "its `retrieval.mode` is 'keyword', and the store 'vec' runs 'vector' (default 'vector'); a source is never " + + "searched in a mode other than the one it declares. Write one of 'vector' as `retrieval.mode`, or remove it " + + "for the store's default, or bind the source to a store that runs 'keyword'.", + ); + expect(retrievalRefusalText('memory', 'vector', silent)).toContain( + "the store 'memory' reports no retrieval modes, so a source on it may only leave `retrieval.mode` out", + ); + }); + + it('the operator reading carries the declaration, the effective mode, its origin and the store modes', () => { + expect(readRetrieval(source('s', 'turso'), hybridStore)).toEqual({ + mode: 'hybrid', + from: 'adapter', + modes: ALL_MODES, + default: 'hybrid', + }); + expect(readRetrieval(source('s', 'vec', 'keyword'), vectorOnly)).toEqual({ + declared: 'keyword', + refused: true, + modes: ['vector'], + default: 'vector', + }); + expect(readRetrieval(source('s', 'memory'), silent)).toEqual({}); + }); +}); + +describe('the search hands the adapter its effective mode', () => { + it('declared, defaulted, and nothing at all for an adapter that reports no modes', async () => { + const { lines, logger } = logged(); + const svc = new KnowledgeService({ logger }); + const turso = adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' }); + const memory = adapterOf('memory'); + svc.registerAdapter('turso', turso); + svc.registerAdapter('memory', memory); + svc.registerSource(source('kw', 'turso', 'keyword')); + svc.registerSource(source('dflt', 'turso')); + svc.registerSource(source('plain', 'memory')); + + const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(report.refused).toEqual([]); + const modeOf = (name: string) => + turso.searchSpy.mock.calls.find(([, o]) => (o as { source: KnowledgeSource }).source.name === name)?.[1]?.retrieval; + expect(modeOf('kw')).toEqual({ mode: 'keyword' }); + expect(modeOf('dflt')).toEqual({ mode: 'hybrid' }); + expect(memory.searchSpy).toHaveBeenCalledOnce(); + expect('retrieval' in (memory.searchSpy.mock.calls[0]![1] as object)).toBe(false); + + // The mode and its origin are the operator's, at debug; the caller's answer carries neither. + const debug = lines.filter(([level]) => level === 'debug').map(([, m]) => m); + expect(debug).toContain("[knowledge] source 'kw' searched in 'keyword' mode (declared by the source)."); + expect(debug).toContain("[knowledge] source 'dflt' searched in 'hybrid' mode (the default of adapter 'turso')."); + expect(JSON.stringify(report)).not.toMatch(/keyword|hybrid|retrieval/); + }); +}); + +describe('a declared mode the adapter does not run — the four refusal points', () => { + function bootLike() { + const { lines, logger } = logged(); + const svc = new KnowledgeService({ logger }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + const memory = adapterOf('memory'); + return { svc, vec, memory, lines }; + } + + it('1 · the save is refused 400 VALIDATION_ERROR, listing the modes the store runs', async () => { + const svc = new KnowledgeService({ dataEngine: {} as IDataEngine }); + svc.registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + svc.registerAdapter('memory', adapterOf('memory')); + const ctx = { userId: 'u1', positions: [], permissions: [] } as never; + const onVec = await svc.admitAuthoredSource(source('s1', 'vec', 'keyword'), ctx); + expect(onVec).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 }); + expect((onVec as { message: string }).message).toContain("the store 'vec' runs 'vector' (default 'vector')"); + const onMemory = await svc.admitAuthoredSource(source('s2', 'memory', 'hybrid'), ctx); + expect(onMemory).toMatchObject({ admitted: false, code: 'VALIDATION_ERROR', status: 400 }); + expect((onMemory as { message: string }).message).toContain("the store 'memory' reports no retrieval modes"); + // A mode the store runs passes this point (the save goes on to its next check). + const ok = await svc.admitAuthoredSource(source('s3', 'vec', 'vector'), ctx); + expect((ok as { message?: string }).message ?? '').not.toContain('retrieval.mode'); + }); + + it('2 · registration in code refuses it only when its adapter already resolves; the loader takes it', () => { + const { svc, vec } = bootLike(); + svc.registerAdapter('vec', vec); + let refused: unknown; + try { + svc.registerSource(source('s1', 'vec', 'keyword')); + } catch (err) { + refused = err; + } + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("registerSource refused source 's1': its `retrieval.mode` is 'keyword'"); + expect(svc.getSource('s1')).toBeUndefined(); + // A published item meets no save and is not refused by the loader: 3 and 4 hold it. + svc.registerMetadataSource(source('s2', 'vec', 'hybrid')); + expect(svc.getSource('s2')).toBeDefined(); + // A store not registered yet is no verdict: the source is taken. + svc.registerSource(source('s3', 'pgvector', 'keyword')); + expect(svc.getSource('s3')).toBeDefined(); + }); + + it('3 · the boot reading names it once at error; 4 · every search lists it in `refused`, never runs it at the default', async () => { + const { svc, vec, lines } = bootLike(); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerSource(source('good', 'vec')); + svc.registerAdapter('vec', vec); + + expect(svc.reportUnsupportedRetrieval()).toEqual(['bad']); + const errors = lines.filter(([level]) => level === 'error').map(([, m]) => m); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("[knowledge] source 'bad' is not searched: its `retrieval.mode` is 'keyword'"); + expect(errors[0]).toContain(`answers ${RETRIEVAL_UNSUPPORTED_CODE}`); + + const both = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(both.hits.map((h) => h.sourceId)).toEqual(['good']); + expect(both.refused).toEqual([ + expect.objectContaining({ sourceId: 'bad', code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }), + ]); + expect(both.refused[0]!.message).toContain("Knowledge source 'bad' is not searched: its `retrieval.mode` is 'keyword'"); + // Never searched another way. + expect(vec.searchSpy.mock.calls.map(([, o]) => (o as { source: KnowledgeSource }).source.name)).toEqual(['good']); + + const alone = await svc.search('q', { sourceIds: ['bad'], executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }); + }); + + it('a mode declared on an adapter that reports none is refused at every search the same way', async () => { + const { svc, memory } = bootLike(); + svc.registerSource(source('s1', 'memory', 'vector')); + svc.registerAdapter('memory', memory); + expect(svc.reportUnsupportedRetrieval()).toEqual(['s1']); + const alone = await svc.search('q', { sourceIds: ['s1'], executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }); + expect(memory.searchSpy).not.toHaveBeenCalled(); + }); + + it('such a source is still indexed: the mode is read by search alone', async () => { + const find = vi.fn(async (_o: string, query: { where?: unknown }) => + query.where === undefined ? [{ id: 'r1', title: 'T1', notes: 'N1' }] : [], + ); + const svc = new KnowledgeService({ dataEngine: { find } as unknown as IDataEngine }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerAdapter('vec', vec); + const res = await svc.reindexSource('bad'); + expect(res.ok).toBe(true); + expect(res.indexed).toBe(1); + expect(vec.upsertSpy).toHaveBeenCalledOnce(); + }); + + it('a published item (the loader, its store already started) is registered and indexed, named at error, refused on every search', async () => { + const { lines, logger } = logged(); + const find = vi.fn(async (_o: string, query: { where?: unknown }) => + query.where === undefined ? [{ id: 'r1', title: 'T1', notes: 'N1' }] : [], + ); + const svc = new KnowledgeService({ logger, dataEngine: { find } as unknown as IDataEngine }); + const vec = adapterOf('vec', { modes: ['vector'], default: 'vector' }); + // The loader runs at kernel:ready and on metadata:reloaded, after every store's start(). + svc.registerAdapter('vec', vec); + const loader = new KnowledgeSourceLoader({ + service: svc, + logger, + readItems: async () => [source('pkg_bad', 'vec', 'keyword'), source('pkg_good', 'vec')], + namespaceOf: () => undefined, + buildOnReload: false, + }); + const pass = await loader.reconcile('boot'); + expect(pass.added.sort()).toEqual(['pkg_bad', 'pkg_good']); + expect(svc.getSource('pkg_bad')).toBeDefined(); + expect(lines.filter(([level, m]) => level === 'warn' && m.includes('pkg_bad'))).toEqual([]); + + // Still indexes: the mode is read by search alone. + expect(await svc.reindexSource('pkg_bad')).toMatchObject({ ok: true, indexed: 1 }); + expect(vec.upsertSpy).toHaveBeenCalledOnce(); + + // 3 · the boot reading names it at error. + expect(svc.reportUnsupportedRetrieval()).toEqual(['pkg_bad']); + const errors = lines.filter(([level]) => level === 'error').map(([, m]) => m); + expect(errors).toHaveLength(1); + expect(errors[0]).toContain("[knowledge] source 'pkg_bad' is not searched: its `retrieval.mode` is 'keyword'"); + + // 4 · every search lists it in `refused` and never runs it. + const both = await svc.searchWithRefusals('q', { executionContext: SYSTEM }); + expect(both.hits.map((h) => h.sourceId)).toEqual(['pkg_good']); + expect(both.refused).toEqual([ + expect.objectContaining({ sourceId: 'pkg_bad', code: RETRIEVAL_UNSUPPORTED_CODE, status: 503 }), + ]); + expect(vec.searchSpy.mock.calls.map(([, o]) => (o as { source: KnowledgeSource }).source.name)).toEqual(['pkg_good']); + }); + + it('a source on a store not mounted is named by the unmounted reading, not this one', () => { + const { svc } = bootLike(); + svc.registerSource(source('s1', 'pgvector', 'keyword')); + expect(svc.reportUnsupportedRetrieval()).toEqual([]); + expect(svc.describeRetrieval(svc.getSource('s1')!)).toBeUndefined(); + }); + + it('the plugin takes the reading at kernel:bootstrapped, beside the unmounted-adapter reading', async () => { + const reading = vi.spyOn(KnowledgeService.prototype, 'reportUnsupportedRetrieval'); + try { + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + kernel.use( + new KnowledgeServicePlugin({ + sources: [source('bad', 'vec', 'keyword'), source('good', 'vec')], + enableEventSync: false, + buildAtBoot: false, + }), + ); + kernel.use({ + name: 'test.late-store', + init: async () => undefined, + start: async (ctx) => { + ctx.getService('knowledge').registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + }, + }); + await kernel.bootstrap(); + expect(reading).toHaveBeenCalledTimes(1); + expect(reading.mock.results[0]?.value).toEqual(['bad']); + await kernel.shutdown(); + } finally { + reading.mockRestore(); + } + }); +}); + +describe('index_status carries each source\'s retrieval and each store\'s modes', () => { + it('the effective mode and its origin, the refusal, and "reports none" as an absent member', async () => { + const svc = new KnowledgeService(); + svc.registerSource(source('dflt', 'turso')); + svc.registerSource(source('bad', 'vec', 'keyword')); + svc.registerSource(source('plain', 'memory')); + svc.registerAdapter('turso', adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' })); + svc.registerAdapter('vec', adapterOf('vec', { modes: ['vector'], default: 'vector' })); + svc.registerAdapter('memory', adapterOf('memory')); + const answer = await knowledgeIndexStatusActionHandler(svc)({ + namespace: 'knowledge', + actionId: 'index_status', + values: {}, + payload: {}, + ctx: {}, + } as never); + const details = (answer as { + details: { sources: Array<{ id: string; retrieval?: unknown }>; adapters: unknown; defaultAdapter?: string }; + }).details; + // Three stores and none marked the deployment's: a source naming none binds to none. + expect(details.defaultAdapter).toBeUndefined(); + const byId = Object.fromEntries(details.sources.map((s) => [s.id, s.retrieval])); + expect(byId.dflt).toEqual({ mode: 'hybrid', from: 'adapter', modes: ALL_MODES, default: 'hybrid' }); + expect(byId.bad).toEqual({ declared: 'keyword', refused: true, modes: ['vector'], default: 'vector' }); + expect(byId.plain).toEqual({}); + expect(details.adapters).toEqual([ + { id: 'turso', retrieval: { modes: ALL_MODES, default: 'hybrid' } }, + { id: 'vec', retrieval: { modes: ['vector'], default: 'vector' } }, + { id: 'memory' }, + ]); + }); + + it('names the store a source that names none binds to: the deployment\'s, else the only one', async () => { + const marked = new KnowledgeService({ deploymentAdapter: 'turso' }); + marked.registerAdapter('memory', adapterOf('memory')); + marked.registerAdapter('turso', adapterOf('turso', { modes: ALL_MODES, default: 'hybrid' })); + const only = new KnowledgeService(); + only.registerAdapter('memory', adapterOf('memory')); + const ask = { namespace: 'knowledge', actionId: 'index_status', values: {}, payload: {}, ctx: {} } as never; + const read = async (svc: KnowledgeService) => + ((await knowledgeIndexStatusActionHandler(svc)(ask)) as { details: { defaultAdapter?: string } }).details.defaultAdapter; + expect(await read(marked)).toBe('turso'); + expect(await read(only)).toBe('memory'); + }); +}); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index 7b6e8f6ac82..0b68acfa628 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -64,10 +64,12 @@ export { knowledgeRebuildActionHandler, } from './knowledge-build-actions.js'; export type { + KnowledgeIndexStatusAdapter, KnowledgeIndexStatusBuild, KnowledgeIndexStatusEntry, KnowledgeIndexStatusQueue, } from './knowledge-build-actions.js'; +export type { KnowledgeRetrievalReading, RetrievalModeOrigin } from './knowledge-retrieval-mode.js'; export { KNOWLEDGE_SYNC_STATE_OBJECT, ObjectStoreKnowledgeSyncState } from './knowledge-sync-state.js'; export type { KnowledgeStoredBuild, diff --git a/packages/services/service-knowledge/src/knowledge-build-actions.ts b/packages/services/service-knowledge/src/knowledge-build-actions.ts index a8540c0f8bb..accd5719635 100644 --- a/packages/services/service-knowledge/src/knowledge-build-actions.ts +++ b/packages/services/service-knowledge/src/knowledge-build-actions.ts @@ -21,7 +21,10 @@ * build, with its counts while it runs and once it ended, and its record * syncs that failed and are not yet repaired. Beside the sources, the * record-sync messages waiting on the queue (`pendingRecordSyncs`, every - * source's together). + * source's together). [#38692 phase 1a] Each source's retrieval reading + * (`retrieval`: its effective mode and where it came from, the modes its + * store runs, a refusal), each mounted store's modes (`adapters`) and the + * store a source that names none binds to (`defaultAdapter`). * * Both run through the settings action door (`POST /api/settings/knowledge/ACTION`), * which gates an HTTP caller on the namespace's write permission, @@ -47,6 +50,8 @@ import type { import type { KnowledgeService, KnowledgeSourceDescription } from './knowledge-service.js'; import type { KnowledgeStoredBuild, KnowledgeSyncFailures } from './knowledge-sync-state.js'; import { KNOWLEDGE_RECORD_SYNC_QUEUE } from './knowledge-record-sync-queue.js'; +import type { KnowledgeRetrievalReading } from './knowledge-retrieval-mode.js'; +import type { KnowledgeRetrievalMode, KnowledgeSource } from '@objectstack/spec/ai'; /** The `knowledge` settings action that starts a rebuild of one source. */ export const KNOWLEDGE_REBUILD_ACTION = 'rebuild'; @@ -66,6 +71,9 @@ export type KnowledgeBuildActionsService = Pick< | 'syncStateOf' | 'hasDurableSyncState' | 'pendingRecordSyncs' + | 'describeRetrieval' + | 'listAdapters' + | 'getAdapter' >; /** One source in an `index_status` answer. */ @@ -88,6 +96,19 @@ export interface KnowledgeIndexStatusEntry { failures: KnowledgeSyncFailures | null; /** Why the sync state could not be read; absent when it was. */ syncStateError?: string; + /** + * The source's retrieval mode (#38692 phase 1a): the mode its searches run + * and where it came from, the modes its adapter runs, and whether its + * searches are refused. Absent while its adapter is not placed or mounted. + */ + retrieval?: KnowledgeRetrievalReading; +} + +/** One mounted adapter in an `index_status` answer, and the retrieval modes it reports. */ +export interface KnowledgeIndexStatusAdapter { + id: string; + /** The modes it runs and its default; absent: it reports none (Studio shows "驱动未声明"). */ + retrieval?: { modes: KnowledgeRetrievalMode[]; default: KnowledgeRetrievalMode }; } /** @@ -327,6 +348,7 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions const sources: KnowledgeIndexStatusEntry[] = []; for (const source of targets) { const adapter = service.boundAdapterId(source.source); + const retrieval = service.describeRetrieval(source.source); sources.push({ id: source.id, label: source.source.label, @@ -334,8 +356,16 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ...(source.packageId === undefined ? {} : { packageId: source.packageId }), index: await service.readIndexState(source.id), ...(await readSyncState(service, source.id)), + ...(retrieval === undefined ? {} : { retrieval }), }); } + // The store a source that names none binds to (ADR-0161 K4), for a form + // that shows a new source's retrieval modes before it names a store. + const defaultAdapter = service.boundAdapterId({ name: '', label: '' } as unknown as KnowledgeSource); + const adapters: KnowledgeIndexStatusAdapter[] = service.listAdapters().map((id) => { + const report = service.getAdapter(id).capabilities?.retrieval; + return { id, ...(report === undefined ? {} : { retrieval: { modes: [...report.modes], default: report.default } }) }; + }); const queue = await readQueue(service); const due = sources.filter((s) => s.index.due).length; const running = sources.filter((s) => s.build?.status === 'running').length; @@ -345,7 +375,12 @@ export function knowledgeIndexStatusActionHandler(service: KnowledgeBuildActions ok: true, severity: 'info', message: `${sources.length} source(s): ${due} need a build, ${running} building, ${failing} with failed syncs${pending}.`, - details: { sources, ...(queue === undefined ? {} : { queue }) }, + details: { + sources, + adapters, + ...(defaultAdapter === undefined ? {} : { defaultAdapter }), + ...(queue === undefined ? {} : { queue }), + }, }; }; } diff --git a/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts new file mode 100644 index 00000000000..b36da162126 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-retrieval-mode.ts @@ -0,0 +1,138 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A source's retrieval mode (ADR-0161, the dated note of 2026-11-30 under K8; + * ruling 7270218011 on #38692, phase 1a): which mode a search of the source + * runs, where that came from, and the refusal of a mode its adapter does not + * run. + * + * ## The effective mode + * + * The source's declaration (`source.retrieval.mode`), else the adapter's + * reported default (`capabilities.retrieval.default`). An adapter that + * reports no modes is never told one: a source on it that declares none is + * searched as before, and one that declares a mode is refused. + * + * ## The four refusal points + * + * A source that declares a mode its adapter does not list is refused, never + * searched another way: + * + * 1. at an author's save (Studio, REST, an MCP draft): `400 + * VALIDATION_ERROR`, listing the modes the adapter runs + * (`admitAuthoredSource`); + * 2. at registration in code, only when its adapter already resolves — a + * store registers in its own `start()`, after a source registered at + * `init()`, so "not registered yet" is no verdict (AGENTS.md, startup + * registry reads) (`registerSource`). A published item (a package + * install, the stack's `knowledgeSources`) meets no save and is not + * refused by the loader: it is registered and indexed, and 3 and 4 hold + * it (`registerMetadataSource`); + * 3. once after boot, at `error`, naming the source and the modes + * (`reportUnsupportedRetrieval`, beside `reportUnmountedAdapters`); + * 4. on every search: the source is listed in `refused` with + * {@link RETRIEVAL_UNSUPPORTED_CODE}, as a source whose adapter is not + * mounted is (`planSearches`). + * + * Such a source still builds and syncs its index: the mode is read by search + * alone, so changing it rebuilds nothing. + */ + +import type { KnowledgeRetrievalMode, KnowledgeSource } from '@objectstack/spec/ai'; +import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; + +/** + * The code of a search refused because the source declares a mode its + * adapter does not run: the code a source whose adapter is not mounted is + * refused with, since in both the deployment cannot serve the source as + * written (`503`). + */ +export const RETRIEVAL_UNSUPPORTED_CODE = 'SERVICE_UNAVAILABLE'; + +/** Where a search's effective mode came from. */ +export type RetrievalModeOrigin = 'source' | 'adapter'; + +/** {@link resolveRetrievalMode}'s answer. */ +export type RetrievalResolution = + /** Searched in `mode`, from `from`; absent `mode`: the adapter reports no modes and none is declared. */ + | { refused: false; mode?: KnowledgeRetrievalMode; from?: RetrievalModeOrigin } + /** The source declares `declared`, which the adapter does not list (`modes`; absent: it reports none). */ + | { refused: true; declared: KnowledgeRetrievalMode; modes?: readonly KnowledgeRetrievalMode[] }; + +/** + * A source's retrieval as the operator reads it (the `index_status` entry's + * `retrieval`): never in a search's answer to the caller. + */ +export interface KnowledgeRetrievalReading { + /** The mode the source declares; absent: it declares none. */ + declared?: KnowledgeRetrievalMode; + /** The mode its searches run; absent when refused, or when the adapter reports no modes and none is declared. */ + mode?: KnowledgeRetrievalMode; + /** Where {@link mode} came from. */ + from?: RetrievalModeOrigin; + /** The modes its adapter runs; absent: the adapter reports none (Studio shows "驱动未声明"). */ + modes?: readonly KnowledgeRetrievalMode[]; + /** Its adapter's default mode; absent with {@link modes}. */ + default?: KnowledgeRetrievalMode; + /** Every search of it is refused with {@link RETRIEVAL_UNSUPPORTED_CODE}: it declares a mode its adapter does not run. */ + refused?: true; +} + +/** {@link KnowledgeRetrievalReading} of `source` on `adapter`. */ +export function readRetrieval(source: Pick, adapter: IKnowledgeAdapter): KnowledgeRetrievalReading { + const report = adapter.capabilities?.retrieval; + const declared = declaredRetrievalMode(source); + const resolved = resolveRetrievalMode(source, adapter); + return { + ...(declared === undefined ? {} : { declared }), + ...(resolved.refused ? { refused: true as const } : {}), + ...(!resolved.refused && resolved.mode !== undefined ? { mode: resolved.mode, from: resolved.from } : {}), + ...(report === undefined ? {} : { modes: [...report.modes], default: report.default }), + }; +} + +/** The mode `source` declares, if any (`retrieval: {}` declares none). */ +export function declaredRetrievalMode(source: Pick): KnowledgeRetrievalMode | undefined { + return source.source?.retrieval?.mode; +} + +/** The effective mode of a search of `source` on `adapter`, or the refusal (see the module header). */ +export function resolveRetrievalMode(source: Pick, adapter: IKnowledgeAdapter): RetrievalResolution { + const report = adapter.capabilities?.retrieval; + const declared = declaredRetrievalMode(source); + if (declared === undefined) { + return report === undefined ? { refused: false } : { refused: false, mode: report.default, from: 'adapter' }; + } + if (report === undefined || !report.modes.includes(declared)) { + return { refused: true, declared, ...(report === undefined ? {} : { modes: report.modes }) }; + } + return { refused: false, mode: declared, from: 'source' }; +} + +/** The modes an adapter runs, as a sentence part: `'vector', 'keyword' and 'hybrid' (default 'hybrid')`, or that it reports none. */ +export function adapterModesText(adapterId: string, modes: readonly KnowledgeRetrievalMode[] | undefined, byDefault?: KnowledgeRetrievalMode): string { + if (modes === undefined || modes.length === 0) return `the store '${adapterId}' reports no retrieval modes, so a source on it may only leave \`retrieval.mode\` out`; + const listed = modes.map((m) => `'${m}'`); + const joined = listed.length === 1 ? listed[0] : `${listed.slice(0, -1).join(', ')} and ${listed[listed.length - 1]}`; + return `the store '${adapterId}' runs ${joined}${byDefault === undefined ? '' : ` (default '${byDefault}')`}`; +} + +/** + * Why a source declaring `declared` is refused on `adapterId`, and what to + * write: the rule, then the remedies. One text for every point; each point + * puts its own subject before it and its own consequence after it. + */ +export function retrievalRefusalText( + adapterId: string, + declared: KnowledgeRetrievalMode, + adapter: IKnowledgeAdapter, +): string { + const report = adapter.capabilities?.retrieval; + const remedies = report === undefined || report.modes.length === 0 + ? 'Remove `retrieval.mode`, or bind the source to a store that runs it' + : `Write one of ${report.modes.map((m) => `'${m}'`).join(', ')} as \`retrieval.mode\`, or remove it for the store's default, or bind the source to a store that runs '${declared}'`; + return ( + `its \`retrieval.mode\` is '${declared}', and ${adapterModesText(adapterId, report?.modes, report?.default)}; ` + + `a source is never searched in a mode other than the one it declares. ${remedies}.` + ); +} diff --git a/packages/services/service-knowledge/src/knowledge-service-admission.ts b/packages/services/service-knowledge/src/knowledge-service-admission.ts index eef37eca116..b1411c77172 100644 --- a/packages/services/service-knowledge/src/knowledge-service-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-service-admission.ts @@ -65,6 +65,7 @@ import { unplacedSourceText, } from './knowledge-service-top-level.js'; import type { KnowledgeService } from './knowledge-service.js'; +import { resolveRetrievalMode, retrievalRefusalText } from './knowledge-retrieval-mode.js'; /** * The `KnowledgeService` members the bodies in this module read: every one @@ -75,7 +76,9 @@ import type { KnowledgeService } from './knowledge-service.js'; * body here assigns. */ export interface KnowledgeAdmissionHost { + readonly adapters: KnowledgeService['adapters']; readonly admissionDeps: KnowledgeService['admissionDeps']; + readonly boundAdapterId: KnowledgeService['boundAdapterId']; readonly handed: KnowledgeService['handed']; readonly handedSources: KnowledgeService['handedSources']; readonly held: KnowledgeService['held']; @@ -192,7 +195,14 @@ export function admissionDeps( export async function admitAuthoredSource( this: Pick< KnowledgeAdmissionHost, - 'admissionDeps' | 'held' | 'listAdapters' | 'options' | 'reportGateFailure' | 'unmountedAdapterSaveText' + | 'adapters' + | 'admissionDeps' + | 'boundAdapterId' + | 'held' + | 'listAdapters' + | 'options' + | 'reportGateFailure' + | 'unmountedAdapterSaveText' >, item: unknown, ctx: ExecutionContext | undefined, @@ -255,6 +265,22 @@ export async function admitAuthoredSource( if (typeof authoredAdapter === 'string' && !registeredAdapters.includes(authoredAdapter)) { return refuse(400, 'VALIDATION_ERROR', `${named}: ${this.unmountedAdapterSaveText(authoredAdapter, registeredAdapters, wording.again)}`); } + // [ADR-0161, the dated note of 2026-11-30 under K8; refusal point 1] A source + // that declares a retrieval mode its store does not run is refused at its + // save, listing the modes the store runs. The store is the one it names, + // else the deployment's: both are registered by now (above). A mode + // outside the three is the parse's to refuse. + const declaredMode = (declared as { retrieval?: { mode?: unknown } }).retrieval?.mode; + if (declaredMode === 'vector' || declaredMode === 'keyword' || declaredMode === 'hybrid') { + const adapterId = this.boundAdapterId({ adapter: typeof authoredAdapter === 'string' ? authoredAdapter : undefined } as KnowledgeSource); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId !== undefined && adapter !== undefined) { + const resolved = resolveRetrievalMode({ source: { retrieval: { mode: declaredMode } } } as KnowledgeSource, adapter); + if (resolved.refused) { + return refuse(400, 'VALIDATION_ERROR', `${named}: ${retrievalRefusalText(adapterId, declaredMode, adapter)}`); + } + } + } const engine = this.options.dataEngine; if (!engine) return unavailable('the knowledge service has no data engine'); diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index db57d22e7a8..c129dc6dbc8 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -782,11 +782,13 @@ export class KnowledgeServicePlugin implements Plugin { } }); // Every store registers its adapter in its own start(), so the reading of - // which sources name an unmounted one is taken once all have started. + // which sources name an unmounted one, or a retrieval mode their store + // does not run, is taken once all have started. // Held, the one line of the held state names what is missing instead. ctx.hook('kernel:bootstrapped', () => { if (this.service?.heldReading()) return; this.service?.reportUnmountedAdapters(); + this.service?.reportUnsupportedRetrieval(); }); // [ADR-0161 K1] The daily reconcile. The job service may start after this // plugin: it is resolved once every plugin has started, when an absent diff --git a/packages/services/service-knowledge/src/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index e2d2e8e440d..c55fa078483 100644 --- a/packages/services/service-knowledge/src/knowledge-service-search.ts +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -38,6 +38,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { TenancyPosture } from '@objectstack/spec/security'; import { refusal } from './knowledge-tools.js'; +import { RETRIEVAL_UNSUPPORTED_CODE, resolveRetrievalMode, retrievalRefusalText } from './knowledge-retrieval-mode.js'; import { type AffinityCallerFacts, affinityFactNeeds, @@ -777,6 +778,33 @@ export async function planSearches( out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); continue; } + // [#38692 phase 1a] The effective retrieval mode: the source's + // declaration, else the adapter's default. A declared mode the adapter + // does not run is refused like an adapter that cannot serve, never + // searched another way; the boot said so at `error` + // (`reportUnsupportedRetrieval`). The mode and where it came from are the + // operator's, at `debug`, never the caller's answer. + const retrieval = resolveRetrievalMode(entry.source, adapter); + if (retrieval.refused) { + out.push({ + ...entry, + binding: { + refusal: { + code: RETRIEVAL_UNSUPPORTED_CODE, + status: 503, + message: `Knowledge source '${this.label(entry.source)}' is not searched: ` + + retrievalRefusalText(adapterId, retrieval.declared, adapter), + }, + }, + }); + continue; + } + if (retrieval.mode !== undefined) { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(entry.source)}' searched in '${retrieval.mode}' mode ` + + `(${retrieval.from === 'source' ? 'declared by the source' : `the default of adapter '${adapterId}'`}).`, + ); + } const plan = await this.planIndex(entry.source, adapter, chunkTarget); if (proveIndex === true) { const unproven = await this.unprovenIndex(plan); @@ -803,6 +831,7 @@ export async function planSearches( binding: { adapterId, adapter }, fingerprint: plan.index.fingerprint, ...(proveIndex === true ? { verifyHits: true as const } : {}), + ...(retrieval.mode === undefined ? {} : { retrieval: { mode: retrieval.mode } }), }); } return out; @@ -908,7 +937,7 @@ export async function searchRound( refused: KnowledgeSearchRefusal[], ): Promise> { const out = new Map(); - for (const { source, organizationIds, fingerprint, scope, binding } of sources) { + for (const { source, organizationIds, fingerprint, scope, binding, retrieval } of sources) { // 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. The adapter was @@ -927,6 +956,7 @@ export async function searchRound( ...(organizationIds === undefined ? {} : { organizationIds }), ...(fingerprint === undefined ? {} : { index: { fingerprint } }), ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), + ...(retrieval === undefined ? {} : { retrieval: { mode: retrieval.mode } }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts index a46f5c61400..d82fce85087 100644 --- a/packages/services/service-knowledge/src/knowledge-service-sources.ts +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -8,7 +8,10 @@ * `onSourcesChanged`, `sourcesChanged`, `unregisterSource`, `dropMetadataSource`, * `forget`, `listSources`, `describeSources`, `getSource`, `describeSource`, * `handed`, `handedSources`, `adapterLabel`, `faceOfKey`, `requireEntry`, moved - * out of `knowledge-service.ts` whole. + * out of `knowledge-service.ts` whole. `reportUnsupportedRetrieval`, `describeRetrieval` and + * the registration refusal beside them were written here (#38692 phase 1a), the + * retrieval-mode counterparts of `reportUnmountedAdapters` and + * `refuseUnplacedSource`. * * A MOVE, not a redesign. Each function below is the body of the * `KnowledgeService` member of the same name as it stood, re-indented one @@ -51,6 +54,13 @@ import { unplacedSourceError, } from './knowledge-service-top-level.js'; import type { KnowledgeService } from './knowledge-service.js'; +import { + type KnowledgeRetrievalReading, + RETRIEVAL_UNSUPPORTED_CODE, + readRetrieval, + resolveRetrievalMode, + retrievalRefusalText, +} from './knowledge-retrieval-mode.js'; /** * The `KnowledgeService` members the bodies in this module read: every one @@ -187,6 +197,72 @@ export function reportUnmountedAdapters( return named; } +/** + * Refuse, at registration in code, a source that declares a retrieval mode its + * adapter does not run (#38692 phase 1a, refusal point 2) — only when that + * adapter already resolves: a store registers in its own `start()`, after a + * source registered at `init()`, so "not registered yet" is no verdict + * (AGENTS.md, startup registry reads). The boot's reading + * ({@link reportUnsupportedRetrieval}) and every search hold the rest. + * + * The code door alone: a published `knowledge_source` item (a package + * install, the stack's `knowledgeSources`, a peer's write) meets no save, and + * the loader always runs after every store has started, so a refusal there + * would drop the item whole. It is registered and indexed as any other, and + * points 3 and 4 hold it: named at `error` after boot, refused on every + * search. + */ +function refuseUnsupportedRetrieval( + this: Pick, + source: KnowledgeSource, + door: string, +): void { + if (source.source?.retrieval?.mode === undefined) return; + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId === undefined || adapter === undefined) return; + const resolved = resolveRetrievalMode(source, adapter); + if (!resolved.refused) return; + throw codedError( + 'VALIDATION_ERROR', + 400, + `[knowledge] ${door} refused source '${source.name}': ${retrievalRefusalText(adapterId, resolved.declared, adapter)}`, + ); +} + +/** The body of {@link KnowledgeService.reportUnsupportedRetrieval}; the member's docblock there is its contract. */ +export function reportUnsupportedRetrieval( + this: Pick, +): string[] { + const named: string[] = []; + for (const { id, source } of this.describeSources()) { + if (source.source?.retrieval?.mode === undefined) continue; + // A source this boot cannot place, or whose adapter is not mounted, is + // named by `reportUnmountedAdapters`; its mode has no adapter to read. + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + if (adapterId === undefined || adapter === undefined) continue; + const resolved = resolveRetrievalMode(source, adapter); + if (!resolved.refused) continue; + this.options.logger?.error?.( + `[knowledge] source '${id}' is not searched: ${retrievalRefusalText(adapterId, resolved.declared, adapter)} ` + + `Every search of it answers ${RETRIEVAL_UNSUPPORTED_CODE} until then; it is still indexed.`, + ); + named.push(id); + } + return named; +} + +/** The body of {@link KnowledgeService.describeRetrieval}; the member's docblock there is its contract. */ +export function describeRetrieval( + this: Pick, + source: KnowledgeSource, +): KnowledgeRetrievalReading | undefined { + const adapterId = this.boundAdapterId(source); + const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); + return adapter === undefined ? undefined : readRetrieval(source, adapter); +} + /** The body of {@link KnowledgeService.listAdapters}; the member's docblock there is its contract. */ export function listAdapters(this: Pick): string[] { return [...this.adapters.keys()]; @@ -194,7 +270,10 @@ export function listAdapters(this: Pick): stri /** The body of {@link KnowledgeService.registerSource}; the member's docblock there is its contract. */ export function registerSource( - this: Pick, + this: Pick< + KnowledgeSourcesHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, source: KnowledgeSource, ): void { const parsed = parseKnowledgeSource(source); @@ -206,6 +285,7 @@ export function registerSource( ); } this.refuseUnplacedSource(parsed.source, 'registerSource'); + refuseUnsupportedRetrieval.call(this, parsed.source, 'registerSource'); const packageId = packageIdOfItem(parsed.source); if (packageId !== undefined) { throw codedError( @@ -224,11 +304,17 @@ export function registerSource( /** The body of {@link KnowledgeService.registerMetadataSource}; the member's docblock there is its contract. */ export function registerMetadataSource( - this: Pick, + this: Pick< + KnowledgeSourcesHost, + 'adapterLabel' | 'adapters' | 'boundAdapterId' | 'options' | 'refuseUnplacedSource' | 'registry' | 'sourcesChanged' + >, source: KnowledgeSource, holder: KnowledgeSourceHolder = {}, ): KnowledgeSourceEntry { this.refuseUnplacedSource(source, 'The knowledge_source loader'); + // A mode its store does not run is not refused here (see + // refuseUnsupportedRetrieval): the item is registered and indexed, and the + // boot's reading and every search refuse it. const { entry, replaced } = this.registry.register(source, 'metadata', holder); this.options.logger?.info?.( `[knowledge] source ${replaced ? 'reloaded' : 'registered'}: ${entry.face} (adapter=${this.adapterLabel(entry.authored)}` + diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts index 21c8398272a..2c3f4df3094 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -22,7 +22,13 @@ import type { IQueueService, } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { + KnowledgeDocument, + KnowledgeHit, + KnowledgeRetrievalMode, + KnowledgeSource, + ObjectKnowledgeSource, +} from '@objectstack/spec/ai'; import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields } from '@objectstack/core'; import { type TenancyPosture, postureEnforcesWall } from '@objectstack/spec/security'; import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; @@ -353,6 +359,11 @@ export interface SearchTarget { scope?: AdapterScopeTerm[]; /** Each hit is checked against its live record before it is served ({@link KnowledgeService.dropUnverifiedHits}). */ verifyHits?: true; + /** + * The effective retrieval mode the adapter is told (`knowledge-retrieval-mode.ts`): + * absent where the adapter reports no modes and the source declares none. + */ + retrieval?: { mode: KnowledgeRetrievalMode }; } /** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 1382ceaf226..b490863ec70 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -22,6 +22,7 @@ import { } from './knowledge-source-registry.js'; import type { KnowledgeAdmissionDeps } from './knowledge-source-admission.js'; import type { SearchScopeEntry } from './knowledge-search-scope.js'; +import type { KnowledgeRetrievalReading } from './knowledge-retrieval-mode.js'; import type { KnowledgeBuildFence, KnowledgeBuildProgress, @@ -285,6 +286,28 @@ export class KnowledgeService implements IKnowledgeService { return KnowledgeSourcesFacet.reportUnmountedAdapters.call(knowledgeServiceHost.of(this)); } + /** + * Say once, at `error`, which registered sources declare a retrieval mode + * (`source.retrieval.mode`) their mounted adapter does not run — the boot's + * reading, taken beside {@link reportUnmountedAdapters} (#38692 phase 1a, + * refusal point 3). Every search of such a source lists it in `refused`; + * it is still indexed. Answers the sources named. + */ + reportUnsupportedRetrieval(): string[] { + return KnowledgeSourcesFacet.reportUnsupportedRetrieval.call(knowledgeServiceHost.of(this)); + } + + /** + * `source`'s retrieval mode as the operator reads it: the mode it declares, + * the one its searches run and where that came from, the modes its adapter + * runs, and whether its searches are refused (`knowledge-retrieval-mode.ts`). + * `undefined` while its adapter is not placed or not mounted. For a status + * answer, never for a search's answer. + */ + describeRetrieval(source: KnowledgeSource): KnowledgeRetrievalReading | undefined { + return KnowledgeSourcesFacet.describeRetrieval.call(knowledgeServiceHost.of(this), source); + } + listAdapters(): string[] { return KnowledgeSourcesFacet.listAdapters.call(knowledgeServiceHost.of(this)); } diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index f4e41c3d050..55202a5f3ca 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -79,6 +79,10 @@ * (`capabilities.retrieval`), and the same fixture is searched under each * mode it lists: `vector` leaves that passage out, `keyword` answers it * alone, and the default handed explicitly answers what no mode answers. + * Through a real `KnowledgeService`, every adapter is handed the mode a + * source declares, or its own default, or nothing when it reports no modes; + * a declared mode it does not list is refused at registration and at every + * search, and the source still indexes. */ import { describe, expect, it, vi } from 'vitest'; @@ -90,7 +94,7 @@ import type { AdapterScopeTerm, AdapterSearchOptions, } from '@objectstack/spec/contracts'; -import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { KnowledgeDocument, KnowledgeRetrievalMode, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import { KNOWLEDGE_RETRIEVAL_MODES } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; @@ -708,6 +712,74 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + // objectstack#38692 phase 1a. + describe('the retrieval mode through KnowledgeService.search', () => { + const ROWS: Row[] = [{ id: 'r1', body: 'alpine meadow harbour', status: 'published' }]; + const withMode = (id: string, mode?: KnowledgeRetrievalMode): KnowledgeSource => + objectSource(id, mode === undefined ? {} : { retrieval: { mode } }); + + it('no mode declared: the adapter is handed its own default, or nothing when it reports no modes', async () => { + const source = withMode('mode_default'); + const h = await serviceOver(make, ROWS, source); + await h.svc.reindexSource(source.name); + await h.svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }); + const report = h.adapter.capabilities?.retrieval; + expect(lastOf(h.searched)?.retrieval).toEqual(report === undefined ? undefined : { mode: report.default }); + }); + + for (const mode of KNOWLEDGE_RETRIEVAL_MODES) { + it(`'${mode}' declared: handed to the adapter when it lists it; when it does not, refused at registration in code and at every search, and a published item still indexes`, async () => { + const source = withMode(`mode_${mode}`, mode); + const probe: IKnowledgeAdapter = await make(); + const listed = probe.capabilities?.retrieval?.modes.includes(mode) === true; + if (listed) { + const h = await serviceOver(make, ROWS, source); + await h.svc.reindexSource(source.name); + await h.svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }); + expect(lastOf(h.searched)?.retrieval).toEqual({ mode }); + return; + } + // Its adapter already registered: registration refuses it. + const refused = await serviceOver(make, ROWS, source).then( + () => undefined, + (err: unknown) => err, + ); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + // Registered before its store: it still indexes, and every search refuses it, never run another way. + const svc = new KnowledgeService({ dataEngine: rowsEngine(ROWS) }); + svc.registerSource(source); + const adapter: IKnowledgeAdapter = await make(); + const search = vi.spyOn(adapter, 'search'); + svc.registerAdapter('under_test', adapter); + expect(await svc.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1 }); + expect(svc.reportUnsupportedRetrieval()).toEqual([source.name]); + // The only source asked for is refused, so the search answers the refusal, naming it. + const alone = await svc.search('alpine meadow', { topK: 1, executionContext: SYSTEM }).catch((e: unknown) => e); + expect(alone).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect((alone as { refused?: unknown }).refused).toEqual([ + expect.objectContaining({ sourceId: source.name, code: 'SERVICE_UNAVAILABLE', status: 503 }), + ]); + expect(search).not.toHaveBeenCalled(); + + // A published item, loaded after its store started (the loader's door): never refused + // there, it is registered and indexes, and the boot's reading and every search refuse it. + const published = new KnowledgeService({ dataEngine: rowsEngine(ROWS) }); + const store: IKnowledgeAdapter = await make(); + const storeSearch = vi.spyOn(store, 'search'); + published.registerAdapter('under_test', store); + published.registerMetadataSource(source); + expect(published.getSource(source.name)).toBeDefined(); + expect(await published.reindexSource(source.name)).toMatchObject({ ok: true, indexed: 1 }); + expect(published.reportUnsupportedRetrieval()).toEqual([source.name]); + const refusedSearch = await published + .search('alpine meadow', { topK: 1, executionContext: SYSTEM }) + .catch((e: unknown) => e); + expect(refusedSearch).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(storeSearch).not.toHaveBeenCalled(); + }); + } + }); + describe('the organization filter through KnowledgeService.search', () => { for (const posture of ['isolated', 'group'] as const) { it(`${posture}: a search from organization A never ranks or returns B's documents`, async () => { diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index f50d75d32b5..3be78301bfd 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -122,16 +122,18 @@ } }, "retrieval": { - "status": "planned", + "status": "live", "verifiedAt": "2026-11-30", - "authorWarn": true, - "authorHint": "Keep it, but nothing reads it yet: until the knowledge service reads it, a source is searched in its store's default mode whatever it declares, and a mode the store does not run is not refused.", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it, and drop `authorWarn` / `authorHint` in that same edit (a warned `live` row reds this gate). Enters neither the index fingerprint nor the recipe hash.", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — the effective mode: the source's declaration, else the adapter's `capabilities.retrieval.default`; packages/services/service-knowledge/src/knowledge-service-search.ts#planSearches — every search resolves it, hands it to the adapter as `AdapterSearchOptions.retrieval` (`searchRound`) and refuses a mode the adapter does not list in `refused` (SERVICE_UNAVAILABLE); packages/services/service-knowledge/src/knowledge-service-admission.ts#admitAuthoredSource — the save refuses it (400 VALIDATION_ERROR, listing the modes the store runs); packages/services/service-knowledge/src/knowledge-service-sources.ts#registerSource — registration in code refuses it when the adapter already resolves (a published item is registered and indexed through #registerMetadataSource, and the next two refuse it); packages/services/service-knowledge/src/knowledge-service-sources.ts#reportUnsupportedRetrieval — the boot's reading names it at `error`.", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "Ruling 7270218011 on #38692, phase 1a (ADR-0161, the dated note of 2026-11-30 under K8). Strict, `retrieval: {}` allowed. Read by search alone: enters neither the index fingerprint nor the recipe hash, so changing it rebuilds nothing, and a source whose mode is refused still indexes. knowledge-turso and knowledge-pgvector run each mode; an adapter that reports no modes (knowledge-memory) takes a source that leaves the mode out.", "children": { "mode": { - "status": "planned", + "status": "live", "verifiedAt": "2026-11-30", - "note": "Planned with its container `retrieval` (see that row): `vector`, `keyword` or `hybrid`; omitted means the adapter's default." + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-retrieval-mode.ts#resolveRetrievalMode — `vector`, `keyword` or `hybrid`, handed to the adapter as `AdapterSearchOptions.retrieval.mode`; omitted means the adapter's default." } } }, diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index 1fcc479c9f3..011bd5fd35d 100644 --- a/packages/spec/liveness/state-counts/knowledge_source.md +++ b/packages/spec/liveness/state-counts/knowledge_source.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `knowledge_source` | 26 | 0 | 0 | 6 | 1 | 33 | +| `knowledge_source` | 27 | 0 | 0 | 6 | 0 | 33 |