diff --git a/.changeset/37311-search-knowledge-scope-granularity-groupby.md b/.changeset/37311-search-knowledge-scope-granularity-groupby.md new file mode 100644 index 00000000000..95a5b0a91f2 --- /dev/null +++ b/.changeset/37311-search-knowledge-scope-granularity-groupby.md @@ -0,0 +1,15 @@ +--- +'@objectstack/service-knowledge': patch +--- + +feat(service-knowledge): `search_knowledge` takes `scope`, `granularity` and `groupBy` + +Clause-②: yes +Metadata-protocol: none + +ADR-0161 K9, rule 2 (#37311): the one `search_knowledge` definition gains the three arguments its knowledge service already reads, so an MCP client (HTTP and stdio) and the in-product agent are offered them alike. No transport adds or edits an argument. + +- `granularity: "record"` answers one hit per record, its best passage; `groupBy` answers one hit per value of a field the source lists in `metadataFields`, the value carried as the hit's `groupValue` (as the index stores it); an object source that does not list the field answers nothing for that search, and a `file` / `http` source answers one hit per document with no `groupValue`; `scope` searches only inside the named records, or the records linking to the named parents. Each is handed to `IKnowledgeService.search` as its option of the same name. +- A hit also carries `headingPath` where its passage has headings. The hit stays a whitelist: no `chunkId`, `docHash` or `metadata`. +- The executor refuses each malformed argument `VALIDATION_ERROR` (400) naming it; over MCP, a shape the definition's schema states is refused first by the SDK's input validation (`-32602`). The tool is stricter than the service: an empty `scope` or an entry with no ids is refused (as an empty `sourceIds` is), and an object name, record id or field name over 255 characters or holding a NUL character is refused. A refusal quotes a caller's string and cuts it to 64 characters, and lists at most five. +- The executor searches only `aiExposed` sources, so a `scope` entry or `groupBy` field only a withheld source would answer gets the same empty answer as one no source answers. The answer carries no count of hits the permission re-check or the scope removed. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index fac4b859c1b..eef9cde8f68 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -113,6 +113,29 @@ const hits = await knowledge.search('notice period', { 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). +## The `search_knowledge` tool + +An AI client searches through one tool, `search_knowledge`, defined once by the knowledge service. The MCP door (HTTP and stdio) and the in-product agent serve that one definition unchanged, so every client is offered the same arguments and gets the same answer. It searches only sources whose `aiExposed` is not `false`, and reads as the person asking. + +| Argument | What it does | +|:--|:--| +| `query` | What to look for, in plain words. Required. | +| `sourceIds` | Only these sources, by the ids every answer lists in `sources`. Omit to search them all. | +| `topK` | At most this many hits, 1 to 20, default 5. Counts records or groups in the two modes below. | +| `granularity` | `"chunk"` (the default): one hit per passage. `"record"`: one hit per record, its best passage. | +| `groupBy` | One hit per value of a field the source lists in `metadataFields`, such as `policy`: "which policies", not "which clauses". Implies `"record"`; refused with `"chunk"`. A source of indexed records that does not list the field answers nothing for that call; a file or web source still answers, one hit per document, with no `groupValue`. | +| `scope` | Only inside these records: a list of `{ object, ids }`, as `KnowledgeSearchOptions.scope` reads it above. At most 10 entries of at most 500 ids. | + +Each hit carries `sourceId`, `documentId`, `title`, `snippet`, `score`, and for an indexed record `record: { object, id }`, which the record tools read. It also carries `headingPath`, the headings its passage sits under, where the document has headings, and under `groupBy` the group's value as `groupValue`: the value as the index stores it (a string, a number, or a list for a multi-value lookup), absent on a hit of a file or web source. The answer also lists the searchable `sources`, and in `refused` any source that could not be searched. + +The tool is stricter than the service in a few places, so that a mistake is reported instead of being answered as "nothing matched": + +- An empty `scope`, an entry with no ids, and an empty `sourceIds` are refused, not answered with no hits. +- An object name, record id or field name over 255 characters, or one holding a NUL character, is refused. +- Each malformed argument is refused `VALIDATION_ERROR` (400), naming the argument. Over MCP, a shape the tool's schema states (an empty or over-long `scope`, a string over 255 characters, an unknown `granularity` or key) is refused first by the MCP input-validation check, as error `-32602` naming the argument, without that code. The coded refusal answers what the schema cannot state, such as a NUL character or `groupBy` with `"chunk"`, and every malformed argument the in-product agent sends. + +The answer never says how many hits the permission re-check or the scope removed. A `scope` entry or `groupBy` field that only a withheld source would answer gets the same empty answer as one that no source answers, so the answer never shows that a withheld source exists. + ## 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/packages/mcp/package.json b/packages/mcp/package.json index ea43c9f8537..e60892d27c0 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -43,6 +43,7 @@ "@objectstack/metadata-protocol": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/service-analytics": "workspace:*", + "@objectstack/service-knowledge": "workspace:*", "@objectstack/service-record-context": "workspace:*", "@types/node": "^26.6.5", "typescript": "^6.0.3", diff --git a/packages/mcp/src/mcp-knowledge-tools.test.ts b/packages/mcp/src/mcp-knowledge-tools.test.ts index c1efaf57669..59eef1f3ccf 100644 --- a/packages/mcp/src/mcp-knowledge-tools.test.ts +++ b/packages/mcp/src/mcp-knowledge-tools.test.ts @@ -14,10 +14,24 @@ * in `prompts/list` where the tool is served and withheld, with a debug line * naming the tool, where it is not; and the stdio bridge runs each call as the * principal it resolves for that call. + * + * And over the knowledge service's REAL definition and executor (ADR-0161 K9, + * rules 1, 2 and 4): `tools/list` over HTTP and over stdio answer the same + * `search_knowledge` definition, byte for byte, carrying `scope`, + * `granularity` and `groupBy` (the definition converts to the SDK's input + * schema whole: a definition that did not would register no tool at all); and + * a call over either door answers one hit per record, one per group with its + * value, and only the scoped records' hits. */ import { describe, it, expect, vi } from 'vitest'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; import { MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE } from '@objectstack/spec/ai'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import { KnowledgeService, getKnowledgeToolDefinitions, recordToDocument } from '@objectstack/service-knowledge'; import { MCPServerRuntime } from './mcp-server-runtime.js'; import { SEARCH_KNOWLEDGE_TOOL_NAME, type McpDataBridge } from './mcp-http-tools.js'; import type { McpSkillBridge } from './skill-prompts.js'; @@ -235,3 +249,174 @@ describe('[ADR-0149 D2] search_knowledge on the stdio bridge', () => { expect(searchKnowledge).toHaveBeenCalledWith({ query: 'refund' }, principal); }); }); + +describe('[ADR-0161 K9] search_knowledge over the real definition — every transport serves it unchanged', () => { + type Row = Record & { id: string }; + const CLAUSES: Row[] = [ + { id: 'c1', body: 'annual leave', policy: 'P_leave' }, + { id: 'c2', body: 'sick leave', policy: 'P_leave' }, + { id: 'c3', body: 'travel', policy: 'P_travel' }, + ]; + const SOURCE: KnowledgeSource = { + id: 'clauses', + label: 'Clauses', + adapter: 'memory', + source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: ['policy'] } as ObjectKnowledgeSource, + }; + + function indexHit(row: Row, n: number, score: number): KnowledgeHit { + const doc = recordToDocument(SOURCE, SOURCE.source as ObjectKnowledgeSource, row); + return { + chunkId: `${doc.id}#${n}`, documentId: doc.id, sourceId: SOURCE.id, sourceRecordId: row.id, + score, snippet: `${row.body as string} (${n})`, metadata: doc.metadata, docHash: doc.docHash, + }; + } + + /** A stdio bridge over a real knowledge service: one clause source, an adapter ranking the index's hits, an engine over CLAUSES. */ + function realBridge(): McpDataBridge { + const corpus = [indexHit(CLAUSES[0], 0, 0.9), indexHit(CLAUSES[0], 1, 0.8), indexHit(CLAUSES[1], 0, 0.7), indexHit(CLAUSES[2], 0, 0.6)]; + const adapter = { + id: 'memory', + upsert: async () => undefined, + delete: async () => undefined, + search: async (_q: string, opts: { topK: number }) => corpus.slice(0, opts.topK), + } as unknown as IKnowledgeAdapter; + const matches = (row: Row, where: Record = {}): boolean => + Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as Record[]).every((w) => matches(row, w)); + if (v !== null && typeof v === 'object') return (v as { $in: string[] }).$in.includes(row[k] as string); + return row[k] === v; + }); + const engine = { + find: async (_object: string, q: { where?: Record; fields?: string[]; limit?: number }) => { + const rows = CLAUSES.filter((r) => matches(r, q.where)); + const page = typeof q.limit === 'number' ? rows.slice(0, q.limit) : rows; + return page.map((r) => (q.fields ? Object.fromEntries(q.fields.filter((f) => f in r).map((f) => [f, r[f]])) : { ...r })); + }, + } as unknown as IDataEngine; + const service = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined, debug: () => undefined } }); + service.registerAdapter('memory', adapter); + service.registerSource(SOURCE); + return createStdioDataBridge({ + engine: {} as never, + metadataService: { list: async () => [], getObject: async () => undefined } as never, + resolvePrincipal: async () => ({ userId: 'u_key_owner', isSystem: false }) as never, + knowledgeTools: service, + }); + } + + async function overStdio(bridge: McpDataBridge, use: (client: Client) => Promise): Promise { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + runtime.bridgeDataTools(bridge); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await runtime.server.connect(serverSide); + const client = new Client({ name: 't', version: '1.0.0' }); + await client.connect(clientSide); + try { + return await use(client); + } finally { + await client.close(); + } + } + + /** + * One JSON-RPC request over stdio, answered as the wire carries it: read off + * the transport, not through the SDK client, whose result parse re-orders + * an input schema's keys and would make a byte comparison read the client. + */ + async function rawOverStdio(bridge: McpDataBridge, message: JSONRPCMessage & { id: number }) { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + runtime.bridgeDataTools(bridge); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await runtime.server.connect(serverSide); + const reply = new Promise((resolve) => { + clientSide.onmessage = (m) => { + if ((m as { id?: number }).id === message.id) resolve(m); + }; + }); + await clientSide.start(); + await clientSide.send(message); + try { + return await reply; + } finally { + await clientSide.close(); + } + } + + async function callBoth(args: Record) { + const http = (await callTool(realBridge(), args)).result!; + const stdio = (await overStdio(realBridge(), (c) => c.callTool({ name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args }))) as { + content: Array<{ text: string }>; + isError?: boolean; + }; + expect(http.isError).toBeFalsy(); + expect(stdio.isError).toBeFalsy(); + expect(stdio.content[0].text).toBe(http.content[0].text); + return JSON.parse(http.content[0].text) as { hits: Array<{ record?: { id: string }; groupValue?: unknown }> }; + } + + it('tools/list over HTTP and over stdio answer byte-identical definitions, carrying scope, granularity and groupBy', async () => { + const http = knowledgeTool(await listTools(realBridge())); + const stdio = knowledgeTool((await rawOverStdio(realBridge(), { jsonrpc: '2.0', id: 1, method: 'tools/list' })).result.tools); + expect(http).toBeDefined(); + expect(JSON.stringify(stdio)).toBe(JSON.stringify(http)); + const [definition] = getKnowledgeToolDefinitions(); + expect(http!.description).toBe(definition.description); + // The listed schema IS the definition's: no transport-side edit of a bound, a description or a key. + const { $schema: _dialect, ...listed } = http!.inputSchema; + expect(listed).toEqual(definition.parameters); + expect(Object.keys(http!.inputSchema.properties).sort()).toEqual(['granularity', 'groupBy', 'query', 'scope', 'sourceIds', 'topK']); + // The nested scope schema reaches the client whole, bounds included. + expect(http!.inputSchema.properties.scope).toMatchObject({ + type: 'array', minItems: 1, maxItems: 10, + items: { type: 'object', required: ['object', 'ids'], additionalProperties: false, properties: { ids: { maxItems: 500 } } }, + }); + expect(http!.inputSchema.properties.granularity.enum).toEqual(['chunk', 'record']); + }); + + it("granularity 'record' answers one hit per record over both doors", async () => { + const answer = await callBoth({ query: 'leave', granularity: 'record' }); + expect(answer.hits.map((h) => h.record?.id)).toEqual(['c1', 'c2', 'c3']); + }); + + it('groupBy answers one hit per group, with its value, over both doors', async () => { + const answer = await callBoth({ query: 'leave', groupBy: 'policy' }); + expect(answer.hits.map((h) => [h.record?.id, h.groupValue])).toEqual([['c1', 'P_leave'], ['c3', 'P_travel']]); + }); + + it('scope answers only the named records over both doors', async () => { + const answer = await callBoth({ query: 'leave', scope: [{ object: 'clause', ids: ['c3'] }] }); + expect(answer.hits.map((h) => h.record?.id)).toEqual(['c3']); + }); + + it('a scope past its bound is refused by the schema check before the bridge is asked, with the same answer on both doors', async () => { + const args = { query: 'q', scope: Array.from({ length: 11 }, () => ({ object: 'clause', ids: ['c1'] })) }; + const bridge = realBridge(); + const search = vi.spyOn(bridge, 'searchKnowledge'); + const http = (await callTool(bridge, args)).result!; + const stdio = (await rawOverStdio(realBridge(), { + jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args }, + })).result as { content: Array<{ text: string }>; isError?: boolean }; + expect(search).not.toHaveBeenCalled(); + // The SDK's input-validation refusal (-32602), naming the argument: a schema-stated shape never reaches the + // executor over MCP, so it carries no ADR-0112 code. The coded VALIDATION_ERROR is the executor's own. + expect(http.isError).toBe(true); + expect(http.content[0].text).toContain('-32602'); + expect(http.content[0].text).toContain('scope'); + expect(stdio.isError).toBe(true); + expect(stdio.content[0].text).toBe(http.content[0].text); + }); + + it('a shape the schema cannot state (a NUL in an id) reaches the executor and answers its coded VALIDATION_ERROR on both doors', async () => { + const args = { query: 'q', scope: [{ object: 'clause', ids: ['c1\u0000x'] }] }; + const http = (await callTool(realBridge(), args)).result!; + const stdio = (await rawOverStdio(realBridge(), { + jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: SEARCH_KNOWLEDGE_TOOL_NAME, arguments: args }, + })).result as { content: Array<{ text: string }>; isError?: boolean }; + expect(http.isError).toBe(true); + expect(JSON.parse(http.content[0].text).error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(http.content[0].text).toContain('`scope`'); + expect(stdio.isError).toBe(true); + expect(stdio.content[0].text).toBe(http.content[0].text); + }); +}); diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts index ff949e7c934..ac58f8b5360 100644 --- a/packages/mcp/vitest.config.ts +++ b/packages/mcp/vitest.config.ts @@ -87,6 +87,8 @@ export default defineConfig({ { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../drivers/driver-sql/src/index.ts') }, // [ADR-0160] The record-context executor, so `get_record_context`'s transport parity runs the real one. { find: /^@objectstack\/service-record-context$/, replacement: path.resolve(__dirname, '../services/service-record-context/src/index.ts') }, + // [ADR-0161 K9] The knowledge tool's one definition and executor, so `search_knowledge`'s transport parity runs the real ones. + { find: /^@objectstack\/service-knowledge$/, replacement: path.resolve(__dirname, '../services/service-knowledge/src/index.ts') }, ], }, }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts index 3568718e25c..1de64044070 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -2,14 +2,20 @@ /** * `search_knowledge`'s one definition and executor (ADR-0149 D2): the - * `aiExposed` refusal and preservation halves, and the caller's execution - * context reaching the row-level re-check. + * `aiExposed` refusal and preservation halves, the caller's execution + * context reaching the row-level re-check, and the `scope`, `granularity` and + * `groupBy` arguments (ADR-0161 K9, rule 2): their bounds, their reaching the + * service, the answer's whitelisted hit, and a withheld source answered as an + * absent one. */ import { describe, it, expect, vi } from 'vitest'; -import { KnowledgeService } from '../knowledge-service.js'; +import { KnowledgeService, recordToDocument } from '../knowledge-service.js'; import { SEARCH_KNOWLEDGE_DEFAULT_TOP_K, + SEARCH_KNOWLEDGE_MAX_NAME_LENGTH, + SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES, + SEARCH_KNOWLEDGE_MAX_SCOPE_IDS, SEARCH_KNOWLEDGE_MAX_TOP_K, SEARCH_KNOWLEDGE_TOOL_NAME, createKnowledgeTools, @@ -267,3 +273,306 @@ describe('search_knowledge — a refused source (ADR-0161 K7, rule 5)', () => { expect(answer).not.toHaveProperty('refused'); }); }); + +describe('search_knowledge — scope, granularity and groupBy: the definition', () => { + it('declares the three arguments with the bounds the executor holds them to', () => { + const [definition] = getKnowledgeToolDefinitions(); + const props = (definition.parameters as { properties: Record }).properties; + expect(Object.keys(props).sort()).toEqual(['granularity', 'groupBy', 'query', 'scope', 'sourceIds', 'topK']); + expect(props.scope).toMatchObject({ + type: 'array', + minItems: 1, + maxItems: SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES, + items: { + type: 'object', + required: ['object', 'ids'], + additionalProperties: false, + properties: { + object: { type: 'string', minLength: 1, maxLength: SEARCH_KNOWLEDGE_MAX_NAME_LENGTH }, + ids: { + type: 'array', + minItems: 1, + maxItems: SEARCH_KNOWLEDGE_MAX_SCOPE_IDS, + items: { type: 'string', minLength: 1, maxLength: SEARCH_KNOWLEDGE_MAX_NAME_LENGTH }, + }, + }, + }, + }); + expect(props.granularity).toMatchObject({ type: 'string', enum: ['chunk', 'record'] }); + expect(props.groupBy).toMatchObject({ type: 'string', minLength: 1, maxLength: SEARCH_KNOWLEDGE_MAX_NAME_LENGTH }); + // The bounds the service holds its own `scope` option to. + expect(SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES).toBe(10); + expect(SEARCH_KNOWLEDGE_MAX_SCOPE_IDS).toBe(500); + }); + + it('names each argument, and each hit member the new modes add, in the description', () => { + const [{ description }] = getKnowledgeToolDefinitions(); + for (const name of ['`scope`', '`granularity: "record"`', '`groupBy`', '`groupValue`', '`headingPath`']) { + expect(description).toContain(name); + } + }); +}); + +describe('search_knowledge — scope, granularity and groupBy: malformed arguments', () => { + const long = 'x'.repeat(SEARCH_KNOWLEDGE_MAX_NAME_LENGTH + 1); + const nul = 'p1\u0000x'; + const entry = (extra: Record = {}) => ({ object: 'policy_clause', ids: ['p1'], ...extra }); + it.each([ + ['not a list', { scope: { object: 'policy_clause', ids: ['p1'] } }, 'scope'], + ['empty', { scope: [] }, 'scope'], + ['too many entries', { scope: Array.from({ length: SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES + 1 }, () => entry()) }, 'scope'], + ['an entry that is not an object', { scope: ['policy_clause'] }, 'scope'], + ['an entry with another key', { scope: [entry({ field: 'policy' })] }, 'scope'], + ['an entry with no object', { scope: [{ ids: ['p1'] }] }, 'scope'], + ['an empty object', { scope: [entry({ object: '' })] }, 'scope'], + ['an object over the length bound', { scope: [entry({ object: long })] }, 'scope'], + ['an object with a NUL', { scope: [entry({ object: 'policy\u0000clause' })] }, 'scope'], + ['an entry with no ids', { scope: [{ object: 'policy_clause' }] }, 'scope'], + ['an entry with empty ids', { scope: [entry({ ids: [] })] }, 'scope'], + ['too many ids', { scope: [entry({ ids: Array.from({ length: SEARCH_KNOWLEDGE_MAX_SCOPE_IDS + 1 }, (_, i) => `p${i}`) })] }, 'scope'], + ['an empty id', { scope: [entry({ ids: ['p1', ''] })] }, 'scope'], + ['an id that is not a string', { scope: [entry({ ids: [1] })] }, 'scope'], + ['an id over the length bound', { scope: [entry({ ids: [long] })] }, 'scope'], + ['an id with a NUL', { scope: [entry({ ids: [nul] })] }, 'scope'], + ['an unknown granularity', { granularity: 'passage' }, 'granularity'], + ['an empty groupBy', { groupBy: '' }, 'groupBy'], + ['a groupBy that is not a string', { groupBy: ['policy'] }, 'groupBy'], + ['a groupBy over the length bound', { groupBy: long }, 'groupBy'], + ['a groupBy with a NUL', { groupBy: 'pol\u0000icy' }, 'groupBy'], + ['groupBy with granularity chunk', { groupBy: 'policy', granularity: 'chunk' }, 'groupBy'], + ])('refuses %s with VALIDATION_ERROR naming the argument, and searches nothing', async (_case, args, named) => { + const { service, adapter } = setup(); + const err = await service.knowledgeTools().searchKnowledge({ query: 'q', ...args }, caller).catch((e) => e); + expect(err).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(err.message).toContain(`\`${named}\``); + // A refusal never repeats a raw control byte or a caller string whole. + expect(err.message).not.toContain('\u0000'); + expect(err.message).not.toContain(long); + expect(adapter.searched).toEqual([]); + }); + + it('quotes and cuts a caller string a refusal repeats: an unknown key, an unknown source id', async () => { + const { service } = setup(); + const tools = service.knowledgeTools(); + const key = `k${'y'.repeat(4000)}\u0000`; + const keyErr = await tools.searchKnowledge({ query: 'q', [key]: 1 }, caller).catch((e) => e); + expect(keyErr).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(keyErr.message).toContain(`"k${'y'.repeat(63)}…"`); + expect(keyErr.message.length).toBeLessThan(300); + const many = Array.from({ length: 40 }, (_, i) => `unknown_${i}`); + const manyErr = await tools.searchKnowledge({ query: 'q', ...Object.fromEntries(many.map((k) => [k, 1])) }, caller).catch((e) => e); + expect(manyErr.message).toContain('and 35 more'); + expect(manyErr.message).not.toContain('unknown_39'); + const idErr = await tools.searchKnowledge({ query: 'q', sourceIds: [`s${'z'.repeat(4000)}`] }, caller).catch((e) => e); + expect(idErr).toMatchObject({ code: 'NOT_FOUND', status: 404 }); + expect(idErr.message).toContain(`"s${'z'.repeat(63)}…"`); + expect(idErr.message.length).toBeLessThan(300); + }); + + it('repeats a short caller string as its JSON escape: a quote, a newline and a NUL never come back raw', async () => { + const { service } = setup(); + const tools = service.knowledgeTools(); + const odd = 'a"b\nc\u0000d'; + const escaped = '"a\\"b\\nc\\u0000d"'; + expect(JSON.stringify(odd)).toBe(escaped); + const keyErr = await tools.searchKnowledge({ query: 'q', [odd]: 1 }, caller).catch((e) => e); + const idErr = await tools.searchKnowledge({ query: 'q', sourceIds: [odd] }, caller).catch((e) => e); + expect(keyErr).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(idErr).toMatchObject({ code: 'NOT_FOUND', status: 404 }); + for (const err of [keyErr, idErr]) { + expect(err.message).toContain(escaped); + expect(err.message).not.toContain('\n'); + expect(err.message).not.toContain('\u0000'); + } + }); +}); + +/** + * The three arguments against the real knowledge service: one exposed clause + * source over `clause` (content `body`, metadata `policy` and `status`), one + * withheld note source over `note` (metadata `author`), an engine answering + * the caller's re-read with the `readable` ids and the system freshness read + * with the rows, and an adapter ranking the hits an index would answer. + */ +describe('search_knowledge — scope, granularity and groupBy over the knowledge service', () => { + type Row = Record & { id: string }; + const CLAUSES: Row[] = [ + { id: 'c1', body: 'annual leave', policy: 'P_leave', status: 'draft' }, + { id: 'c2', body: 'sick leave', policy: 'P_leave', status: 'live' }, + { id: 'c3', body: 'travel', policy: 'P_travel', status: 'live' }, + ]; + const NOTES: Row[] = [{ id: 'n1', body: 'staff note', author: 'A' }]; + const clauses = objectSource('clauses', 'clause', { + source: { kind: 'object', object: 'clause', contentFields: ['body'], metadataFields: ['policy', 'status'] } as ObjectKnowledgeSource, + }); + const notes = objectSource('notes', 'note', { + aiExposed: false, + source: { kind: 'object', object: 'note', contentFields: ['body'], metadataFields: ['author'] } as ObjectKnowledgeSource, + }); + + /** The hit an index answers for `row`'s passage `n`: the document's metadata and stored docHash, as an adapter returns them. */ + function indexHit(source: KnowledgeSource, row: Row, n: number, score: number, headingPath?: string[]): KnowledgeHit { + const doc = recordToDocument(source, source.source as ObjectKnowledgeSource, row); + return { + chunkId: `${doc.id}#${n}`, + documentId: doc.id, + sourceId: source.id, + sourceRecordId: row.id, + score, + snippet: `${row.body as string} (${n})`, + metadata: doc.metadata, + docHash: doc.docHash, + ...(headingPath ? { headingPath } : {}), + }; + } + + function setupModes(readable: readonly string[] = ['c1', 'c2', 'c3', 'n1']) { + const tables: Record = { clause: CLAUSES, note: NOTES }; + const corpus: Record = { + clauses: [ + indexHit(clauses, CLAUSES[0], 0, 0.9, ['Leave', 'Annual']), + indexHit(clauses, CLAUSES[0], 1, 0.8), + indexHit(clauses, CLAUSES[1], 0, 0.7), + indexHit(clauses, CLAUSES[2], 0, 0.6), + ], + notes: [indexHit(notes, NOTES[0], 0, 0.99)], + }; + const asked: Array<{ source: string; opts: Record }> = []; + const adapter = { + id: 'memory', + upsert: vi.fn(async () => undefined), + delete: vi.fn(async () => undefined), + search: vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number }) => { + asked.push({ source: opts.source.id, opts: opts as unknown as Record }); + return [...(corpus[opts.source.id] ?? [])].slice(0, opts.topK); + }), + } as unknown as IKnowledgeAdapter; + const matches = (row: Row, where: Record = {}): boolean => + Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as Record[]).every((w) => matches(row, w)); + if (v !== null && typeof v === 'object') return ((v as { $in: string[] }).$in).includes(row[k] as string); + return row[k] === v; + }); + const engine = { + find: vi.fn(async (object: string, q: { where?: Record; fields?: string[]; limit?: number; context?: { isSystem?: boolean } }, o?: { context?: { isSystem?: boolean } }) => { + const system = (q.context ?? o?.context)?.isSystem === true; + const rows = (tables[object] ?? []).filter((r) => matches(r, q.where) && (system || readable.includes(r.id))); + const page = typeof q.limit === 'number' ? rows.slice(0, q.limit) : rows; + return page.map((r) => (q.fields ? Object.fromEntries(q.fields.filter((f) => f in r).map((f) => [f, r[f]])) : { ...r })); + }), + } as unknown as IDataEngine; + const service = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined, debug: () => undefined } }); + service.registerAdapter('memory', adapter); + service.registerSource(clauses); + service.registerSource(notes); + return { service, tools: service.knowledgeTools(), asked }; + } + + const SOURCES = [{ id: 'clauses', label: 'clauses label' }]; + + it('hands scope, granularity and groupBy to the service as its options of the same names', async () => { + const { service, tools } = setupModes(); + const spy = vi.spyOn(service, 'searchWithRefusals'); + const scope = [{ object: 'clause', ids: ['c1', 'c2'] }]; + await tools.searchKnowledge({ query: 'leave', scope, granularity: 'record', groupBy: 'policy', topK: 3 }, caller); + expect(spy).toHaveBeenCalledWith('leave', { + sourceIds: ['clauses'], + topK: 3, + scope, + granularity: 'record', + groupBy: 'policy', + executionContext: caller, + }); + }); + + it("granularity 'record': one hit per record, its best passage; the default stays one per passage", async () => { + const { tools } = setupModes(); + const byRecord = await tools.searchKnowledge({ query: 'q', granularity: 'record' }, caller); + expect(byRecord.hits.map((h) => [h.record?.id, h.score])).toEqual([['c1', 0.9], ['c2', 0.7], ['c3', 0.6]]); + const byChunk = await tools.searchKnowledge({ query: 'q' }, caller); + expect(byChunk.hits.map((h) => h.record?.id)).toEqual(['c1', 'c1', 'c2', 'c3']); + }); + + it("groupBy: one hit per group, carrying its groupValue and no other metadata", async () => { + const { tools } = setupModes(); + const answer = await tools.searchKnowledge({ query: 'q', groupBy: 'policy' }, caller); + expect(answer.hits.map((h) => [h.record?.id, h.groupValue])).toEqual([['c1', 'P_leave'], ['c3', 'P_travel']]); + expect(JSON.stringify(answer)).not.toContain('draft'); + }); + + it('groupBy over a file source: one hit per document, and no groupValue even where its hit carries the field', async () => { + const manuals = { + id: 'manuals', + label: 'Manuals', + adapter: 'memory', + source: { kind: 'file', uris: ['file:///manual.md'] }, + } as unknown as KnowledgeSource; + const adapter = adapterWith({ + manuals: [{ chunkId: 'manuals:m#0', documentId: 'manuals:m', sourceId: 'manuals', score: 0.95, snippet: 'manual', metadata: { policy: 'P_manual' } }], + }); + const service = new KnowledgeService({ logger: { warn: () => undefined, debug: () => undefined } }); + service.registerAdapter('memory', adapter); + service.registerSource(manuals); + const answer = await service.knowledgeTools().searchKnowledge({ query: 'q', groupBy: 'policy' }, caller); + expect(answer.hits).toEqual([{ sourceId: 'manuals', documentId: 'manuals:m', snippet: 'manual', score: 0.95 }]); + }); + + it('scope: only hits from the named records', async () => { + const { tools } = setupModes(); + const answer = await tools.searchKnowledge({ query: 'q', scope: [{ object: 'clause', ids: ['c2', 'c3'] }] }, caller); + expect(answer.hits.map((h) => h.record?.id)).toEqual(['c2', 'c3']); + }); + + it('the hit is a whitelist: no chunkId, no docHash, no metadata; headingPath where the passage has one', async () => { + const { tools } = setupModes(); + const answer = await tools.searchKnowledge({ query: 'q', groupBy: 'policy' }, caller); + expect(answer.hits[0]).toEqual({ + sourceId: 'clauses', + documentId: 'clauses:c1', + snippet: 'annual leave (0)', + score: 0.9, + record: { object: 'clause', id: 'c1' }, + headingPath: ['Leave', 'Annual'], + groupValue: 'P_leave', + }); + for (const hit of answer.hits) { + expect(hit).not.toHaveProperty('docHash'); + expect(hit).not.toHaveProperty('chunkId'); + expect(hit).not.toHaveProperty('metadata'); + } + }); + + it('reports no count of what the re-check or the scope removed: the whole answer is the hits and the sources', async () => { + // c1 is unreadable to the caller; the scope removes c3. + const { tools } = setupModes(['c2', 'c3']); + const answer = await tools.searchKnowledge( + { query: 'q', granularity: 'record', scope: [{ object: 'clause', ids: ['c1', 'c2'] }] }, + caller, + ); + expect(answer).toEqual({ + hits: [{ sourceId: 'clauses', documentId: 'clauses:c2', snippet: 'sick leave (0)', score: 0.7, record: { object: 'clause', id: 'c2' } }], + sources: SOURCES, + }); + }); + + it('a scope entry whose object only a withheld source indexes is answered as one whose object no source indexes', async () => { + const withheld = setupModes(); + const absent = setupModes(); + const a = await withheld.tools.searchKnowledge({ query: 'q', scope: [{ object: 'note', ids: ['n1'] }] }, caller); + const b = await absent.tools.searchKnowledge({ query: 'q', scope: [{ object: 'no_such_object', ids: ['n1'] }] }, caller); + expect(a).toEqual({ hits: [], sources: SOURCES }); + expect(a).toEqual(b); + expect(withheld.asked.map((x) => x.source)).toEqual(absent.asked.map((x) => x.source)); + expect(withheld.asked.map((x) => x.source)).not.toContain('notes'); + }); + + it('a groupBy field only a withheld source indexes is answered as one no source indexes', async () => { + const withheld = setupModes(); + const absent = setupModes(); + const a = await withheld.tools.searchKnowledge({ query: 'q', groupBy: 'author' }, caller); + const b = await absent.tools.searchKnowledge({ query: 'q', groupBy: 'no_such_field' }, caller); + expect(a).toEqual({ hits: [], sources: SOURCES }); + expect(a).toEqual(b); + expect(withheld.asked.map((x) => x.source)).not.toContain('notes'); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index f6d2acca5dd..f48de464aeb 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -3,6 +3,7 @@ import type { AIToolDefinition, IKnowledgeService } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { SEARCH_SCOPE_MAX_ENTRIES, SEARCH_SCOPE_MAX_IDS } from './knowledge-search-scope.js'; /** * The knowledge AI tool, `search_knowledge`, defined once with one executor @@ -32,6 +33,20 @@ import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@obje * serves the platform's own callers, which are not agents, and `aiExposed` * governs what the AGENT tool may expose. * + * ## Scope, record granularity and grouping (ADR-0161 K9, rule 2) + * + * `scope`, `granularity` and `groupBy` enter here, in the one definition, + * and are handed to `IKnowledgeService.search` as its options of the same + * names; no transport adds an argument of its own. The executor holds each to + * the bounds its definition states and refuses a malformed one + * `VALIDATION_ERROR` naming it, before the service is asked: past the + * service's own bounds, it refuses an empty scope or an entry with no ids (as + * it refuses an empty `sourceIds`), an id, object or field name longer than + * {@link SEARCH_KNOWLEDGE_MAX_NAME_LENGTH} or holding a NUL, and `groupBy` + * with `granularity: 'chunk'`. Because the executor searches only exposed + * sources, a scope entry or a `groupBy` field that only a withheld source + * would answer gets the answer one no source answers: no hits. + * * ## No second gate, none bypassed (ADR-0090 D10) * * Every call reaches data only through `IKnowledgeService.search` with the @@ -50,11 +65,44 @@ export const SEARCH_KNOWLEDGE_MAX_TOP_K = 20; /** The hits one `search_knowledge` answer carries when the call names no `topK`. */ export const SEARCH_KNOWLEDGE_DEFAULT_TOP_K = 5; +/** + * The most entries one `scope` argument holds, and the most ids one entry + * holds: the bounds `IKnowledgeService.search` holds its `scope` option to + * (`KnowledgeSearchOptions.scope`, `knowledge-search-scope.ts`), read from + * there and stated in the definition. + */ +export const SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES: number = SEARCH_SCOPE_MAX_ENTRIES; +export const SEARCH_KNOWLEDGE_MAX_SCOPE_IDS: number = SEARCH_SCOPE_MAX_IDS; + +/** + * The longest object name, record id or field name the tool takes, in UTF-16 + * code units: the length the platform stores a record's id and its object's + * name in (`sys_recycle_bin.record_id` / `object_name`, `maxLength: 255`). + * A longer one names no record, object or field, so it is refused at the + * door rather than carried into every adapter's query. + */ +export const SEARCH_KNOWLEDGE_MAX_NAME_LENGTH = 255; + +/** What one hit of a `search_knowledge` answer stands for (`KnowledgeSearchOptions.granularity`). */ +export type SearchKnowledgeGranularity = 'chunk' | 'record'; + +/** One entry of the `scope` argument: records of one object, by id. */ +export interface SearchKnowledgeScopeEntry { + object: string; + ids: string[]; +} + /** The arguments `search_knowledge` takes, as its definition's JSON Schema declares them. */ export interface SearchKnowledgeInput { query: string; sourceIds?: string[]; topK?: number; + /** Search only inside these records, or inside the children of these parent records (ADR-0161 K8, item 17). */ + scope?: SearchKnowledgeScopeEntry[]; + /** One hit per passage (`chunk`, the default) or per record (`record`) (ADR-0161 K1). */ + granularity?: SearchKnowledgeGranularity; + /** One hit per value of this metadata field instead of per record; implies `granularity: 'record'`. */ + groupBy?: string; } /** One searchable source, as a `search_knowledge` answer names it. */ @@ -78,6 +126,15 @@ export interface SearchKnowledgeHit { score: number; /** The record the passage was indexed from, for an object source: read it with the record tools. */ record?: { object: string; id: string }; + /** The headings the passage sits under, outermost first, where its document has headings. */ + headingPath?: string[]; + /** + * Under `groupBy`: the value of that field the hit's record holds — the + * group the hit stands for — as the index stores it (a string, a number, a + * list for a `multiple` lookup). Absent on a hit of a `file` / `http` + * source, which answers under `groupBy` one hit per document. + */ + groupValue?: unknown; } /** @@ -96,7 +153,12 @@ export interface SearchKnowledgeRefusedSource { /** A `search_knowledge` answer. */ export interface SearchKnowledgeOutput { - /** The passages, most relevant first, at most `topK`. */ + /** + * The hits, most relevant first, at most `topK`: passages, or one per + * record under `granularity: 'record'`, or one per group under `groupBy`. + * No count of what the permission re-check or the scope removed, and + * nothing derived from one (ADR-0161 K9, rule 6). + */ hits: SearchKnowledgeHit[]; /** Every source this tool may search; `sourceIds` takes their `id`s. */ sources: SearchKnowledgeSourceSummary[]; @@ -115,8 +177,9 @@ export interface KnowledgeTools { /** * Run one `search_knowledge` call AS `context`. Refuses, by throwing an * ADR-0112 coded error (`code` and `status`), malformed arguments - * (`VALIDATION_ERROR`, 400) and a `sourceIds` entry that names no source - * this tool may search (`NOT_FOUND`, 404). + * (`VALIDATION_ERROR`, 400, naming the argument) and a `sourceIds` entry + * that names no source this tool may search (`NOT_FOUND`, 404). A caller's + * string a refusal repeats is quoted and cut to 64 characters. */ searchKnowledge(input: unknown, context?: ExecutionContext): Promise; } @@ -133,7 +196,22 @@ const SEARCH_KNOWLEDGE_DESCRIPTION = + 'person\'s own permissions decide, never more. No passage means nothing the caller may read matched: say so ' + 'rather than answer from general knowledge. A source listed in `refused` could not be searched (its index is ' + 'being rebuilt, for example): its passages are missing, not absent, so say that this source could not be ' - + 'searched rather than that it holds nothing.'; + + 'searched rather than that it holds nothing. ' + + 'To find which records match rather than which passages (which policies, not which clauses), send ' + + '`granularity: "record"`: one hit per record, its best passage, and `topK` counts records. To group by a ' + + 'field the source indexes with its passages instead (one hit per policy for a search over clauses, say), send ' + + '`groupBy` with that field\'s name: one hit per value, which the hit carries as `groupValue` (the value as the ' + + 'index stores it: a string, a number or a list). A source of indexed records that does not index that field ' + + 'answers nothing for that search; a file or web source still answers, one hit per document and with no ' + + '`groupValue`. To look inside records you already know (one ' + + 'policy, say), send `scope`: a list of `{ object, ids }` entries, at most ' + + `${SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES} entries of at most ${SEARCH_KNOWLEDGE_MAX_SCOPE_IDS} ids. An entry naming ` + + 'the object a source indexes searches those records\' passages; an entry naming a parent object searches the ' + + 'passages of records that link to those parents (the clauses of a policy). A hit carries `headingPath`, the ' + + 'headings its passage sits under, where its document has headings.'; + +/** A caller's id or name, as the definition bounds it. */ +const NAME_SCHEMA = Object.freeze({ type: 'string', minLength: 1, maxLength: SEARCH_KNOWLEDGE_MAX_NAME_LENGTH }); const SEARCH_KNOWLEDGE_PARAMETERS: Record = Object.freeze({ type: 'object', @@ -153,7 +231,37 @@ const SEARCH_KNOWLEDGE_PARAMETERS: Record = Object.freeze({ type: 'integer', minimum: 1, maximum: SEARCH_KNOWLEDGE_MAX_TOP_K, - description: `At most this many passages (default ${SEARCH_KNOWLEDGE_DEFAULT_TOP_K})`, + description: `At most this many hits (default ${SEARCH_KNOWLEDGE_DEFAULT_TOP_K}): passages, or records or groups under \`granularity: "record"\` or \`groupBy\``, + }, + scope: { + type: 'array', + minItems: 1, + maxItems: SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES, + items: { + type: 'object', + properties: { + object: { ...NAME_SCHEMA, description: 'The object the records belong to: the indexed object, or a parent it links to' }, + ids: { + type: 'array', + minItems: 1, + maxItems: SEARCH_KNOWLEDGE_MAX_SCOPE_IDS, + items: NAME_SCHEMA, + description: 'The records\' ids', + }, + }, + required: ['object', 'ids'], + additionalProperties: false, + }, + description: 'Only inside these records (any entry); omit to search everything', + }, + granularity: { + type: 'string', + enum: ['chunk', 'record'], + description: 'One hit per passage (`chunk`, the default) or per record (`record`)', + }, + groupBy: { + ...NAME_SCHEMA, + description: 'One hit per value of this indexed field instead of per record; not with `granularity: "chunk"`', }, }, required: ['query'], @@ -186,7 +294,74 @@ export function refusal(code: 'VALIDATION_ERROR' | 'NOT_FOUND', status: 400 | 40 return Object.assign(new Error(message), { code, status }); } -const INPUT_KEYS: ReadonlySet = new Set(['query', 'sourceIds', 'topK']); +const INPUT_KEYS: ReadonlySet = new Set(['query', 'sourceIds', 'topK', 'scope', 'granularity', 'groupBy']); +const SCOPE_ENTRY_KEYS: ReadonlySet = new Set(['object', 'ids']); + +/** + * A caller's string as a refusal repeats it: JSON-quoted, so a control + * character reads as its escape and never as a raw byte, and cut to 64 + * characters, so a long argument never comes back whole. + */ +function quoted(value: string): string { + return JSON.stringify(value.length > 64 ? `${value.slice(0, 64)}…` : value); +} + +/** At most five caller strings, quoted, then how many more there were. */ +function quotedList(values: readonly string[]): string { + const shown = values.slice(0, 5).map(quoted).join(', '); + return values.length > 5 ? `${shown} and ${values.length - 5} more` : shown; +} + +/** + * Whether `value` is an id or name the tool takes: a non-empty string of at + * most {@link SEARCH_KNOWLEDGE_MAX_NAME_LENGTH} characters with no NUL. A NUL + * names no record, object or field, and a SQL store refuses the statement + * that carries one, so it is refused here rather than answered as a failed + * search of every source the scope reaches. + */ +function isName(value: unknown): value is string { + return typeof value === 'string' + && value.length > 0 + && value.length <= SEARCH_KNOWLEDGE_MAX_NAME_LENGTH + && !value.includes('\u0000'); +} + +const NAME_RULE = `a non-empty string of at most ${SEARCH_KNOWLEDGE_MAX_NAME_LENGTH} characters, with no NUL character`; + +/** The `scope` argument, or a `VALIDATION_ERROR` naming `scope` and what is wrong in it. */ +function parseScope(scope: unknown): SearchKnowledgeScopeEntry[] { + const refuse = (what: string): Error => refusal('VALIDATION_ERROR', 400, `\`scope\` ${what}`); + if (!Array.isArray(scope)) throw refuse('is a list of { object, ids } entries.'); + // An empty scope, or an entry with no ids, names no record. Refused rather + // than answered with no passage, which this tool's description tells the + // model to report as "nothing matched" (as an empty `sourceIds` is). + if (scope.length === 0) { + throw refuse('names no record: omit it to search everything, or name at least one { object, ids } entry.'); + } + if (scope.length > SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES) { + throw refuse(`takes at most ${SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES} entries, got ${scope.length}.`); + } + return scope.map((entry: unknown, i): SearchKnowledgeScopeEntry => { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { + throw refuse(`entry ${i} is not an object; each entry is { object, ids }.`); + } + const unknownKeys = Object.keys(entry).filter((key) => !SCOPE_ENTRY_KEYS.has(key)); + if (unknownKeys.length > 0) { + throw refuse(`entry ${i} has ${quotedList(unknownKeys)}; an entry takes only \`object\` and \`ids\`.`); + } + const { object, ids } = entry as { object?: unknown; ids?: unknown }; + if (!isName(object)) throw refuse(`entry ${i} needs \`object\`, ${NAME_RULE}, naming an object.`); + if (!Array.isArray(ids) || ids.length === 0) { + throw refuse(`entry ${i} needs \`ids\`, a list of at least one record id of ${quoted(object)}.`); + } + if (ids.length > SEARCH_KNOWLEDGE_MAX_SCOPE_IDS) { + throw refuse(`entry ${i} takes at most ${SEARCH_KNOWLEDGE_MAX_SCOPE_IDS} ids, got ${ids.length}.`); + } + const bad = ids.findIndex((id) => !isName(id)); + if (bad >= 0) throw refuse(`entry ${i} id ${bad} is not a record id: each id is ${NAME_RULE}.`); + return { object, ids: [...(ids as string[])] }; + }); +} /** The call's arguments, or a `VALIDATION_ERROR` naming the first one that is wrong. */ function parseInput(input: unknown): SearchKnowledgeInput { @@ -199,8 +374,8 @@ function parseInput(input: unknown): SearchKnowledgeInput { throw refusal( 'VALIDATION_ERROR', 400, - `${SEARCH_KNOWLEDGE_TOOL_NAME} does not take ${unknownKeys.map((k) => `\`${k}\``).join(', ')}; it takes ` - + '`query`, `sourceIds` and `topK`.', + `${SEARCH_KNOWLEDGE_TOOL_NAME} does not take ${quotedList(unknownKeys)}; it takes ` + + '`query`, `sourceIds`, `topK`, `scope`, `granularity` and `groupBy`.', ); } const query = typeof record.query === 'string' ? record.query.trim() : ''; @@ -231,6 +406,27 @@ function parseInput(input: unknown): SearchKnowledgeInput { } parsed.topK = topK; } + if (record.scope !== undefined) parsed.scope = parseScope(record.scope); + if (record.granularity !== undefined) { + if (record.granularity !== 'chunk' && record.granularity !== 'record') { + throw refusal('VALIDATION_ERROR', 400, '`granularity` is "chunk" (one hit per passage) or "record" (one hit per record).'); + } + parsed.granularity = record.granularity; + } + if (record.groupBy !== undefined) { + if (!isName(record.groupBy)) { + throw refusal('VALIDATION_ERROR', 400, `\`groupBy\` names a field the source indexes: ${NAME_RULE}.`); + } + if (parsed.granularity === 'chunk') { + throw refusal( + 'VALIDATION_ERROR', + 400, + `\`groupBy\` ${quoted(record.groupBy)} answers one hit per group, so it does not combine with \`granularity: "chunk"\`: ` + + 'omit `granularity`, or send "record".', + ); + } + parsed.groupBy = record.groupBy; + } return parsed; } @@ -247,9 +443,28 @@ function summarize(source: KnowledgeSource): SearchKnowledgeSourceSummary { }; } -function hitOf(hit: KnowledgeHit, sources: ReadonlyMap): SearchKnowledgeHit { +/** + * One hit as the answer carries it: a whitelist, member by member. Nothing + * else of the service's hit reaches the agent — not its `chunkId`, not the + * stored `docHash` the record-level freshness check compares, and not its + * `metadata`, of which only the `groupBy` field's value is answered, and only + * for an object source that lists that field (source admission holds every + * listed field queryable by the caller, ADR-0161 K8). + */ +function hitOf( + hit: KnowledgeHit, + sources: ReadonlyMap, + groupBy: string | undefined, +): SearchKnowledgeHit { const source = sources.get(hit.sourceId); - const object = source?.source.kind === 'object' ? (source.source as ObjectKnowledgeSource).object : undefined; + const objSource = source?.source.kind === 'object' ? (source.source as ObjectKnowledgeSource) : undefined; + const object = objSource?.object; + const headingPath = Array.isArray(hit.headingPath) && hit.headingPath.every((h) => typeof h === 'string') + ? [...hit.headingPath] + : undefined; + const groupValue = groupBy !== undefined && objSource?.metadataFields?.includes(groupBy) + ? hit.metadata?.[groupBy] + : undefined; return { sourceId: hit.sourceId, documentId: hit.documentId, @@ -257,6 +472,8 @@ function hitOf(hit: KnowledgeHit, sources: ReadonlyMap) snippet: hit.snippet, score: hit.score, ...(object && hit.sourceRecordId ? { record: { object, id: hit.sourceRecordId } } : {}), + ...(headingPath && headingPath.length > 0 ? { headingPath } : {}), + ...(groupValue !== undefined && groupValue !== null ? { groupValue } : {}), }; } @@ -282,7 +499,7 @@ export function createKnowledgeTools(service: IKnowledgeService | (() => IKnowle return { definitions: getKnowledgeToolDefinitions(), async searchKnowledge(input, context) { - const { query, sourceIds, topK } = parseInput(input); + const { query, sourceIds, topK, scope, granularity, groupBy } = parseInput(input); const knowledge = resolve(); const searchable = searchableSources(knowledge); const byId = new Map(searchable.map((source) => [source.id, source] as const)); @@ -293,9 +510,9 @@ export function createKnowledgeTools(service: IKnowledgeService | (() => IKnowle throw refusal( 'NOT_FOUND', 404, - `No knowledge source this tool may search is named ${unknown.map((id) => `"${id}"`).join(', ')}. ` + `No knowledge source this tool may search is named ${quotedList(unknown)}. ` + (summaries.length > 0 - ? `Searchable sources: ${summaries.map((s) => `"${s.id}"`).join(', ')}; omit \`sourceIds\` to search them all.` + ? `Searchable sources: ${summaries.map((s) => JSON.stringify(s.id)).join(', ')}; omit \`sourceIds\` to search them all.` : 'No source is searchable here.'), ); } @@ -304,9 +521,15 @@ export function createKnowledgeTools(service: IKnowledgeService | (() => IKnowle if (targets.length === 0) return { hits: [], sources: summaries }; // [ADR-0090 D10] As the caller: the service re-checks every object-source // hit against this context's row-level security. + // [ADR-0161 K9, rule 3] `targets` are exposed sources only, so a `scope` + // entry or a `groupBy` field that only a withheld source would answer is + // answered as one no source answers: no hits, the same answer. const searchOpts = { sourceIds: targets, topK: topK ?? SEARCH_KNOWLEDGE_DEFAULT_TOP_K, + ...(scope ? { scope } : {}), + ...(granularity ? { granularity } : {}), + ...(groupBy !== undefined ? { groupBy } : {}), ...(context ? { executionContext: context } : {}), }; // [ADR-0161 K7, rule 5] A refused source is named, never answered as @@ -319,7 +542,7 @@ export function createKnowledgeTools(service: IKnowledgeService | (() => IKnowle .filter((r) => byId.has(r.sourceId)) .map((r) => ({ sourceId: r.sourceId, code: r.code, message: r.message })); return { - hits: report.hits.filter((hit) => byId.has(hit.sourceId)).map((hit) => hitOf(hit, byId)), + hits: report.hits.filter((hit) => byId.has(hit.sourceId)).map((hit) => hitOf(hit, byId, groupBy)), sources: summaries, ...(refused.length > 0 ? { refused } : {}), }; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 97e1ba06f76..6c75bb6422e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1469,6 +1469,9 @@ importers: '@objectstack/service-analytics': specifier: workspace:* version: link:../services/service-analytics + '@objectstack/service-knowledge': + specifier: workspace:* + version: link:../services/service-knowledge '@objectstack/service-record-context': specifier: workspace:* version: link:../services/service-record-context