From 8a64f99ffd1d0056e85a3ea9fa233a8b4a12357c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 16:56:11 +0000 Subject: [PATCH 1/7] =?UTF-8?q?docs(adr):=20ADR-0161=20dated=20note=20?= =?UTF-8?q?=E2=80=94=20item=2017,=20the=20typed=20scope=20a=20search=20han?= =?UTF-8?q?ds=20its=20adapter=20(#37324)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A second dated note under the table of K8, and a second Amended bullet in the header list. The note records the maintainer's ruling on Q3 (ruling record 7168192820) and gives item 17 its final shape: the member is AdapterSearchOptions.scope, a list of terms the service builds from scope: [{ object, ids }] and the adapter applies before it ranks. No code, no schema, no changeset. The status line is left as it is. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude --- ...eturn-knowledge-source-is-a-governed-type.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) 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 971306f9089..eb7ab8d08ae 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 @@ -17,6 +17,7 @@ - **Leaves unchanged**: permission-aware retrieval (every object-source hit is re-read as the caller, and a source is searched for a caller only after the exposure and field-level admission of PR #36850); the reap guard of #4672 as landed; the signature and return type of `IKnowledgeService.search`; the settings shape of #33933 (knowledge settings only where the service is mounted), which #37102 keeps: without the capability token there is no knowledge service and no knowledge settings page; the open AI door, which stays MCP-only (cloud ADR-0119 D4). - **Inputs**: every code and docs text quoted below was read on `objectstack-ai/objectstack` `main` at `254e396a29`, the commit this record's branch starts from. Positions are in [Readings](#readings-taken-at-254e396a29). PR #36823 and PR #36850 are merged and are in that tree; PR #37075 is open and edits §6 of `content/docs/protocol/knowledge.mdx`, so the §6 quotations may move when it lands. - **Amended** (2026-11-25, [#37097](https://github.com/objectstack-ai/objectstack/issues/37097)): a dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item) records that the document hash of item 2 covers `organizationId` when the document has one (item 9), with no version bump. The status line above is left as it is. +- **Amended** (2026-11-25, [#37324](https://github.com/objectstack-ai/objectstack/issues/37324)): a second dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item) gives item 17 its final shape, `AdapterSearchOptions.scope?`: the typed scope the service builds from `scope: [{ object, ids }]`, on the maintainer's ruling of that day, 「也能指定上级对象(制度)」 (record `7168192820` on #37308). The status line above is left as it is. --- @@ -326,6 +327,22 @@ The epic holds the contract shut until this record merges ("No new adapter-contr > > Item 9's first reader, #37097, is built by PR #37256, and this change to item 2 lands with it. The reasoning is contract review [`7157191417`](https://github.com/objectstack-ai/objectstack/pull/37256#issuecomment-7157191417) on that PR (its M1 and S2). The table is left as written; read items 2 and 9 with this note. +> **Note (2026-11-25, [#37324](https://github.com/objectstack-ai/objectstack/issues/37324)) — item 17: the typed scope filter is `AdapterSearchOptions.scope?`, a list of terms the service builds from `scope: [{ object, ids }]` and the adapter applies before it ranks.** Item 17 is accepted with the shape below. Its open question was whether an entry may name a parent object. The maintainer ruled it on 2026-11-25 by choosing option B of the Q3 decision card, verbatim and untranslated: 「也能指定上级对象(制度)」 — 「直接给制度 id 就只在这份制度里搜;前提是知识源把指向制度的字段列为筛选字段,没列就返回空。1 个 PR,略大。」 (ruling record [`7168192820`](https://github.com/objectstack-ai/objectstack/issues/37308#issuecomment-7168192820) on #37308). So an entry names the object a source indexes, or a parent object the source reaches through a lookup field it lists in `metadataFields`, and a source that lists no such field answers nothing for the entry. A ◆ marks what this note decides past those words, for the approver to accept with it or strike. +> +> - **◆ The member.** `AdapterSearchOptions.scope?: AdapterScopeTerm[]`. A term is `{ kind: 'record', ids: string[] }`, which holds for a document whose `sourceRecordId` is in `ids`, or `{ kind: 'metadata', field: string, ids: string[] }`, which holds for a document whose `metadata[field]` is in `ids` or is a list with an element in `ids`. The adapter is handed terms it can apply, never `{ object, ids }`: turning an object into a field needs the object's definition, and reading that is the platform's (K1). +> - **◆ Absent, present, empty**, read as item 9's `organizationIds` is. Absent: no scope; every document of the source is ranked, as before the member. Present: only the documents some term holds for are ranked, and the filter runs BEFORE ranking, so `topK` is filled from in-scope documents alone. Empty: a list with no term ranks nothing, a term with no `ids` holds for no document, and neither is ever read as "no filter". `organizationIds`, `scope` and the opaque `filter` all apply: a document is ranked only when it passes each one that is present. +> - **How the service builds it**, per source, from `KnowledgeSearchOptions.scope?: Array<{ object: string; ids: string[] }>`. An entry that names the source's own object gives a `record` term. An entry that names another object gives a `metadata` term for the member of the source's `metadataFields` that points at that object, by the object's registered definition. A lookup is stored as a record id, and as a list of them under `multiple: true`, which is why a list is in scope when any element is. With no such member, or no registered definition, the entry does not reach the source. A source no entry reaches is not searched, and a `file` or `http` source answers nothing under a scope. +> - **◆ Four readings the ruling's words leave open.** (1) Several entries that reach one source give several terms, and a document is in scope when any term holds: a scope names a set of records. (2) An entry that names the source's own object is the `record` term and nothing else; a field of that object that points back at it (a `tree` field, a self-lookup) adds no term. (3) Only a `lookup` or a `master_detail` field is a parent link, and the object it points at is the spec's one answer, `packages/spec/src/data/field-value.zod.ts#referenceTargetOf`. A `user` field, whose target is fixed to `sys_user`, is not one: nothing scopes by user today, and it returns by a dated note with its reader. A field assembly withholds (credential-class, `internal`) is not one either: no document carries it. (4) A source that lists two or more such fields pointing at the entry's object is not reached by it, and the service logs that once per source, naming the fields. The other answers: a union of the fields, which answers "inside this policy" with clauses that only cite it through the other field; the first field listed, which gives the order of `metadataFields` a meaning no author wrote; and a key on the entry naming the field, which has no consumer and returns by a dated note with its reader. +> - **What a scope does not reach.** A parent two hops away (policy → chapter → clause) is not covered: only a field of the indexed object itself reaches a parent. A scope entry that reaches no searched source answers no hits, the same empty answer a caller gets when the source is withheld from them, so the answer never tells which of the two it was. +> - **◆ The service's guarantee, whatever the adapter does.** After the adapter answers, the service checks every hit against the terms and drops the ones none holds for. It judges a `record` term on `KnowledgeHit.sourceRecordId` and a `metadata` term on `KnowledgeHit.metadata[field]`, and drops a hit that does not carry the value (fail closed). So an adapter returns the document's metadata on its hits, as `knowledge-memory` does. No capability flag is added: `capabilities.chunks` stays the one flag, and the service learns from the answer. The first time an adapter returns a hit that check drops, the service logs once for that adapter: it does not apply `scope` before ranking, or it returns hits without the document's metadata, and its scoped searches may answer fewer than `topK` (rule 2: nothing is skipped silently). +> - **◆ Judged on the index copy; never an access decision.** The adapter and the service judge the same values, the ones assembly stored with the document, fresh as of the last sync, so an adapter that applies the member loses no hit to the service's check. A document indexed before its source listed the field is in no scope through it until a complete reindex writes it again. Scope narrows and never widens. The access decision stays the permission re-read of the live row, for every hit (`applyPermissionFilter` of `packages/services/service-knowledge/src/knowledge-service.ts#KnowledgeService`). +> - **No new permission question.** Source admission (`packages/services/service-knowledge/src/knowledge-source-admission.ts#admitSourceFields`) already requires every `metadataFields` member an index carries to be queryable by the caller before the source is searched for them; the system identity bypasses it, as it bypasses the re-read. So "that field in ids" is a filter the caller could run on the object's own rows. ◆ The parent row is never read and need not be readable by the caller. How many hits the scope or the permission filter removed is never returned to the caller (K9 rule 6, K10 rule 4); it goes to logs only. +> - **◆ The opaque `filter` stays as it is**, on `AdapterSearchOptions` and on `KnowledgeSearchOptions`: handed through, adapter-specific, and checked by nothing in the service after the adapter answers. The typed scope is never built from it, and the service's check judges the typed scope alone. Its readers in this tree are `knowledge-memory` (`matchesFilter`: metadata equality, before ranking) and `knowledge-ragflow`, which #37004 retires; no caller in this tree passes one, tests aside. Whether it retires is its own card, not this note's. +> - **The suite cases the member lands with** (rule 1; `packages/services/service-knowledge/src/testing.ts#runKnowledgeAdapterContract`). On the adapter, for each term kind: filtered before ranking, so `topK` is filled from in-scope documents; an empty list ranks nothing; without the member every document is ranked, as before. Through a real `KnowledgeService`, over an adapter that ignores the member: no out-of-scope hit is answered, and the service logs once. +> - **Not here.** `KnowledgeSearchOptions.scope` is an option of the service, not a member ("What counts as a member", below). #37308 bounds it, in entries and in ids per entry, with a coded refusal (ADR-0112) before any adapter is called, and states the bounds on the member so that an adapter can rely on them; this note fixes no number. The `scope` argument of `search_knowledge` is row 12, #37311 (K9 rule 2). Record-level return is #37103. +> +> This note adds exactly one member, `AdapterSearchOptions.scope` with its term type, and no other: the list stays closed beyond it (rules 3 and 5). #37308 builds it after this note merges, in one PR: the member, its first reader in `knowledge-memory`, and the suite cases. The code this note cites was read on `main` at `829a45e96c`. The table is left as written; read item 17 with this note. + **What "capabilities" became.** #36990's rule named "capabilities" among the members that waited for this record. Two things answer it. A method that is absent is the capability signal for listing, dropping, status, and the start and end of a build: the service asks whether the method is there. One flag covers what a method cannot say, `capabilities.chunks` (item 5). No wider descriptor is added. **What counts as a member** (for rule 5 below, and for the epic's "no new adapter-contract member"). A member is anything an adapter author must read to be correct: From 857a2e2024c14709e2da98fc910ef56168ca139f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:48:24 +0000 Subject: [PATCH 2/7] feat(service-knowledge): a knowledge search can be held to chosen records, or to the records under one parent ADR-0161 K8 item 17, as its dated note of 2026-11-25 shapes it. - spec: KnowledgeSearchOptions.scope [{ object, ids }] with its bounds; AdapterSearchOptions.scope and the AdapterScopeTerm type (record / metadata terms), the bounds and the service's check stated on the member. - service-knowledge: knowledge-search-scope.ts holds a scope to its bounds (VALIDATION_ERROR 400 before any adapter is called), builds each source's terms (own object -> record term; a parent -> the one listed lookup or master_detail field pointing at it, read through referenceTargetOf; user fields, withheld fields and two-or-more links reach nothing), and checks every hit after the adapter answers, fail closed, logging once per adapter. A source no entry reaches is not searched; an empty scope answers nothing. - knowledge-memory: applies the scope before ranking (first reader). - testing.ts: implements.scope; per-term-kind adapter cases and cases through a real KnowledgeService, one over the adapter with the member stripped. - docs: protocol "Record scope" section; RAG guide section. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude --- .changeset/37308-knowledge-search-scope.md | 23 ++ content/docs/ai/knowledge-rag.mdx | 15 ++ content/docs/protocol/knowledge.mdx | 63 ++++- .../src/__tests__/contract.test.ts | 2 +- .../plugins/knowledge-memory/src/index.ts | 34 ++- .../src/__tests__/contract-stubs.test.ts | 9 +- .../__tests__/knowledge-search-scope.test.ts | 229 +++++++++++++++++ .../src/__tests__/knowledge-service.test.ts | 177 +++++++++++++ .../src/knowledge-search-scope.ts | 193 ++++++++++++++ .../src/knowledge-service.ts | 107 +++++++- .../services/service-knowledge/src/testing.ts | 243 +++++++++++++++++- packages/spec/api-surface/contracts.json | 1 + packages/spec/export-origins/contracts.json | 1 + .../spec/src/contracts/knowledge-adapter.ts | 54 ++++ .../spec/src/contracts/knowledge-service.ts | 31 +++ 15 files changed, 1160 insertions(+), 22 deletions(-) create mode 100644 .changeset/37308-knowledge-search-scope.md create mode 100644 packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts create mode 100644 packages/services/service-knowledge/src/knowledge-search-scope.ts diff --git a/.changeset/37308-knowledge-search-scope.md b/.changeset/37308-knowledge-search-scope.md new file mode 100644 index 00000000000..a496b81cecd --- /dev/null +++ b/.changeset/37308-knowledge-search-scope.md @@ -0,0 +1,23 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-memory': patch +--- + +feat(service-knowledge): a knowledge search can be held to chosen records, or to the records under one parent, and the adapter filters before it ranks + +Clause-②: yes +Metadata-protocol: none + +A knowledge search can now look only inside chosen records, for example only inside one policy, and every one of the `topK` hits comes from inside that scope. A scope only narrows what is searched; each hit is still re-read as the caller, as before. + +New, both optional, in `@objectstack/spec` (types only, no metadata key): + +- `KnowledgeSearchOptions.scope?: Array<{ object: string; ids: string[] }>`. An entry naming the object a source indexes holds that source to those records. An entry naming another object reaches a source that lists, in its `metadataFields`, a `lookup` or `master_detail` field pointing at that object, and holds it to the documents whose stored value of that field is one of the ids. Entries are a union. A source no entry reaches is not searched, and a `file` / `http` source answers nothing under a scope. `scope: []`, or an entry with no ids, answers no hits; it never means "no scope". At most 10 entries, each with at most 500 ids, every `object` and id a non-empty string, no other key on an entry; past those bounds `search` refuses before any adapter is called, with an error carrying `code: 'VALIDATION_ERROR'` and `status: 400` and naming the bound. +- `AdapterSearchOptions.scope?: AdapterScopeTerm[]`, and the exported type `AdapterScopeTerm` (`{ kind: 'record', ids }` or `{ kind: 'metadata', field, ids }`). The knowledge service builds it per source from `KnowledgeSearchOptions.scope`; an adapter that reads it ranks only the documents some term holds for, filtering before it ranks, comparing values as strings (a list value matches when any element does). + +`KnowledgeService` checks every hit after the adapter answers and drops a hit no term holds for, including a hit that does not carry the value, so an adapter returns the document's `metadata` on its hits. An adapter that ignores the member keeps working: its scoped searches may answer fewer than `topK`, and the service logs that once per adapter at `warn`. A source that lists two or more lookups to the scoped object is not reached by that entry, logged once at `warn` naming the fields. A `user` field is not a parent link, and a parent two hops away is not reached. How many hits the scope removed is logged, never returned. + +`@objectstack/knowledge-memory` applies `scope` before ranking. `runKnowledgeAdapterContract` (from `@objectstack/service-knowledge/testing`) now requires `implements.scope`. It adds scope cases for the adapter alone, for each term kind, and cases through a real `KnowledgeService`, including one over the adapter with the member stripped. + +What to do: an adapter package reads `scope` in its search, returns each document's `metadata` on its hits, and passes `implements.scope` to the contract suite. A source that should be searchable inside one parent record lists the lookup to that parent in `metadataFields`; documents indexed before the lookup was listed are in no parent scope until a complete reindex writes them again. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 2edce821cd2..b4590e87740 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -79,6 +79,21 @@ Protocol, adapters, embedder, and `KnowledgeService.search` — is open, so you installed ([Connect an MCP Client](/docs/ai/connect-mcp)). +## Searching inside chosen records + +Pass `scope` to search only inside some records: the records an object source indexes, or a parent record that source reaches through a lookup it lists in `metadataFields`. + +```ts +// Only the clauses of one policy: the clause source lists its `policy` lookup in metadataFields. +const hits = await knowledge.search('notice period', { + topK: 5, + scope: [{ object: 'policy', ids: [policyId] }], + executionContext, +}); +``` + +The adapter filters before it ranks, so the `topK` hits all come from inside the scope, and the service drops any hit outside it whatever the adapter does. A source the scope does not reach is not searched, and `scope: []` answers nothing, never everything. A scope narrows what is searched; each hit is still re-checked against the caller, so it never shows a record the caller could not read. Bounds, the parent-link rules and what an adapter must do are in [the protocol's record scope](/docs/protocol/knowledge#record-scope). + ## What you get for free - **Permission-aware retrieval.** Every hit with a `sourceRecordId` is re-checked against the caller's `ExecutionContext` via `IDataEngine` — the same RLS that gates plain ObjectQL queries. A salesperson asking "find proposals about ACME" only sees the proposals they could already read directly. Before a source is searched, the caller's field-level read rules and the object's API exposure are asked too: a source serving a field the caller may not query is not searched for them (see [the protocol's source admission](/docs/protocol/knowledge#source-admission-exposure-and-field-level-rules)). File / HTTP hits pass through (ACL is the adapter's problem). diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 11764f95a80..ef72d1cc4e4 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -288,7 +288,9 @@ K8): an adapter that lacks one keeps working, and the service does what it did before that member existed. `AdapterSearchOptions.organizationIds` is the caller's organizations; an adapter that reads it ranks only those organizations' documents, filtering before it ranks — see -[Organization scope](#organization-scope). `listDocuments` lists the documents the +[Organization scope](#organization-scope). `AdapterSearchOptions.scope` holds a +search to chosen records the same way — see [Record scope](#record-scope). +`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 listing is complete. A document written while a listing runs may be missing @@ -303,7 +305,7 @@ import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/test runKnowledgeAdapterContract({ name: 'my-adapter', makeAdapter: () => new MyAdapter(/* a fresh, empty store */), - implements: { listDocuments: true, chunks: true, organizationIds: true }, + implements: { listDocuments: true, chunks: true, organizationIds: true, scope: true }, }); ``` @@ -481,6 +483,63 @@ them again. The organization is part of `docHash`, so the reindex does not skip them. Under `single` nothing changes: a document without an organization hashes as before, and the reindex skips it as before. +### Record scope + +A search can be held to chosen records (ADR-0161 K8, item 17): "only inside +this policy". `KnowledgeSearchOptions.scope` is a list of `{ object, ids }` +entries. + +```ts +const hits = await knowledge.search('notice period', { + topK: 5, + scope: [{ object: 'policy', ids: [policyId] }], + executionContext: ctx, +}); +``` + +- **The object a source indexes.** An entry naming it holds that source to + those records. +- **A parent object.** An entry naming another object reaches a source that + lists, in its `metadataFields`, a `lookup` or `master_detail` field pointing + at that object. The source is then held to the documents whose stored value + of that field is one of the ids (any one of them, for a lookup declared + `multiple`). A `user` field is not a parent link. A source that lists no such + field is not reached by the entry, and neither is one that lists two or more + of them (logged once at `warn`, naming the fields). A parent two hops away + (policy → chapter → clause) is not reached. +- **Several entries** are a union. A source no entry reaches is not searched, + and a `file` / `http` source answers nothing under a scope. +- **Empty.** `scope: []`, or an entry whose `ids` is empty, answers no hits; it + never means "no scope". Without `scope`, nothing changes. +- **Bounds.** At most 10 entries, each with at most 500 ids; `object` and every + id a non-empty string, and no other key on an entry. Past them the call is + refused before any adapter is asked, with `code: 'VALIDATION_ERROR'`, + `status: 400` and a message naming the bound. + +The service turns the entries into terms for each source and hands them to the +adapter as `AdapterSearchOptions.scope`: `{ kind: 'record', ids }`, judged on +the document's `sourceRecordId`, or `{ kind: 'metadata', field, ids }`, judged +on its stored `metadata[field]`, values compared as strings. An adapter that +reads the member filters before it ranks, so `topK` is filled from in-scope +documents; `organizationIds`, `scope` and the opaque `filter` all apply. +Whatever the adapter does, the service checks every hit after it answers and +drops a hit no term holds for, a hit without the value included, so an adapter +returns the document's `metadata` on its hits. An adapter written before the +member keeps working: out-of-scope documents then take ranking places, its +scoped searches may answer fewer than `topK`, and the service logs that once +for the adapter. The contract suite pins both halves: each term kind on the +adapter alone, and the service's check over the adapter with the member +stripped. + +The scope is judged on the index copy and only narrows. Every hit is still +re-read as the caller, so a caller who cannot read a scoped record gets +nothing from it. Source admission already requires each `metadataFields` +member to be queryable by the caller, and the parent record is never read. A +document indexed before its source listed the lookup is in no parent scope +until a complete reindex writes it again. How many hits the scope removed is +logged, never returned, and an entry that reaches no source answers the same +empty result a source withheld from the caller gives. + ### Source admission: exposure and field-level rules A passage is built at index time, under a system context, from every diff --git a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts index a1ec02fb4e6..e089094ab04 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts @@ -10,5 +10,5 @@ import { KnowledgeMemoryAdapter } from '../index'; runKnowledgeAdapterContract({ name: 'knowledge-memory', makeAdapter: () => new KnowledgeMemoryAdapter('under_test'), - implements: { listDocuments: true, chunks: true, organizationIds: true }, + implements: { listDocuments: true, chunks: true, organizationIds: true, scope: true }, }); diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 2b793119f28..382633d19e5 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -6,6 +6,7 @@ import type { AdapterContext, AdapterListDocumentsOptions, AdapterListDocumentsPage, + AdapterScopeTerm, AdapterSearchOptions, } from '@objectstack/spec/contracts'; import type { @@ -34,6 +35,15 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; * document-id order, the cursor being the last id of the page before. It runs * the contract suite of `@objectstack/service-knowledge/testing`. * + * The first reader of the record scope (ADR-0161 K8, item 17): when a search + * is handed `scope`, it ranks only the passages of documents some term holds + * for — a `record` term on the document's `sourceRecordId`, a `metadata` term + * on its stored `metadata[field]` (a list when any element is in `ids`), + * compared as strings — after the organization filter and before the scoring, + * so `topK` is filled from them alone. An empty list ranks nothing. Each hit + * carries its document's `metadata`, which the service's check after the + * answer reads. + * * The first reader of the organization filter (ADR-0161 K8, item 9): it * stores each document's `organizationId` as given and, when a search is * handed `organizationIds`, ranks only the documents whose organization is in @@ -96,10 +106,13 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { const inScope = organizations === undefined ? chunks : chunks.filter((c) => c.organizationId !== undefined && organizations.has(c.organizationId)); + // The record scope next (ADR-0161 K8, item 17): absent → every document; + // present → only the documents some term holds for; `[]` → nothing. + const scoped = opts.scope === undefined ? inScope : inScope.filter(inRecordScope(opts.scope)); const filter = opts.filter ?? {}; const filtered = Object.keys(filter).length - ? inScope.filter((c) => matchesFilter(c.metadata, filter)) - : inScope; + ? scoped.filter((c) => matchesFilter(c.metadata, filter)) + : scoped; const scored = filtered.map((c) => ({ chunk: c, @@ -203,6 +216,23 @@ function cosineSimilarity( return dot / (aNorm * bNorm); } +/** + * Whether a passage's document is in the record scope: some term holds, a + * `record` term on `sourceRecordId`, a `metadata` term on `metadata[field]`. + * A stored string or number matches when `String(value)` is one of the ids, a + * list when any element does; anything else, or no value, never. + */ +function inRecordScope(terms: readonly AdapterScopeTerm[]): (chunk: ChunkRecord) => boolean { + const compiled = terms.map((term) => ({ term, ids: new Set(term.ids) })); + const holds = (value: unknown, ids: ReadonlySet): boolean => + (typeof value === 'string' || typeof value === 'number') && ids.has(String(value)); + return (chunk) => + compiled.some(({ term, ids }) => { + const value = term.kind === 'record' ? chunk.sourceRecordId : chunk.metadata[term.field]; + return Array.isArray(value) ? value.some((element) => holds(element, ids)) : holds(value, ids); + }); +} + function matchesFilter( metadata: Record, filter: Record, diff --git a/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts index 18a37f87146..5583520534e 100644 --- a/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts +++ b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts @@ -11,7 +11,10 @@ * handed exactly as given, one hit per passage. * * Neither implements `listDocuments`, so the suite also runs its - * "without listDocuments" cases against them. + * "without listDocuments" cases against them. Neither applies + * `AdapterSearchOptions.scope` (ADR-0161 K8, item 17), and their hits carry no + * `metadata`: an adapter written before the member, over which the service's + * check after the answer still answers no out-of-scope hit. */ import type { AdapterContext, AdapterSearchOptions, IKnowledgeAdapter } from '@objectstack/spec/contracts'; @@ -95,11 +98,11 @@ class StubAdapter implements IKnowledgeAdapter { runKnowledgeAdapterContract({ name: 'whole-stub (no capabilities)', makeAdapter: () => new StubAdapter(false), - implements: { listDocuments: false, chunks: false, organizationIds: false }, + implements: { listDocuments: false, chunks: false, organizationIds: false, scope: false }, }); runKnowledgeAdapterContract({ name: 'chunk-stub (capabilities.chunks)', makeAdapter: () => new StubAdapter(true), - implements: { listDocuments: false, chunks: true, organizationIds: false }, + implements: { listDocuments: false, chunks: true, organizationIds: false, scope: false }, }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts new file mode 100644 index 00000000000..80bd1a34aa8 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts @@ -0,0 +1,229 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The record scope of a search (ADR-0161 K8, item 17, as its dated note of +// 2026-11-25 shapes it): the bounds a caller's scope is held to, the terms each +// source is handed, and the check every hit passes after the adapter answers. + +import { describe, expect, it } from 'vitest'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { + SEARCH_SCOPE_MAX_ENTRIES, + SEARCH_SCOPE_MAX_IDS, + readSearchScope, + scopeCheck, + scopeTermsFor, +} from '../knowledge-search-scope.js'; + +/** A thrown error's ADR-0112 code and status, and its message. */ +function refusalOf(fn: () => unknown): { code?: unknown; status?: unknown; message: string } { + try { + fn(); + } catch (err) { + const e = err as Error & { code?: unknown; status?: unknown }; + return { code: e.code, status: e.status, message: e.message }; + } + throw new Error('expected a refusal, got none'); +} + +const ids = (n: number): string[] => Array.from({ length: n }, (_, i) => `r${i}`); + +describe('readSearchScope — the bounds, before any adapter is called', () => { + it('the bounds are 10 entries and 500 ids per entry, as AdapterSearchOptions.scope states them', () => { + expect(SEARCH_SCOPE_MAX_ENTRIES).toBe(10); + expect(SEARCH_SCOPE_MAX_IDS).toBe(500); + }); + + it('absent is no scope; an empty list and an entry with no ids are kept, never read as "no scope"', () => { + expect(readSearchScope(undefined)).toBeUndefined(); + expect(readSearchScope([])).toEqual([]); + expect(readSearchScope([{ object: 'policy', ids: [] }])).toEqual([{ object: 'policy', ids: [] }]); + }); + + it('a scope at its bounds is accepted, as a copy', () => { + const input = Array.from({ length: 10 }, (_, i) => ({ object: `o${i}`, ids: ids(500) })); + const out = readSearchScope(input)!; + expect(out).toEqual(input); + expect(out[0].ids).not.toBe(input[0].ids); + }); + + it.each([ + ['not a list', { object: 'policy', ids: ['p1'] }, /takes a list of \{ object, ids \} entries/], + ['null', null, /takes a list/], + ['11 entries', Array.from({ length: 11 }, () => ({ object: 'policy', ids: ['p1'] })), /at most 10 entries, got 11/], + ['501 ids in one entry', [{ object: 'policy', ids: ids(501) }], /entry 0 takes at most 500 ids, got 501/], + ['an entry that is not an object', ['policy'], /entry 0 is not an object/], + ['an entry naming a field', [{ object: 'policy', ids: ['p1'], field: 'policy' }], /entry 0 has the key 'field'/], + ['no object', [{ ids: ['p1'] }], /entry 0 needs object/], + ['an empty object name', [{ object: '', ids: ['p1'] }], /entry 0 needs object/], + ['ids not a list', [{ object: 'policy', ids: 'p1' }], /entry 0 needs ids, a list/], + ['a numeric id', [{ object: 'policy', ids: [7] }], /entry 0 has an id that is not a non-empty string/], + ['an empty id', [{ object: 'policy', ids: [''] }], /entry 0 has an id that is not a non-empty string/], + ])('%s: a coded refusal naming the bound (VALIDATION_ERROR, 400)', (_label, scope, message) => { + const refusal = refusalOf(() => readSearchScope(scope)); + expect(refusal).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(refusal.message).toMatch(message); + }); +}); + +/** A clause source over `clause` that lists `fields` as metadata. */ +function clauseSource(fields: string[]): KnowledgeSource { + return { + id: 'clauses', + label: 'Clauses', + adapter: 'memory', + source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: fields } as ObjectKnowledgeSource, + } as KnowledgeSource; +} + +const CLAUSE_FIELDS = { + body: { type: 'textarea' }, + policy: { type: 'lookup', reference: 'policy' }, + chapter: { type: 'master_detail', reference: 'chapter' }, + owner: { type: 'user' }, + reviewer: { type: 'lookup', reference: 'sys_user' }, + parent_clause: { type: 'lookup', reference: 'clause' }, + supersedes: { type: 'tree', reference: 'clause' }, + audit_policy: { type: 'lookup', reference: 'policy', internal: true }, + status: { type: 'select' }, +}; +const schemaOf = (fields: Record = CLAUSE_FIELDS) => (object: string): unknown => + object === 'clause' ? { name: 'clause', fields } : undefined; + +describe('scopeTermsFor — the terms a source is handed', () => { + it("an entry naming the source's own object is a record term, and nothing else", () => { + const source = clauseSource(['parent_clause', 'supersedes', 'status']); + expect(scopeTermsFor(source, [{ object: 'clause', ids: ['c1', 'c2'] }], schemaOf())).toEqual({ + terms: [{ kind: 'record', ids: ['c1', 'c2'] }], + ambiguous: [], + }); + }); + + it('an entry naming a parent is a metadata term on the one listed lookup or master_detail field pointing at it', () => { + const source = clauseSource(['policy', 'chapter', 'status']); + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], schemaOf()).terms).toEqual([ + { kind: 'metadata', field: 'policy', ids: ['p1'] }, + ]); + expect(scopeTermsFor(source, [{ object: 'chapter', ids: ['ch1'] }], schemaOf()).terms).toEqual([ + { kind: 'metadata', field: 'chapter', ids: ['ch1'] }, + ]); + }); + + it('several entries are several terms, a union', () => { + const source = clauseSource(['policy']); + const scope = [ + { object: 'clause', ids: ['c1'] }, + { object: 'policy', ids: ['p1', 'p2'] }, + ]; + expect(scopeTermsFor(source, scope, schemaOf()).terms).toEqual([ + { kind: 'record', ids: ['c1'] }, + { kind: 'metadata', field: 'policy', ids: ['p1', 'p2'] }, + ]); + }); + + it('a field the source does not list reaches nothing', () => { + const source = clauseSource(['status']); + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], schemaOf())).toEqual({ terms: [], ambiguous: [] }); + }); + + it('a user field is not a parent link; a lookup to sys_user is', () => { + const owner = clauseSource(['owner']); + expect(scopeTermsFor(owner, [{ object: 'sys_user', ids: ['u1'] }], schemaOf()).terms).toEqual([]); + const reviewer = clauseSource(['reviewer']); + expect(scopeTermsFor(reviewer, [{ object: 'sys_user', ids: ['u1'] }], schemaOf()).terms).toEqual([ + { kind: 'metadata', field: 'reviewer', ids: ['u1'] }, + ]); + }); + + it('a field assembly withholds is not a parent link: no document carries it', () => { + const source = clauseSource(['audit_policy']); + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], schemaOf()).terms).toEqual([]); + }); + + it('two listed fields pointing at the entry\'s object: the entry does not reach the source, and both are named', () => { + const fields = { ...CLAUSE_FIELDS, cited_policy: { type: 'lookup', reference: 'policy' } }; + const source = clauseSource(['policy', 'cited_policy']); + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], schemaOf(fields))).toEqual({ + terms: [], + ambiguous: [{ object: 'policy', fields: ['policy', 'cited_policy'] }], + }); + }); + + it('no registered definition: a parent entry reaches nothing, an own-object entry still does', () => { + const source = clauseSource(['policy']); + const none = (): unknown => undefined; + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], none).terms).toEqual([]); + expect(scopeTermsFor(source, [{ object: 'clause', ids: ['c1'] }], none).terms).toEqual([{ kind: 'record', ids: ['c1'] }]); + }); + + it('a definition whose fields are a list is read as well', () => { + const source = clauseSource(['policy']); + const listed = (): unknown => ({ name: 'clause', fields: [{ name: 'policy', type: 'lookup', reference: 'policy' }] }); + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], listed).terms).toEqual([ + { kind: 'metadata', field: 'policy', ids: ['p1'] }, + ]); + }); + + it('a field whose target cannot be read is no link', () => { + const fields = { policy: { type: 'lookup', reference: { object: 'policy' } } }; + const source = clauseSource(['policy']); + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], schemaOf(fields)).terms).toEqual([]); + }); + + it('an entry with no ids gives no term', () => { + const source = clauseSource(['policy']); + expect(scopeTermsFor(source, [{ object: 'clause', ids: [] }, { object: 'policy', ids: [] }], schemaOf()).terms).toEqual([]); + }); + + it('a file or http source is handed no term: it answers nothing under a scope', () => { + const file = { id: 'handbook', label: 'Handbook', adapter: 'memory', source: { kind: 'file', paths: ['a.md'] } } as unknown as KnowledgeSource; + expect(scopeTermsFor(file, [{ object: 'clause', ids: ['c1'] }], schemaOf()).terms).toEqual([]); + }); +}); + +describe('scopeCheck — every hit, after the adapter answers', () => { + const hit = (sourceRecordId: string | undefined, metadata?: Record): KnowledgeHit => ({ + chunkId: 'x#0', documentId: 'x', sourceId: 'clauses', score: 1, snippet: '', + ...(sourceRecordId === undefined ? {} : { sourceRecordId }), + ...(metadata === undefined ? {} : { metadata }), + }); + + it("a record term holds on the hit's sourceRecordId", () => { + const check = scopeCheck([{ kind: 'record', ids: ['c1'] }]); + expect(check(hit('c1'))).toBe(true); + expect(check(hit('c2'))).toBe(false); + expect(check(hit(undefined))).toBe(false); + }); + + it("a metadata term holds on the hit's metadata[field] — a list when any element does", () => { + const check = scopeCheck([{ kind: 'metadata', field: 'policy', ids: ['p1'] }]); + expect(check(hit('c1', { policy: 'p1' }))).toBe(true); + expect(check(hit('c1', { policy: ['p3', 'p1'] }))).toBe(true); + expect(check(hit('c1', { policy: ['p3'] }))).toBe(false); + expect(check(hit('c1', { policy: 'p2' }))).toBe(false); + }); + + it('values are compared as strings: a number matches its id; an object, null or a boolean never does', () => { + expect(scopeCheck([{ kind: 'metadata', field: 'policy', ids: ['7'] }])(hit('c1', { policy: 7 }))).toBe(true); + const objectId = scopeCheck([{ kind: 'metadata', field: 'policy', ids: ['[object Object]', 'null', 'true'] }]); + expect(objectId(hit('c1', { policy: { id: 'p1' } }))).toBe(false); + expect(objectId(hit('c1', { policy: null }))).toBe(false); + expect(objectId(hit('c1', { policy: true }))).toBe(false); + }); + + it('a hit without the value is out of scope (fail closed)', () => { + const check = scopeCheck([{ kind: 'metadata', field: 'policy', ids: ['p1'] }]); + expect(check(hit('c1'))).toBe(false); + expect(check(hit('c1', {}))).toBe(false); + }); + + it('terms are a union; no term holds for nothing', () => { + const check = scopeCheck([ + { kind: 'record', ids: ['c9'] }, + { kind: 'metadata', field: 'policy', ids: ['p1'] }, + ]); + expect(check(hit('c9'))).toBe(true); + expect(check(hit('c1', { policy: 'p1' }))).toBe(true); + expect(check(hit('c1', { policy: 'p2' }))).toBe(false); + expect(scopeCheck([])(hit('c1', { policy: 'p1' }))).toBe(false); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 113ed2f93d3..08e5f197ee4 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1616,6 +1616,183 @@ describe('KnowledgeService — search refills after the permission filter', () = // ADR-0161 K5: the title a document carries is declared — the object's display // field (ADR-0079 `resolveDisplayField`), never a field that happens to be // named `title`. +describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { + const MEMBER = { userId: 'u1', positions: ['member'], permissions: [], isSystem: false }; + const SYSTEM = { positions: [], permissions: [], isSystem: true }; + type Term = { kind: 'record'; ids: string[] } | { kind: 'metadata'; field: string; ids: string[] }; + + /** + * Twenty records of `task`, three passages each, every passage best first. + * The passages of `rec_3` and `rec_7` score below every other record's; + * record `rec_i` belongs to policy `p${i % 4}` through the lookup `policy`. + */ + function corpus(sourceId: string): KnowledgeHit[] { + const hits: KnowledgeHit[] = []; + for (let i = 0; i < 20; i++) { + const low = i === 3 || i === 7; + for (let p = 0; p < 3; p++) { + hits.push({ + chunkId: `${sourceId}:rec_${i}#${p}`, documentId: `${sourceId}:rec_${i}`, sourceId, + sourceRecordId: `rec_${i}`, score: (low ? 0.4 : 0.9) - i / 1000 - p / 10000, snippet: `passage ${p} of ${i}`, + metadata: { status: 'open', policy: `p${i % 4}` }, + }); + } + } + return hits.sort((a, b) => b.score - a.score); + } + + /** Whether a term of `scope` holds for `hit` — the adapter's own reading, written apart from the service's. */ + const holds = (hit: KnowledgeHit, scope: Term[]): boolean => + scope.some((t) => (t.kind === 'record' ? t.ids.includes(String(hit.sourceRecordId)) : t.ids.includes(String(hit.metadata?.[t.field])))); + + /** An adapter that ranks `hits` of the source asked; `honours` applies the scope before ranking, else ignores it. */ + function adapterOver(hits: Record, honours: boolean) { + const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number; scope?: Term[] }) => { + const all = hits[opts.source.id] ?? []; + const ranked = honours && opts.scope !== undefined ? all.filter((h) => holds(h, opts.scope!)) : all; + return ranked.slice(0, opts.topK); + }); + return { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy }; + } + + /** An engine whose re-check as a non-system caller admits only `readable`, answering `schemas` from `getSchema`. */ + function engineOver(readable: (id: string) => boolean, schemas: Record = {}) { + const find = vi.fn(async (_obj: string, q: { where?: { id?: { $in?: string[] } }; context?: { isSystem?: boolean } }) => + (q.where?.id?.$in ?? []).filter((id) => q.context?.isSystem || readable(id)).map((id) => ({ id }))); + return { find, getSchema: (name: string) => schemas[name] } as unknown as IDataEngine & { find: typeof find }; + } + + const TASK_SCHEMA = { + name: 'task', + fields: { + title: { type: 'text' }, notes: { type: 'textarea' }, status: { type: 'select' }, + policy: { type: 'lookup', reference: 'policy' }, + cited_policy: { type: 'lookup', reference: 'policy' }, + }, + }; + + function taskSource(id: string, metadataFields: string[] = ['status', 'policy'], object = 'task'): KnowledgeSource { + return { + id, label: id, adapter: 'memory', + source: { kind: 'object', object, contentFields: ['title', 'notes'], metadataFields } as ObjectKnowledgeSource, + }; + } + + function setup(opts: { + honours?: boolean; + readable?: (id: string) => boolean; + sources?: KnowledgeSource[]; + /** More hits of the first source, ranked with its corpus. */ + extra?: KnowledgeHit[]; + } = {}) { + const sources = opts.sources ?? [taskSource('s1')]; + const hits = Object.fromEntries(sources.map((s, i) => [ + s.id, + [...corpus(s.id), ...(i === 0 ? opts.extra ?? [] : [])].sort((a, b) => b.score - a.score), + ])); + const adapter = adapterOver(hits, opts.honours ?? true); + const engine = engineOver(opts.readable ?? (() => true), { task: TASK_SCHEMA }); + const warn = vi.fn(); + const svc = new KnowledgeService({ dataEngine: engine, logger: { warn, debug: vi.fn(), error: vi.fn() } }); + svc.registerAdapter('memory', adapter); + for (const s of sources) svc.registerSource(s); + const handed = () => adapter.searchSpy.mock.calls.map((c) => (c[1] as { scope?: Term[] }).scope); + return { svc, adapter, engine, warn, handed }; + } + + const records = (hits: KnowledgeHit[]) => [...new Set(hits.map((h) => h.sourceRecordId))].sort(); + + it('20 records, two of them in scope, topK 5: every hit is one of the two, and the page is full', async () => { + const { svc, handed } = setup(); + const out = await svc.search('q', { topK: 5, scope: [{ object: 'task', ids: ['rec_3', 'rec_7'] }], executionContext: MEMBER }); + expect(out).toHaveLength(5); + expect(records(out)).toEqual(['rec_3', 'rec_7']); + expect(handed()).toEqual([[{ kind: 'record', ids: ['rec_3', 'rec_7'] }]]); + }); + + it('an adapter that ignores the scope: no out-of-scope hit is answered, and the service logs once for the adapter', async () => { + const { svc, warn } = setup({ honours: false }); + const scope = [{ object: 'task', ids: ['rec_3', 'rec_7'] }]; + // A person: the refill after the permission filter reaches past the out-of-scope ranks. + const asMember = await svc.search('q', { topK: 5, scope, executionContext: MEMBER }); + expect(records(asMember)).toEqual(['rec_3', 'rec_7']); + // The system identity gets one round: the out-of-scope ranks are emptied, never answered. + const asSystem = await svc.search('q', { topK: 5, scope, executionContext: SYSTEM }); + expect(asSystem).toEqual([]); + const reports = warn.mock.calls.map(([m]) => String(m)).filter((m) => m.includes("outside the search's scope")); + expect(reports).toHaveLength(1); + expect(reports[0]).toContain("adapter 'memory'"); + }); + + it('ids are compared as strings: a lookup value stored as the number 7 is in scope for the id "7"', async () => { + const numeric: KnowledgeHit = { + chunkId: 's1:rec_n#0', documentId: 's1:rec_n', sourceId: 's1', sourceRecordId: 'rec_n', score: 0.1, snippet: '', + metadata: { status: 'open', policy: 7 }, + }; + const { svc } = setup({ extra: [numeric] }); + const out = await svc.search('q', { topK: 5, scope: [{ object: 'policy', ids: ['7'] }], executionContext: MEMBER }); + expect(out.map((h) => h.chunkId)).toEqual(['s1:rec_n#0']); + }); + + it('a parent scope: the adapter is handed a metadata term on the listed lookup, and only that parent\'s records answer', async () => { + const { svc, handed } = setup(); + const out = await svc.search('q', { topK: 5, scope: [{ object: 'policy', ids: ['p1'] }], executionContext: MEMBER }); + expect(handed()).toEqual([[{ kind: 'metadata', field: 'policy', ids: ['p1'] }]]); + expect(out).toHaveLength(5); + for (const hit of out) expect(hit.metadata?.policy).toBe('p1'); + }); + + it('an object no searched source reaches: no adapter is asked, and the answer is empty', async () => { + const { svc, adapter } = setup(); + expect(await svc.search('q', { topK: 5, scope: [{ object: 'invoice', ids: ['i1'] }], executionContext: MEMBER })).toEqual([]); + expect(adapter.searchSpy).not.toHaveBeenCalled(); + }); + + it('an empty scope, and an entry with no ids, answer nothing — never read as "no scope"', async () => { + const { svc, adapter } = setup(); + expect(await svc.search('q', { topK: 5, scope: [], executionContext: MEMBER })).toEqual([]); + expect(await svc.search('q', { topK: 5, scope: [{ object: 'task', ids: [] }], executionContext: MEMBER })).toEqual([]); + expect(adapter.searchSpy).not.toHaveBeenCalled(); + }); + + it('a source the scope reaches is searched; one it does not reach is not', async () => { + const { svc, adapter } = setup({ sources: [taskSource('s1'), taskSource('s2', ['status'], 'note')] }); + const out = await svc.search('q', { topK: 5, scope: [{ object: 'policy', ids: ['p1'] }], executionContext: MEMBER }); + expect(adapter.searchSpy.mock.calls.map((c) => (c[1] as { source: KnowledgeSource }).source.id)).toEqual(['s1']); + expect(new Set(out.map((h) => h.sourceId))).toEqual(new Set(['s1'])); + }); + + it('a source listing two lookups to the scoped object is not searched, reported once naming both fields', async () => { + const { svc, adapter, warn } = setup({ sources: [taskSource('s1', ['status', 'policy', 'cited_policy'])] }); + for (let i = 0; i < 2; i++) { + expect(await svc.search('q', { topK: 5, scope: [{ object: 'policy', ids: ['p1'] }], executionContext: MEMBER })).toEqual([]); + } + expect(adapter.searchSpy).not.toHaveBeenCalled(); + const reports = warn.mock.calls.map(([m]) => String(m)).filter((m) => m.includes("fields pointing at 'policy'")); + expect(reports).toHaveLength(1); + expect(reports[0]).toContain('policy, cited_policy'); + }); + + it('a caller who cannot read one of the scoped records gets no hit from it', async () => { + const { svc } = setup({ readable: (id) => id !== 'rec_3' }); + const out = await svc.search('q', { topK: 5, scope: [{ object: 'task', ids: ['rec_3', 'rec_7'] }], executionContext: MEMBER }); + expect(out.length).toBeGreaterThan(0); + expect(records(out)).toEqual(['rec_7']); + }); + + it.each([ + ['11 entries', Array.from({ length: 11 }, () => ({ object: 'task', ids: ['rec_1'] })), /at most 10 entries/], + ['501 ids', [{ object: 'task', ids: Array.from({ length: 501 }, (_, i) => `rec_${i}`) }], /at most 500 ids/], + ])('bounds exceeded (%s): a coded refusal naming the bound, before any adapter or engine is asked', async (_label, scope, message) => { + const { svc, adapter, engine } = setup(); + const refused = svc.search('q', { topK: 5, scope, executionContext: MEMBER }); + await expect(refused).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + await expect(refused).rejects.toThrow(message); + expect(adapter.searchSpy).not.toHaveBeenCalled(); + expect(engine.find).not.toHaveBeenCalled(); + }); +}); + describe('recordToDocument reads the title from the object\'s display field', () => { const src: KnowledgeSource = { id: 's1', label: 's1', adapter: 'memory', diff --git a/packages/services/service-knowledge/src/knowledge-search-scope.ts b/packages/services/service-knowledge/src/knowledge-search-scope.ts new file mode 100644 index 00000000000..ace9fe65043 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-search-scope.ts @@ -0,0 +1,193 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K8, item 17, as its dated note of 2026-11-25 shapes it] The record + * scope of a search: the bounds a caller's `KnowledgeSearchOptions.scope` is + * held to, the terms the service builds from it for each source + * (`AdapterSearchOptions.scope`), and the check every hit passes after the + * adapter answers. + * + * An entry `{ object, ids }` becomes, for one source: + * + * - a `record` term, when `object` is the object the source indexes; + * - a `metadata` term on the ONE field of the source's `metadataFields` that is + * a parent link to `object` — a `lookup` or `master_detail` field whose + * target (`referenceTargetOf`, the spec's one answer) is `object`, and that + * assembly does not withhold (credential-class, `internal`); + * - nothing otherwise: no such field, no registered definition, or two or more + * such fields (reading (4) of the note: the entry does not reach the source). + * + * A `user` field is not a parent link (reading (3)), and neither is a field of + * the indexed object that points back at it: an entry naming the source's own + * object is the `record` term and nothing else (reading (2)). + * + * The scope is judged on the index copy — the values assembly stored with the + * document — and never decides access: the permission re-read of every hit + * stays the access decision. Source admission already holds every + * `metadataFields` member to be queryable by the caller, so a `metadata` term + * is a filter the caller could run on the object's own rows; the parent row is + * never read. + */ + +import type { AdapterScopeTerm, KnowledgeSearchOptions } from '@objectstack/spec/contracts'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { referenceTargetOf } from '@objectstack/spec/data'; +import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields } from '@objectstack/core'; +import { declaredFields } from './knowledge-source-admission.js'; + +/** One entry of `KnowledgeSearchOptions.scope`. */ +export type SearchScopeEntry = NonNullable[number]; + +/** Most entries a search scope may hold (stated on `AdapterSearchOptions.scope`). */ +export const SEARCH_SCOPE_MAX_ENTRIES = 10; +/** Most ids one scope entry may hold (stated on `AdapterSearchOptions.scope`). */ +export const SEARCH_SCOPE_MAX_IDS = 500; + +/** The field types that link a record to a parent record (reading (3)): never `user`, never `tree`. */ +const PARENT_LINK_TYPES: ReadonlySet = new Set(['lookup', 'master_detail']); + +const ENTRY_KEYS: ReadonlySet = new Set(['object', 'ids']); + +/** An ADR-0112 coded refusal of a scope past its bounds. */ +function scopeRefusal(message: string): Error { + return Object.assign(new Error(`[knowledge] search scope: ${message}`), { + code: 'VALIDATION_ERROR' as const, + status: 400 as const, + }); +} + +/** + * The caller's `scope`, held to its bounds: `undefined` for no scope, else the + * entries as given (an empty list, or an entry with no ids, is kept — it is + * answered with no hits, never read as "no scope"). Throws a coded refusal + * (`VALIDATION_ERROR`, 400) naming the first thing that is wrong: anything but + * a list, more than {@link SEARCH_SCOPE_MAX_ENTRIES} entries, an entry that is + * not `{ object, ids }`, an `object` or id that is not a non-empty string, or + * more than {@link SEARCH_SCOPE_MAX_IDS} ids in one entry. + */ +export function readSearchScope(scope: unknown): SearchScopeEntry[] | undefined { + if (scope === undefined) return undefined; + if (!Array.isArray(scope)) throw scopeRefusal('takes a list of { object, ids } entries.'); + if (scope.length > SEARCH_SCOPE_MAX_ENTRIES) { + throw scopeRefusal(`takes at most ${SEARCH_SCOPE_MAX_ENTRIES} entries, got ${scope.length}.`); + } + return scope.map((entry: unknown, i): SearchScopeEntry => { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { + throw scopeRefusal(`entry ${i} is not an object; each entry is { object, ids }.`); + } + const unknownKey = Object.keys(entry).find((key) => !ENTRY_KEYS.has(key)); + if (unknownKey !== undefined) { + throw scopeRefusal(`entry ${i} has the key '${unknownKey}'; an entry takes only object and ids.`); + } + const { object, ids } = entry as { object?: unknown; ids?: unknown }; + if (typeof object !== 'string' || object.length === 0) { + throw scopeRefusal(`entry ${i} needs object, a non-empty string naming an object.`); + } + if (!Array.isArray(ids)) throw scopeRefusal(`entry ${i} needs ids, a list of record ids.`); + if (ids.length > SEARCH_SCOPE_MAX_IDS) { + throw scopeRefusal(`entry ${i} takes at most ${SEARCH_SCOPE_MAX_IDS} ids, got ${ids.length}.`); + } + if (!ids.every((id) => typeof id === 'string' && id.length > 0)) { + throw scopeRefusal(`entry ${i} has an id that is not a non-empty string.`); + } + return { object, ids: [...(ids as string[])] }; + }); +} + +/** What {@link scopeTermsFor} answers for one source. */ +export interface SourceScope { + /** The terms the source's search is handed; empty when no entry reaches it (not searched). */ + terms: AdapterScopeTerm[]; + /** Entries a source does not reach because it lists two or more parent links to their object (reading (4)). */ + ambiguous: Array<{ object: string; fields: string[] }>; +} + +/** + * The terms `scope` gives one source. `schemaOf` answers an object's + * registered definition (`undefined` when none is registered). An entry with + * no ids gives no term: it holds for no document. + */ +export function scopeTermsFor( + source: KnowledgeSource, + scope: readonly SearchScopeEntry[], + schemaOf: (object: string) => unknown, +): SourceScope { + const out: SourceScope = { terms: [], ambiguous: [] }; + if (source.source.kind !== 'object') return out; + const objSource = source.source as ObjectKnowledgeSource; + let links: Map | undefined; + for (const entry of scope) { + if (entry.ids.length === 0) continue; + if (entry.object === objSource.object) { + out.terms.push({ kind: 'record', ids: [...entry.ids] }); + continue; + } + links ??= parentLinksOf(objSource, schemaOf(objSource.object)); + const fields = links.get(entry.object) ?? []; + if (fields.length === 1) out.terms.push({ kind: 'metadata', field: fields[0], ids: [...entry.ids] }); + else if (fields.length > 1) out.ambiguous.push({ object: entry.object, fields: [...fields] }); + } + return out; +} + +/** + * The parent links a source carries: each `metadataFields` member that is a + * `lookup` / `master_detail` field of the indexed object, not withheld by + * assembly, by the object it points at. Empty without a registered definition. + * A field whose target cannot be read is no link. + */ +function parentLinksOf(objSource: ObjectKnowledgeSource, schema: unknown): Map { + const links = new Map(); + const declared = declaredFields(schema); + if (declared === undefined) return links; + const defs = new Map(declared); + const withheld = new Set([ + ...collectCredentialWriteResponseFields(schema), + ...collectInternalWriteResponseFields(schema), + ]); + for (const field of new Set(objSource.metadataFields ?? [])) { + if (withheld.has(field)) continue; + const def = defs.get(field); + const type = (def as { type?: unknown } | null | undefined)?.type; + if (typeof type !== 'string' || !PARENT_LINK_TYPES.has(type)) continue; + let target: string | undefined; + try { + target = referenceTargetOf(def); + } catch { + target = undefined; + } + if (target === undefined || target === objSource.object) continue; + const fields = links.get(target); + if (fields) fields.push(field); + else links.set(target, [field]); + } + return links; +} + +/** + * The check every hit passes after its adapter answers, whatever the adapter + * did: `true` when some term holds for the hit, judged on the hit's + * `sourceRecordId` (a `record` term) or `metadata[field]` (a `metadata` term). + * A hit that does not carry the value is out of scope (fail closed). + */ +export function scopeCheck(terms: readonly AdapterScopeTerm[]): (hit: KnowledgeHit) => boolean { + const compiled = terms.map((term) => ({ term, ids: new Set(term.ids) })); + return (hit) => + compiled.some(({ term, ids }) => + valueInIds(term.kind === 'record' ? hit.sourceRecordId : hit.metadata?.[term.field], ids), + ); +} + +/** + * A stored value against a term's ids, compared as strings: a string or a + * number matches when `String(value)` is one of them, a list when any element + * does (a `multiple: true` lookup), anything else never. + */ +function valueInIds(value: unknown, ids: ReadonlySet): boolean { + if (Array.isArray(value)) return value.some((element) => scalarInIds(element, ids)); + return scalarInIds(value, ids); +} + +function scalarInIds(value: unknown, ids: ReadonlySet): boolean { + return (typeof value === 'string' || typeof value === 'number') && ids.has(String(value)); +} diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 5047b3dbf59..4a0513f6f95 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'; import type { + AdapterScopeTerm, IDataEngine, IKnowledgeAdapter, IKnowledgeService, @@ -37,6 +38,7 @@ import { type KnowledgeSourceAdmission, type ObjectAdmission, } from './knowledge-source-admission.js'; +import { readSearchScope, scopeCheck, scopeTermsFor, type SearchScopeEntry } from './knowledge-search-scope.js'; /** * Minimal logger shape; falls back to no-op when none is provided. @@ -122,6 +124,10 @@ export class KnowledgeService implements IKnowledgeService { private readonly adapters = new Map(); private readonly sources = new Map(); private readonly defaultTopK: number; + /** Adapters whose answer the scope check has already dropped a hit from — reported once each ({@link searchRound}). */ + private readonly scopeIgnoredReported = new Set(); + /** `${source id}\u0000${object}` pairs a scope entry did not reach for two or more parent links — reported once each. */ + private readonly scopeAmbiguousReported = new Set(); /** * The tail of each document's record-sync chain, keyed by document id * (`${source.id}:${recordId}`) — see {@link serializeRecordSync}. A key @@ -655,6 +661,18 @@ export class KnowledgeService implements IKnowledgeService { * hit as the caller ({@link applyPermissionFilter}), and answer the best * `topK` hits by score. * + * ## The record scope (`scope`, ADR-0161 K8, item 17) + * + * A scope is held to its bounds before anything else is done + * ({@link readSearchScope}: a coded refusal past them), then turned into the + * terms of each admitted source ({@link sourcesInScope}). A source no entry + * reaches is not searched, so an empty scope answers no hits and asks no + * adapter. Each searched adapter is handed its source's terms, and every hit + * it answers is checked against them, whatever the adapter did + * ({@link searchRound}). The refill below counts the hits that passed both + * that check and the re-check; whether a source may hold more is still judged + * on how many hits its adapter answered. + * * ## The refill after the permission filter * * The re-check runs AFTER ranking, so a caller who may read few of the @@ -683,9 +701,11 @@ export class KnowledgeService implements IKnowledgeService { * never returned: the count is an oracle on rows the caller may not read. */ async search(query: string, opts: KnowledgeSearchOptions = {}): Promise { + const scope = readSearchScope(opts.scope); const topK = opts.topK ?? this.defaultTopK; const ctx = opts.executionContext; - const sources = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); + let sources = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); + if (scope !== undefined) sources = this.sourcesInScope(sources, scope); if (sources.length === 0) return []; const filtered = ctx !== undefined && ctx.isSystem !== true && this.options.dataEngine !== undefined; @@ -727,18 +747,27 @@ export class KnowledgeService implements IKnowledgeService { /** * One round of {@link search}: ask each source's adapter for `ask(source)` * hits. Answers, per source that answered, the hits it serves and how many - * the adapter returned (`answered`, before a hit naming another source is - * dropped — what decides whether the adapter may hold more). A source whose - * adapter is unknown or throws is absent from the answer, logged. + * the adapter returned (`answered`, before a hit naming another source or + * outside the scope is dropped — what decides whether the adapter may hold + * more). A source whose adapter is unknown or throws is absent from the + * answer, logged. + * + * Under a scope, the adapter is handed the source's terms, and every hit it + * answers is checked against them ({@link scopeCheck}, fail closed). The first + * time the check drops a hit of an adapter, that is reported once for the + * adapter, at `warn`: it does not apply the scope before ranking, or answers + * hits without the document's metadata, so its scoped searches may answer + * fewer than `topK` (ADR-0161 K8, rule 2). How many hits were dropped is + * logged, never returned. */ private async searchRound( query: string, - sources: Array<{ source: KnowledgeSource; organizationIds?: string[] }>, + sources: Array<{ source: KnowledgeSource; organizationIds?: string[]; scope?: AdapterScopeTerm[] }>, ask: (source: KnowledgeSource) => number, filter: Record | undefined, ): Promise> { const out = new Map(); - for (const { source, organizationIds } of sources) { + for (const { source, organizationIds, scope } of sources) { const adapter = this.adapters.get(source.adapter); if (!adapter) { this.options.logger?.warn?.( @@ -752,6 +781,7 @@ export class KnowledgeService implements IKnowledgeService { topK: ask(source), filter, ...(organizationIds === undefined ? {} : { organizationIds }), + ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store @@ -766,7 +796,10 @@ export class KnowledgeService implements IKnowledgeService { 'another source; dropped — a hit is served only as the source it was searched for.', ); } - out.set(source.id, { hits: served, answered: hits.length }); + out.set(source.id, { + hits: scope === undefined ? served : this.checkScope(served, scope, source), + answered: hits.length, + }); } catch (err) { this.options.logger?.error?.( `[knowledge] adapter '${source.adapter}' search failed for source '${source.id}': ${(err as Error).message}`, @@ -776,6 +809,66 @@ export class KnowledgeService implements IKnowledgeService { return out; } + /** + * [ADR-0161 K8, item 17] Pair each admitted source with the terms `scope` + * gives it ({@link scopeTermsFor}): a `record` term for an entry naming the + * object the source indexes, a `metadata` term for an entry naming a parent + * object the source reaches through the one parent link it lists in + * `metadataFields`, read from the object's registered definition. A source + * no entry reaches — every `file` / `http` source among them — is not + * searched, logged at `debug`. A source that lists two or more parent links + * to an entry's object is not reached by that entry, reported once per + * source and object at `warn`, naming the fields. + */ + private sourcesInScope( + sources: T[], + scope: readonly SearchScopeEntry[], + ): Array { + const out: Array = []; + for (const entry of sources) { + const { terms, ambiguous } = scopeTermsFor(entry.source, scope, (object) => this.schemaFor(object)); + for (const { object, fields } of ambiguous) { + const key = `${entry.source.id}\u0000${object}`; + if (this.scopeAmbiguousReported.has(key)) continue; + this.scopeAmbiguousReported.add(key); + this.options.logger?.warn?.( + `[knowledge] source '${entry.source.id}' lists ${fields.length} fields pointing at '${object}' ` + + `(${fields.join(', ')}); a search scoped to '${object}' records does not reach it — ` + + 'it is not told which field the scope means.', + ); + } + if (terms.length === 0) { + this.options.logger?.debug?.( + `[knowledge] source '${entry.source.id}' not searched: no entry of the search's scope reaches it.`, + ); + continue; + } + out.push({ ...entry, scope: terms }); + } + return out; + } + + /** + * The hits of `source` that some scope term holds for ({@link scopeCheck}); + * the rest are dropped, and the first time an adapter's answer loses a hit + * here it is reported once, at `warn` ({@link searchRound}). + */ + private checkScope(hits: KnowledgeHit[], terms: readonly AdapterScopeTerm[], source: KnowledgeSource): KnowledgeHit[] { + const inScope = scopeCheck(terms); + const kept = hits.filter(inScope); + const dropped = hits.length - kept.length; + if (dropped > 0 && !this.scopeIgnoredReported.has(source.adapter)) { + this.scopeIgnoredReported.add(source.adapter); + this.options.logger?.warn?.( + `[knowledge] adapter '${source.adapter}' answered ${dropped} hit(s) for source '${source.id}' outside the ` + + "search's scope; dropped. The adapter does not apply AdapterSearchOptions.scope before ranking, or answers " + + "hits without the document's metadata, so its scoped searches may answer fewer than topK. " + + 'Reported once for this adapter.', + ); + } + return kept; + } + // ── Sync entrypoints (called by the host plugin's event bridge) ─── /** diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 2580d99a3b0..6f365e0d2eb 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -32,17 +32,31 @@ * Every optional member is DECLARED by the caller in `implements`, and the * suite asserts the declaration against the adapter: a member an adapter lacks * runs the case that pins the service's behaviour without it, never nothing. - * `organizationIds` is a search option, not a method, so its declaration is - * asserted by behaviour: the cases it turns on fail for an adapter that - * ignores the option. + * `organizationIds` and `scope` are search options, not methods, so their + * declarations are asserted by behaviour: the cases they turn on fail for an + * adapter that ignores the option. + * + * The record scope (ADR-0161 K8, item 17) is covered on the adapter alone, + * for each term kind — filtered before ranking, so `topK` is filled from + * in-scope documents; an empty list ranks nothing; without the member every + * document is ranked — and through a real `KnowledgeService`, by the record a + * source indexes and by a parent object reached through a listed lookup, and + * over the adapter with the member stripped from its search: no out-of-scope + * hit is answered, and the service logs once. */ -import { describe, expect, it } from 'vitest'; -import type { IDataEngine, IKnowledgeAdapter, AdapterContext, AdapterSearchOptions } from '@objectstack/spec/contracts'; +import { describe, expect, it, vi } from 'vitest'; +import type { + IDataEngine, + IKnowledgeAdapter, + AdapterContext, + AdapterScopeTerm, + AdapterSearchOptions, +} from '@objectstack/spec/contracts'; import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; -import { KnowledgeService } from './knowledge-service.js'; +import { KnowledgeService, type KnowledgeLogger } from './knowledge-service.js'; import { resolveSplit, splitDocument } from './split/index.js'; /** Input of {@link runKnowledgeAdapterContract}. */ @@ -66,6 +80,12 @@ export interface KnowledgeAdapterContractOptions { * it is handed, filtering before it ranks. */ organizationIds: boolean; + /** + * The adapter's search honours `AdapterSearchOptions.scope` (ADR-0161 K8, + * item 17): it ranks only the documents some term holds for, filtering + * before it ranks, and returns each document's `metadata` on its hits. + */ + scope: boolean; }; } @@ -202,6 +222,12 @@ interface ServiceSetup { * (`embedding.maxInputTokens`); omitted, the adapter's own report is used. */ maxInputTokens?: number; + /** Registered object definitions the engine double answers from `getSchema`, by object name; absent → none. */ + schemas?: Record; + /** Strips `scope` from every search the service hands the adapter: an adapter that ignores the member. */ + stripScope?: boolean; + /** The service's logger; absent → none. */ + logger?: KnowledgeLogger; } /** @@ -237,6 +263,10 @@ async function serviceOver( }, search: (query, searchOpts) => { searched.push(searchOpts); + if (setup.stripScope === true) { + const { scope: _ignored, ...rest } = searchOpts; + return adapter.search(query, rest); + } return adapter.search(query, searchOpts); }, delete: (ids, ctx) => adapter.delete(ids, ctx), @@ -245,9 +275,12 @@ async function serviceOver( : {}), }; const posture = setup.posture; + const engine = rowsEngine(rows, setup.wall); + const schemas = setup.schemas; const svc = new KnowledgeService({ - dataEngine: rowsEngine(rows, setup.wall), + dataEngine: schemas === undefined ? engine : Object.assign(engine, { getSchema: (name: string) => schemas[name] }), ...(posture === undefined ? {} : { resolveTenancyPosture: async () => posture() }), + ...(setup.logger === undefined ? {} : { logger: setup.logger }), }); svc.registerAdapter('under_test', counting); svc.registerSource(source); @@ -287,6 +320,39 @@ function wallOf(posture: TenancyPosture): (row: Row, context: ExecutionContext) return () => true; } +/** + * Twenty clauses of four policies (ADR-0161 K8, item 17): clause `cNN` belongs + * to policy `p${NN % 4}` through the lookup `policy`. The clauses `c03` and + * `c07` hold the query once in each of three paragraphs among other words; + * every other clause is the query alone, so each of those outranks them. + */ +const clauseRows = (): Row[] => + Array.from({ length: 20 }, (_, i) => ({ + id: `c${String(i).padStart(2, '0')}`, + body: + i === 3 || i === 7 + ? 'Harbour crane north quay shift.\n\nHarbour crane south berth shift.\n\nHarbour crane night watch shift.' + : 'Harbour crane.\n\nHarbour crane.\n\nHarbour crane.', + status: 'published', + policy: `p${i % 4}`, + })); +const SCOPE_QUERY = 'harbour crane'; +/** The clauses' registered definition: `policy` is a lookup to `policy`, the parent a scope may name. */ +const CLAUSE_SCHEMA = { + name: 'article', + fields: { + body: { type: 'textarea' }, + status: { type: 'text' }, + policy: { type: 'lookup', reference: 'policy' }, + }, +}; +/** An `article` source that lists the `policy` lookup and cuts each paragraph into its own passage. */ +const clauseSource = (id: string): KnowledgeSource => + objectSource(id, { + metadataFields: ['status', 'policy'], + split: { strategy: 'recursive', maxChars: 40, minChars: 0 }, + } as Partial); + const rowsOf = (n: number): Row[] => Array.from({ length: n }, (_, i) => ({ id: `r${i}`, body: `body number ${i} zebra${i}`, status: 'published' })); @@ -446,6 +512,169 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption } }); + if (opts.implements.scope) { + describe('scope (ADR-0161 K8, item 17)', () => { + /** + * `c1` outranks every other document. `c2` belongs to policy `p1`, `c3` + * to `p1` through a list, `c4` to the policy stored as the number 7, + * and `c5` to none. + */ + async function seeded(): Promise<{ adapter: IKnowledgeAdapter; a: KnowledgeSource }> { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('scope', { metadataFields: ['status', 'policy'] }); + const withPolicy = (n: string, content: string, policy?: unknown, organizationId?: string): KnowledgeDocument => ({ + ...doc(a, n, content, undefined, organizationId), + metadata: policy === undefined ? { status: 'published' } : { status: 'published', policy }, + }); + await adapter.upsert( + [ + withPolicy('c1', 'harbour crane harbour crane', 'p2'), + withPolicy('c2', 'harbour crane north quay', 'p1'), + withPolicy('c3', 'harbour crane south berth', ['p3', 'p1']), + withPolicy('c4', 'harbour crane night watch', 7), + withPolicy('c5', 'harbour crane east dock'), + ], + ctxOf(a), + ); + return { adapter, a }; + } + const search = (adapter: IKnowledgeAdapter, a: KnowledgeSource, topK: number, scope?: AdapterScopeTerm[]) => + adapter.search(SCOPE_QUERY, { source: a, topK, ...(scope === undefined ? {} : { scope }) }); + const records = (hits: Array<{ sourceRecordId?: string }>): string[] => + hits.map((h) => String(h.sourceRecordId)).sort(); + + it('a record term: ranks only those records, filtering before it ranks', async () => { + const { adapter, a } = await seeded(); + // topK 1: a filter applied after ranking would keep c1's better hit and drop it, answering nothing. + expect(records(await search(adapter, a, 1, [{ kind: 'record', ids: ['c2'] }]))).toEqual(['c2']); + expect(records(await search(adapter, a, 5, [{ kind: 'record', ids: ['c2', 'c4'] }]))).toEqual(['c2', 'c4']); + }); + + it("a metadata term: ranks only the documents whose field holds an id — a list when any element does — and returns each one's metadata", async () => { + const { adapter, a } = await seeded(); + const term: AdapterScopeTerm = { kind: 'metadata', field: 'policy', ids: ['p1'] }; + const hits = await search(adapter, a, 5, [term]); + expect(records(hits)).toEqual(['c2', 'c3']); + // The service checks every hit on its metadata, so the hit carries the document's. + for (const hit of hits) expect(hit.metadata?.policy).toEqual(hit.sourceRecordId === 'c2' ? 'p1' : ['p3', 'p1']); + const top = await search(adapter, a, 1, [term]); + expect(top).toHaveLength(1); + expect(['c2', 'c3']).toContain(top[0].sourceRecordId); + // A document that carries no value for the field is in no metadata scope. + const any = await search(adapter, a, 5, [{ kind: 'metadata', field: 'policy', ids: ['p1', 'p2', 'p3', '7'] }]); + expect(records(any)).toEqual(['c1', 'c2', 'c3', 'c4']); + }); + + it('compares as strings: a value stored as the number 7 matches the id "7"', async () => { + const { adapter, a } = await seeded(); + expect(records(await search(adapter, a, 5, [{ kind: 'metadata', field: 'policy', ids: ['7'] }]))).toEqual(['c4']); + }); + + it('several terms are a union: a document is in scope when any one holds', async () => { + const { adapter, a } = await seeded(); + const hits = await search(adapter, a, 5, [ + { kind: 'record', ids: ['c1'] }, + { kind: 'metadata', field: 'policy', ids: ['p1'] }, + ]); + expect(records(hits)).toEqual(['c1', 'c2', 'c3']); + }); + + it('an empty list ranks nothing, and so does a term with no ids — never read as "no filter"', async () => { + const { adapter, a } = await seeded(); + expect(await search(adapter, a, 5, [])).toEqual([]); + expect(await search(adapter, a, 5, [{ kind: 'record', ids: [] }])).toEqual([]); + expect(await search(adapter, a, 5, [{ kind: 'metadata', field: 'policy', ids: [] }])).toEqual([]); + }); + + it('without the member every document is ranked, as before', async () => { + const { adapter, a } = await seeded(); + expect(records(await search(adapter, a, 5))).toEqual(['c1', 'c2', 'c3', 'c4', 'c5']); + }); + + if (opts.implements.organizationIds) { + it('organizationIds and scope both apply: a document is ranked only when it passes each', async () => { + const { adapter, a } = await seeded(); + await adapter.upsert( + [{ ...doc(a, 'c6', 'harbour crane west pier', undefined, 'org_a'), metadata: { status: 'published', policy: 'p1' } }], + ctxOf(a), + ); + const hits = await adapter.search(SCOPE_QUERY, { + source: a, + topK: 5, + organizationIds: ['org_a'], + scope: [{ kind: 'metadata', field: 'policy', ids: ['p1'] }], + }); + expect(records(hits)).toEqual(['c6']); + }); + } + }); + } + + describe('the record scope through KnowledgeService.search (ADR-0161 K8, item 17)', () => { + /** A person reading every row, under no tenancy posture: no organization filter. */ + const READER = CALLER_A; + // The system identity gets one round of `topK` (no refill after the + // permission filter), so a full page there is the adapter's filter + // before ranking, not the refill's reach. + + it('an own-object scope: every hit is one of the scoped records, and topK is filled from their passages', async () => { + const source = clauseSource('scope_record'); + const h = await serviceOver(make, clauseRows(), source, { schemas: { article: CLAUSE_SCHEMA } }); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 20 }); + const scoped = new Set(['c03', 'c07']); + const hits = await h.svc.search(SCOPE_QUERY, { + topK: 5, + scope: [{ object: 'article', ids: ['c03', 'c07'] }], + executionContext: SYSTEM, + }); + expect(lastOf(h.searched)?.scope).toEqual([{ kind: 'record', ids: ['c03', 'c07'] }]); + for (const hit of hits) expect(scoped.has(String(hit.sourceRecordId))).toBe(true); + if (opts.implements.scope) { + // Filtered before ranking: the eighteen better clauses take no place. + const passages = h.received + .filter((d) => scoped.has(String(d.sourceRecordId))) + .reduce((n, d) => n + (d.chunks?.length ?? 1), 0); + expect(hits).toHaveLength(Math.min(5, passages)); + } + }); + + it('a parent scope: only the clauses whose listed lookup holds one of the policy ids', async () => { + const source = clauseSource('scope_parent'); + const h = await serviceOver(make, clauseRows(), source, { schemas: { article: CLAUSE_SCHEMA } }); + await h.svc.reindexSource(source.id); + const hits = await h.svc.search(SCOPE_QUERY, { + topK: 5, + scope: [{ object: 'policy', ids: ['p1'] }], + executionContext: SYSTEM, + }); + expect(lastOf(h.searched)?.scope).toEqual([{ kind: 'metadata', field: 'policy', ids: ['p1'] }]); + const ofP1 = new Set(clauseRows().filter((r) => r.policy === 'p1').map((r) => String(r.id))); + for (const hit of hits) expect(ofP1.has(String(hit.sourceRecordId))).toBe(true); + if (opts.implements.scope) { + expect(hits).toHaveLength(5); + for (const hit of hits) expect(hit.metadata?.policy).toBe('p1'); + } + }); + + it('over the adapter with the member stripped: no out-of-scope hit is answered, and the service logs once', async () => { + const warn = vi.fn(); + const source = clauseSource('scope_ignored'); + const h = await serviceOver(make, clauseRows(), source, { + schemas: { article: CLAUSE_SCHEMA }, + stripScope: true, + logger: { warn, debug: () => undefined, info: () => undefined, error: () => undefined }, + }); + await h.svc.reindexSource(source.id); + for (const ids of [['c03', 'c07'], ['c07']]) { + const hits = await h.svc.search(SCOPE_QUERY, { topK: 5, scope: [{ object: 'article', ids }], executionContext: READER }); + for (const hit of hits) expect(ids).toContain(hit.sourceRecordId); + } + const reports = warn.mock.calls.map(([message]) => String(message)).filter((m) => m.includes("outside the search's scope")); + expect(reports).toHaveLength(1); + expect(reports[0]).toContain("adapter 'under_test'"); + }); + }); + if (opts.implements.listDocuments) { describe('listDocuments', () => { it.each([ diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index dbd0f4d45ea..cdf264e777e 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -40,6 +40,7 @@ "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", + "AdapterScopeTerm (type)", "AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities (interface)", "AnalyticsQuery (type)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index a95aa66d464..f429ba4f0cd 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -40,6 +40,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)", + "AdapterScopeTerm": "src/contracts/knowledge-adapter.ts#AdapterScopeTerm (type)", "AdapterSearchOptions": "src/contracts/knowledge-adapter.ts#AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities": "src/contracts/analytics-service.ts#AnalyticsDriverCapabilities (interface)", "AnalyticsQuery": "src/data/analytics.zod.ts#AnalyticsQuery (type)", diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 58fdd6683f9..70a7527dbbd 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -47,6 +47,43 @@ export interface AdapterSearchOptions { topK: number; /** Adapter-specific filter (e.g. `{ status: 'active' }`). */ filter?: Record; + /** + * The record scope of this search (ADR-0161 K8, item 17, as its dated note + * of 2026-11-25 shapes it): a list of {@link AdapterScopeTerm}s the knowledge + * service builds from `KnowledgeSearchOptions.scope` for this source — never + * taken from a caller's input as given, never `{ object, ids }`: turning an + * object into a field needs the object's registered definition, which is the + * platform's. + * + * - **Absent** (`undefined`): no scope. Rank every document of the source, + * as before this member. + * - **Present**: rank only the documents some term holds for, and filter + * BEFORE ranking, so `topK` is filled from in-scope documents alone. The + * terms are a union: a document is in scope when any one of them holds. + * - **Empty** (`[]`), or a term whose `ids` is empty: that holds for no + * document. Never read as "no filter". + * + * `organizationIds`, `scope` and the opaque `filter` all apply: a document is + * ranked only when it passes each one that is present. + * + * **Bounds an adapter can rely on.** The service refuses a scope past its + * bounds before any adapter is called, so a search hands at most 10 terms, + * each with at most 500 ids, every id a non-empty string. A `metadata` term's + * ids can go into one `IN` list on a stored column. + * + * **The service checks every hit after the adapter answers**, whatever the + * adapter did: a `record` term on `KnowledgeHit.sourceRecordId`, a `metadata` + * term on `KnowledgeHit.metadata[field]`, and a hit that does not carry the + * value is dropped (fail closed). So an adapter returns the document's + * `metadata` on its hits. An adapter that ignores this member keeps working: + * out-of-scope documents then take ranking places the check empties, so its + * scoped searches may answer fewer than `topK`, and the service logs that + * once for the adapter. + * + * A ranking scope, not the access decision: the service still re-reads every + * object-source hit as the caller. + */ + scope?: AdapterScopeTerm[]; /** * The caller's organizations (ADR-0161 K8, item 9), computed by the knowledge * service from the caller's identity and the deployment's tenancy posture @@ -75,6 +112,23 @@ export interface AdapterSearchOptions { traceId?: string; } +/** + * One term of `AdapterSearchOptions.scope` (ADR-0161 K8, item 17). Values are + * compared as strings: a stored string or number `v` matches when `String(v)` + * is one of `ids` (a record id stored as the number `7` matches the id `'7'`). + * Any other stored value (an object, `null`, a boolean) matches no id. + * + * - `record`: holds for a document whose `sourceRecordId` is in `ids` — a + * scope entry that names the object the source indexes. + * - `metadata`: holds for a document whose `metadata[field]` is in `ids`, or + * is a list with an element in `ids` (a lookup declared `multiple: true` is + * stored as a list of record ids) — a scope entry that names a parent object + * the source reaches through `field`, a lookup it lists in `metadataFields`. + */ +export type AdapterScopeTerm = + | { kind: 'record'; ids: string[] } + | { kind: 'metadata'; field: string; ids: string[] }; + /** Options accepted by `IKnowledgeAdapter.listDocuments`. */ export interface AdapterListDocumentsOptions { /** diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index 92d21e084d8..09b714460b1 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -41,6 +41,37 @@ export interface KnowledgeSearchOptions { * `IDataEngine`. */ executionContext?: ExecutionContext; + /** + * Search only inside these records (ADR-0161 K8, item 17, as its dated note + * of 2026-11-25 shapes it). Each entry names an object and record ids of it: + * + * - **The object a source indexes**: only the documents of those records + * are searched in that source. + * - **A parent object**: only the documents whose lookup to it holds one of + * those ids are searched, in a source that lists that lookup (a `lookup` + * or `master_detail` field pointing at the object) in its + * `metadataFields` — "the clauses of this policy". A source that lists no + * such field, or two or more of them, is not reached by the entry; a + * parent two hops away is not reached either. + * + * Several entries are a union: a document is searched when any entry holds + * for it. A source no entry reaches is not searched, and a `file` / `http` + * source answers nothing under a scope. + * + * - **Absent**: no scope, as before this option. + * - **Empty** (`[]`), or an entry whose `ids` is empty: nothing is in scope, + * and the search answers no hits. Never read as "no scope". + * + * **Bounds.** At most 10 entries, each with at most 500 ids; `object` and + * every id a non-empty string, and no other key on an entry. A scope past + * them is refused before any adapter is called, with a coded error + * (ADR-0112: `code: 'VALIDATION_ERROR'`, `status: 400`). + * + * A ranking scope, not the access decision: every hit is still re-read as + * the caller, and an entry that reaches nothing answers the same empty + * answer a source withheld from the caller gives. + */ + scope?: Array<{ object: string; ids: string[] }>; } /** Options accepted by `IKnowledgeService.reindexSource`. */ From 3deef5fecc6281d094c702b2656925e92814d0c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:56:47 +0000 Subject: [PATCH 3/7] fix(service-knowledge): pin that a parent scope asks nothing of the parent and that an adapter cannot widen the check - A service case: a parent-scoped search makes no engine call naming the parent object, and an adapter that widens the terms it was handed (more ids, an extra term) still has every out-of-scope hit dropped; every round is handed the service's own terms. - AdapterSearchOptions.scope: a metadata term's field is a name from the source's metadataFields; the ids are the caller's strings as given, checked only against the bounds, so an adapter binds them as parameters. - parentLinksOf: drop the self-target guard; the own-object entry is answered before the links are read, so the guard changed no answer. - The RAG guide says an adapter that reads the scope filters before it ranks, and that the service's check may leave an ignoring adapter short of topK. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude --- content/docs/ai/knowledge-rag.mdx | 2 +- .../src/__tests__/knowledge-service.test.ts | 45 +++++++++++++++++++ .../src/knowledge-search-scope.ts | 2 +- .../spec/src/contracts/knowledge-adapter.ts | 11 +++-- 4 files changed, 54 insertions(+), 6 deletions(-) diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index c9699ed123a..87684dba1ce 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -111,7 +111,7 @@ const hits = await knowledge.search('notice period', { }); ``` -The adapter filters before it ranks, so the `topK` hits all come from inside the scope, and the service drops any hit outside it whatever the adapter does. A source the scope does not reach is not searched, and `scope: []` answers nothing, never everything. A scope narrows what is searched; each hit is still re-checked against the caller, so it never shows a record the caller could not read. Bounds, the parent-link rules and what an adapter must do are in [the protocol's record scope](/docs/protocol/knowledge#record-scope). +An adapter that reads the scope filters before it ranks, so the `topK` hits all come from inside the scope. Whatever the adapter does, the service drops any hit outside the scope, so an adapter that ignores it may answer fewer than `topK`. A source the scope does not reach is not searched, and `scope: []` answers nothing, never everything. A scope narrows what is searched; each hit is still re-checked against the caller, so it never shows a record the caller could not read. Bounds, the parent-link rules and what an adapter must do are in [the protocol's record scope](/docs/protocol/knowledge#record-scope). ## What you get for free diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 860be1d1bab..2fc548970ea 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1743,6 +1743,51 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { for (const hit of out) expect(hit.metadata?.policy).toBe('p1'); }); + it('a parent scope asks the engine nothing about the parent object, and an adapter that changes the terms it was handed does not change the check', async () => { + const held = corpus('s1'); + const handed: unknown[] = []; + // An adapter that widens the terms it is handed to every policy and every record, then ranks by them. + const search = vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number; scope?: Term[] }) => { + handed.push(structuredClone(opts.scope)); + const scope = opts.scope ?? []; + for (const term of scope) term.ids.push('p0', 'p2', 'p3'); + scope.push({ kind: 'record', ids: held.map((h) => String(h.sourceRecordId)) }); + return held.filter((h) => holds(h, scope)).slice(0, opts.topK); + }); + // Every call the service makes on the engine, by method and arguments. + const asked: Array<{ method: string; args: unknown[] }> = []; + const inner = engineOver(() => true, { task: TASK_SCHEMA }); + const engine = new Proxy(inner, { + get(target, prop, receiver) { + const value: unknown = Reflect.get(target, prop, receiver); + if (typeof value !== 'function') return value; + return (...args: unknown[]) => { + asked.push({ method: String(prop), args }); + return (value as (...a: unknown[]) => unknown).apply(target, args); + }; + }, + }); + const warn = vi.fn(); + const svc = new KnowledgeService({ dataEngine: engine, logger: { warn, debug: vi.fn(), error: vi.fn() } }); + svc.registerAdapter('memory', { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search }); + svc.registerSource(taskSource('s1')); + const scope = [{ object: 'policy', ids: ['p1'] }]; + + for (const executionContext of [SYSTEM, MEMBER]) { + const out = await svc.search('q', { topK: 5, scope, executionContext }); + expect(out.length).toBeGreaterThan(0); + for (const hit of out) expect(hit.metadata?.policy).toBe('p1'); + } + // Every round was handed the service's own terms, whatever the adapter did with the last ones. + expect(handed.length).toBeGreaterThan(2); + for (const terms of handed) expect(terms).toEqual([{ kind: 'metadata', field: 'policy', ids: ['p1'] }]); + expect(scope).toEqual([{ object: 'policy', ids: ['p1'] }]); + // The indexed object's definition was read; nothing of the parent object was asked. + expect(asked.some((c) => c.method === 'getSchema' && c.args[0] === 'task')).toBe(true); + expect(asked.filter((c) => c.args[0] === 'policy')).toEqual([]); + expect(warn.mock.calls.map(([m]) => String(m)).filter((m) => m.includes("outside the search's scope"))).toHaveLength(1); + }); + it('an object no searched source reaches: no adapter is asked, and the answer is empty', async () => { const { svc, adapter } = setup(); expect(await svc.search('q', { topK: 5, scope: [{ object: 'invoice', ids: ['i1'] }], executionContext: MEMBER })).toEqual([]); diff --git a/packages/services/service-knowledge/src/knowledge-search-scope.ts b/packages/services/service-knowledge/src/knowledge-search-scope.ts index ace9fe65043..02591043beb 100644 --- a/packages/services/service-knowledge/src/knowledge-search-scope.ts +++ b/packages/services/service-knowledge/src/knowledge-search-scope.ts @@ -156,7 +156,7 @@ function parentLinksOf(objSource: ObjectKnowledgeSource, schema: unknown): Map Date: Wed, 25 Nov 2026 20:07:59 +0000 Subject: [PATCH 4/7] test(service-knowledge): pin the record scope under groupBy and under record granularity A scoped search with groupBy, and one with granularity 'record', over an adapter that ignores the scope: every round is handed the record term, and no out-of-scope record answers. Red when the scope is skipped under groupBy or under record granularity, and when the groupBy source filter rebuilds its entries without the terms. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude --- .../src/__tests__/knowledge-service.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 2fc548970ea..2dbcc580abb 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1788,6 +1788,18 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { expect(warn.mock.calls.map(([m]) => String(m)).filter((m) => m.includes("outside the search's scope"))).toHaveLength(1); }); + it('a scope with groupBy, or with granularity record, over an adapter that ignores it: every round is handed the terms, and no out-of-scope record answers', async () => { + const scope = [{ object: 'task', ids: ['rec_1', 'rec_3'] }]; + for (const shape of [{ groupBy: 'policy' }, { granularity: 'record' as const }]) { + const { svc, handed } = setup({ honours: false }); + const out = await svc.search('q', { topK: 5, scope, executionContext: MEMBER, ...shape }); + expect(out.length).toBeGreaterThan(0); + for (const record of records(out)) expect(['rec_1', 'rec_3']).toContain(record); + expect(handed().length).toBeGreaterThan(0); + for (const terms of handed()) expect(terms).toEqual([{ kind: 'record', ids: ['rec_1', 'rec_3'] }]); + } + }); + it('an object no searched source reaches: no adapter is asked, and the answer is empty', async () => { const { svc, adapter } = setup(); expect(await svc.search('q', { topK: 5, scope: [{ object: 'invoice', ids: ['i1'] }], executionContext: MEMBER })).toEqual([]); From d1ca7f0174a2644ca6b94b54d4134bb21122cdc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 22:49:23 +0000 Subject: [PATCH 5/7] test(core): classify the knowledge search scope in the second-object read census knowledge-search-scope.ts names the object a knowledge source's listed lookup points at, only to turn a scope entry naming that parent into a filter on the source's own stored lookup value. It reads no record of the parent and serves nothing of it: kind not-a-served-read, pinned by the service case that a parent-scoped search makes no engine call naming the parent object. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude --- .../security/second-object-read-exposure.pin.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 3ed1502d69b..5daf9cbe10c 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -266,6 +266,16 @@ const CALLERS: Record = { "each target the decision before the engine reads it: the data door's `refuseUnservedRelationTarget`, the MCP " + "stdio data bridge's `enforceRelationTargetExposure` and the runtime `callData`'s `refuseUnservedRelationTargets`", }, + // [#37308] A knowledge search's record scope (ADR-0161 K8, item 17). + 'packages/services/service-knowledge/src/knowledge-search-scope.ts': { + kind: 'not-a-served-read', + reason: + "names the object a knowledge source's listed lookup points at, only to turn a search scope entry that names " + + "that parent into a filter on the source's own stored lookup value; it reads no record of the parent and serves " + + "nothing of it. The hits are the source's own documents, each re-read as the caller (`applyPermissionFilter`). " + + 'Pinned by `packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts` (a parent-scoped ' + + 'search makes no engine call naming the parent object) and `knowledge-search-scope.test.ts`', + }, 'packages/qa/scenarios/src/score/scenario-graph.ts': { kind: 'not-a-served-read', reason: From 4552e7c49a1e7cf33687d7c2dc6c74f5432eea78 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:35:33 +0000 Subject: [PATCH 6/7] chore(spec): regenerate the contracts api surface and export origins after merging main The merge took both sides of the two generated artifacts without a text merge; regenerated from the merged tree, they list main's AdapterIndexExpectation and AdapterIndexStatus beside AdapterScopeTerm. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude --- packages/spec/api-surface/contracts.json | 2 ++ packages/spec/export-origins/contracts.json | 2 ++ 2 files changed, 4 insertions(+) diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index cdf264e777e..6e89a4e8e62 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -37,6 +37,8 @@ "AdapterCapabilities (interface)", "AdapterContext (interface)", "AdapterEmbeddingDescriptor (interface)", + "AdapterIndexExpectation (interface)", + "AdapterIndexStatus (interface)", "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index f429ba4f0cd..64d7d075b6b 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -37,6 +37,8 @@ "AdapterCapabilities": "src/contracts/knowledge-adapter.ts#AdapterCapabilities (interface)", "AdapterContext": "src/contracts/knowledge-adapter.ts#AdapterContext (interface)", "AdapterEmbeddingDescriptor": "src/contracts/knowledge-adapter.ts#AdapterEmbeddingDescriptor (interface)", + "AdapterIndexExpectation": "src/contracts/knowledge-adapter.ts#AdapterIndexExpectation (interface)", + "AdapterIndexStatus": "src/contracts/knowledge-adapter.ts#AdapterIndexStatus (interface)", "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", From 760716bcbbcc3e4a64ae9ecae9b710d76743b289 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 23:35:54 +0000 Subject: [PATCH 7/7] feat(knowledge-pgvector): apply the record scope in the search SQL knowledge-pgvector landed first (#37337), so it implements the scope as every in-tree adapter that runs the suite does (#37308 item 4). The terms are a union in the same inner WHERE as the organization filter, before ranking: a record term on source_record_id, a metadata term on the stored jsonb value of its field (a string or number equal to an id as text, or a list with such an element; anything else holds for nothing). Ids and field names go as bound parameters. A scope with no term that has ids ranks nothing. The live contract run declares implements.scope, so the suite's record-term, metadata-term and service-level parent cases run against PostgreSQL. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude --- .changeset/37308-knowledge-search-scope.md | 3 ++- content/docs/protocol/knowledge.mdx | 7 ++--- .../__tests__/contract.live-postgres.test.ts | 1 + .../src/pgvector-adapter.ts | 27 +++++++++++++++++++ 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/.changeset/37308-knowledge-search-scope.md b/.changeset/37308-knowledge-search-scope.md index a496b81cecd..cb60593dcff 100644 --- a/.changeset/37308-knowledge-search-scope.md +++ b/.changeset/37308-knowledge-search-scope.md @@ -2,6 +2,7 @@ '@objectstack/spec': patch '@objectstack/service-knowledge': patch '@objectstack/knowledge-memory': patch +'@objectstack/knowledge-pgvector': patch --- feat(service-knowledge): a knowledge search can be held to chosen records, or to the records under one parent, and the adapter filters before it ranks @@ -18,6 +19,6 @@ New, both optional, in `@objectstack/spec` (types only, no metadata key): `KnowledgeService` checks every hit after the adapter answers and drops a hit no term holds for, including a hit that does not carry the value, so an adapter returns the document's `metadata` on its hits. An adapter that ignores the member keeps working: its scoped searches may answer fewer than `topK`, and the service logs that once per adapter at `warn`. A source that lists two or more lookups to the scoped object is not reached by that entry, logged once at `warn` naming the fields. A `user` field is not a parent link, and a parent two hops away is not reached. How many hits the scope removed is logged, never returned. -`@objectstack/knowledge-memory` applies `scope` before ranking. `runKnowledgeAdapterContract` (from `@objectstack/service-knowledge/testing`) now requires `implements.scope`. It adds scope cases for the adapter alone, for each term kind, and cases through a real `KnowledgeService`, including one over the adapter with the member stripped. +`@objectstack/knowledge-memory` applies `scope` before ranking, and `@objectstack/knowledge-pgvector` applies it in the same SQL `WHERE` as the organization filter, ids and field names as bound parameters. `runKnowledgeAdapterContract` (from `@objectstack/service-knowledge/testing`) now requires `implements.scope`. It adds scope cases for the adapter alone, for each term kind, and cases through a real `KnowledgeService`, including one over the adapter with the member stripped. What to do: an adapter package reads `scope` in its search, returns each document's `metadata` on its hits, and passes `implements.scope` to the contract suite. A source that should be searchable inside one parent record lists the lookup to that parent in `metadataFields`; documents indexed before the lookup was listed are in no parent scope until a complete reindex writes them again. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 77c75a17c9c..b3e64e2afdc 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -546,8 +546,9 @@ an exact scan. no SQL. A caller reads one sentence; the driver's text and the SQL go only to the operator — the health check, the boot warning and the log. - **Search.** An exact scan by cosine distance, so any width works — - including a 3072-wide model. The organization filter and the metadata - `filter` (equality per key) run in the same `WHERE`, before ranking. + including a 3072-wide model. The organization filter, the + [record scope](#record-scope) and the metadata `filter` (equality per key) + run in the same `WHERE`, before ranking. `queryPrefix` is put before every query before it is embedded, for a model that embeds questions and passages differently. - **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is @@ -926,7 +927,7 @@ up. | Audit + metrics | ⏳ Phase 2 | | | `knowledge-llamaindex` | ⏳ Phase 2 | | | `knowledge-dify` | ⏳ Phase 3 / community | | -| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization and metadata filter in SQL, index fingerprint (§4.1) | +| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) | ### 7.1 Non-goals for Phase 1 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 6c3c827580d..4b5b9b00d58 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 @@ -27,6 +27,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { builds: true, refusesOtherFingerprint: true, generations: false, + scope: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 459d904c374..2911b98c9d2 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -380,6 +380,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { async search(query: string, opts: AdapterSearchOptions): Promise { // An empty organization set ranks nothing (ADR-0161 K8, item 9). if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return []; + // A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17). + if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return []; const pool = this.requirePool(); const readiness = await this.ready(); // The embedder first: without one the service's fingerprint carries no @@ -414,6 +416,31 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { params.push(opts.organizationIds); where.push(`organization_id = ANY($${params.length}::text[])`); } + if (opts.scope !== undefined) { + // The record scope (ADR-0161 K8, item 17), a union of terms, beside the + // organization filter so `topK` is filled from in-scope documents. Ids + // and field names go as bound parameters. A `metadata` term holds for a + // stored string or number equal to an id as text, or a list with such an + // element; a missing value or any other kind holds for nothing. + const terms: string[] = []; + for (const term of opts.scope) { + if (term.ids.length === 0) continue; + params.push(term.ids); + const ids = `$${params.length}::text[]`; + if (term.kind === 'record') { + terms.push(`source_record_id = ANY(${ids})`); + continue; + } + params.push(term.field); + const value = `(metadata -> $${params.length}::text)`; + terms.push( + `EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(${value}) WHEN 'array' THEN ${value} ` + + `ELSE jsonb_build_array(${value}) END) AS e(v) ` + + `WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY(${ids}))`, + ); + } + where.push(`(${terms.join(' OR ')})`); + } for (const [key, value] of Object.entries(opts.filter ?? {})) { params.push(key, JSON.stringify(value === undefined ? null : value)); where.push(`(metadata -> $${params.length - 1}) = $${params.length}::jsonb`);