From 1ff58575674eb31c246ca3f6a40858c596158ceb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:32:22 +0000 Subject: [PATCH 01/14] feat(spec): source.retrieval.mode, AdapterCapabilities.retrieval and AdapterSearchOptions.retrieval (wip) --- .../src/__tests__/index-fingerprint.test.ts | 14 +++ .../services/service-knowledge/src/testing.ts | 91 +++++++++++++++++++ packages/spec/liveness/knowledge_source.json | 12 +++ .../src/ai/knowledge-source.metadata-form.ts | 20 ++++ packages/spec/src/ai/knowledge-source.test.ts | 43 +++++++++ packages/spec/src/ai/knowledge-source.zod.ts | 68 ++++++++++++++ .../spec/src/contracts/knowledge-adapter.ts | 49 +++++++++- 7 files changed, 294 insertions(+), 3 deletions(-) diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 9061a06536f..2168abc0b70 100644 --- a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -170,3 +170,17 @@ describe('recipe hash (ADR-0161 K7)', () => { expect(computeRecipeHash({ source: source({ content: ['body'] }), schema })).toBe(computeRecipeHash({ source: source(), schema })); }); }); + +// `source.retrieval` is read on every search and by no build (ADR-0161, the +// dated note on retrieval modes): neither hash moves with it, so changing a +// source's retrieval mode rebuilds nothing. +describe('retrieval mode (ADR-0161, the dated note on retrieval modes)', () => { + it('changes neither the index fingerprint nor the recipe hash', () => { + const fingerprint = computeIndexFingerprint({ source: source(), embedding, split }); + const recipe = computeRecipeHash({ source: source() }); + for (const retrieval of [{}, { mode: 'vector' }, { mode: 'keyword' }, { mode: 'hybrid' }]) { + expect(computeIndexFingerprint({ source: source({ retrieval }), embedding, split })).toBe(fingerprint); + expect(computeRecipeHash({ source: source({ retrieval }) })).toBe(recipe); + } + }); +}); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 036bf9be61c..ba240142225 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -74,6 +74,11 @@ * whose figure and exception words one passage holds, among passages that * hold the question's characters one by one and none of its words: the * passage is ranked. + * + * An adapter that declares `retrieval` reports its modes and default + * (`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. */ import { describe, expect, it, vi } from 'vitest'; @@ -86,6 +91,7 @@ import type { AdapterSearchOptions, } from '@objectstack/spec/contracts'; import type { KnowledgeDocument, 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'; import { KnowledgeService, type KnowledgeLogger } from './knowledge-service.js'; @@ -148,6 +154,17 @@ export interface KnowledgeAdapterContractOptions { * behaviour. Absent: `false`. */ keywordLeg?: boolean; + /** + * `capabilities.retrieval` (ADR-0161, the dated note on retrieval modes): + * the adapter reports the modes it runs and its default, and its search + * honours `AdapterSearchOptions.retrieval`. The report is checked against + * the three modes, and each listed mode is asserted by behaviour: `vector` + * leaves out the passage only the keyword leg ranks, `keyword` ranks by + * the query's words alone, `hybrid` answers what the default answers when + * it is the default. A `vector` or `keyword` case needs `keywordLeg`. + * Absent: `false`. + */ + retrieval?: boolean; }; } @@ -510,6 +527,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect(typeof adapter.beginBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.completeBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.dropSource === 'function').toBe(opts.implements.dropSource); + expect(adapter.capabilities?.retrieval !== undefined).toBe(opts.implements.retrieval === true); if (opts.implements.generations) { expect(opts.implements.builds && opts.implements.refusesOtherFingerprint).toBe(true); } @@ -568,6 +586,79 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + if (opts.implements.retrieval === true) { + describe('retrieval modes (ADR-0161, the dated note on retrieval modes)', () => { + it('reports the modes it runs, each once and each one of the three, and a default it lists', async () => { + const adapter: IKnowledgeAdapter = await make(); + const report = adapter.capabilities?.retrieval; + expect(report).toBeDefined(); + if (report === undefined) return; + expect(report.modes.length).toBeGreaterThan(0); + expect(new Set(report.modes).size).toBe(report.modes.length); + for (const mode of report.modes) expect(KNOWLEDGE_RETRIEVAL_MODES).toContain(mode); + expect(report.modes).toContain(report.default); + }); + + /** + * The keyword-leg fixture: five passages hold the question's + * characters one by one (a bag-of-words embedder ranks them first by + * vector) and none of its words; one passage holds its figure and + * words, which the vector leg alone ranks below `topK`. + */ + const QUESTION = '出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗'; + async function seeded(): Promise<{ adapter: IKnowledgeAdapter; a: KnowledgeSource; listed: readonly string[]; byDefault: string }> { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('retrieval_modes'); + const spread = ['a', 'b', 'c', 'd', 'e'].map((n) => + doc(a, `spread_${n}`, `出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 ${n}`), + ); + await adapter.upsert([...spread, doc(a, 'clause', '采购单笔金额2000元以下除外,其余一律公开招标')], ctxOf(a)); + const report = adapter.capabilities?.retrieval; + return { adapter, a, listed: report?.modes ?? [], byDefault: report?.default ?? '' }; + } + const nonIncreasing = (hits: Array<{ score: number }>) => { + for (let i = 1; i < hits.length; i++) expect(hits[i - 1].score).toBeGreaterThanOrEqual(hits[i].score); + }; + + it('`vector` runs the vector leg alone: the passage only the keyword leg ranks is not answered', async () => { + const { adapter, a, listed } = await seeded(); + if (!listed.includes('vector')) return; + expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); + const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); + expect(hits.length).toBeGreaterThan(0); + expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); + nonIncreasing(hits); + }); + + it('`keyword` runs the keyword leg alone: only the passage holding the question\'s words is answered', async () => { + const { adapter, a, listed } = await seeded(); + if (!listed.includes('keyword')) return; + expect(opts.implements.keywordLeg, 'the keyword case reads the keyword-leg fixture').toBe(true); + const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'keyword' } }); + expect(hits.map((h) => h.documentId)).toEqual([`${a.name}:clause`]); + // A query with no word any passage holds answers nothing under keyword alone. + expect(await adapter.search('zzqx', { source: a, topK: 3, retrieval: { mode: 'keyword' } })).toEqual([]); + }); + + it('`hybrid` ranks both legs; as the default it answers exactly what a search without the member answers', async () => { + const { adapter, a, listed, byDefault } = await seeded(); + if (!listed.includes('hybrid')) return; + const hybrid = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'hybrid' } }); + nonIncreasing(hybrid); + if (opts.implements.keywordLeg) expect(hybrid.map((h) => h.documentId)).toContain(`${a.name}:clause`); + if (byDefault === 'hybrid') { + expect(hybrid).toEqual(await adapter.search(QUESTION, { source: a, topK: 3 })); + } + }); + + it('the default mode, handed explicitly, answers exactly what a search without the member answers', async () => { + const { adapter, a, byDefault } = await seeded(); + const explicit = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: byDefault as 'vector' } }); + expect(explicit).toEqual(await adapter.search(QUESTION, { source: a, topK: 3 })); + }); + }); + } + if (opts.implements.organizationIds) { describe('organizationIds (ADR-0161 K8, item 9)', () => { /** B's document outranks A's; a third document carries no organization. */ diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index e44ed13b954..56fbab6004f 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -121,6 +121,18 @@ } } }, + "retrieval": { + "status": "planned", + "verifiedAt": "2026-11-30", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note on retrieval modes): `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. Enters neither the index fingerprint nor the recipe hash.", + "children": { + "mode": { + "status": "planned", + "verifiedAt": "2026-11-30", + "note": "Planned with its container `retrieval` (see that row): `vector`, `keyword` or `hybrid`; omitted means the adapter's default." + } + } + }, "where": { "status": "live", "verifiedAt": "2026-11-26", diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index d84610e3be3..1215e5f31b2 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -25,6 +25,8 @@ import { defineMetadataForm } from '../ui/view.zod'; * - `source.affinity` is the JSON editor too: a list of `{ field, caller, * mode, places? }` entries whose cross-key rules (a `field` listed in * `metadataFields`, `places` on a `boost` alone) no list widget states. + * - `source.retrieval.mode` is a select of the three modes, blank for the + * store's default; which modes the store runs is judged at save. * * ADR-0161 K5 and K10 rule 5: embedding is egress, so `content` offers named * fields only, and its help says beside it what a build sends and to whom. @@ -77,6 +79,24 @@ export const knowledgeSourceForm = defineMetadataForm({ { field: 'metadataFields', label: 'Filter fields', widget: 'field-multi', dependsOn: 'object', helpText: 'Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query.' }, { field: 'documentBy', label: 'Document unit', widget: 'field-ref', dependsOn: 'object', helpText: 'Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. Setting it rebuilds nothing; adding the field to Filter fields does.' }, { field: 'affinity', label: 'Order for the asker', widget: 'json', helpText: 'Optional. Lists entries that move hits related to the person asking up the answer, for example [{"field": "business_unit", "caller": "business_unit", "mode": "nearest"}] puts their own unit first, then its parent units, then the rest, and [{"field": "owner", "caller": "user", "mode": "boost", "places": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing.' }, + { + field: 'retrieval', + label: 'Search', + type: 'composite', + helpText: 'How a search of this source finds passages. Leave it blank for the store\'s default. Changing it rebuilds nothing.', + fields: [ + { + field: 'mode', + label: 'Retrieval mode', + options: [ + { label: 'Vector only (by meaning)', value: 'vector' }, + { label: 'Keyword only (by words)', value: 'keyword' }, + { label: 'Hybrid (both)', value: 'hybrid' }, + ], + helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.', + }, + ], + }, { field: 'where', label: 'Records to index', widget: 'json', helpText: 'An ObjectQL filter on the object, for example {"status": {"$ne": "done"}}. Only the records it matches are indexed. Blank: every record.' }, { field: 'split', diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index cf5c5b01ae0..663ecd5d07f 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -28,6 +28,7 @@ import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { ObjectStackDefinitionSchema } from '../stack.zod'; import { KNOWLEDGE_AFFINITY_MAX_PLACES, + KNOWLEDGE_RETRIEVAL_MODES, KnowledgeSourceSchema, type KnowledgeSource, type KnowledgeSourceParsed, @@ -415,3 +416,45 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller expect(issues.map(([code, path]) => [code, path])).toEqual([['unrecognized_keys', 'source.affinity.0']]); }); }); + +describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note on retrieval modes)', () => { + const withRetrieval = (retrieval: unknown): unknown => ({ ...SOURCE, source: { ...SOURCE.source, retrieval } }); + + it('positive control: each of the three modes parses and is kept as written; absent stays absent', () => { + expect(KNOWLEDGE_RETRIEVAL_MODES).toEqual(['vector', 'keyword', 'hybrid']); + for (const mode of KNOWLEDGE_RETRIEVAL_MODES) { + const r = KnowledgeSourceSchema.safeParse(withRetrieval({ mode })); + expect(r.success, mode).toBe(true); + if (r.success) expect(r.data.source.retrieval).toEqual({ mode }); + } + expect('retrieval' in KnowledgeSourceSchema.parse(SOURCE).source).toBe(false); + }); + + it('accepts `retrieval: {}`, which declares nothing and adds no default', () => { + const r = KnowledgeSourceSchema.safeParse(withRetrieval({})); + expect(r.success).toBe(true); + if (r.success) expect(r.data.source.retrieval).toEqual({}); + }); + + it('refuses a mode outside the three, naming the three', () => { + const issues = issuesOf(withRetrieval({ mode: 'semantic' })); + expect(issues.map(([code, path]) => [code, path])).toEqual([['invalid_value', 'source.retrieval.mode']]); + expect(issues[0]![2]).toMatch(/^`knowledge_source.source.retrieval.mode` is 'vector', 'keyword' or 'hybrid', got 'semantic'/); + }); + + it('refuses an unknown key under `retrieval` — `vectorWeight` included, which this version does not carry — never drops it', () => { + for (const key of ['vectorWeight', 'keywordWeight', 'fusion']) { + const issues = issuesOf(withRetrieval({ mode: 'hybrid', [key]: 0.5 })); + expect(issues.map(([code, path]) => [code, path]), key).toEqual([['unrecognized_keys', 'source.retrieval']]); + } + }); + + it('is published by the type\'s JSON Schema, so a document validated against it is not refused a release later', () => { + const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as { + properties: { source: { properties: Record; additionalProperties?: unknown }> } }; + }; + const retrieval = json.properties.source.properties.retrieval; + expect(retrieval?.properties?.mode?.enum).toEqual(['vector', 'keyword', 'hybrid']); + expect(retrieval?.additionalProperties).toBe(false); + }); +}); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 50af210a137..64e6ef189c6 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -128,6 +128,60 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( }, )); +/** + * The retrieval modes a knowledge source may declare (ADR-0161, the dated note + * on retrieval modes; ruling 7270218011 on #38692): + * + * - `vector`: only the vector leg runs, ranking passages by meaning. + * - `keyword`: only the keyword leg runs, ranking passages by the words they + * hold. The embedder is not called and no query vector is made; passages of + * equal keyword score are ranked by passage id, so the answer is + * deterministic, and a question with no words to match answers nothing. It + * suits exact lookups: a document number, a clause number, a name. + * - `hybrid`: both legs run, merged by the store's fusion. + * + * Which modes a store runs is the store's report (`AdapterCapabilities.retrieval`), + * never configuration; a source that declares a mode its store does not run is + * refused, never silently searched another way. + */ +export const KNOWLEDGE_RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; + +/** One of {@link KNOWLEDGE_RETRIEVAL_MODES}. */ +export const KnowledgeRetrievalModeSchema = lazySchema(() => z.enum(KNOWLEDGE_RETRIEVAL_MODES, { + error: (issue) => (typeof issue.input === 'string' + ? `\`knowledge_source.source.retrieval.mode\` is 'vector', 'keyword' or 'hybrid', got '${issue.input}'. ` + + 'Write `mode: \'vector\'` to rank by meaning alone, `mode: \'keyword\'` to rank by the words a passage holds ' + + '(no embedding call), or `mode: \'hybrid\'` for both; leave `mode` out for the store\'s default.' + : undefined), +})); + +/** + * How a source is searched (ADR-0161, the dated note on retrieval modes): + * which legs the store runs. A declaration of the source, read on every search + * and never by a build, so it enters neither the index fingerprint nor the + * recipe hash: changing it rebuilds nothing. `retrieval: {}` declares nothing + * and reads as the key left out. + */ +export const KnowledgeRetrievalSchema = lazySchema(() => strictObject( + { + surface: 'this source\'s `retrieval`', + history: 'This shape is strict from birth — `retrieval` had no earlier spelling, so an unknown key here was never accepted.', + }, + { + /** + * Which legs run: `vector`, `keyword` or `hybrid` + * ({@link KNOWLEDGE_RETRIEVAL_MODES}). Omitted: the store's default + * (`AdapterCapabilities.retrieval.default`; `hybrid` on turso and + * pgvector), today's behaviour. A store that does not list the mode + * refuses the source at save, at registration when its store already + * resolves, once after boot, and on every search (the source is listed as + * refused); a store that reports no modes accepts only the key left out. + */ + mode: KnowledgeRetrievalModeSchema.optional() + .describe('Which legs a search runs: vector, keyword or hybrid; omitted means the store\'s default'), + }, +)); + /** * `source.documentBy` must be one of `source.metadataFields`: a record-level * search groups each hit by the value the index stores beside its passage, @@ -449,6 +503,17 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( */ affinity: z.array(KnowledgeAffinityEntrySchema).optional() .describe('How this source\'s hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score'), + /** + * [ADR-0161, the dated note on retrieval modes] How this source is + * searched: `retrieval.mode` names the legs the store runs + * ({@link KnowledgeRetrievalSchema}). Beside {@link affinity} and before + * it: the mode decides which passages the store ranks and their scores, + * then affinity re-orders them for the caller. Omitted: the store's + * default, as before this key. It enters neither the index fingerprint + * nor the recipe hash, so changing it rebuilds nothing. + */ + retrieval: KnowledgeRetrievalSchema.optional() + .describe('How this source is searched: mode vector, keyword or hybrid; omitted means the store\'s default, and changing it rebuilds nothing'), }, ).superRefine(refineObjectSource)); @@ -583,3 +648,6 @@ export type KnowledgeAffinityMode = z.input; export type KnowledgeAffinityModeParsed = z.infer; export type KnowledgeAffinityEntry = z.input; export type KnowledgeAffinityEntryParsed = z.infer; +export type KnowledgeRetrievalMode = z.input; +export type KnowledgeRetrieval = z.input; +export type KnowledgeRetrievalParsed = z.infer; diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 4728cd8b136..4d729a55900 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -4,7 +4,7 @@ import type { KnowledgeDocument, KnowledgeHit, } from '../ai/knowledge-document.zod'; -import type { KnowledgeSource } from '../ai/knowledge-source.zod'; +import type { KnowledgeRetrievalMode, KnowledgeSource } from '../ai/knowledge-source.zod'; /** * `IKnowledgeAdapter` — plugin-side contract. @@ -176,6 +176,26 @@ export interface AdapterSearchOptions { * answers it from that generation. Absent: no check. */ index?: { fingerprint: string }; + /** + * The retrieval mode this search runs (ADR-0161, the dated note on + * retrieval modes): the EFFECTIVE mode, which the knowledge service resolves + * from the source's `source.retrieval.mode`, else the adapter's + * {@link AdapterCapabilities.retrieval} `default`. A per-request parameter, + * as `topK` and `scope` are — not configuration (ADR-0161 K8, rule 4). + * + * - `vector`: run only the vector leg. + * - `keyword`: run only the keyword leg. Do not call the embedder and make + * no query vector; rank passages of equal keyword score by passage id. + * A query with no terms to match answers no hits. + * - `hybrid`: run both legs and fuse them, as the adapter's default does. + * + * The service hands only a mode the adapter lists in + * `capabilities.retrieval.modes`, and never hands this member to an adapter + * that reports no `capabilities.retrieval`. Absent: the adapter's default. + * Scores need only not increase with rank within one source's answer; under + * a one-leg mode they reflect rank alone. + */ + retrieval?: { mode: KnowledgeRetrievalMode }; /** Trace id for correlation. */ traceId?: string; } @@ -244,6 +264,28 @@ export interface AdapterCapabilities { * `chunks`, and splits them itself. */ chunks?: boolean; + /** + * The retrieval modes the adapter runs, and which one it runs when a + * source declares none (ADR-0161, the dated note on retrieval modes). A + * report, not configuration: `default` is one of `modes`, and an adapter + * that lists `hybrid` honours the source's vector share when that arrives. + * + * The knowledge service refuses a source that declares a mode outside + * `modes` — at save, at registration when the adapter already resolves, + * once after boot, and on every search, where the source is listed as + * refused — and never searches it another way. Absent: the adapter reports + * no modes, and only a source that declares none is searched by it; the + * service is never told which legs it runs. + */ + retrieval?: AdapterRetrievalCapability; +} + +/** {@link AdapterCapabilities.retrieval}: the modes an adapter runs, and its default. */ +export interface AdapterRetrievalCapability { + /** The modes the adapter runs; not empty, no mode twice. */ + readonly modes: readonly KnowledgeRetrievalMode[]; + /** The mode it runs for a source that declares none; one of {@link modes}. */ + readonly default: KnowledgeRetrievalMode; } /** @@ -308,8 +350,9 @@ export interface IKnowledgeAdapter { readonly id: string; /** - * What the adapter accepts beyond whole documents (ADR-0161 K8, item 5). - * Absent: whole documents only. + * What the adapter accepts beyond whole documents (ADR-0161 K8, item 5), + * and the retrieval modes it runs. Absent: whole documents only, and no + * modes reported. */ readonly capabilities?: AdapterCapabilities; From 8dc9af75d4ff3f1c849ddefcd6e58ce8fae6da00 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:39:49 +0000 Subject: [PATCH 02/14] chore(spec): regenerate the generated artifacts for source.retrieval --- content/docs/protocol/knowledge.mdx | 10 +++++- .../docs/references/ai/knowledge-source.mdx | 34 +++++++++++++++++-- content/docs/references/index.mdx | 10 +++--- .../ai.md | 2 +- packages/spec/api-surface/ai.json | 6 ++++ packages/spec/api-surface/contracts.json | 1 + packages/spec/authorable-surface/ai.json | 2 ++ packages/spec/declaration-map/ai.json | 4 +++ packages/spec/export-origins/ai.json | 6 ++++ packages/spec/export-origins/contracts.json | 1 + packages/spec/json-schema.manifest/ai.json | 2 ++ .../liveness/state-counts/knowledge_source.md | 2 +- packages/spec/src/ai/knowledge-source.test.ts | 2 +- 13 files changed, 71 insertions(+), 11 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 105eb543109..9b4c0e338d0 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -483,7 +483,10 @@ and [3.5 The split](#35-the-split). ```ts interface IKnowledgeAdapter { readonly id: string; - readonly capabilities?: { chunks?: boolean }; // takes the service's passages + readonly capabilities?: { + chunks?: boolean; // takes the service's passages + retrieval?: { modes: readonly ('vector' | 'keyword' | 'hybrid')[]; default: 'vector' | 'keyword' | 'hybrid' }; + }; // the retrieval modes it runs, and its default readonly embedding?: { // what its embedder is maxInputTokens?: number; // longest input it accepts model?: string; dimensions?: number; variant?: string; // what its vectors are @@ -523,6 +526,11 @@ caller's organizations; an adapter that reads it ranks only those organizations' documents, filtering before it ranks — see [Organization scope](#organization-scope). `AdapterSearchOptions.scope` holds a search to chosen records the same way — see [Record scope](#record-scope). +`capabilities.retrieval` reports the retrieval modes an adapter runs +(`vector`, `keyword`, `hybrid`) and the one it runs by default; it is a +report, not configuration. `AdapterSearchOptions.retrieval` carries the mode +a search runs, a per-request parameter like `topK`, and only ever a mode the +adapter lists. `listDocuments` lists the documents the adapter holds for a source, a page of at most `limit` entries at a time, each with the `docHash` it was stored with; `nextCursor` is absent once the diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 423e186a7ad..2e11a10f60a 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -23,8 +23,8 @@ See `content/docs/protocol/knowledge.mdx` for the design. ## TypeScript Usage ```typescript -import { KnowledgeAffinityCallerSchema, KnowledgeAffinityEntrySchema, KnowledgeAffinityModeSchema, KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; -import type { KnowledgeAffinityCaller, KnowledgeAffinityEntry, KnowledgeAffinityMode, KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeAffinityCallerSchema, KnowledgeAffinityEntrySchema, KnowledgeAffinityModeSchema, KnowledgeRefreshPolicySchema, KnowledgeRetrievalSchema, KnowledgeRetrievalModeSchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; +import type { KnowledgeAffinityCaller, KnowledgeAffinityEntry, KnowledgeAffinityMode, KnowledgeRefreshPolicy, KnowledgeRetrieval, KnowledgeRetrievalMode, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; // Validate data const result = KnowledgeAffinityCallerSchema.parse(data); @@ -76,6 +76,28 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **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. | +--- + +## KnowledgeRetrieval + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | + + +--- + +## KnowledgeRetrievalMode + +### Allowed Values + +* `vector` +* `keyword` +* `hybrid` + + --- ## KnowledgeSource @@ -116,6 +138,7 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **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 | | **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `KnowledgeSource.refresh` @@ -166,6 +189,7 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **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 | | **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `ObjectKnowledgeSource.split` @@ -184,6 +208,12 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **mode** | `Enum<'boost' \| 'nearest'>` | ✅ | boost lifts a match by places; nearest puts the caller's own unit first, then its parents | | **places** | `integer` | optional | boost only: how many non-matching hits a match may pass, 1 to 20 | +### Nested Shape: `ObjectKnowledgeSource.retrieval` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | + --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 920f1a62496..03b540df209 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1745 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1747 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -22,7 +22,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 17 | 105 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 17 | 107 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -36,13 +36,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 187 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **223** | **1745** | 14 protocol modules | +| **Total** | **223** | **1747** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 105 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 107 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -55,7 +55,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | | [`draft-review.zod.ts`](/docs/references/ai/draft-review) | `DraftReviewItem`, `DraftReviewLinks`, `DraftReviewList`, `DraftReviewVerdict`, `DraftReviewVerdictRefusal` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | -| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | +| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeRetrieval`, `KnowledgeRetrievalMode`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | | [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` | | [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` | | [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 5f25e0c458c..050f8f7f1d7 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 121 | +| `ai/` | 122 | diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index b5f1388e297..0bfeb1ab566 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -132,6 +132,7 @@ "GetRecordContextOutputSchema (const)", "ImageContentSchema (const)", "KNOWLEDGE_AFFINITY_MAX_PLACES (const)", + "KNOWLEDGE_RETRIEVAL_MODES (const)", "KnowledgeAffinityCaller (type)", "KnowledgeAffinityCallerParsed (type)", "KnowledgeAffinityCallerSchema (const)", @@ -150,6 +151,11 @@ "KnowledgeRefreshPolicy (type)", "KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema (const)", + "KnowledgeRetrieval (type)", + "KnowledgeRetrievalMode (type)", + "KnowledgeRetrievalModeSchema (const)", + "KnowledgeRetrievalParsed (type)", + "KnowledgeRetrievalSchema (const)", "KnowledgeSource (type)", "KnowledgeSourceParsed (type)", "KnowledgeSourceSchema (const)", diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index f012c7992d5..dd0891c1994 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", + "AdapterRetrievalCapability (interface)", "AdapterScopeTerm (type)", "AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities (interface)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 0ee44069dda..529db46b843 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -292,6 +292,7 @@ "ai/KnowledgeHit:title", "ai/KnowledgeRefreshPolicy:cron [RETIRED]", "ai/KnowledgeRefreshPolicy:onRecordChange", + "ai/KnowledgeRetrieval:mode", "ai/KnowledgeSource:_lock", "ai/KnowledgeSource:_lockDocsUrl", "ai/KnowledgeSource:_lockReason", @@ -391,6 +392,7 @@ "ai/ObjectKnowledgeSource:kind", "ai/ObjectKnowledgeSource:metadataFields", "ai/ObjectKnowledgeSource:object", + "ai/ObjectKnowledgeSource:retrieval", "ai/ObjectKnowledgeSource:split", "ai/ObjectKnowledgeSource:where", "ai/ObjectQuerySource:aggregations", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 8a975cdd035..70474f71dfe 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -101,6 +101,10 @@ "KnowledgeHitSchema": "ai/KnowledgeHit", "KnowledgeRefreshPolicy": "ai/KnowledgeRefreshPolicy", "KnowledgeRefreshPolicySchema": "ai/KnowledgeRefreshPolicy", + "KnowledgeRetrieval": "ai/KnowledgeRetrieval", + "KnowledgeRetrievalMode": "ai/KnowledgeRetrievalMode", + "KnowledgeRetrievalModeSchema": "ai/KnowledgeRetrievalMode", + "KnowledgeRetrievalSchema": "ai/KnowledgeRetrieval", "KnowledgeSource": "ai/KnowledgeSource", "KnowledgeSourceSchema": "ai/KnowledgeSource", "KnowledgeSplit": "ai/KnowledgeSplit", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index e7d955f2f85..2114847e360 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -130,6 +130,7 @@ "GetRecordContextOutputSchema": "src/ai/record-context-tools.zod.ts#GetRecordContextOutputSchema (const)", "ImageContentSchema": "src/ai/conversation.zod.ts#ImageContentSchema (const)", "KNOWLEDGE_AFFINITY_MAX_PLACES": "src/ai/knowledge-source.zod.ts#KNOWLEDGE_AFFINITY_MAX_PLACES (const)", + "KNOWLEDGE_RETRIEVAL_MODES": "src/ai/knowledge-source.zod.ts#KNOWLEDGE_RETRIEVAL_MODES (const)", "KnowledgeAffinityCaller": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCaller (type)", "KnowledgeAffinityCallerParsed": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCallerParsed (type)", "KnowledgeAffinityCallerSchema": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCallerSchema (const)", @@ -148,6 +149,11 @@ "KnowledgeRefreshPolicy": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicy (type)", "KnowledgeRefreshPolicyParsed": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicySchema (const)", + "KnowledgeRetrieval": "src/ai/knowledge-source.zod.ts#KnowledgeRetrieval (type)", + "KnowledgeRetrievalMode": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalMode (type)", + "KnowledgeRetrievalModeSchema": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalModeSchema (const)", + "KnowledgeRetrievalParsed": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalParsed (type)", + "KnowledgeRetrievalSchema": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalSchema (const)", "KnowledgeSource": "src/ai/knowledge-source.zod.ts#KnowledgeSource (type)", "KnowledgeSourceParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSourceParsed (type)", "KnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema (const)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 4d03a5d5c49..e2d26712da4 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", + "AdapterRetrievalCapability": "src/contracts/knowledge-adapter.ts#AdapterRetrievalCapability (interface)", "AdapterScopeTerm": "src/contracts/knowledge-adapter.ts#AdapterScopeTerm (type)", "AdapterSearchOptions": "src/contracts/knowledge-adapter.ts#AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities": "src/contracts/analytics-service.ts#AnalyticsDriverCapabilities (interface)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 4bc2c8920db..3f17e4320fe 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -54,6 +54,8 @@ "ai/KnowledgeDocument", "ai/KnowledgeHit", "ai/KnowledgeRefreshPolicy", + "ai/KnowledgeRetrieval", + "ai/KnowledgeRetrievalMode", "ai/KnowledgeSource", "ai/KnowledgeSplit", "ai/KnowledgeSplitStrategy", diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index a575042db63..1fcc479c9f3 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 | 0 | 32 | +| `knowledge_source` | 26 | 0 | 0 | 6 | 1 | 33 | diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index 663ecd5d07f..af044bd5816 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -450,7 +450,7 @@ describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched }); it('is published by the type\'s JSON Schema, so a document validated against it is not refused a release later', () => { - const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as { + const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as unknown as { properties: { source: { properties: Record; additionalProperties?: unknown }> } }; }; const retrieval = json.properties.source.properties.retrieval; From e582d5e89f67baebf3e2801116837abdb6abf872 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:45:45 +0000 Subject: [PATCH 03/14] chore(changeset): source.retrieval.mode and the adapter's retrieval report --- .../38692-knowledge-retrieval-mode-spec.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/38692-knowledge-retrieval-mode-spec.md diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md new file mode 100644 index 00000000000..c48981f369f --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +--- + +feat(spec): a knowledge source may declare its retrieval mode, `source.retrieval.mode` (`vector`, `keyword` or `hybrid`), and a knowledge adapter reports the modes it runs + +Clause-②: yes (widening) +Metadata-protocol: added + +A `knowledge_source` may now declare how it is searched: `source: { …, retrieval: { mode: 'vector' } }`. `vector` runs only the vector leg (ranking passages by meaning), `keyword` only the keyword leg (ranking passages by the words they hold, with no call to the embedder), and `hybrid` both, merged by the store's fusion. Leaving `mode` out, or writing `retrieval: {}`, keeps the store's default, which is today's behaviour. The key is read on every search and by no build, so it enters neither the index fingerprint nor the recipe hash: changing it rebuilds nothing. The parse refuses a mode outside the three, and any other key under `retrieval`, each with the fix. Studio's knowledge source form offers the key as a "Retrieval mode" select under "Search". + +`IKnowledgeAdapter` gains two optional members. `capabilities.retrieval: { modes, default }` is the adapter's report of the modes it runs and the one it runs when a source declares none; it is a report, not configuration. `AdapterSearchOptions.retrieval: { mode }` carries the mode a search runs, a per-request parameter like `topK`. An adapter that reports no modes keeps working unchanged; a source that names it may only leave `mode` out. + +The adapter contract suite (`@objectstack/service-knowledge/testing`) takes a new optional declaration, `implements.retrieval`: it checks the adapter's report (each mode one of the three, none twice, the default listed), searches a fixed set of passages under each listed mode (`vector` leaves out the passage only the keyword leg ranks, `keyword` answers that passage alone and nothing for a query with no word any passage holds), and checks that the default mode handed explicitly answers exactly what a search without the member answers. An adapter that does not declare it is checked to report no modes. + +The knowledge service's reading of the mode (and its refusal of a mode the source's store does not run) and the turso and pgvector stores' support for it ship as separate changes. From 9e576393c79ea0d5fedea54217b52e842cdaf15b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:50:00 +0000 Subject: [PATCH 04/14] test(service-knowledge): the vector-mode contract case reads the vector leg by a passage's own text --- packages/services/service-knowledge/src/testing.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index ba240142225..1eb8060fa13 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -625,9 +625,12 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption if (!listed.includes('vector')) return; expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); - expect(hits.length).toBeGreaterThan(0); expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); nonIncreasing(hits); + // The vector leg still runs: a passage's own text ranks that passage first. + const own = await adapter.search('出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 c', { source: a, topK: 3, retrieval: { mode: 'vector' } }); + expect(own[0]?.documentId).toBe(`${a.name}:spread_c`); + nonIncreasing(own); }); it('`keyword` runs the keyword leg alone: only the passage holding the question\'s words is answered', async () => { From 7ab8db5d683a07314d8cce5d62cb7eb69ba34321 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:50:22 +0000 Subject: [PATCH 05/14] feat(knowledge-pgvector): run one leg or both by the search's retrieval mode; report the three modes, hybrid by default --- ...8692-knowledge-pgvector-retrieval-modes.md | 10 ++ content/docs/protocol/knowledge.mdx | 5 +- packages/plugins/knowledge-pgvector/README.md | 2 + .../__tests__/contract.live-postgres.test.ts | 1 + .../src/__tests__/retrieval-modes.test.ts | 120 ++++++++++++++++++ .../src/pgvector-adapter.ts | 67 +++++++--- 6 files changed, 186 insertions(+), 19 deletions(-) create mode 100644 .changeset/38692-knowledge-pgvector-retrieval-modes.md create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts diff --git a/.changeset/38692-knowledge-pgvector-retrieval-modes.md b/.changeset/38692-knowledge-pgvector-retrieval-modes.md new file mode 100644 index 00000000000..64cc62beb66 --- /dev/null +++ b/.changeset/38692-knowledge-pgvector-retrieval-modes.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +feat(knowledge-pgvector): the store runs the vector leg alone, the keyword leg alone, or both, as a source's retrieval mode says + +Clause-②: no +Metadata-protocol: none + +`knowledge-pgvector` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the cosine scan alone and `keyword` the keyword match alone; the other leg is not written into the statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 9b4c0e338d0..c20de17daee 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -780,7 +780,10 @@ an exact scan. [record scope](#record-scope) and the metadata `filter` (equality per key) are one `WHERE`, run in both legs before either ranks. `queryPrefix` is put before every query before it is embedded, for a model - that embeds questions and passages differently. + that embeds questions and passages differently. It runs all three + retrieval modes, `hybrid` by default: `vector` or `keyword` leaves the + other leg out of the statement and scores a hit `61 / (60 + rank)`, and + `keyword` does not embed the question. - **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is not embedded again; its row's metadata is rewritten. - **Rebuilds.** A write or a search under another fingerprint is refused diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index 726f6f9fba5..c37919f5d94 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -58,6 +58,8 @@ The next call retries; no restart is needed. A database the plugin cannot reach Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge service re-checks each hit as the caller. Each leg ranks at most `topK` passages; a hit's `score` is the sum of `1 / (60 + rank)` over the legs that rank it, divided by that of a passage first in both, so it lies in `(0, 1]`: 1 for first in both legs, 0.5 for first in one alone. The organization filter, the record scope and the metadata `filter` are one `WHERE`, run in both legs before either ranks. +**Retrieval modes.** The store reports all three modes (`capabilities.retrieval`: `vector`, `keyword`, `hybrid`), `hybrid` by default, and a source chooses with `source.retrieval.mode`. `hybrid` runs both legs as above. `vector` runs the vector leg alone and `keyword` the keyword leg alone: the other leg is not written into the statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing the mode rebuilds nothing. + - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` is one term (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A word of three characters or more is matched as a phrase (`phraseto_tsquery('simple', …)`) on the passage's `to_tsvector('simple', content)`, which a GIN expression index (`knowledge_vec_d_content_tsv`) serves. The `simple` configuration lower-cases and neither stems nor drops stop words, so a code or a name matches as written. A shorter term (「出差」), and a term holding a Han, kana or Hangul character — which the parser never splits, so a `tsvector` holds a whole run of them as one word — is matched as a substring over the rows in scope: by `content LIKE '%…%'` when the term holds no cased letter (a piece of Han, kana or Hangul, a figure), where case folding could find nothing more, and by `content ILIKE '%…%'` otherwise. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. - **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write or search of that width (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds). - **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it. diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts index 4a8be8ed477..c48d725e9cf 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -30,6 +30,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { scope: true, dropSource: true, keywordLeg: true, + retrieval: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts new file mode 100644 index 00000000000..e4c9b3bb40b --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts @@ -0,0 +1,120 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The retrieval modes (ADR-0161, the dated note on retrieval modes), without + * a database: the capability report, the legs each mode writes into the + * ranking statement, that `keyword` never calls the embedder, and the + * fusion's scores — `hybrid` bit-identical to the fusion before modes + * existed, one leg `61 / (60 + rank)`. The behaviour against a real + * PostgreSQL is the contract suite's (`contract.live-postgres.test.ts`). + */ + +import { describe, expect, it } from 'vitest'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js'; +import { RETRIEVAL, RRF_K, fuse } from '../pgvector-adapter.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { name: 'modes', label: 'modes', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; + +/** A store with one active generation whose ranking statement is recorded and answers nothing. */ +function recordingPool(): { pool: PgPoolLike; rankings: string[] } { + const rankings: string[] = []; + const answer = async (text: string): Promise<{ rows: R[] }> => { + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('GROUP BY chunk_id')) rankings.push(text); + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { pool: { query: answer, connect: async () => client() }, rankings }; +} + +async function searched(mode: 'vector' | 'keyword' | 'hybrid' | undefined, query = 'granite quarry') { + const store = recordingPool(); + const embedder = new FakeEmbedder(); + const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder }); + const hits = await adapter.search(query, { + source, + topK: 5, + index: { fingerprint: 'fp' }, + ...(mode === undefined ? {} : { retrieval: { mode } }), + }); + return { hits, embedder, rankings: store.rankings }; +} + +describe('knowledge-pgvector retrieval modes', () => { + it('reports all three modes, hybrid by default', () => { + const adapter = new PgvectorKnowledgeAdapter({ pool: recordingPool().pool, embedder: new FakeEmbedder() }); + expect(adapter.capabilities.retrieval).toBe(RETRIEVAL); + expect(RETRIEVAL).toEqual({ modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }); + }); + + it('hybrid, and no mode, write both legs into the statement', async () => { + for (const mode of ['hybrid', undefined] as const) { + const { rankings, embedder } = await searched(mode); + expect(rankings).toHaveLength(1); + expect(rankings[0]).toContain('vec AS ('); + expect(rankings[0]).toContain('kw AS ('); + expect(embedder.calls).toBe(1); + } + }); + + it('vector writes the vector leg alone', async () => { + const { rankings, embedder } = await searched('vector'); + expect(rankings).toHaveLength(1); + expect(rankings[0]).toContain('vec AS ('); + expect(rankings[0]).not.toContain('kw AS ('); + expect(embedder.calls).toBe(1); + }); + + it('keyword writes the keyword leg alone and never calls the embedder', async () => { + const { rankings, embedder } = await searched('keyword'); + expect(rankings).toHaveLength(1); + expect(rankings[0]).not.toContain('vec AS ('); + expect(rankings[0]).toContain('kw AS ('); + // Equal keyword scores fall to the chunk id: the candidates carry no distance. + expect(rankings[0]).toContain('0 AS distance'); + expect(embedder.calls).toBe(0); + }); + + it('keyword with no term to match answers nothing and reads no passage', async () => { + const { hits, rankings, embedder } = await searched('keyword', ' '); + expect(hits).toEqual([]); + expect(rankings).toHaveLength(0); + expect(embedder.calls).toBe(0); + }); +}); + +describe('knowledge-pgvector fusion under the retrieval modes', () => { + type Row = { chunk_id: string; vpos: number | null; kpos: number | null }; + + /** The fusion's score as it stood before retrieval modes existed: the hybrid pin's reference. */ + const before = (row: Row): number => { + const best = 2 / (RRF_K + 1); + const leg = (pos: number | null) => (pos === null ? 0 : 1 / (RRF_K + Number(pos))); + return (leg(row.vpos) + leg(row.kpos)) / best; + }; + + it('hybrid is bit-identical to the fusion before modes, for every pair of ranks up to 200', () => { + const ranks: Array = [null, ...Array.from({ length: 200 }, (_, i) => i + 1)]; + const rows: Row[] = []; + for (const vpos of ranks) for (const kpos of ranks) if (vpos !== null || kpos !== null) rows.push({ chunk_id: `${vpos}:${kpos}`, vpos, kpos }); + const fused = fuse(rows, rows.length, 2); + expect(fused).toHaveLength(rows.length); + let differing = 0; + for (const { row, score } of fused) if (!Object.is(score, before(row))) differing += 1; + expect(differing).toBe(0); + }); + + it('one leg scores 61 / (60 + rank): the first is 1, and scores fall with rank', () => { + const rows: Row[] = Array.from({ length: 50 }, (_, i) => ({ chunk_id: `c${String(i + 1).padStart(3, '0')}`, vpos: i + 1, kpos: null })); + const fused = fuse(rows, 50, 1); + expect(fused[0]?.score).toBe(1); + for (const { row, score } of fused) expect(score).toBeCloseTo(61 / (60 + Number(row.vpos)), 12); + for (let i = 1; i < fused.length; i++) expect(fused[i - 1]!.score).toBeGreaterThan(fused[i]!.score); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index c73f0f0a0b2..df036e9d23e 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -124,6 +124,17 @@ const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION'; /** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */ export const RRF_K = 60; +/** + * The retrieval modes this adapter runs, and its default (ADR-0161, the dated + * note on retrieval modes): all three, `hybrid` when a source declares none. + * A report, not configuration; the default does not move with what the + * database offers. + */ +export const RETRIEVAL = Object.freeze({ + modes: Object.freeze(['vector', 'keyword', 'hybrid'] as const), + default: 'hybrid' as const, +}); + /** A generation row: one complete index of one source under one fingerprint. */ interface GenerationRow { generation: number; @@ -177,8 +188,17 @@ interface Readiness { * Two legs, merged by reciprocal rank fusion (`k` = {@link RRF_K}) before the * knowledge service re-checks each hit as the caller. Each leg ranks at most * `topK` passages; a passage's score is the sum of `1 / (k + rank)` over the - * legs that rank it, divided by the score of a passage first in both, so it - * lies in `(0, 1]`. Both legs run in one statement, so in one snapshot. + * legs that rank it, divided by the score of a passage first in every leg + * that runs, so it lies in `(0, 1]`. Both legs run in one statement, so in one + * snapshot. + * + * The search's retrieval mode (`AdapterSearchOptions.retrieval`, {@link + * RETRIEVAL}) names the legs that run: `hybrid` (the default) both, `vector` + * the vector leg alone, `keyword` the keyword leg alone — the leg left out is + * not written into the statement. Under one leg a passage's score is + * `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the query: + * the keyword leg's passages of equal score are ranked by chunk id, and a + * query with no terms answers nothing. * * - The vector leg: an exact scan by cosine distance — no approximate index, * so a 3072-wide model works (pgvector's HNSW index stops at 2000 @@ -277,7 +297,7 @@ interface Readiness { */ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { readonly id: string; - readonly capabilities = { chunks: true } as const; + readonly capabilities = { chunks: true, retrieval: RETRIEVAL } as const; private readonly pool?: PgPoolLike; private readonly unavailable?: string; private readonly resolveEmbedder: () => IEmbedder | undefined; @@ -579,16 +599,24 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; - // The query is embedded before a connection is taken. - const [vector] = await embedder.embed([`${this.queryPrefix}${query}`]); - if (!Array.isArray(vector) || vector.length !== generation.dim) { - throw new Error( - `knowledge-pgvector: the embedder answered a ${Array.isArray(vector) ? vector.length : 'missing'}-wide query ` + - `vector, and this source's index holds ${generation.dim}-wide vectors.`, - ); + // The legs the search's mode runs (ADR-0161, the dated note on retrieval + // modes); the service hands only a mode this adapter lists. + const mode = opts.retrieval?.mode ?? RETRIEVAL.default; + // The query is embedded before a connection is taken — never under + // `keyword`, which makes no query vector. + let vector: number[] = []; + if (mode !== 'keyword') { + const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]); + if (!Array.isArray(embedded) || embedded.length !== generation.dim) { + throw new Error( + `knowledge-pgvector: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` + + `vector, and this source's index holds ${generation.dim}-wide vectors.`, + ); + } + vector = embedded; } - const vectorLeg = !vector.every((x) => x === 0); - const terms = keywordTerms(query); + const vectorLeg = mode !== 'keyword' && !vector.every((x) => x === 0); + const terms = mode === 'vector' ? [] : keywordTerms(query); if (!vectorLeg && terms.length === 0) return []; if (terms.length > 0) await this.ensureKeywordIndex(generation.dim); @@ -724,7 +752,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const now = await this.generations(opts.source.name); if (now.active?.generation !== generation.generation) return undefined; } - return fuse(result.rows, topK).map(({ row: r, score }) => ({ + return fuse(result.rows, topK, mode === 'hybrid' ? 2 : 1).map(({ row: r, score }) => ({ chunkId: r.chunk_id, documentId: r.document_id, sourceId: opts.source.name, @@ -1377,16 +1405,19 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } /** - * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank - * in each leg, or null): best first, at most `topK`; a tie goes to the better + * Reciprocal rank fusion of the legs' rows (`vpos`, `kpos`: a row's rank in + * each leg, or null): best first, at most `topK`; a tie goes to the better * vector rank, then to the chunk id. The score is the fused sum divided by - * that of a row first in both legs. + * that of a row first in each of the `legs` the search's mode runs: under + * `hybrid` (two) exactly as before modes existed, under one leg + * `61 / (60 + rank)`. Exported for its pin test, not from the package entry. */ -function fuse( +export function fuse( rows: readonly R[], topK: number, + legs: 1 | 2, ): Array<{ row: R; score: number }> { - const best = 2 / (RRF_K + 1); + const best = legs / (RRF_K + 1); const leg = (pos: string | number | null) => (pos === null ? 0 : 1 / (RRF_K + Number(pos))); const vectorRank = (row: R) => (row.vpos === null ? Infinity : Number(row.vpos)); return rows From e8053716659c3d779cafe585328098641c1658bc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:25:08 +0000 Subject: [PATCH 06/14] test(spec): pin KnowledgeRetrievalModeSchema as isomorphic (ADR-0122) Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- packages/spec/src/type-alias-convention.pin.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 79d059e5ed7..0cfb59e9f2d 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -393,6 +393,7 @@ export type Iso_ai_knowledgeDocument__KnowledgeDocumentSchema = Assert, z.infer< typeof M3.KnowledgeHitSchema > >>; // ai/knowledge-source.zod.ts +export type Iso_ai_knowledgeSource__KnowledgeRetrievalModeSchema = Assert, z.infer< typeof M4.KnowledgeRetrievalModeSchema > >>; export type Iso_ai_knowledgeSource__ObjectKnowledgeSourceSchema = Assert, z.infer< typeof M4.ObjectKnowledgeSourceSchema > >>; // ai/mcp.zod.ts From 14b8b7a4ae831f7a73d91ac2289bfa5be1152321 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:35:41 +0000 Subject: [PATCH 07/14] docs(knowledge): the adapter contract carries the retrieval mode; name its per-search refusal code ADR-0161's K2 row on the adapter surface no longer says "no hybrid toggle": the contract carries the modes an adapter runs and the mode a search runs in, which a source declares. Protocol doc 7.1 says the same. The contract doc of AdapterSearchOptions.retrieval names the refusal of a mode the adapter does not list: SERVICE_UNAVAILABLE in a search's refused, VALIDATION_ERROR at save and registration. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 4 +++- ...plit-record-return-knowledge-source-is-a-governed-type.md | 2 +- packages/spec/src/contracts/knowledge-adapter.ts | 5 +++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 9b4c0e338d0..685004cae35 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -1504,7 +1504,9 @@ followed (§4.1, §4.2) are the adapters to run in production. ### 7.1 Non-goals for Phase 1 -- Reranker hooks, hybrid retrieval toggles, MMR — adapter-private. +- Reranker hooks, MMR — adapter-private. Which legs a search runs is not: + a source declares it (`source.retrieval.mode`, §3.1); how the legs are + weighted is not authorable yet. - Field-level masking inside a passage. A source serving a field the caller may not query is not searched for that caller at all (§5, source admission); a passage is never re-projected or redacted per caller. diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index e8612d48a02..0f771225031 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -147,7 +147,7 @@ Each text below states the old position. The left column quotes it as it reads a | Same file, §1: "We have nothing distinctive to add to those layers." and "The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins." | The framework's list grows by the four of K1; what is delegated is the adapter's four. | #37096 | | Same file, §3.1: a source "is stored as metadata (versioned, environment-scoped) just like a view or a flow", against the schema note on `packages/spec/src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema`: "the shape of a **runtime registration**, ⛔ not a governed metadata type". | The two agree: a source is a `knowledge_source` item (K4). Until row 3 lands, the schema note is the true one. | row 3 | | Same file, §3.2: "The framework does **not** chunk; adapters do." | The framework splits; adapters index the passages. | #37098 (row 6) | -| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and still no configuration, no rerank and no hybrid toggle. | #37096, then each card that adds a member | +| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`), which a source declares; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | | Same file, §6: "that surface stays unbuilt until a real `object` source calls for it." | The enumeration surface is built (K8, item 1); reconcile covers application-level predicate writes. | #37096 and row 15 | | Same file, §7 and §8: `knowledge-pgvector` as "Phase 3", and "a `KnowledgeSource.embedding` field". | `knowledge-pgvector` is an open adapter of this repository (cloud ADR-0119 D5); `embedding` is removed (K6). | #37100, row 3 | | `packages/spec/src/ai/embedding.zod.ts`, file note: "NOT in scope (these belong to application code, not the platform): Chunking strategies (fixed/semantic/recursive/markdown)." and "These were removed in v1 because they describe one specific way to build a RAG application". | Structural splitting is a platform capability of the knowledge service. It does not return as the pipeline vocabulary that was removed. Retrieval pipelines, document loaders and end-to-end orchestration stay out of scope. | #37098 | diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 4d729a55900..0790d351e29 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -192,6 +192,11 @@ export interface AdapterSearchOptions { * The service hands only a mode the adapter lists in * `capabilities.retrieval.modes`, and never hands this member to an adapter * that reports no `capabilities.retrieval`. Absent: the adapter's default. + * A source declaring a mode its adapter does not list is never searched + * another way: the knowledge service lists it in a search's `refused` with + * `SERVICE_UNAVAILABLE` (503, the ADR-0112 standard code a source whose + * adapter is not mounted is refused with there), and refuses it at its save + * and registration with `VALIDATION_ERROR` (400). * Scores need only not increase with rank within one source's answer; under * a one-leg mode they reflect rank alone. */ From 08788c6156c1e92d49d4dbe5c5cbfe571b829675 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:32:14 +0000 Subject: [PATCH 08/14] fix(platform-objects): name the retrieval-mode choices in every locale; count the new isomorphic pin The knowledge source form's Search group and its Retrieval mode select get their translation bundle entries, translated in the ten locales, and the ADR-0122 pin count moves 880 -> 881 for KnowledgeRetrievalModeSchema. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../translations/ar.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/de.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/en.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/es-ES.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/fr.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ja-JP.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ko.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/pt-BR.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ru.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/zh-CN.metadata-forms.generated.ts | 13 +++++++++++++ .../zh-Hant.metadata-forms.generated.ts | 13 +++++++++++++ packages/spec/src/type-alias-convention.pin.test.ts | 10 +++++++--- 12 files changed, 150 insertions(+), 3 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 122b54abb87..077577dcfa0 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const arMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "البحث", + helpText: "كيف يعثر البحث في هذا المصدر على المقاطع. اتركه فارغًا لاستخدام الوضع الافتراضي للمخزن. تغييره لا يعيد بناء أي شيء." + }, + "source.retrieval.mode": { + label: "وضع الاسترجاع", + helpText: "فارغ: الوضع الافتراضي للمخزن (هجين في turso وpgvector). المتجه يرتّب المقاطع حسب المعنى؛ والكلمات المفتاحية حسب الكلمات التي تحتويها، دون استدعاء مزوّد التضمين، وهو ما يناسب أرقام المستندات أو البنود؛ والهجين يدمج الاثنين. يُرفض عند الحفظ أي وضع لا يشغّله المخزن.", + options: { + vector: "المتجه فقط (حسب المعنى)", + keyword: "الكلمات المفتاحية فقط (حسب الكلمات)", + hybrid: "هجين (كلاهما)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index fa9fe31de92..31d44962244 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const deMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Suche", + helpText: "Wie eine Suche in dieser Quelle Passagen findet. Leer lassen für den Standard des Speichers. Eine Änderung löst keinen Neuaufbau aus." + }, + "source.retrieval.mode": { + label: "Abrufmodus", + helpText: "Leer: der Standard des Speichers (hybrid bei turso und pgvector). Vektor ordnet Passagen nach Bedeutung; Stichwort nach den enthaltenen Wörtern, ohne Aufruf des Embedding-Anbieters, was zu Dokument- oder Klauselnummern passt; hybrid führt beides zusammen. Ein Modus, den der Speicher nicht ausführt, wird beim Speichern abgelehnt.", + options: { + vector: "Nur Vektor (nach Bedeutung)", + keyword: "Nur Stichwort (nach Wörtern)", + hybrid: "Hybrid (beides)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index b857c9545f3..f6607bfb55f 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const enMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Search", + helpText: "How a search of this source finds passages. Leave it blank for the store's default. Changing it rebuilds nothing." + }, + "source.retrieval.mode": { + label: "Retrieval mode", + helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.", + options: { + vector: "Vector only (by meaning)", + keyword: "Keyword only (by words)", + hybrid: "Hybrid (both)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 9bea909628d..b859ff778ee 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const esESMetadataForms: NonNullable = label: "Orden según quien pregunta", helpText: "Opcional. Enumera entradas que suben en la respuesta los resultados relacionados con quien pregunta; por ejemplo, [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] pone primero su propia unidad, luego sus unidades superiores y después el resto, y [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] deja que un resultado suyo adelante hasta 3 otros (de 1 a 20). Cada campo debe figurar en los campos de filtro y apuntar a usuarios (caller user) o a unidades de negocio (caller business_unit); como máximo un nearest. No se descarta ningún resultado ni cambia su puntuación, y configurarlo no reconstruye nada.\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Búsqueda", + helpText: "Cómo una búsqueda en esta fuente encuentra pasajes. Déjalo vacío para usar el modo predeterminado del almacén. Cambiarlo no reconstruye nada." + }, + "source.retrieval.mode": { + label: "Modo de recuperación", + helpText: "Vacío: el modo predeterminado del almacén (híbrido en turso y pgvector). Vectorial ordena los pasajes por su significado; palabra clave por las palabras que contienen, sin llamar al proveedor de embeddings, lo que sirve para números de documento o de cláusula; híbrido combina ambos. Un modo que el almacén no ejecuta se rechaza al guardar.", + options: { + vector: "Solo vectorial (por significado)", + keyword: "Solo palabra clave (por palabras)", + hybrid: "Híbrido (ambos)" + } + }, "source.where": { label: "Registros que indexar", helpText: "Un filtro ObjectQL sobre el objeto, por ejemplo {\"status\": {\"$ne\": \"done\"}}. Solo se indexan los registros que coinciden. En blanco: todos los registros." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index d5b376fbe0b..1d5e5fa33f4 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const frMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Recherche", + helpText: "Comment une recherche dans cette source trouve les passages. Laissez vide pour le mode par défaut du magasin. Le modifier ne reconstruit rien." + }, + "source.retrieval.mode": { + label: "Mode de recherche", + helpText: "Vide : le mode par défaut du magasin (hybride sur turso et pgvector). Vectoriel classe les passages par leur sens ; mot-clé par les mots qu'ils contiennent, sans appel au fournisseur d'embeddings, ce qui convient aux numéros de document ou de clause ; hybride fusionne les deux. Un mode que le magasin n'exécute pas est refusé à l'enregistrement.", + options: { + vector: "Vectoriel seul (par le sens)", + keyword: "Mot-clé seul (par les mots)", + hybrid: "Hybride (les deux)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index fd74ec8dbac..199f97863e3 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const jaJPMetadataForms: NonNullable = label: "質問者に合わせた並び順", helpText: "任意。質問者に関係するヒットを上位に移すエントリを並べます。例:[{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] は質問者自身の部門を先頭に、次に上位部門を順に、最後にその他を並べ、[{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] は質問者が所有するヒットを最大 3 件分上に移します(1〜20)。各フィールドはフィルターフィールドに含まれ、ユーザー(caller が user)またはビジネスユニット(caller が business_unit)を指す必要があります。nearest は 1 つまでです。ヒットを除外することもスコアを変えることもなく、設定しても再構築は行われません。\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "検索", + helpText: "このソースを検索するときのパッセージの探し方。空欄にするとストアの既定になります。変更しても再構築は行われません。" + }, + "source.retrieval.mode": { + label: "検索モード", + helpText: "空欄:ストアの既定(turso と pgvector ではハイブリッド)。ベクトルは意味でパッセージを順位付けし、キーワードは含まれる語句で順位付けします(埋め込みプロバイダーは呼び出さないため、文書番号や条項番号に向いています)。ハイブリッドは両方を統合します。ストアが実行しないモードは保存時に拒否されます。", + options: { + vector: "ベクトルのみ(意味で)", + keyword: "キーワードのみ(語句で)", + hybrid: "ハイブリッド(両方)" + } + }, "source.where": { label: "インデックス化するレコード", helpText: "オブジェクトに対する ObjectQL フィルター。例:{\"status\": {\"$ne\": \"done\"}}。一致するレコードだけがインデックス化されます。空欄:すべてのレコード。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 2b5de15d92f..92f3c7326ff 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const koMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "검색", + helpText: "이 소스를 검색할 때 구절을 찾는 방식입니다. 비워 두면 저장소의 기본값을 사용합니다. 변경해도 다시 빌드하지 않습니다." + }, + "source.retrieval.mode": { + label: "검색 방식", + helpText: "비워 두면 저장소의 기본값(turso와 pgvector에서는 하이브리드)을 사용합니다. 벡터는 의미로 구절의 순위를 매기고, 키워드는 구절에 담긴 단어로 순위를 매기며 임베딩 제공자를 호출하지 않아 문서 번호나 조항 번호에 적합합니다. 하이브리드는 둘을 합칩니다. 저장소가 실행하지 않는 방식은 저장 시 거부됩니다.", + options: { + vector: "벡터만(의미 기준)", + keyword: "키워드만(단어 기준)", + hybrid: "하이브리드(둘 다)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index f359904d89f..63d3a209749 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const ptBRMetadataForms: NonNullable = label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Busca", + helpText: "Como uma busca nesta fonte encontra trechos. Deixe em branco para usar o padrão do armazenamento. Alterar não reconstrói nada." + }, + "source.retrieval.mode": { + label: "Modo de recuperação", + helpText: "Em branco: o padrão do armazenamento (híbrido no turso e no pgvector). Vetorial ordena os trechos pelo significado; palavra-chave pelas palavras que contêm, sem chamar o provedor de embeddings, o que serve para números de documento ou de cláusula; híbrido combina os dois. Um modo que o armazenamento não executa é recusado ao salvar.", + options: { + vector: "Somente vetorial (pelo significado)", + keyword: "Somente palavra-chave (pelas palavras)", + hybrid: "Híbrido (ambos)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 88ff3a6b1bf..0937d28506d 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const ruMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Поиск", + helpText: "Как поиск по этому источнику находит фрагменты. Оставьте пустым, чтобы использовать режим хранилища по умолчанию. Изменение ничего не перестраивает." + }, + "source.retrieval.mode": { + label: "Режим поиска", + helpText: "Пусто: режим хранилища по умолчанию (гибридный в turso и pgvector). Векторный упорядочивает фрагменты по смыслу; по ключевым словам — по содержащимся в них словам, без обращения к провайдеру эмбеддингов, что подходит для номеров документов или пунктов; гибридный объединяет оба. Режим, который хранилище не выполняет, отклоняется при сохранении.", + options: { + vector: "Только векторный (по смыслу)", + keyword: "Только ключевые слова (по словам)", + hybrid: "Гибридный (оба)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 83afaf885ea..d527bd0cc50 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const zhCNMetadataForms: NonNullable = label: "按提问人排序", helpText: "可选。列出把与提问人相关的命中往前排的条目,例如 [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] 先排提问人本单位,再按上级单位逐级,最后其余;[{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] 让提问人负责的命中最多越过 3 条其他命中(1 到 20)。每个字段须列在筛选字段中,并指向用户(caller 为 user)或业务单位(caller 为 business_unit);nearest 最多一条。不会丢弃命中,也不改分数,设置它不会触发重建。\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "检索", + helpText: "检索此来源时如何查找段落。留空则使用存储的默认方式。修改它不会触发重建。" + }, + "source.retrieval.mode": { + label: "检索方式", + helpText: "留空:使用存储的默认方式(turso 和 pgvector 为混合)。向量按含义对段落排序;关键词按段落包含的词语排序,不调用嵌入服务,适合文件编号或条款编号;混合则合并两者。存储不支持的方式在保存时会被拒绝。", + options: { + vector: "仅向量(按含义)", + keyword: "仅关键词(按词语)", + hybrid: "混合(两者)" + } + }, "source.where": { label: "要索引的记录", helpText: "对该对象的 ObjectQL 筛选条件,例如 {\"status\": {\"$ne\": \"done\"}}。只有匹配的记录会被索引。留空:所有记录。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index cd7cc6e30cf..25d84eaf09e 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const zhHantMetadataForms: NonNullable label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "檢索", + helpText: "檢索此來源時如何查找段落。留空則使用儲存的預設方式。修改它不會觸發重建。" + }, + "source.retrieval.mode": { + label: "檢索方式", + helpText: "留空:使用儲存的預設方式(turso 和 pgvector 為混合)。向量依含義排序段落;關鍵字依段落包含的詞語排序,不呼叫嵌入服務,適合文件編號或條款編號;混合則合併兩者。儲存不支援的方式在儲存時會被拒絕。", + options: { + vector: "僅向量(依含義)", + keyword: "僅關鍵字(依詞語)", + hybrid: "混合(兩者)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 0cfb59e9f2d..5b46eddeb02 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -305,7 +305,7 @@ import type * as M205 from './ai/object-query-source.zod.js'; import type * as M207 from './api/ai-answer.zod.js'; // --------------------------------------------------------------------------- -// 880 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 881 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -1848,7 +1848,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 880 isomorphic pins', () => { + it('still declares all 881 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2988,7 +2988,11 @@ describe('ADR-0122 type-alias convention', () => { // `RecordQuickActionsLocationSchema` (`ui/action.zod.ts`), the shared // location enum less `record`, with no default or transform // (Iso_ui_action__RecordQuickActionsLocationSchema). +1 added. - expect(pins).toHaveLength(880); + // 880 -> 881 is #38692: the mode a knowledge source's searches run in, + // `KnowledgeRetrievalModeSchema` (`ai/knowledge-source.zod.ts`), a plain + // enum with no default or transform + // (Iso_ai_knowledgeSource__KnowledgeRetrievalModeSchema). +1 added. + expect(pins).toHaveLength(881); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either From 7436d4f2e31fad5d3a79154b0a591dfa0bfad198 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:52:18 +0000 Subject: [PATCH 09/14] test(platform-objects): count the retrieval-mode rows in the translated metadata-form catalog Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../object-lifecycle-panel-echo-decisions.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 9058db36f9c..68ffe3980d7 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1361,7 +1361,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // authored in all three locales. // 869 since #37792: the object form's `pinOverview` row (the record // page layout switch) — one row label, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(869); + // 871 since #38692: the `knowledge_source` form's `source.retrieval` + // group and its `mode` row (the retrieval mode) — two row labels, + // authored in every locale. + expect(translated.length, `${locale} positive control`).toBe(871); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From fe740d089970f44b2c7967c71f21115d7155aa4b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:01:51 +0000 Subject: [PATCH 10/14] test(knowledge-pgvector): a vector-mode search writes no keyword condition into any statement Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../src/__tests__/retrieval-modes.test.ts | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts index e4c9b3bb40b..5599c364fe6 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts @@ -18,9 +18,11 @@ import { FakeEmbedder } from './live-pg.testkit.js'; const source = { name: 'modes', label: 'modes', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; /** A store with one active generation whose ranking statement is recorded and answers nothing. */ -function recordingPool(): { pool: PgPoolLike; rankings: string[] } { +function recordingPool(): { pool: PgPoolLike; rankings: string[]; statements: string[] } { const rankings: string[] = []; + const statements: string[] = []; const answer = async (text: string): Promise<{ rows: R[] }> => { + statements.push(text); if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { @@ -30,7 +32,7 @@ function recordingPool(): { pool: PgPoolLike; rankings: string[] } { return { rows: [] as R[] }; }; const client = (): PgClientLike => ({ query: answer, release: () => undefined }); - return { pool: { query: answer, connect: async () => client() }, rankings }; + return { pool: { query: answer, connect: async () => client() }, rankings, statements }; } async function searched(mode: 'vector' | 'keyword' | 'hybrid' | undefined, query = 'granite quarry') { @@ -43,7 +45,7 @@ async function searched(mode: 'vector' | 'keyword' | 'hybrid' | undefined, query index: { fingerprint: 'fp' }, ...(mode === undefined ? {} : { retrieval: { mode } }), }); - return { hits, embedder, rankings: store.rankings }; + return { hits, embedder, rankings: store.rankings, statements: store.statements }; } describe('knowledge-pgvector retrieval modes', () => { @@ -71,6 +73,19 @@ describe('knowledge-pgvector retrieval modes', () => { expect(embedder.calls).toBe(1); }); + it('vector writes no keyword condition into any statement, not just none into the fusion', async () => { + // Measured on PG17 + pgvector 0.8.7 over 59,949 clauses: the keyword terms (sixteen + // LIKEs over every row in scope) were most of a hybrid statement's cost. + const hybrid = await searched('hybrid', 'granite quarry w3x 出差'); + expect(hybrid.rankings[0]).toMatch(/\bI?LIKE\b/); + const { statements } = await searched('vector', 'granite quarry w3x 出差'); + expect(statements.length).toBeGreaterThan(0); + for (const text of statements) { + expect(text).not.toMatch(/\bI?LIKE\b/); + expect(text).not.toMatch(/tsquery|@@/); + } + }); + it('keyword writes the keyword leg alone and never calls the embedder', async () => { const { rankings, embedder } = await searched('keyword'); expect(rankings).toHaveLength(1); From b15ac8df9799f66e3993ca40c44e6388c2884953 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:42:19 +0000 Subject: [PATCH 11/14] docs(spec): cite the ADR-0161 note of 2026-11-30 under K8 by its place; regenerate the spec artifacts after the merge of main The merge of main had left the ai shards of the generated spec artifacts without main's TurnEnd rows; check:generated --fix rewrites them from a fresh build. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/references/index.mdx | 9 +++++---- .../2026-07-unknown-key-strictness-ledger.counts/ai.md | 2 +- .../src/__tests__/index-fingerprint.test.ts | 4 ++-- packages/services/service-knowledge/src/testing.ts | 4 ++-- packages/spec/api-surface/ai.json | 4 ++++ packages/spec/authorable-surface/ai.json | 7 ++++++- packages/spec/declaration-map/ai.json | 4 +++- packages/spec/export-origins/ai.json | 4 ++++ packages/spec/json-schema.manifest/ai.json | 3 ++- packages/spec/liveness/knowledge_source.json | 2 +- packages/spec/src/ai/knowledge-source.test.ts | 2 +- packages/spec/src/ai/knowledge-source.zod.ts | 6 +++--- packages/spec/src/contracts/knowledge-adapter.ts | 6 +++--- 13 files changed, 37 insertions(+), 20 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 03b540df209..40f494a7901 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1747 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1748 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -22,7 +22,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 17 | 107 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -36,13 +36,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 187 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **223** | **1747** | 14 protocol modules | +| **Total** | **224** | **1748** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 107 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 108 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -64,6 +64,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`skill.zod.ts`](/docs/references/ai/skill) | `Skill`, `SkillTriggerCondition` | | [`solution-blueprint.zod.ts`](/docs/references/ai/solution-blueprint) | `BlueprintApp`, `BlueprintCondition`, `BlueprintDashboard`, `BlueprintField`, `BlueprintNavItem`, `BlueprintObject`, `BlueprintSeed`, `BlueprintSummaryOperations`, `BlueprintView`, `BlueprintWidgetCondition`, `SolutionBlueprint`, `SolutionBlueprintStrict` | | [`tool.zod.ts`](/docs/references/ai/tool) | `Tool` | +| [`turn-end.zod.ts`](/docs/references/ai/turn-end) | `TurnEnd` | | [`usage.zod.ts`](/docs/references/ai/usage) | `AIUsageRecord`, `TokenUsage` | --- diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 050f8f7f1d7..3ecff028bbc 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 122 | +| `ai/` | 123 | diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 2168abc0b70..5ea16f03535 100644 --- a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -172,9 +172,9 @@ describe('recipe hash (ADR-0161 K7)', () => { }); // `source.retrieval` is read on every search and by no build (ADR-0161, the -// dated note on retrieval modes): neither hash moves with it, so changing a +// dated note of 2026-11-30 under K8): neither hash moves with it, so changing a // source's retrieval mode rebuilds nothing. -describe('retrieval mode (ADR-0161, the dated note on retrieval modes)', () => { +describe('retrieval mode (ADR-0161, the dated note of 2026-11-30 under K8)', () => { it('changes neither the index fingerprint nor the recipe hash', () => { const fingerprint = computeIndexFingerprint({ source: source(), embedding, split }); const recipe = computeRecipeHash({ source: source() }); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 1eb8060fa13..78f526856b2 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -155,7 +155,7 @@ export interface KnowledgeAdapterContractOptions { */ keywordLeg?: boolean; /** - * `capabilities.retrieval` (ADR-0161, the dated note on retrieval modes): + * `capabilities.retrieval` (ADR-0161, the dated note of 2026-11-30 under K8): * the adapter reports the modes it runs and its default, and its search * honours `AdapterSearchOptions.retrieval`. The report is checked against * the three modes, and each listed mode is asserted by behaviour: `vector` @@ -587,7 +587,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption } if (opts.implements.retrieval === true) { - describe('retrieval modes (ADR-0161, the dated note on retrieval modes)', () => { + describe('retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8)', () => { it('reports the modes it runs, each once and each one of the three, and a default it lists', async () => { const adapter: IKnowledgeAdapter = await make(); const report = adapter.capabilities?.retrieval; diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 0bfeb1ab566..c9ffbb4d6d6 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -296,6 +296,7 @@ "StructuredOutputConfigSchema (const)", "StructuredOutputFormat (type)", "StructuredOutputFormatSchema (const)", + "TURN_END_PART_TYPE (const)", "TextContent (type)", "TextContentSchema (const)", "TokenBudgetConfig (type)", @@ -315,6 +316,9 @@ "ToolSchema (const)", "TransformPipelineStep (type)", "TransformPipelineStepSchema (const)", + "TurnEnd (type)", + "TurnEndParsed (type)", + "TurnEndSchema (const)", "agentForm (const)", "aiContextForm (const)", "aiContextWhereFields (function)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 529db46b843..ab5bb1bb688 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -577,6 +577,11 @@ "ai/Tool:protection", "ai/ToolCall:function", "ai/ToolCall:id", - "ai/ToolCall:type" + "ai/ToolCall:type", + "ai/TurnEnd:reason", + "ai/TurnEnd:resumable", + "ai/TurnEnd:resumesLeft", + "ai/TurnEnd:turnId", + "ai/TurnEnd:wrapUp" ] } diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 70474f71dfe..0d874a661cb 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -209,7 +209,9 @@ "ToolCallSchema": "ai/ToolCall", "ToolSchema": "ai/Tool", "TransformPipelineStep": "ai/TransformPipelineStep", - "TransformPipelineStepSchema": "ai/TransformPipelineStep" + "TransformPipelineStepSchema": "ai/TransformPipelineStep", + "TurnEnd": "ai/TurnEnd", + "TurnEndSchema": "ai/TurnEnd" }, "collisions": [] } diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 2114847e360..610779dc917 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -293,6 +293,7 @@ "StructuredOutputConfigSchema": "src/ai/agent.zod.ts#StructuredOutputConfigSchema (const)", "StructuredOutputFormat": "src/ai/agent.zod.ts#StructuredOutputFormat (type)", "StructuredOutputFormatSchema": "src/ai/agent.zod.ts#StructuredOutputFormatSchema (const)", + "TURN_END_PART_TYPE": "src/ai/turn-end.zod.ts#TURN_END_PART_TYPE (const)", "TextContent": "src/ai/conversation.zod.ts#TextContent (type)", "TextContentSchema": "src/ai/conversation.zod.ts#TextContentSchema (const)", "TokenBudgetConfig": "src/ai/conversation.zod.ts#TokenBudgetConfig (type)", @@ -312,6 +313,9 @@ "ToolSchema": "src/ai/tool.zod.ts#ToolSchema (const)", "TransformPipelineStep": "src/ai/agent.zod.ts#TransformPipelineStep (type)", "TransformPipelineStepSchema": "src/ai/agent.zod.ts#TransformPipelineStepSchema (const)", + "TurnEnd": "src/ai/turn-end.zod.ts#TurnEnd (type)", + "TurnEndParsed": "src/ai/turn-end.zod.ts#TurnEndParsed (type)", + "TurnEndSchema": "src/ai/turn-end.zod.ts#TurnEndSchema (const)", "agentForm": "src/ai/agent.metadata-form.ts#agentForm (const)", "aiContextForm": "src/ai/ai-context.metadata-form.ts#aiContextForm (const)", "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 3f17e4320fe..56fd5331ef4 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -108,6 +108,7 @@ "ai/TokenUsageStats", "ai/Tool", "ai/ToolCall", - "ai/TransformPipelineStep" + "ai/TransformPipelineStep", + "ai/TurnEnd" ] } diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index ca269505e36..672e1a0b0e8 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -124,7 +124,7 @@ "retrieval": { "status": "planned", "verifiedAt": "2026-11-30", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note on retrieval modes): `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. Enters neither the index fingerprint nor the recipe hash.", + "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. Enters neither the index fingerprint nor the recipe hash.", "children": { "mode": { "status": "planned", diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index af044bd5816..1be90217149 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -417,7 +417,7 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller }); }); -describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note on retrieval modes)', () => { +describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note of 2026-11-30 under K8)', () => { const withRetrieval = (retrieval: unknown): unknown => ({ ...SOURCE, source: { ...SOURCE.source, retrieval } }); it('positive control: each of the three modes parses and is kept as written; absent stays absent', () => { diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 64e6ef189c6..a07a538429c 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -130,7 +130,7 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( /** * The retrieval modes a knowledge source may declare (ADR-0161, the dated note - * on retrieval modes; ruling 7270218011 on #38692): + * of 2026-11-30 under K8; ruling 7270218011 on #38692): * * - `vector`: only the vector leg runs, ranking passages by meaning. * - `keyword`: only the keyword leg runs, ranking passages by the words they @@ -156,7 +156,7 @@ export const KnowledgeRetrievalModeSchema = lazySchema(() => z.enum(KNOWLEDGE_RE })); /** - * How a source is searched (ADR-0161, the dated note on retrieval modes): + * How a source is searched (ADR-0161, the dated note of 2026-11-30 under K8): * which legs the store runs. A declaration of the source, read on every search * and never by a build, so it enters neither the index fingerprint nor the * recipe hash: changing it rebuilds nothing. `retrieval: {}` declares nothing @@ -504,7 +504,7 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( affinity: z.array(KnowledgeAffinityEntrySchema).optional() .describe('How this source\'s hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score'), /** - * [ADR-0161, the dated note on retrieval modes] How this source is + * [ADR-0161, the dated note of 2026-11-30 under K8] How this source is * searched: `retrieval.mode` names the legs the store runs * ({@link KnowledgeRetrievalSchema}). Beside {@link affinity} and before * it: the mode decides which passages the store ranks and their scores, diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 0790d351e29..b1e074cb4d7 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -177,8 +177,8 @@ export interface AdapterSearchOptions { */ index?: { fingerprint: string }; /** - * The retrieval mode this search runs (ADR-0161, the dated note on - * retrieval modes): the EFFECTIVE mode, which the knowledge service resolves + * The retrieval mode this search runs (ADR-0161, the dated note of + * 2026-11-30 under K8): the EFFECTIVE mode, which the knowledge service resolves * from the source's `source.retrieval.mode`, else the adapter's * {@link AdapterCapabilities.retrieval} `default`. A per-request parameter, * as `topK` and `scope` are — not configuration (ADR-0161 K8, rule 4). @@ -271,7 +271,7 @@ export interface AdapterCapabilities { chunks?: boolean; /** * The retrieval modes the adapter runs, and which one it runs when a - * source declares none (ADR-0161, the dated note on retrieval modes). A + * source declares none (ADR-0161, the dated note of 2026-11-30 under K8). A * report, not configuration: `default` is one of `modes`, and an adapter * that lists `hybrid` honours the source's vector share when that arrives. * From a76dc2eb6c79427ed4e60684f2900faa94bd095a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:14:50 +0000 Subject: [PATCH 12/14] chore(changeset): the platform-objects translations of the retrieval-mode form ship as a patch Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .changeset/38692-knowledge-retrieval-mode-spec.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md index c48981f369f..754d85822e2 100644 --- a/.changeset/38692-knowledge-retrieval-mode-spec.md +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -1,6 +1,7 @@ --- '@objectstack/spec': minor '@objectstack/service-knowledge': minor +'@objectstack/platform-objects': patch --- feat(spec): a knowledge source may declare its retrieval mode, `source.retrieval.mode` (`vector`, `keyword` or `hybrid`), and a knowledge adapter reports the modes it runs @@ -14,4 +15,6 @@ A `knowledge_source` may now declare how it is searched: `source: { …, retriev The adapter contract suite (`@objectstack/service-knowledge/testing`) takes a new optional declaration, `implements.retrieval`: it checks the adapter's report (each mode one of the three, none twice, the default listed), searches a fixed set of passages under each listed mode (`vector` leaves out the passage only the keyword leg ranks, `keyword` answers that passage alone and nothing for a query with no word any passage holds), and checks that the default mode handed explicitly answers exactly what a search without the member answers. An adapter that does not declare it is checked to report no modes. +The Studio metadata-form translations (`@objectstack/platform-objects`) name the "Search" group and the "Retrieval mode" select and its three choices in every locale. + The knowledge service's reading of the mode (and its refusal of a mode the source's store does not run) and the turso and pgvector stores' support for it ship as separate changes. From 75d7437697965789272958e77ee83334a65a8459 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 11:03:57 +0000 Subject: [PATCH 13/14] fix(spec): the retrieval key warns until the service reads it; the contract leaves the per-search code to the service The planned liveness row of source.retrieval warns an author (authorWarn and authorHint) until the knowledge service reads it. The texts that state the refusals name the knowledge service as the refuser; the contract's jsdoc no longer names the per-search refusal code. The shared suite's vector case no longer needs a keyword leg, so a vector-only store attests. The ADR K2 row says the member carries the effective mode, and the protocol doc's section 3.1 names the key. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 8 ++++++++ ...rd-return-knowledge-source-is-a-governed-type.md | 2 +- .../translations/en.metadata-forms.generated.ts | 2 +- packages/services/service-knowledge/src/testing.ts | 5 +++-- packages/spec/liveness/knowledge_source.json | 4 +++- .../spec/src/ai/knowledge-source.metadata-form.ts | 2 +- packages/spec/src/ai/knowledge-source.zod.ts | 13 +++++++------ packages/spec/src/contracts/knowledge-adapter.ts | 6 ++---- 8 files changed, 26 insertions(+), 16 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 685004cae35..0a84154c23f 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -181,6 +181,14 @@ that name (ADR-0161 K4): `VALIDATION_ERROR` (400), naming them. The adapter is placed where it is 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 +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. + **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 diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index 91e0d334663..c2348262641 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -150,7 +150,7 @@ Each text below states the old position. The left column quotes it as it reads a | Same file, §1: "We have nothing distinctive to add to those layers." and "The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins." | The framework's list grows by the four of K1; what is delegated is the adapter's four. | #37096 | | Same file, §3.1: a source "is stored as metadata (versioned, environment-scoped) just like a view or a flow", against the schema note on `packages/spec/src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema`: "the shape of a **runtime registration**, ⛔ not a governed metadata type". | The two agree: a source is a `knowledge_source` item (K4). Until row 3 lands, the schema note is the true one. | row 3 | | Same file, §3.2: "The framework does **not** chunk; adapters do." | The framework splits; adapters index the passages. | #37098 (row 6) | -| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`), which a source declares; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | +| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`): the source's declaration, else the adapter's default; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | | Same file, §6: "that surface stays unbuilt until a real `object` source calls for it." | The enumeration surface is built (K8, item 1); reconcile covers application-level predicate writes. | #37096 and row 15 | | Same file, §7 and §8: `knowledge-pgvector` as "Phase 3", and "a `KnowledgeSource.embedding` field". | `knowledge-pgvector` is an open adapter of this repository (cloud ADR-0119 D5); `embedding` is removed (K6). | #37100, row 3 | | `packages/spec/src/ai/embedding.zod.ts`, file note: "NOT in scope (these belong to application code, not the platform): Chunking strategies (fixed/semantic/recursive/markdown)." and "These were removed in v1 because they describe one specific way to build a RAG application". | Structural splitting is a platform capability of the knowledge service. It does not return as the pipeline vocabulary that was removed. Retrieval pipelines, document loaders and end-to-end orchestration stay out of scope. | #37098 | diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index f6607bfb55f..a888b4925f7 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3571,7 +3571,7 @@ export const enMetadataForms: NonNullable = { }, "source.retrieval.mode": { label: "Retrieval mode", - helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.", + helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. The knowledge service refuses a mode the store does not run when the source is saved.", options: { vector: "Vector only (by meaning)", keyword: "Keyword only (by words)", diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 78f526856b2..f4e41c3d050 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -161,7 +161,9 @@ export interface KnowledgeAdapterContractOptions { * the three modes, and each listed mode is asserted by behaviour: `vector` * leaves out the passage only the keyword leg ranks, `keyword` ranks by * the query's words alone, `hybrid` answers what the default answers when - * it is the default. A `vector` or `keyword` case needs `keywordLeg`. + * it is the default. The `keyword` case needs `keywordLeg`; the `vector` + * case holds for a store with no keyword leg too, so a vector-only store + * (`modes: ['vector']`) attests. * Absent: `false`. */ retrieval?: boolean; @@ -623,7 +625,6 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('`vector` runs the vector leg alone: the passage only the keyword leg ranks is not answered', async () => { const { adapter, a, listed } = await seeded(); if (!listed.includes('vector')) return; - expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); nonIncreasing(hits); diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index 672e1a0b0e8..f50d75d32b5 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -124,7 +124,9 @@ "retrieval": { "status": "planned", "verifiedAt": "2026-11-30", - "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. Enters neither the index fingerprint nor the recipe hash.", + "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.", "children": { "mode": { "status": "planned", diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index 1215e5f31b2..75a86d7d7df 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -93,7 +93,7 @@ export const knowledgeSourceForm = defineMetadataForm({ { label: 'Keyword only (by words)', value: 'keyword' }, { label: 'Hybrid (both)', value: 'hybrid' }, ], - helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.', + helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. The knowledge service refuses a mode the store does not run when the source is saved.', }, ], }, diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index a07a538429c..8f61e67cdb2 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -141,8 +141,8 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( * - `hybrid`: both legs run, merged by the store's fusion. * * Which modes a store runs is the store's report (`AdapterCapabilities.retrieval`), - * never configuration; a source that declares a mode its store does not run is - * refused, never silently searched another way. + * never configuration. A source that declares a mode its store does not run is + * refused by the knowledge service, never silently searched another way. */ export const KNOWLEDGE_RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; @@ -172,10 +172,11 @@ export const KnowledgeRetrievalSchema = lazySchema(() => strictObject( * Which legs run: `vector`, `keyword` or `hybrid` * ({@link KNOWLEDGE_RETRIEVAL_MODES}). Omitted: the store's default * (`AdapterCapabilities.retrieval.default`; `hybrid` on turso and - * pgvector), today's behaviour. A store that does not list the mode - * refuses the source at save, at registration when its store already - * resolves, once after boot, and on every search (the source is listed as - * refused); a store that reports no modes accepts only the key left out. + * pgvector), today's behaviour. The knowledge service refuses a source + * whose store does not list the mode: at save, at registration when its + * store already resolves, once after boot, and on every search (the source + * is listed as refused). A store that reports no modes takes only a source + * that leaves the key out. */ mode: KnowledgeRetrievalModeSchema.optional() .describe('Which legs a search runs: vector, keyword or hybrid; omitted means the store\'s default'), diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index b1e074cb4d7..b62c7af7d17 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -193,10 +193,8 @@ export interface AdapterSearchOptions { * `capabilities.retrieval.modes`, and never hands this member to an adapter * that reports no `capabilities.retrieval`. Absent: the adapter's default. * A source declaring a mode its adapter does not list is never searched - * another way: the knowledge service lists it in a search's `refused` with - * `SERVICE_UNAVAILABLE` (503, the ADR-0112 standard code a source whose - * adapter is not mounted is refused with there), and refuses it at its save - * and registration with `VALIDATION_ERROR` (400). + * another way: the knowledge service refuses it, at its save and its + * registration, and lists it in a search's `refused` with its code. * Scores need only not increase with rank within one source's answer; under * a one-leg mode they reflect rank alone. */ From 6707107d1680f0965c67e9805130810f6ab98573 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 14:04:29 +0000 Subject: [PATCH 14/14] Refuse a retrieval mode the store does not list; declare the widening MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A mode outside the store's list ran both legs on the one-leg scale; it is now refused (400 VALIDATION_ERROR) before anything is embedded or read. The exported adapter's capabilities grow a member, so the changeset says Clause-② yes (widening). The README's keyword-index sentence says a vector search does not build a missing index. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../38692-knowledge-pgvector-retrieval-modes.md | 4 ++-- packages/plugins/knowledge-pgvector/README.md | 2 +- .../src/__tests__/retrieval-modes.test.ts | 12 +++++++++++- .../knowledge-pgvector/src/pgvector-adapter.ts | 12 +++++++++++- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/.changeset/38692-knowledge-pgvector-retrieval-modes.md b/.changeset/38692-knowledge-pgvector-retrieval-modes.md index 64cc62beb66..927460236e5 100644 --- a/.changeset/38692-knowledge-pgvector-retrieval-modes.md +++ b/.changeset/38692-knowledge-pgvector-retrieval-modes.md @@ -4,7 +4,7 @@ feat(knowledge-pgvector): the store runs the vector leg alone, the keyword leg alone, or both, as a source's retrieval mode says -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none -`knowledge-pgvector` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the cosine scan alone and `keyword` the keyword match alone; the other leg is not written into the statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. +`knowledge-pgvector` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the cosine scan alone and `keyword` the keyword match alone; the other leg is not written into the statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. A mode it does not list is refused (`400 VALIDATION_ERROR`), never run. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index 19d704cc55f..d7fb0af98d1 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -62,7 +62,7 @@ Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF, **Retrieval modes.** The store reports all three modes (`capabilities.retrieval`: `vector`, `keyword`, `hybrid`), `hybrid` by default, and a source chooses with `source.retrieval.mode`. `hybrid` runs both legs as above. `vector` runs the vector leg alone and `keyword` the keyword leg alone: the other leg is not written into the statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing the mode rebuilds nothing. - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` is one term (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A word of three characters or more is matched as a phrase (`phraseto_tsquery('simple', …)`) on the passage's `to_tsvector('simple', content)`, which a GIN expression index (`knowledge_vec_d_content_tsv`) serves. The `simple` configuration lower-cases and neither stems nor drops stop words, so a code or a name matches as written. A shorter term (「出差」), and a term holding a Han, kana or Hangul character — which the parser never splits, so a `tsvector` holds a whole run of them as one word — is matched as a substring over the rows in scope: by `content LIKE '%…%'` when the term holds no cased letter (a piece of Han, kana or Hangul, a figure), where case folding could find nothing more, and by `content ILIKE '%…%'` otherwise. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. -- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write or search of that width (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds). +- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write of that width, or the first search of that width with keyword terms (never under `vector`) (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds). - **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it. ## Pool size and time limit diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts index 22ce1747e6c..e93c41181b2 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts @@ -36,6 +36,10 @@ function recordingPool(): { pool: PgPoolLike; rankings: string[]; statements: st } async function searched(mode: 'vector' | 'keyword' | 'hybrid' | undefined, query = 'granite quarry') { + return searchedRaw(mode, query); +} + +async function searchedRaw(mode: string | undefined, query = 'granite quarry') { const store = recordingPool(); const embedder = new FakeEmbedder(); const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder }); @@ -43,7 +47,7 @@ async function searched(mode: 'vector' | 'keyword' | 'hybrid' | undefined, query source, topK: 5, index: { fingerprint: 'fp' }, - ...(mode === undefined ? {} : { retrieval: { mode } }), + ...(mode === undefined ? {} : { retrieval: { mode: mode as 'hybrid' } }), }); return { hits, embedder, rankings: store.rankings, statements: store.statements }; } @@ -96,6 +100,12 @@ describe('knowledge-pgvector retrieval modes', () => { expect(embedder.calls).toBe(0); }); + it('a mode it does not list is refused before anything is embedded or ranked', async () => { + const refused = await searchedRaw('rerank').catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("does not run the retrieval mode 'rerank'"); + }); + it('keyword with no term to match answers nothing and reads no passage', async () => { const { hits, rankings, embedder } = await searched('keyword', ' '); expect(hits).toEqual([]); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 6ff921d5aac..ef41a406c9d 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -638,8 +638,18 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (topK === 0) return []; // The legs the search's mode runs (ADR-0161, the dated note of 2026-11-30 - // under K8); the service hands only a mode this adapter lists. + // under K8); the service hands only a mode this adapter lists, and any + // other is refused, never run on a scale it was not built for. const mode = opts.retrieval?.mode ?? RETRIEVAL.default; + if (!(RETRIEVAL.modes as readonly string[]).includes(mode)) { + throw Object.assign( + new Error( + `knowledge-pgvector does not run the retrieval mode '${String(mode)}': it runs ` + + `${RETRIEVAL.modes.map((m) => `'${m}'`).join(', ')}.`, + ), + { code: 'VALIDATION_ERROR', status: 400 }, + ); + } // The query is embedded before a connection is taken — never under // `keyword`, which makes no query vector. let vector: number[] = [];