Skip to content

Commit c6cdc71

Browse files
committed
feat(service-knowledge): a search_knowledge hit carries its source's declared metadataFields values
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
1 parent 600197a commit c6cdc71

2 files changed

Lines changed: 143 additions & 15 deletions

File tree

‎packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts‎

Lines changed: 99 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
createKnowledgeTools,
2222
getKnowledgeToolDefinitions,
2323
} from '../knowledge-tools.js';
24-
import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts';
24+
import type { IDataEngine, IKnowledgeAdapter, IKnowledgeService } from '@objectstack/spec/contracts';
2525
import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai';
2626
import type { ExecutionContext } from '@objectstack/spec/kernel';
2727
import { PLATFORM_TOOLS_BY_PACKAGE } from '@objectstack/spec/system';
@@ -304,7 +304,7 @@ describe('search_knowledge — scope, granularity and groupBy: the definition',
304304

305305
it('names each argument, and each hit member the new modes add, in the description', () => {
306306
const [{ description }] = getKnowledgeToolDefinitions();
307-
for (const name of ['`scope`', '`granularity: "record"`', '`groupBy`', '`groupValue`', '`headingPath`']) {
307+
for (const name of ['`scope`', '`granularity: "record"`', '`groupBy`', '`groupValue`', '`headingPath`', '`metadata`']) {
308308
expect(description).toContain(name);
309309
}
310310
});
@@ -423,7 +423,16 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge
423423
};
424424
}
425425

426-
function setupModes(readable: readonly string[] = ['c1', 'c2', 'c3', 'n1']) {
426+
/**
427+
* `declared` is what the registered clause source lists in `metadataFields`
428+
* now; the corpus was indexed under `['policy', 'status']` whatever it says.
429+
* `queryable` answers the caller's queryable fields per object (absent: no
430+
* security service, so every unmasked field is queryable).
431+
*/
432+
function setupModes(
433+
readable: readonly string[] = ['c1', 'c2', 'c3', 'n1'],
434+
opts: { declared?: string[]; queryable?: (object: string, ctx?: ExecutionContext) => string[] } = {},
435+
) {
427436
const tables: Record<string, Row[]> = { clause: CLAUSES, note: NOTES };
428437
const corpus: Record<string, KnowledgeHit[]> = {
429438
clauses: [
@@ -458,9 +467,19 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge
458467
return page.map((r) => (q.fields ? Object.fromEntries(q.fields.filter((f) => f in r).map((f) => [f, r[f]])) : { ...r }));
459468
}),
460469
} as unknown as IDataEngine;
461-
const service = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined, debug: () => undefined } });
470+
const service = new KnowledgeService({
471+
dataEngine: engine,
472+
logger: { warn: () => undefined, debug: () => undefined },
473+
...(opts.queryable
474+
? { resolveSecurity: () => ({ getQueryableFields: async (object: string, ctx?: ExecutionContext) => opts.queryable!(object, ctx) }) }
475+
: {}),
476+
});
462477
service.registerAdapter('memory', adapter);
463-
service.registerSource(clauses);
478+
service.registerSource(
479+
opts.declared
480+
? { ...clauses, source: { ...(clauses.source as ObjectKnowledgeSource), metadataFields: opts.declared } }
481+
: clauses,
482+
);
464483
service.registerSource(notes);
465484
return { service, tools: service.knowledgeTools(), asked };
466485
}
@@ -490,11 +509,10 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge
490509
expect(byChunk.hits.map((h) => h.record?.id)).toEqual(['c1', 'c1', 'c2', 'c3']);
491510
});
492511

