diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md new file mode 100644 index 00000000000..754d85822e2 --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -0,0 +1,20 @@ +--- +'@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 + +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 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. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 77aa903e07d..80c896266a8 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 @@ -483,7 +491,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 +534,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 @@ -1504,7 +1520,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/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 79bec21aedc..c3b14606ade 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 — 1749 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) | 18 | 106 | 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 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **224** | **1747** | 14 protocol modules | +| **Total** | **224** | **1749** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 106 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 108 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/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 49cc9210340..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 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`): 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/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/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index e588dc242ab..ec7dfb99aa9 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 @@ -3569,6 +3569,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 a0e5fd99336..259dfca9885 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 @@ -3569,6 +3569,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 d2d0406335a..7780031c80e 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 @@ -3569,6 +3569,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. 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)", + 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 b27c6e0ad76..f80ab0fe699 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 @@ -3569,6 +3569,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 06019c2ad67..8c220dac697 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 @@ -3569,6 +3569,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 1128e10a7fb..946b3a5a6cb 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 @@ -3569,6 +3569,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 63c00ed3945..4c871bccdf7 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 @@ -3569,6 +3569,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/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index c3f6e971bb4..6b94b1d16b8 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 @@ -1363,7 +1363,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // page layout switch) — one row label, authored in all three locales. // 870 since #36496: the object form's `actionLayout.selection` row // (the multi-select bar's order), authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(870); + // 872 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(872); } // ⭐ 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 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 753f8903ba3..c99ccbfb967 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 @@ -3569,6 +3569,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 42eed8d3467..ade11e38373 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 @@ -3569,6 +3569,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 0ff6fe813f2..0a51c8d7b32 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 @@ -3569,6 +3569,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 0437ffe7343..7027c4a2dc4 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 @@ -3569,6 +3569,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/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 9061a06536f..5ea16f03535 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 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 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() }); + 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..f4e41c3d050 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,19 @@ export interface KnowledgeAdapterContractOptions { * behaviour. Absent: `false`. */ keywordLeg?: boolean; + /** + * `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` + * 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. 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; }; } @@ -510,6 +529,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 +588,81 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + if (opts.implements.retrieval === true) { + 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; + 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; + 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); + // 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 () => { + 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/api-surface/ai.json b/packages/spec/api-surface/ai.json index 6b15b2d71e3..c9ffbb4d6d6 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 dc640e55c27..ab5bb1bb688 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 605aad14471..0d874a661cb 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 827a292ece0..610779dc917 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 98570dea054..56fd5331ef4 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/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index f796c040986..f50d75d32b5 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -121,6 +121,20 @@ } } }, + "retrieval": { + "status": "planned", + "verifiedAt": "2026-11-30", + "authorWarn": true, + "authorHint": "Keep it, but nothing reads it yet: until the knowledge service reads it, a source is searched in its store's default mode whatever it declares, and a mode the store does not run is not refused.", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it, and drop `authorWarn` / `authorHint` in that same edit (a warned `live` row reds this gate). Enters neither the index fingerprint nor the recipe hash.", + "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/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.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index d84610e3be3..75a86d7d7df 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. The knowledge service refuses a mode the store does not run when the source is saved.', + }, + ], + }, { 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..1be90217149 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 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', () => { + 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 unknown 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..8f61e67cdb2 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -128,6 +128,61 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( }, )); +/** + * The retrieval modes a knowledge source may declare (ADR-0161, the dated note + * 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 + * 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 by the knowledge service, 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 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 + * 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. 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'), + }, +)); + /** * `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 +504,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 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, + * 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 +649,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..b62c7af7d17 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,29 @@ 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 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). + * + * - `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. + * A source declaring a mode its adapter does not list is never searched + * 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. + */ + retrieval?: { mode: KnowledgeRetrievalMode }; /** Trace id for correlation. */ traceId?: string; } @@ -244,6 +267,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 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. + * + * 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 +353,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; diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 409dd11c7f3..e4148007f59 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'; // --------------------------------------------------------------------------- -// 881 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 882 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 @@ -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 @@ -1848,7 +1849,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 881 isomorphic pins', () => { + it('still declares all 882 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 @@ -2992,7 +2993,11 @@ describe('ADR-0122 type-alias convention', () => { // component takes, `PageComponentActionLocationSchema` (`ui/action.zod.ts`), // the shared location enum less `selection`, with no default or transform // (Iso_ui_action__PageComponentActionLocationSchema). +1 added. - expect(pins).toHaveLength(881); + // 881 -> 882 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(882); // 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