From c6cdc71c00834ec74856ef3fb99eac35daa45592 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:50:46 +0000 Subject: [PATCH 1/3] feat(service-knowledge): a search_knowledge hit carries its source's declared metadataFields values Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../src/__tests__/knowledge-tools.test.ts | 109 ++++++++++++++++-- .../service-knowledge/src/knowledge-tools.ts | 49 +++++++- 2 files changed, 143 insertions(+), 15 deletions(-) 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 581733e84f2..b027f228861 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -21,7 +21,7 @@ import { createKnowledgeTools, getKnowledgeToolDefinitions, } from '../knowledge-tools.js'; -import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { IDataEngine, IKnowledgeAdapter, IKnowledgeService } from '@objectstack/spec/contracts'; import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { PLATFORM_TOOLS_BY_PACKAGE } from '@objectstack/spec/system'; @@ -304,7 +304,7 @@ describe('search_knowledge — scope, granularity and groupBy: the definition', 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`']) { + for (const name of ['`scope`', '`granularity: "record"`', '`groupBy`', '`groupValue`', '`headingPath`', '`metadata`']) { expect(description).toContain(name); } }); @@ -423,7 +423,16 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge }; } - function setupModes(readable: readonly string[] = ['c1', 'c2', 'c3', 'n1']) { + /** + * `declared` is what the registered clause source lists in `metadataFields` + * now; the corpus was indexed under `['policy', 'status']` whatever it says. + * `queryable` answers the caller's queryable fields per object (absent: no + * security service, so every unmasked field is queryable). + */ + function setupModes( + readable: readonly string[] = ['c1', 'c2', 'c3', 'n1'], + opts: { declared?: string[]; queryable?: (object: string, ctx?: ExecutionContext) => string[] } = {}, + ) { const tables: Record = { clause: CLAUSES, note: NOTES }; const corpus: Record = { clauses: [ @@ -458,9 +467,19 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge 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 } }); + const service = new KnowledgeService({ + dataEngine: engine, + logger: { warn: () => undefined, debug: () => undefined }, + ...(opts.queryable + ? { resolveSecurity: () => ({ getQueryableFields: async (object: string, ctx?: ExecutionContext) => opts.queryable!(object, ctx) }) } + : {}), + }); service.registerAdapter('memory', adapter); - service.registerSource(clauses); + service.registerSource( + opts.declared + ? { ...clauses, source: { ...(clauses.source as ObjectKnowledgeSource), metadataFields: opts.declared } } + : clauses, + ); service.registerSource(notes); return { service, tools: service.knowledgeTools(), asked }; } @@ -490,11 +509,10 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge 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 () => { + it('groupBy: one hit per group, carrying its groupValue', 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('scope: only hits from the named records', async () => { @@ -503,7 +521,7 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge 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 () => { + it('the hit is a whitelist: no chunkId, no docHash, only the listed 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({ @@ -514,11 +532,11 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge record: { object: 'clause', id: 'c1' }, headingPath: ['Leave', 'Annual'], groupValue: 'P_leave', + metadata: { policy: 'P_leave', status: 'draft' }, }); for (const hit of answer.hits) { expect(hit).not.toHaveProperty('docHash'); expect(hit).not.toHaveProperty('chunkId'); - expect(hit).not.toHaveProperty('metadata'); } }); @@ -530,7 +548,14 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge caller, ); expect(answer).toEqual({ - hits: [{ sourceId: 'clauses', documentId: 'clauses:c2', snippet: 'sick leave (0)', score: 0.7, record: { object: 'clause', id: 'c2' } }], + hits: [{ + sourceId: 'clauses', + documentId: 'clauses:c2', + snippet: 'sick leave (0)', + score: 0.7, + record: { object: 'clause', id: 'c2' }, + metadata: { policy: 'P_leave', status: 'live' }, + }], sources: SOURCES, }); }); @@ -555,4 +580,68 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge expect(a).toEqual(b); expect(withheld.asked.map((x) => x.source)).not.toContain('notes'); }); + + describe('a hit carries the values of the fields its source lists in `metadataFields`', () => { + it('every hit of an indexed record carries exactly the listed fields, so a clause names its policy with no record read', async () => { + const { tools } = setupModes(); + const answer = await tools.searchKnowledge({ query: 'q' }, caller); + expect(answer.hits.map((h) => [h.record?.id, h.metadata])).toEqual([ + ['c1', { policy: 'P_leave', status: 'draft' }], + ['c1', { policy: 'P_leave', status: 'draft' }], + ['c2', { policy: 'P_leave', status: 'live' }], + ['c3', { policy: 'P_travel', status: 'live' }], + ]); + // In the order the source lists them, and only those. + for (const hit of answer.hits) expect(Object.keys(hit.metadata ?? {})).toEqual(['policy', 'status']); + }); + + it('a field the source no longer lists is not answered, though the index still stores it', async () => { + // The corpus was indexed under ['policy', 'status']; the source lists only `policy` now. + const { tools } = setupModes(undefined, { declared: ['policy'] }); + const answer = await tools.searchKnowledge({ query: 'q' }, caller); + expect(answer.hits.map((h) => h.metadata)).toEqual([ + { policy: 'P_leave' }, { policy: 'P_leave' }, { policy: 'P_leave' }, { policy: 'P_travel' }, + ]); + expect(JSON.stringify(answer)).not.toContain('draft'); + // Listing none answers no `metadata` member at all. + const none = await setupModes(undefined, { declared: [] }).tools.searchKnowledge({ query: 'q' }, caller); + expect(none.hits.length).toBe(4); + for (const hit of none.hits) expect(hit).not.toHaveProperty('metadata'); + }); + + it('a listed field whose stored value is null or absent is left out; a stored key no listed field names never is answered', async () => { + const source: KnowledgeSource = objectSource('clauses', 'clause', { + source: { kind: 'object', object: 'clause', content: ['body'], metadataFields: ['policy', 'owner', 'kind', 'constructor'] } as ObjectKnowledgeSource, + }); + const stored = (metadata: Record): KnowledgeHit => ({ ...hit('clauses', 'c1', 0.9), metadata }); + const service = { + listSources: () => [source], + search: async () => [ + stored({ policy: 'P_leave', owner: null, secret: 's3cr3t' }), + stored({ owner: null }), + ], + } as unknown as IKnowledgeService; + const answer = await createKnowledgeTools(service).searchKnowledge({ query: 'q' }, caller); + expect(answer.hits[0].metadata).toEqual({ policy: 'P_leave' }); + expect(answer.hits[1]).not.toHaveProperty('metadata'); + expect(JSON.stringify(answer)).not.toContain('s3cr3t'); + }); + + it('field gate: a caller who may not query one listed field gets no hit from that source; one who may, gets its values', async () => { + const member = { ...caller, userId: 'u_member' } as ExecutionContext; + const manager = { ...caller, userId: 'u_manager' } as ExecutionContext; + // Without a schema the title is read from a field named `title`, a served field the gate asks about too. + const all = ['id', 'title', 'body', 'policy', 'status', 'author']; + const queryable = (_object: string, ctx?: ExecutionContext) => + ctx?.userId === 'u_member' ? all.filter((f) => f !== 'status') : all; + const gated = setupModes(undefined, { queryable }); + const refused = await gated.tools.searchKnowledge({ query: 'q' }, member); + expect(refused).toEqual({ hits: [], sources: SOURCES }); + expect(gated.asked.map((x) => x.source)).not.toContain('clauses'); // never searched, not searched-then-dropped + const served = await gated.tools.searchKnowledge({ query: 'q', granularity: 'record' }, manager); + expect(served.hits.map((h) => h.metadata)).toEqual([ + { policy: 'P_leave', status: 'draft' }, { policy: 'P_leave', status: 'live' }, { policy: 'P_travel', status: 'live' }, + ]); + }); + }); }); diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index 17530eb5124..b07dfa562bc 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -147,6 +147,15 @@ export interface SearchKnowledgeHit { * list for a `multiple` lookup). */ groupValue?: unknown; + /** + * For a hit of an indexed record: the values of the fields its source lists + * in `metadataFields` (the parent a child record links to, its status), as + * the index stores them, keyed by field name, in the order the source lists + * them. Only fields the source lists now are answered; a field it lists + * whose stored value is absent or null is left out, and so is the member + * when no listed field has a value. + */ + metadata?: Record; } /** @@ -220,7 +229,10 @@ const SEARCH_KNOWLEDGE_DESCRIPTION = + `${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.'; + + 'headings its passage sits under, where its document has headings. A hit of an indexed record also carries ' + + '`metadata`: the values, by field name, of the fields its source indexes with its passages (for a clause, the ' + + 'policy it belongs to), as the index stores them. Read the parent or the status a hit names there: it needs no ' + + 'record read.'; /** 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 }); @@ -481,13 +493,38 @@ function summarize({ id, source }: NamedSource): SearchKnowledgeSourceSummary { }; } +/** + * The values of the fields `objSource` lists in `metadataFields` that the + * stored `metadata` carries, in the order the source lists them: a field the + * source lists now, never a stored key it no longer lists. An own key only, so + * a listed name that is also an `Object.prototype` member never answers the + * prototype's value. Absent and null values are left out; `undefined` when + * none is left. + */ +function declaredMetadataOf( + stored: Record | undefined, + listed: readonly string[] | undefined, +): Record | undefined { + if (!stored || !listed || listed.length === 0) return undefined; + const entries: Array<[string, unknown]> = []; + for (const field of new Set(listed)) { + if (!Object.prototype.hasOwnProperty.call(stored, field)) continue; + const value = stored[field]; + if (value !== undefined && value !== null) entries.push([field, value]); + } + return entries.length > 0 ? Object.fromEntries(entries) : undefined; +} + /** * 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 a source that lists that field (source admission holds every - * listed field queryable by the caller, ADR-0161 K8). + * stored `docHash` the record-level freshness check compares, and of its + * stored `metadata` only the fields its source lists in `metadataFields` now + * (`metadata`, {@link declaredMetadataOf}) and, under `groupBy`, that field's + * value (`groupValue`), only for a source that lists that field. Neither + * serves a field the caller may not query: source admission holds every + * listed field queryable by the caller before the source is searched at all + * (ADR-0161 K8, `admitSourceFields`). */ function hitOf( hit: KnowledgeHit, @@ -502,6 +539,7 @@ function hitOf( const groupValue = groupBy !== undefined && objSource?.metadataFields?.includes(groupBy) ? hit.metadata?.[groupBy] : undefined; + const metadata = declaredMetadataOf(hit.metadata, objSource?.metadataFields); return { sourceId: hit.sourceId, documentId: hit.documentId, @@ -511,6 +549,7 @@ function hitOf( ...(object && hit.sourceRecordId ? { record: { object, id: hit.sourceRecordId } } : {}), ...(headingPath && headingPath.length > 0 ? { headingPath } : {}), ...(groupValue !== undefined && groupValue !== null ? { groupValue } : {}), + ...(metadata ? { metadata } : {}), }; } From 1c8472c7ea912421d5fb03fa381a40ff4f4639ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:04:15 +0000 Subject: [PATCH 2/3] docs(service-knowledge): changeset and knowledge-rag hit shape for the declared metadata values Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/38291-search-knowledge-hit-metadata.md | 15 +++++++++++++++ content/docs/ai/knowledge-rag.mdx | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 .changeset/38291-search-knowledge-hit-metadata.md diff --git a/.changeset/38291-search-knowledge-hit-metadata.md b/.changeset/38291-search-knowledge-hit-metadata.md new file mode 100644 index 00000000000..4237e5924ae --- /dev/null +++ b/.changeset/38291-search-knowledge-hit-metadata.md @@ -0,0 +1,15 @@ +--- +'@objectstack/service-knowledge': patch +--- + +feat(service-knowledge): a `search_knowledge` hit carries the values of its source's `metadataFields` + +Clause-②: yes (widening) +Metadata-protocol: none + +Each `search_knowledge` hit of an indexed record gains `metadata`: the values, keyed by field name, of the fields its knowledge source lists in `metadataFields` now, read from the metadata the index already stores with the passage. A hit of a clause therefore names its policy (or status, or owning unit) directly, and the model no longer needs a `query_records` round on the clause ids to find the parent record. + +- Only fields the source lists now are answered: a key the index still stores for a field the source no longer lists is not. +- A listed field whose stored value is absent or `null` is left out; a hit with no such value carries no `metadata` member. A file or web source's hit carries none. +- No new argument and no live record read. Source admission (ADR-0161 K8, `admitSourceFields`) already requires every listed `metadataFields` member to be queryable by the caller before the source is searched, so no value the caller could not query is served. +- `groupValue` under `groupBy` is unchanged. The tool's description now tells the model that a hit carries these values. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 104919559c3..504e08b1c96 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -206,7 +206,7 @@ An AI client searches through one tool, `search_knowledge`, defined once by the | `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. +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. A hit of an indexed record carries `metadata` too: the values of the fields its source lists in `metadataFields` now, by field name, as the index stores them (a stored field the source no longer lists, and a null value, are left out), so a clause's hit names its policy without a record read. Source admission has already required the caller to be able to query every one of those fields before the source is searched. 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": From 5282883f38580bad2195589f1628b29e38bc7ebc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:43:04 +0000 Subject: [PATCH 3/3] =?UTF-8?q?chore(changeset):=20carry=20the=20claim's?= =?UTF-8?q?=20Clause-=E2=91=A1=20line=20verbatim?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/38291-search-knowledge-hit-metadata.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/38291-search-knowledge-hit-metadata.md b/.changeset/38291-search-knowledge-hit-metadata.md index 4237e5924ae..fa0db5e6533 100644 --- a/.changeset/38291-search-knowledge-hit-metadata.md +++ b/.changeset/38291-search-knowledge-hit-metadata.md @@ -4,7 +4,7 @@ feat(service-knowledge): a `search_knowledge` hit carries the values of its source's `metadataFields` -Clause-②: yes (widening) +Clause-②: yes (widening) — each `search_knowledge` hit gains the values of its source's declared `metadataFields` Metadata-protocol: none Each `search_knowledge` hit of an indexed record gains `metadata`: the values, keyed by field name, of the fields its knowledge source lists in `metadataFields` now, read from the metadata the index already stores with the passage. A hit of a clause therefore names its policy (or status, or owning unit) directly, and the model no longer needs a `query_records` round on the clause ids to find the parent record.