493-
it("groupBy: one hit per group, carrying its groupValue and no other metadata", async () => {
512+
it('groupBy: one hit per group, carrying its groupValue', async () => {
494513
const { tools } = setupModes();
495514
const answer = await tools.searchKnowledge({ query: 'q', groupBy: 'policy' }, caller);
496515
expect(answer.hits.map((h) => [h.record?.id, h.groupValue])).toEqual([['c1', 'P_leave'], ['c3', 'P_travel']]);
497-
expect(JSON.stringify(answer)).not.toContain('draft');
498516
});
499517

500518
it('scope: only hits from the named records', async () => {
@@ -503,7 +521,7 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge
503521
expect(answer.hits.map((h) => h.record?.id)).toEqual(['c2', 'c3']);
504522
});
505523

506-
it('the hit is a whitelist: no chunkId, no docHash, no metadata; headingPath where the passage has one', async () => {
524+
it('the hit is a whitelist: no chunkId, no docHash, only the listed metadata; headingPath where the passage has one', async () => {
507525
const { tools } = setupModes();
508526
const answer = await tools.searchKnowledge({ query: 'q', groupBy: 'policy' }, caller);
509527
expect(answer.hits[0]).toEqual({
@@ -514,11 +532,11 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge
514532
record: { object: 'clause', id: 'c1' },
515533
headingPath: ['Leave', 'Annual'],
516534
groupValue: 'P_leave',
535+
metadata: { policy: 'P_leave', status: 'draft' },
517536
});
518537
for (const hit of answer.hits) {
519538
expect(hit).not.toHaveProperty('docHash');
520539
expect(hit).not.toHaveProperty('chunkId');
521-
expect(hit).not.toHaveProperty('metadata');
522540
}
523541
});
524542

@@ -530,7 +548,14 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge
530548
caller,
531549
);
532550
expect(answer).toEqual({
533-
hits: [{ sourceId: 'clauses', documentId: 'clauses:c2', snippet: 'sick leave (0)', score: 0.7, record: { object: 'clause', id: 'c2' } }],
551+
hits: [{
552+
sourceId: 'clauses',
553+
documentId: 'clauses:c2',
554+
snippet: 'sick leave (0)',
555+
score: 0.7,
556+
record: { object: 'clause', id: 'c2' },
557+
metadata: { policy: 'P_leave', status: 'live' },
558+
}],
534559
sources: SOURCES,
535560
});
536561
});
@@ -555,4 +580,68 @@ describe('search_knowledge — scope, granularity and groupBy over the knowledge
555580
expect(a).toEqual(b);
556581
expect(withheld.asked.map((x) => x.source)).not.toContain('notes');
557582
});
583+
584+
describe('a hit carries the values of the fields its source lists in `metadataFields`', () => {
585+
it('every hit of an indexed record carries exactly the listed fields, so a clause names its policy with no record read', async () => {
586+
const { tools } = setupModes();
587+
const answer = await tools.searchKnowledge({ query: 'q' }, caller);
588+
expect(answer.hits.map((h) => [h.record?.id, h.metadata])).toEqual([
589+
['c1', { policy: 'P_leave', status: 'draft' }],
590+
['c1', { policy: 'P_leave', status: 'draft' }],
591+
['c2', { policy: 'P_leave', status: 'live' }],
592+
['c3', { policy: 'P_travel', status: 'live' }],
593+
]);
594+
// In the order the source lists them, and only those.
595+
for (const hit of answer.hits) expect(Object.keys(hit.metadata ?? {})).toEqual(['policy', 'status']);
596+
});
597+
598+
it('a field the source no longer lists is not answered, though the index still stores it', async () => {
599+
// The corpus was indexed under ['policy', 'status']; the source lists only `policy` now.
600+
const { tools } = setupModes(undefined, { declared: ['policy'] });
601+
const answer = await tools.searchKnowledge({ query: 'q' }, caller);
602+
expect(answer.hits.map((h) => h.metadata)).toEqual([
603+
{ policy: 'P_leave' }, { policy: 'P_leave' }, { policy: 'P_leave' }, { policy: 'P_travel' },
604+
]);
605+
expect(JSON.stringify(answer)).not.toContain('draft');
606+
// Listing none answers no `metadata` member at all.
607+
const none = await setupModes(undefined, { declared: [] }).tools.searchKnowledge({ query: 'q' }, caller);
608+
expect(none.hits.length).toBe(4);
609+
for (const hit of none.hits) expect(hit).not.toHaveProperty('metadata');
610+
});
611+
612+
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 () => {
613+
const source: KnowledgeSource = objectSource('clauses', 'clause', {
614+
source: { kind: 'object', object: 'clause', content: ['body'], metadataFields: ['policy', 'owner', 'kind', 'constructor'] } as ObjectKnowledgeSource,
615+
});
616+
const stored = (metadata: Record<string, unknown>): KnowledgeHit => ({ ...hit('clauses', 'c1', 0.9), metadata });
617+
const service = {
618+
listSources: () => [source],
619+
search: async () => [
620+
stored({ policy: 'P_leave', owner: null, secret: 's3cr3t' }),
621+
stored({ owner: null }),
622+
],
623+
} as unknown as IKnowledgeService;
624+
const answer = await createKnowledgeTools(service).searchKnowledge({ query: 'q' }, caller);
625+
expect(answer.hits[0].metadata).toEqual({ policy: 'P_leave' });
626+
expect(answer.hits[1]).not.toHaveProperty('metadata');
627+
expect(JSON.stringify(answer)).not.toContain('s3cr3t');
628+
});
629+
630+
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 () => {
631+
const member = { ...caller, userId: 'u_member' } as ExecutionContext;
632+
const manager = { ...caller, userId: 'u_manager' } as ExecutionContext;
633+
// Without a schema the title is read from a field named `title`, a served field the gate asks about too.
634+
const all = ['id', 'title', 'body', 'policy', 'status', 'author'];
635+
const queryable = (_object: string, ctx?: ExecutionContext) =>
636+
ctx?.userId === 'u_member' ? all.filter((f) => f !== 'status') : all;
637+
const gated = setupModes(undefined, { queryable });
638+
const refused = await gated.tools.searchKnowledge({ query: 'q' }, member);
639+
expect(refused).toEqual({ hits: [], sources: SOURCES });
640+
expect(gated.asked.map((x) => x.source)).not.toContain('clauses'); // never searched, not searched-then-dropped
641+
const served = await gated.tools.searchKnowledge({ query: 'q', granularity: 'record' }, manager);
642+
expect(served.hits.map((h) => h.metadata)).toEqual([
643+
{ policy: 'P_leave', status: 'draft' }, { policy: 'P_leave', status: 'live' }, { policy: 'P_travel', status: 'live' },
644+
]);
645+
});
646+
});
558647
});

