diff --git a/.changeset/37308-knowledge-search-scope.md b/.changeset/37308-knowledge-search-scope.md new file mode 100644 index 00000000000..cb60593dcff --- /dev/null +++ b/.changeset/37308-knowledge-search-scope.md @@ -0,0 +1,24 @@ +--- +'@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 + +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, 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/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 7214c704c1d..8a96ea9e200 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -98,6 +98,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, +}); +``` + +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 - **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 ad4aadbd35f..b3e64e2afdc 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -334,7 +334,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 @@ -354,6 +356,7 @@ runKnowledgeAdapterContract({ implements: { listDocuments: true, chunks: true, organizationIds: true, indexStatus: true, builds: true, refusesOtherFingerprint: true, generations: true, + scope: true, }, }); ``` @@ -543,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 @@ -635,6 +639,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 @@ -866,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/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: diff --git a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts index fd9217e64a7..0cbcab163d9 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts @@ -18,5 +18,6 @@ runKnowledgeAdapterContract({ builds: true, refusesOtherFingerprint: true, generations: true, + scope: true, }, }); diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 91f158dcd68..1f45903069d 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -7,6 +7,7 @@ import type { AdapterIndexStatus, AdapterListDocumentsOptions, AdapterListDocumentsPage, + AdapterScopeTerm, AdapterSearchOptions, } from '@objectstack/spec/contracts'; import type { @@ -35,6 +36,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 @@ -205,10 +215,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, @@ -356,6 +369,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/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`); 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 fdab898b2f0..31aea0f60f6 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'; @@ -106,6 +109,7 @@ runKnowledgeAdapterContract({ builds: false, refusesOtherFingerprint: false, generations: false, + scope: false, }, }); @@ -120,5 +124,6 @@ runKnowledgeAdapterContract({ builds: false, refusesOtherFingerprint: false, generations: 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 bee9333a0c1..271434ea6fc 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1705,6 +1705,240 @@ 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('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('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([]); + 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..02591043beb --- /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) 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 d2b5674891d..f6725d153a3 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -4,6 +4,7 @@ import { createHash } from 'node:crypto'; import type { AdapterContext, AdapterIndexExpectation, + AdapterScopeTerm, IDataEngine, IKnowledgeAdapter, IKnowledgeService, @@ -41,6 +42,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. @@ -126,6 +128,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 @@ -768,6 +774,18 @@ export class KnowledgeService implements IKnowledgeService { * hit as the caller ({@link applyPermissionFilter}), and answer the best * `topK` hits by score — passages, or records under `granularity: 'record'`. * + * ## 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 @@ -842,6 +860,7 @@ export class KnowledgeService implements IKnowledgeService { * `refused` lists them all. */ async searchWithRefusals(query: string, opts: KnowledgeSearchOptions = {}): Promise { + const scope = readSearchScope(opts.scope); const topK = opts.topK ?? this.defaultTopK; const groupBy = opts.groupBy; if (groupBy !== undefined) { @@ -866,7 +885,9 @@ export class KnowledgeService implements IKnowledgeService { } const byRecord = opts.granularity === 'record' || groupBy !== undefined; const ctx = opts.executionContext; - let admitted = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); + let admitted: Array<{ source: KnowledgeSource; organizationIds?: string[]; scope?: AdapterScopeTerm[] }> = + await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); + if (scope !== undefined) admitted = this.sourcesInScope(admitted, scope); if (groupBy !== undefined) admitted = this.sourcesGroupableBy(admitted, groupBy); if (admitted.length === 0) return { hits: [], refused: [] }; const sources = await this.planSearches(admitted); @@ -938,10 +959,7 @@ export class KnowledgeService implements IKnowledgeService { * `metadataFields`. Any other object source answers no hits for this search * — its hits carry no group value, and a hit is never answered ungrouped. */ - private sourcesGroupableBy( - sources: Array<{ source: KnowledgeSource; organizationIds?: string[] }>, - groupBy: string, - ): Array<{ source: KnowledgeSource; organizationIds?: string[] }> { + private sourcesGroupableBy(sources: T[], groupBy: string): T[] { return sources.filter(({ source }) => { if (source.source.kind !== 'object') return true; if (((source.source as ObjectKnowledgeSource).metadataFields ?? []).includes(groupBy)) return true; @@ -1149,7 +1167,7 @@ export class KnowledgeService implements IKnowledgeService { * (the round skips it, as before). */ private async planSearches( - admitted: Array<{ source: KnowledgeSource; organizationIds?: string[] }>, + admitted: Array<{ source: KnowledgeSource; organizationIds?: string[]; scope?: AdapterScopeTerm[] }>, ): Promise { const out: SearchTarget[] = []; // The settings page's chunk target, read at most once for the whole search. @@ -1170,11 +1188,19 @@ 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: a coded refusal - * (ADR-0112 `code` and `status`) is added to `refused`, anything else is - * 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: a coded refusal (ADR-0112 `code` and `status`) is added to + * `refused`, anything else is 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, @@ -1184,7 +1210,7 @@ export class KnowledgeService implements IKnowledgeService { refused: KnowledgeSearchRefusal[], ): Promise> { const out = new Map(); - for (const { source, organizationIds, fingerprint } of sources) { + for (const { source, organizationIds, fingerprint, scope } of sources) { const adapter = this.adapters.get(source.adapter); if (!adapter) { this.options.logger?.warn?.( @@ -1199,6 +1225,7 @@ export class KnowledgeService implements IKnowledgeService { filter, ...(organizationIds === undefined ? {} : { organizationIds }), ...(fingerprint === undefined ? {} : { index: { fingerprint } }), + ...(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 @@ -1213,7 +1240,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) { const coded = codedRefusalOf(err); if (coded !== undefined) { @@ -1233,6 +1263,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) ─── /** @@ -1740,11 +1830,15 @@ export interface KnowledgeSearchReport { refused: KnowledgeSearchRefusal[]; } -/** One source a search round asks: its organizations scope and the fingerprint its search carries. */ +/** + * One source a search round asks: its organizations scope, the fingerprint its + * search carries, and the record scope's terms for it (ADR-0161 K8, item 17). + */ interface SearchTarget { source: KnowledgeSource; organizationIds?: string[]; fingerprint?: string; + scope?: AdapterScopeTerm[]; } /** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 9614ead1935..2cc09035ec1 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -52,23 +52,32 @@ * 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 { describe, expect, it, vi } from 'vitest'; import type { IDataEngine, IKnowledgeAdapter, AdapterContext, AdapterIndexExpectation, + 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}. */ @@ -108,6 +117,12 @@ export interface KnowledgeAdapterContractOptions { * Asserted by behaviour; needs `builds` and `refusesOtherFingerprint`. */ generations: 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; }; } @@ -270,6 +285,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; } /** @@ -310,6 +331,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) => { @@ -347,9 +372,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); @@ -389,6 +417,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' })); @@ -555,6 +616,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 bbc4d74a845..6e89a4e8e62 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -42,6 +42,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 bddca730059..64d7d075b6b 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -42,6 +42,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/ai/knowledge-document.zod.ts b/packages/spec/src/ai/knowledge-document.zod.ts index 515c614bad5..4a5ba3cb82d 100644 --- a/packages/spec/src/ai/knowledge-document.zod.ts +++ b/packages/spec/src/ai/knowledge-document.zod.ts @@ -157,7 +157,13 @@ export const KnowledgeHitSchema = lazySchema(() => z.object({ snippet: z.string(), /** Optional title surfaced from the document. */ title: z.string().optional(), - /** Free-form metadata propagated from the document. */ + /** + * Free-form metadata propagated from the document. An adapter returns the + * document's `metadata` on each hit, as stored: the knowledge service checks + * a scoped search's hits against it (`AdapterSearchOptions.scope`, ADR-0161 + * K8, item 17) and drops a hit that does not carry the value a scope term + * names. + */ metadata: z.record(z.string(), z.unknown()).default({}).optional(), /** * The `docHash` the adapter stores for the hit's document, returned as diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index e17ce58f856..d11e35b4a65 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -94,6 +94,46 @@ 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. The + * term's shape is the service's, never the caller's `{ object, ids }`: + * turning an object into a field needs the object's registered definition, + * which is the platform's. A `metadata` term's `field` is a name from the + * source's `metadataFields`. A term's `ids` are the caller's strings as + * given, checked only against the bounds below, so an adapter binds them as + * query parameters and never splices them into a query's text. + * + * - **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 @@ -130,6 +170,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 4eb56a1a509..b28697700df 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -74,6 +74,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`. */