‎packages/services/service-knowledge/src/knowledge-tools.ts‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,15 @@ export interface SearchKnowledgeHit {
147147
* list for a `multiple` lookup).
148148
*/
149149
groupValue?: unknown;
150+
/**
151+
* For a hit of an indexed record: the values of the fields its source lists
152+
* in `metadataFields` (the parent a child record links to, its status), as
153+
* the index stores them, keyed by field name, in the order the source lists
154+
* them. Only fields the source lists now are answered; a field it lists
155+
* whose stored value is absent or null is left out, and so is the member
156+
* when no listed field has a value.
157+
*/
158+
metadata?: Record<string, unknown>;
150159
}
151160

152161
/**
@@ -220,7 +229,10 @@ const SEARCH_KNOWLEDGE_DESCRIPTION =
220229
+ `${SEARCH_KNOWLEDGE_MAX_SCOPE_ENTRIES} entries of at most ${SEARCH_KNOWLEDGE_MAX_SCOPE_IDS} ids. An entry naming `
221230
+ 'the object a source indexes searches those records\' passages; an entry naming a parent object searches the '
222231
+ 'passages of records that link to those parents (the clauses of a policy). A hit carries `headingPath`, the '
223-
+ 'headings its passage sits under, where its document has headings.';
232+
+ 'headings its passage sits under, where its document has headings. A hit of an indexed record also carries '
233+
+ '`metadata`: the values, by field name, of the fields its source indexes with its passages (for a clause, the '
234+
+ 'policy it belongs to), as the index stores them. Read the parent or the status a hit names there: it needs no '
235+
+ 'record read.';
224236

225237
/** A caller's id or name, as the definition bounds it. */
226238
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 {
481493
};
482494
}
483495

496+
/**
497+
* The values of the fields `objSource` lists in `metadataFields` that the
498+
* stored `metadata` carries, in the order the source lists them: a field the
499+
* source lists now, never a stored key it no longer lists. An own key only, so
500+
* a listed name that is also an `Object.prototype` member never answers the
501+
* prototype's value. Absent and null values are left out; `undefined` when
502+
* none is left.
503+
*/
504+
function declaredMetadataOf(
505+
stored: Record<string, unknown> | undefined,
506+
listed: readonly string[] | undefined,
507+
): Record<string, unknown> | undefined {
508+
if (!stored || !listed || listed.length === 0) return undefined;
509+
const entries: Array<[string, unknown]> = [];
510+
for (const field of new Set(listed)) {
511+
if (!Object.prototype.hasOwnProperty.call(stored, field)) continue;
512+
const value = stored[field];
513+
if (value !== undefined && value !== null) entries.push([field, value]);
514+
}
515+
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
516+
}
517+
484518
/**
485519
* One hit as the answer carries it: a whitelist, member by member. Nothing
486520
* else of the service's hit reaches the agent — not its `chunkId`, not the
487-
* stored `docHash` the record-level freshness check compares, and not its
488-
* `metadata`, of which only the `groupBy` field's value is answered, and only
489-
* for a source that lists that field (source admission holds every
490-
* listed field queryable by the caller, ADR-0161 K8).
521+
* stored `docHash` the record-level freshness check compares, and of its
522+
* stored `metadata` only the fields its source lists in `metadataFields` now
523+
* (`metadata`, {@link declaredMetadataOf}) and, under `groupBy`, that field's
524+
* value (`groupValue`), only for a source that lists that field. Neither
525+
* serves a field the caller may not query: source admission holds every
526+
* listed field queryable by the caller before the source is searched at all
527+
* (ADR-0161 K8, `admitSourceFields`).
491528
*/
492529
function hitOf(
493530
hit: KnowledgeHit,
@@ -502,6 +539,7 @@ function hitOf(
502539
const groupValue = groupBy !== undefined && objSource?.metadataFields?.includes(groupBy)
503540
? hit.metadata?.[groupBy]
504541
: undefined;
542+
const metadata = declaredMetadataOf(hit.metadata, objSource?.metadataFields);
505543
return {
506544
sourceId: hit.sourceId,
507545
documentId: hit.documentId,
@@ -511,6 +549,7 @@ function hitOf(
511549
...(object && hit.sourceRecordId ? { record: { object, id: hit.sourceRecordId } } : {}),
512550
...(headingPath && headingPath.length > 0 ? { headingPath } : {}),
513551
...(groupValue !== undefined && groupValue !== null ? { groupValue } : {}),
552+
...(metadata ? { metadata } : {}),
514553
};
515554
}
516555

0 commit comments

Comments
 (0)