From 521106742676b84b8d8f40fcdfa36bbb7fde40af Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:33:40 +0000 Subject: [PATCH 01/12] feat(spec): a knowledge source declares its document unit, source.documentBy Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- packages/spec/src/ai/knowledge-source.test.ts | 36 +++++++++++++ packages/spec/src/ai/knowledge-source.zod.ts | 50 ++++++++++++++++++- 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index 596140688b3..a35db590229 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -292,3 +292,39 @@ describe('KnowledgeSource — the compiler is the third channel (ADR-0161 K6 ite expect([viaId, viaContentFields, viaFileKind]).toHaveLength(3); }); }); + +describe('KnowledgeSourceSchema — `source.documentBy`, the document unit, is one of `metadataFields`', () => { + const CLAUSES: KnowledgeSource = { + name: 'policy_clauses', + label: 'Policy clauses', + source: { kind: 'object', object: 'policy_clause', content: ['body'], metadataFields: ['policy', 'clause_hash'] }, + }; + + it('positive control: a `documentBy` listed in `metadataFields` parses and is kept as written', () => { + const parsed = KnowledgeSourceSchema.parse({ ...CLAUSES, source: { ...CLAUSES.source, documentBy: 'policy' } }); + expect(parsed.source.documentBy).toBe('policy'); + // Absent stays absent: no default is stated for it. + expect('documentBy' in KnowledgeSourceSchema.parse(CLAUSES).source).toBe(false); + }); + + it('refuses a `documentBy` that `metadataFields` does not list, naming the field and the fix', () => { + const issues = issuesOf({ ...CLAUSES, source: { ...CLAUSES.source, documentBy: 'owner' } }); + expect(issues.map(([code, path]) => [code, path])).toEqual([['custom', 'source.documentBy']]); + const message = issues[0]![2]; + expect(message).toMatch(/^`knowledge_source\.source\.documentBy` names 'owner', which is not one of `source\.metadataFields`/); + expect(message).toContain("Add 'owner' to `metadataFields`"); + }); + + it('refuses a `documentBy` when `metadataFields` is omitted, and says the list is empty', () => { + const { metadataFields: _listed, ...bare } = CLAUSES.source; + const issues = issuesOf({ ...CLAUSES, source: { ...bare, documentBy: 'policy' } }); + expect(issues.map(([code, path]) => [code, path])).toEqual([['custom', 'source.documentBy']]); + expect(issues[0]![2]).toContain('the list is empty'); + }); + + it('refuses a value that is not a string by its type', () => { + expect( + issuesOf({ ...CLAUSES, source: { ...CLAUSES.source, documentBy: ['policy'] } }).map(([code, path]) => [code, path]), + ).toEqual([['invalid_type', 'source.documentBy']]); + }); +}); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 1549c424afd..211cb6dc13a 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -128,6 +128,32 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( }, )); +/** + * `source.documentBy` must be one of `source.metadataFields`: a record-level + * search groups each hit by the value the index stores beside its passage, + * and the index stores only the listed fields. A cross-key rule, so a + * refinement: the published JSON Schema cannot state it, and the parse does. + */ +function refuseDocumentByOutsideMetadataFields( + value: { documentBy?: string; metadataFields?: string[] }, + ctx: z.RefinementCtx, +): void { + const { documentBy } = value; + if (documentBy === undefined) return; + const listed = value.metadataFields ?? []; + if (listed.includes(documentBy)) return; + ctx.addIssue({ + code: 'custom', + path: ['documentBy'], + message: + `\`knowledge_source.source.documentBy\` names '${documentBy}', which is not one of \`source.metadataFields\` ` + + `(${listed.length === 0 ? 'the list is empty' : listed.map((f) => `'${f}'`).join(', ')}): a record-level search ` + + 'groups each hit by the value the index stores beside its passage, and the index stores only the listed fields, ' + + `so no hit would carry the parent. Add '${documentBy}' to \`metadataFields\` (the field that links each record ` + + 'to its parent record, a lookup or master_detail), or name a field listed there, or remove `documentBy`.', + }); +} + /** * What a source indexes: the records of one object (ADR-0161 K4, "Referencing * objects"). `kind` keeps one arm; the `file` and `http` arms retired with @@ -195,6 +221,28 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( * time (e.g. `status`, `owner_id`, `tags`). */ metadataFields: z.array(z.string()).default([]).optional(), + /** + * The document unit of this source: the field that links each indexed + * record to the parent record it is a part of (a clause to its policy, an + * article to its contract). The index is unchanged — still one document + * per record (ADR-0161 K1) — and the key enters neither the index + * fingerprint nor the recipe hash, so adding it rebuilds nothing. + * + * Read by a record-level search (`granularity: 'record'`) that names no + * `groupBy`: the hits of this source are grouped by the parent the field + * holds, one hit per parent (its best passage), and the hit carries that + * parent as its `groupValue`. A record with no parent is its own hit, as + * before. Two sources never share a group, whatever their parents. An + * explicit `groupBy` is answered as before. + * + * Must be one of {@link metadataFields}: grouping reads the value the + * index stores beside each passage. Saving and `os validate` also refuse + * a field that is not a single-valued parent link: a `lookup` or + * `master_detail` field (never `multiple: true`), not credential-class or + * `internal`. + */ + documentBy: z.string().optional() + .describe('Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent'), /** * Optional filter restricting which records are indexed. * Uses ObjectQL `where` syntax. @@ -208,7 +256,7 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( split: KnowledgeSplitSchema.optional() .describe('How the service cuts this object\'s documents into passages; omitted means recursive'), }, -)); +).superRefine(refuseDocumentByOutsideMetadataFields)); /** * Canonical KnowledgeSource — the one schema of the governed metadata type From 78ab2b909ab7b9eb0dbfeb79bad36d7124ef8bb8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:36:16 +0000 Subject: [PATCH 02/12] feat(service-knowledge): record search groups by a source's document unit by default; the save refuses a document unit that is no single-valued parent link Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .../src/knowledge-search-scope.ts | 94 ++++++++++++++++--- .../src/knowledge-service.ts | 58 +++++++++++- .../src/knowledge-source-admission.ts | 41 ++++++++ .../service-knowledge/src/knowledge-tools.ts | 39 ++++++-- .../ai/knowledge-source.metadata-form.test.ts | 6 +- .../src/ai/knowledge-source.metadata-form.ts | 1 + 6 files changed, 215 insertions(+), 24 deletions(-) diff --git a/packages/services/service-knowledge/src/knowledge-search-scope.ts b/packages/services/service-knowledge/src/knowledge-search-scope.ts index d9534f839d7..63938ff9d93 100644 --- a/packages/services/service-knowledge/src/knowledge-search-scope.ts +++ b/packages/services/service-knowledge/src/knowledge-search-scope.ts @@ -131,36 +131,104 @@ export function scopeTermsFor( /** * 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. + * parent link of the indexed object ({@link parentLinkRule}), by the object it + * points at. Empty without a registered definition. */ function parentLinksOf(objSource: ObjectKnowledgeSource, schema: unknown): Map { const links = new Map(); + const linkOf = parentLinkRule(schema); + if (linkOf === undefined) return links; + for (const field of new Set(objSource.metadataFields ?? [])) { + const verdict = linkOf(field); + if (!verdict.link) continue; + const fields = links.get(verdict.target); + if (fields) fields.push(field); + else links.set(verdict.target, [field]); + } + return links; +} + +/** Why a field of a source's object is no parent link ({@link parentLinkRule}). */ +export type ParentLinkRefusal = + /** The object declares no field of that name (an injected system column included). */ + | 'undeclared' + /** A credential-class or `internal` field: assembly withholds it, so no document carries it. */ + | 'withheld' + /** Declared, of a type that links to no parent record (`text`, `user`, `tree`, ...). */ + | 'not-a-link' + /** A `lookup` / `master_detail` field whose target cannot be read. */ + | 'no-target'; + +/** What {@link parentLinkRule} answers for one field. */ +export type ParentLinkVerdict = + | { link: true; target: string; type: string; multiple: boolean } + | { link: false; reason: ParentLinkRefusal; type?: string }; + +/** + * The parent-link rule, one answer for every reader of it: the search scope + * ({@link scopeTermsFor}, which resolves a parent entry through it) and the + * document unit (`source.documentBy`, {@link documentUnitOf}). + * + * A field is a parent link when the object declares it, its type is `lookup` + * or `master_detail` (reading (3): never `user`, never `tree`), assembly does + * not withhold it (credential-class, `internal`), and its target can be read + * (`referenceTargetOf`, the spec's one answer). `multiple` says whether the + * field holds a list of parents (`multiple: true`); the scope takes such a + * field, the document unit does not. + * + * Takes the object's registered definition and answers a reader over its + * fields, or `undefined` when the definition declares no fields to read (no + * definition, or fields that cannot be enumerated): no verdict can be drawn. + * Pure: it reads only the definition, so a caller with no knowledge service + * (a lint over a stack's definitions) can ask it too. + */ +export function parentLinkRule(schema: unknown): ((field: string) => ParentLinkVerdict) | undefined { const declared = declaredFields(schema); - if (declared === undefined) return links; + if (declared === undefined) return undefined; 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; + return (field) => { + if (!defs.has(field)) return { link: false, reason: 'undeclared' }; const def = defs.get(field); const type = (def as { type?: unknown } | null | undefined)?.type; - if (typeof type !== 'string' || !PARENT_LINK_TYPES.has(type)) continue; + const typeName = typeof type === 'string' ? type : undefined; + if (withheld.has(field)) return { link: false, reason: 'withheld', ...(typeName ? { type: typeName } : {}) }; + if (typeName === undefined || !PARENT_LINK_TYPES.has(typeName)) { + return { link: false, reason: 'not-a-link', ...(typeName ? { type: typeName } : {}) }; + } 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; + if (target === undefined) return { link: false, reason: 'no-target', type: typeName }; + return { link: true, target, type: typeName, multiple: (def as { multiple?: unknown }).multiple === true }; + }; +} + +/** What {@link documentUnitOf} answers: the parent object, or why the field cannot be the document unit. */ +export type DocumentUnitVerdict = + | { unit: true; target: string } + | { unit: false; reason: ParentLinkRefusal | 'multiple'; type?: string }; + +/** + * May `field` be the document unit of a source over the object `schema` + * defines (`source.documentBy`)? Only a single-valued parent link: the + * parent-link rule ({@link parentLinkRule}) and not `multiple: true`, since a + * record that names several parents belongs to no one document. `undefined` + * when no verdict can be drawn (the definition declares no fields to read). + */ +export function documentUnitOf(field: string, schema: unknown): DocumentUnitVerdict | undefined { + const linkOf = parentLinkRule(schema); + if (linkOf === undefined) return undefined; + const verdict = linkOf(field); + if (!verdict.link) return { unit: false, reason: verdict.reason, ...(verdict.type ? { type: verdict.type } : {}) }; + if (verdict.multiple) return { unit: false, reason: 'multiple', type: verdict.type }; + return { unit: true, target: verdict.target }; } /** diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 23f4a6029ce..c98a03680da 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -28,7 +28,7 @@ import { } from '@objectstack/core'; import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/security'; import { resolveInjectedSystemColumns } from '@objectstack/spec/data'; -import { createKnowledgeTools, refusal, type KnowledgeTools } from './knowledge-tools.js'; +import { createKnowledgeTools, documentUnitValueOf, refusal, type KnowledgeTools } from './knowledge-tools.js'; import { resolveSplit, splitDocument, type ResolvedSplit } from './split/index.js'; import { indexExpectation } from './knowledge-index-fingerprint.js'; import { @@ -50,17 +50,20 @@ import { mayServeEarlierRuleTitle, declaredFields, documentTitleField, + documentUnitRefusalText, type KnowledgeAdmissionDeps, type KnowledgeFieldSecurity, type KnowledgeSourceAdmission, type ObjectAdmission, } from './knowledge-source-admission.js'; import { + documentUnitOf, narrowToVisible, readSearchScope, scopeCheck, scopeTermsFor, SEARCH_VISIBLE_IDS_MAX, + type DocumentUnitVerdict, type SearchScopeEntry, } from './knowledge-search-scope.js'; import { @@ -2604,10 +2607,11 @@ export class KnowledgeService implements IKnowledgeService { /** * The group a hit falls in under record granularity: with `groupBy`, the * hit's `metadata[groupBy]` value (`undefined` — no group, never answered — - * when the hit carries none); without it, the hit's record. + * when the hit carries none); without it, the parent record its source's + * `documentBy` names, else the hit's record ({@link documentKeyOf}). */ private groupKeyOf(hit: KnowledgeHit, groupBy: string | undefined): string | undefined { - if (groupBy === undefined) return recordKeyOf(hit); + if (groupBy === undefined) return documentKeyOf(hit, this.handed(hit.sourceId)?.source.documentBy); const value = hit.metadata?.[groupBy]; if (value === undefined || value === null || value === '') return undefined; return `value:${stableJson(value)}`; @@ -3827,7 +3831,12 @@ export class KnowledgeService implements IKnowledgeService { * naming it and the rule `os validate` reports * (`knowledge-source-object-unknown`, `knowledge-source-field-unknown`), * decided from the object's definition alone ({@link absentSourceReference}), - * so no answer about an object or a field that exists changes. A source whose `adapter` names no + * so no answer about an object or a field that exists changes. Next, still + * ahead of every permission arm, a `source.documentBy` that `metadataFields` + * lists and that is not a single-valued parent link of the object + * (`documentUnitOf`: a `lookup` or `master_detail` field, not `multiple`, + * neither credential-class nor `internal`) is refused `400 + * VALIDATION_ERROR`, naming the field and the fix. A source whose `adapter` names no * adapter this deployment mounts is refused `400 VALIDATION_ERROR`, naming * the source, the adapter and the mounted ones; an omitted `adapter` is not * (it is placed by {@link adapterIdFor}). That check is this door's only: @@ -3934,6 +3943,30 @@ export class KnowledgeService implements IKnowledgeService { ); } + // [`source.documentBy`] A document unit that is no single-valued parent + // link is a permanent mistake too, judged on the object's definition alone + // by the parent-link rule the search scope reads. One not listed in + // `metadataFields` is left to the parse, which names that fix. + const documentBy = (declared as { documentBy?: unknown }).documentBy; + if (typeof documentBy === 'string' && objSource.metadataFields?.includes(documentBy)) { + let unit: DocumentUnitVerdict | undefined; + try { + const deps = this.admissionDeps(engine); + unit = deps.isObjectPackageDisabled(object) ? undefined : documentUnitOf(documentBy, deps.readSchema(object)); + } catch (err) { + this.reportGateFailure(object, err instanceof Error ? err : new Error(String(err))); + return unavailable(operatorText(err)); + } + if (unit !== undefined && !unit.unit) { + return refuse( + 400, + 'VALIDATION_ERROR', + `${named}: ${documentUnitRefusalText(object, documentBy, unit)}${wording.thenAgain}.`, + documentBy, + ); + } + } + let admission: ObjectAdmission; try { admission = await admitObject(object, ctx, this.admissionDeps(engine)); @@ -4866,6 +4899,23 @@ function distinctGroups(hits: KnowledgeHit[], groupOf: (hit: KnowledgeHit) => st return keys.size; } +/** + * [`source.documentBy`] A hit's group under record granularity with no + * `groupBy`: the parent record its source's document unit names, keyed with + * the hit's source, so two sources never share a group however equal their + * parent ids. The parent is read from the hit itself, `metadata[documentBy]`, + * the value assembly stored beside the passage (the parse holds `documentBy` + * in `metadataFields`), so grouping reads no record: it runs over the hits the + * adapters already answered. A hit with no parent to group by — its source + * declares no `documentBy`, or the value is absent, null, empty, or not a + * string or a number — is its own record ({@link recordKeyOf}), never dropped. + * Values are compared as strings, as a scope term compares them. + */ +function documentKeyOf(hit: KnowledgeHit, documentBy: string | undefined): string { + const parent = documentBy === undefined ? undefined : documentUnitValueOf(hit.metadata, documentBy); + return parent === undefined ? recordKeyOf(hit) : `parent:${hit.sourceId}#${String(parent)}`; +} + /** A hit's record: its source and record id; a hit that names no record is its document. */ function recordKeyOf(hit: KnowledgeHit): string { return hit.sourceRecordId !== undefined ? `record:${hit.sourceId}#${hit.sourceRecordId}` : `document:${hit.documentId}`; diff --git a/packages/services/service-knowledge/src/knowledge-source-admission.ts b/packages/services/service-knowledge/src/knowledge-source-admission.ts index ac64e4d50e4..7054685acee 100644 --- a/packages/services/service-knowledge/src/knowledge-source-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-source-admission.ts @@ -110,6 +110,7 @@ import { } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { DocumentUnitVerdict } from './knowledge-search-scope.js'; import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields, @@ -381,3 +382,43 @@ export function admitSourceFields( } return { admitted: true }; } + +/** + * [`source.documentBy`] The save-time refusal of a document unit that is not a + * single-valued parent link of the source's object: what the field is, why it + * cannot group a record under a parent, and the fix. `verdict` is the + * parent-link rule's answer (`documentUnitOf`, `knowledge-search-scope.ts`), so + * the save door and the search scope judge a parent link by one rule. Decided + * from the object's definition alone, as the "does not exist" arm of the save + * door is: the sentence tells a `manage_metadata` holder nothing the metadata + * plane does not already serve them. It ends without its full stop, so the + * door can add its own remedy before it. + */ +export function documentUnitRefusalText( + object: string, + field: string, + verdict: Extract, +): string { + const fix = `Name the lookup or master_detail field of '${object}' that points at each record's parent record, or remove \`documentBy\``; + const named = `\`source.documentBy\` names '${field}'`; + const typed = verdict.type === undefined ? 'a field' : `a \`${verdict.type}\` field`; + switch (verdict.reason) { + case 'undeclared': + return `${named}, which object '${object}' does not declare (a system column the platform adds is no parent link), ` + + `so it links no record to a parent. ${fix}`; + case 'withheld': + return `${named}, a credential or internal field of object '${object}': the index never stores such a field, so no ` + + `passage would carry the parent to group by. ${fix}; it must be neither credential-class nor internal`; + case 'not-a-link': + return `${named}, ${typed} of object '${object}': the document unit is a parent record, so the field must be a ` + + 'lookup or master_detail field that points at it' + + (verdict.type === 'user' ? ' (a user field names a person, not the document a record is part of)' : '') + + `. ${fix}`; + case 'no-target': + return `${named}, ${typed} of object '${object}' whose target object cannot be read (it declares no \`reference\`), ` + + `so the parent it holds is not known. Declare the field's \`reference\`, or ${fix.charAt(0).toLowerCase()}${fix.slice(1)}`; + case 'multiple': + return `${named}, ${typed} of object '${object}' declared \`multiple: true\`: a record that names several parents ` + + `belongs to no one document. ${fix}; it must hold one parent (not \`multiple\`)`; + } +} diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index b07dfa562bc..15a3e675a82 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -144,7 +144,9 @@ export interface SearchKnowledgeHit { /** * 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). + * list for a `multiple` lookup). Under `granularity: "record"` with no + * `groupBy`, for a source that declares `documentBy`: the parent record the + * hit stands for (absent for a record with no parent, which stands for itself). */ groupValue?: unknown; /** @@ -521,7 +523,10 @@ function declaredMetadataOf( * 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 + * value (`groupValue`), only for a source that lists that field — or, under + * `granularity: 'record'` with no `groupBy`, the parent its source's + * `documentBy` names ({@link documentUnitValueOf}), a field the parse holds in + * `metadataFields`. 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`). @@ -530,15 +535,20 @@ function hitOf( hit: KnowledgeHit, sources: ReadonlyMap, groupBy: string | undefined, + granularity: SearchKnowledgeInput['granularity'], ): SearchKnowledgeHit { const objSource = sources.get(hit.sourceId)?.source; 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; + // Under `groupBy`, that field's value; under `granularity: 'record'` alone, + // the parent the source's `documentBy` grouped the hit by, when it had one. + const groupValue = groupBy !== undefined + ? (objSource?.metadataFields?.includes(groupBy) ? hit.metadata?.[groupBy] : undefined) + : granularity === 'record' && objSource?.documentBy !== undefined + ? documentUnitValueOf(hit.metadata, objSource.documentBy) + : undefined; const metadata = declaredMetadataOf(hit.metadata, objSource?.metadataFields); return { sourceId: hit.sourceId, @@ -553,6 +563,23 @@ function hitOf( }; } +/** + * [`source.documentBy`] The parent a hit's stored metadata names under its + * source's document unit: `metadata[documentBy]` when it is a non-empty string + * or a finite number, else `undefined` (the hit then stands for its own + * record). One answer for the service's default record grouping + * (`documentKeyOf`) and for the `groupValue` a hit carries ({@link hitOf}). + */ +export function documentUnitValueOf( + metadata: Record | undefined, + documentBy: string, +): string | number | undefined { + const parent = metadata?.[documentBy]; + if (typeof parent === 'string' && parent !== '') return parent; + if (typeof parent === 'number' && Number.isFinite(parent)) return parent; + return undefined; +} + /** A knowledge service that also answers the sources that refused a search (`KnowledgeService.searchWithRefusals`). */ interface RefusalReportingService { searchWithRefusals( @@ -625,7 +652,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, groupBy)), + hits: report.hits.filter((hit) => byId.has(hit.sourceId)).map((hit) => hitOf(hit, byId, groupBy, granularity)), sources: summaries, ...(refused.length > 0 ? { refused } : {}), }; diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.test.ts b/packages/spec/src/ai/knowledge-source.metadata-form.test.ts index fd2efc96593..092987517e1 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.test.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.test.ts @@ -56,6 +56,9 @@ describe('knowledge_source form (ADR-0161 K4 clause 2)', () => { expect(sourceRow('object')).toMatchObject({ widget: 'ref:object', required: true }); expect(sourceRow('content')).toMatchObject({ widget: 'field-multi', dependsOn: 'object', required: true }); expect(sourceRow('metadataFields')).toMatchObject({ widget: 'field-multi', dependsOn: 'object' }); + // One field, not a list: the document unit is a single parent link of the source's object. + expect(sourceRow('documentBy')).toMatchObject({ widget: 'field-ref', dependsOn: 'object' }); + expect(sourceRow('documentBy')?.required).toBeUndefined(); }); it('offers the one kind, `object`, and every split strategy the schema accepts', () => { @@ -114,7 +117,8 @@ describe('knowledge_source form (ADR-0161 K4 clause 2)', () => { kind: 'object', object: 'task', content: ['title', 'notes'], - metadataFields: ['status'], + metadataFields: ['status', 'project'], + documentBy: 'project', where: { status: { $ne: 'done' } }, split: { strategy: 'markdown', maxChars: 600, minChars: 100 }, }, diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index f48a3fde18b..bd478aed378 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -72,6 +72,7 @@ export const knowledgeSourceForm = defineMetadataForm({ helpText: 'The fields whose text is indexed, in order. Each field is named: there is no wildcard. Embedding is egress, and a build costs money: the first build reads every record the filter matches and sends the text of each listed field to your embedding provider, which bills for it, and that text is kept in an index outside the record store. A rebuild after you change the embedding model or the split sends all of it again. A field added to the object later is not indexed until you add it here. Credential and internal fields are never indexed, even when listed.', }, { field: 'metadataFields', label: 'Filter fields', widget: 'field-multi', dependsOn: 'object', helpText: 'Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query.' }, + { field: 'documentBy', label: 'Document unit', widget: 'field-ref', dependsOn: 'object', helpText: 'Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt.' }, { field: 'where', label: 'Records to index', widget: 'json', helpText: 'An ObjectQL filter on the object, for example {"status": {"$ne": "done"}}. Only the records it matches are indexed. Blank: every record.' }, { field: 'split', From d5305ab678249f0da372a1c42005646651dde614 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:41:51 +0000 Subject: [PATCH 03/12] test(service-knowledge): pin the document unit's reader, its save refusals and the unchanged hashes Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .../src/__tests__/document-by-38537.test.ts | 277 ++++++++++++++++++ .../__tests__/knowledge-search-scope.test.ts | 44 +++ packages/spec/authorable-surface/ai.json | 1 + .../spec/dropped-refinements.baseline.json | 14 + 4 files changed, 336 insertions(+) create mode 100644 packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts diff --git a/packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts b/packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts new file mode 100644 index 00000000000..5ed067c0b3b --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts @@ -0,0 +1,277 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `source.documentBy` — a knowledge source declares its document unit, the + * field that links each indexed record to the parent record it is part of. + * + * - **The reader** (ADR-0049, ADR-0161 K4: a key lands with its first reader): + * a record-level search with no `groupBy` answers one hit per parent for a + * source that declares it; a record with no parent is its own hit; two + * sources never share a parent group; an explicit `groupBy` and a source + * without the key are answered as before. The `search_knowledge` hit + * carries the parent as `groupValue`. + * - **No index change**: the key enters neither the index fingerprint nor the + * recipe hash, so adding it rebuilds nothing. + * - **The save door**: a document unit that is not a single-valued parent + * link is refused `400 VALIDATION_ERROR`, naming the field and the fix. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KnowledgeService, recordToDocument } from '../knowledge-service.js'; +import { computeIndexFingerprint, computeRecipeHash } from '../knowledge-index-fingerprint.js'; + +const MEMBER: ExecutionContext = { userId: 'u1', positions: ['member'], permissions: [], isSystem: false }; + +type Row = Record & { id: string }; + +/** A clause source over `policy_clause`: content `body`, metadata `policy` and `clause_hash`. */ +function clauseSource(name: string, extra: Partial = {}): KnowledgeSource { + return { + name, + label: name, + adapter: 'memory', + source: { + kind: 'object', + object: 'policy_clause', + content: ['body'], + metadataFields: ['policy', 'clause_hash'], + ...extra, + } as ObjectKnowledgeSource, + }; +} + +/** The hit an index answers for `row`'s passage `n`, built by assembly so it carries the stored metadata and hash. */ +function indexHit(source: KnowledgeSource, 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.name, + sourceRecordId: row.id, + score, + snippet: `${String(row.body)} (${n})`, + metadata: doc.metadata, + docHash: doc.docHash, + }; +} + +/** An engine over `table`: system reads (the freshness check) and the caller's reads both see every row. */ +function tableEngine(table: Row[]): IDataEngine { + 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; + }); + return { + find: vi.fn(async (_object: string, q: { where?: Record; fields?: string[]; limit?: number }) => { + const rows = table.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; +} + +function searchSetup(table: Row[], sources: KnowledgeSource[], corpus: (byName: Record) => Record) { + const byName = Object.fromEntries(sources.map((s) => [s.name, s])); + const hits = corpus(byName); + 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 }) => + [...(hits[opts.source.name] ?? [])].sort((a, b) => b.score - a.score).slice(0, opts.topK)), + } as unknown as IKnowledgeAdapter; + const svc = new KnowledgeService({ dataEngine: tableEngine(table), logger: { debug: () => undefined, warn: () => undefined } }); + svc.registerAdapter('memory', adapter); + for (const s of sources) svc.registerSource(s); + return svc; +} + +/** Six clauses under two policies, and one clause with no policy. */ +const CLAUSES = (): Row[] => [ + { id: 'c1', body: 'leave one', policy: 'P_leave', clause_hash: 'h1' }, + { id: 'c2', body: 'leave two', policy: 'P_leave', clause_hash: 'h2' }, + { id: 'c3', body: 'leave three', policy: 'P_leave', clause_hash: 'h1' }, + { id: 'c4', body: 'travel one', policy: 'P_travel', clause_hash: 'h3' }, + { id: 'c5', body: 'travel two', policy: 'P_travel', clause_hash: 'h2' }, + { id: 'c6', body: 'travel three', policy: 'P_travel', clause_hash: 'h3' }, + { id: 'c7', body: 'orphan', policy: null, clause_hash: 'h4' }, +]; + +/** One passage per clause, scores descending c1 … c7 except where a test says otherwise. */ +const SCORES: Record = { c1: 0.6, c2: 0.9, c3: 0.5, c4: 0.4, c5: 0.8, c6: 0.3, c7: 0.7 }; +const corpusOf = (table: Row[]) => (byName: Record) => + Object.fromEntries(Object.values(byName).map((s) => [s.name, table.map((r) => indexHit(s, r, 0, SCORES[r.id]!))])); + +describe("documentBy — a record-level search with no groupBy answers one hit per parent", () => { + it("6 records under 2 parents plus 1 with no parent, granularity 'record', topK 10: 3 hits, each parent's best and the orphan", async () => { + const table = CLAUSES(); + const svc = searchSetup(table, [clauseSource('clauses', { documentBy: 'policy' })], corpusOf(table)); + const out = await svc.search('q', { granularity: 'record', topK: 10, executionContext: MEMBER }); + expect(out.map((h) => [h.sourceRecordId, h.metadata?.policy ?? null])).toEqual([ + ['c2', 'P_leave'], + ['c5', 'P_travel'], + ['c7', null], + ]); + }); + + it('a record whose parent is empty, or holds no value at all, is its own hit, never dropped', async () => { + const table: Row[] = [ + { id: 'a1', body: 'a one', policy: 'P1', clause_hash: 'h' }, + { id: 'a2', body: 'a two', policy: 'P1', clause_hash: 'h' }, + { id: 'e1', body: 'empty', policy: '', clause_hash: 'h' }, + { id: 'e2', body: 'absent', clause_hash: 'h' }, + ]; + const scores: Record = { a1: 0.9, a2: 0.8, e1: 0.7, e2: 0.6 }; + const svc = searchSetup(table, [clauseSource('clauses', { documentBy: 'policy' })], (byName) => ({ + clauses: table.map((r) => indexHit(byName.clauses!, r, 0, scores[r.id]!)), + })); + const out = await svc.search('q', { granularity: 'record', topK: 10, executionContext: MEMBER }); + expect(out.map((h) => h.sourceRecordId)).toEqual(['a1', 'e1', 'e2']); + }); + + it('two sources never share a group, however equal their parent ids', async () => { + const table = CLAUSES().slice(0, 3); + const svc = searchSetup( + table, + [clauseSource('s1', { documentBy: 'policy' }), clauseSource('s2', { documentBy: 'policy' })], + corpusOf(table), + ); + const out = await svc.search('q', { granularity: 'record', topK: 10, executionContext: MEMBER }); + expect(out.map((h) => [h.sourceId, h.metadata?.policy])).toEqual([ + ['s1', 'P_leave'], + ['s2', 'P_leave'], + ]); + }); + + it("an explicit groupBy is answered as before: the same hits whether or not the source declares documentBy", async () => { + const table = CLAUSES(); + const opts = { groupBy: 'clause_hash', topK: 10, executionContext: MEMBER }; + const declared = await searchSetup(table, [clauseSource('clauses', { documentBy: 'policy' })], corpusOf(table)).search('q', opts); + const plain = await searchSetup(table, [clauseSource('clauses')], corpusOf(table)).search('q', opts); + expect(declared).toEqual(plain); + expect(declared.map((h) => [h.sourceRecordId, h.metadata?.clause_hash])).toEqual([ + ['c2', 'h2'], + ['c7', 'h4'], + ['c1', 'h1'], + ['c4', 'h3'], + ]); + }); + + it('a source without documentBy is answered as before: one hit per record', async () => { + const table = CLAUSES(); + const out = await searchSetup(table, [clauseSource('clauses')], corpusOf(table)) + .search('q', { granularity: 'record', topK: 10, executionContext: MEMBER }); + expect(out.map((h) => h.sourceRecordId)).toEqual(['c2', 'c5', 'c7', 'c1', 'c3', 'c4', 'c6']); + }); + + it("chunk granularity is answered as before: documentBy groups nothing", async () => { + const table = CLAUSES(); + const out = await searchSetup(table, [clauseSource('clauses', { documentBy: 'policy' })], corpusOf(table)) + .search('q', { topK: 10, executionContext: MEMBER }); + expect(out).toHaveLength(7); + }); + + it("search_knowledge: each hit carries its parent as groupValue; the orphan carries none; chunk hits carry none", async () => { + const table = CLAUSES(); + const svc = searchSetup(table, [clauseSource('clauses', { documentBy: 'policy' })], corpusOf(table)); + const byRecord = await svc.knowledgeTools().searchKnowledge({ query: 'q', granularity: 'record', topK: 10 }, MEMBER); + expect(byRecord.hits.map((h) => [h.record?.id, h.groupValue])).toEqual([ + ['c2', 'P_leave'], + ['c5', 'P_travel'], + ['c7', undefined], + ]); + expect(byRecord.hits[2]).not.toHaveProperty('groupValue'); + const byChunk = await svc.knowledgeTools().searchKnowledge({ query: 'q', topK: 10 }, MEMBER); + for (const hit of byChunk.hits) expect(hit).not.toHaveProperty('groupValue'); + }); +}); + +describe('documentBy — no index change: neither hash reads it', () => { + it('the fingerprint and the recipe hash are the same with and without documentBy', () => { + const plain = clauseSource('clauses'); + const declared = clauseSource('clauses', { documentBy: 'policy' }); + const embedding = { model: 'text-embedding-3-small', dimensions: 1536 }; + const split = { strategy: 'whole' as const, maxChars: 800, minChars: 200 }; + expect(computeIndexFingerprint({ source: declared, embedding, split })) + .toBe(computeIndexFingerprint({ source: plain, embedding, split })); + const schema = { name: 'policy_clause', fields: { body: { type: 'textarea' }, policy: { type: 'lookup', reference: 'policy' } } }; + expect(computeRecipeHash({ source: declared, schema })).toBe(computeRecipeHash({ source: plain, schema })); + // CONTROL: the recipe hash does read metadataFields, so it can tell two sources apart. + expect(computeRecipeHash({ source: clauseSource('clauses', { metadataFields: ['policy'] }), schema })) + .not.toBe(computeRecipeHash({ source: plain, schema })); + }); +}); + +describe('documentBy — the save refuses a document unit that is not a single-valued parent link', () => { + const POLICY_CLAUSE = { + name: 'policy_clause', + fields: { + body: { type: 'textarea' }, + title: { type: 'text' }, + policy: { type: 'lookup', reference: 'policy' }, + chapter: { type: 'master_detail', reference: 'chapter' }, + owner: { type: 'user' }, + audit_policy: { type: 'lookup', reference: 'policy', internal: true }, + cited_policies: { type: 'lookup', reference: 'policy', multiple: true }, + }, + }; + + function saveSetup() { + const engine = { + find: vi.fn(async () => []), + getSchema: (name: string) => (name === POLICY_CLAUSE.name ? POLICY_CLAUSE : undefined), + registry: { isObjectPackageDisabled: () => false }, + } as unknown as IDataEngine; + const svc = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined, error: () => undefined } }); + svc.registerAdapter('memory', { id: 'memory', upsert: async () => undefined, delete: async () => undefined, search: async () => [] }); + return svc; + } + + const item = (documentBy: string, metadataFields: string[] = [documentBy]) => ({ + name: 'clauses', + label: 'Clauses', + adapter: 'memory', + source: { kind: 'object', object: 'policy_clause', content: ['body'], metadataFields, documentBy }, + }); + + type Refusal = { admitted: false; status: number; code: string; message: string; field?: string }; + + it.each([ + ['a text field', 'title', /a `text` field/], + ['a user field', 'owner', /a `user` field .*a user field names a person/], + ['an internal lookup', 'audit_policy', /credential or internal field/], + ['a multiple lookup', 'cited_policies', /declared `multiple: true`/], + ])('refuses %s, 400 VALIDATION_ERROR, naming the field and the fix', async (_what, field, why) => { + const verdict = (await saveSetup().admitAuthoredSource(item(field), MEMBER)) as Refusal; + expect(verdict).toMatchObject({ admitted: false, status: 400, code: 'VALIDATION_ERROR', field }); + expect(verdict.message).toContain(`\`source.documentBy\` names '${field}'`); + expect(verdict.message).toMatch(why); + expect(verdict.message).toContain("Name the lookup or master_detail field of 'policy_clause'"); + expect(verdict.message).toContain('remove `documentBy`'); + }); + + it('admits a single-valued lookup and a master_detail field', async () => { + const svc = saveSetup(); + expect(await svc.admitAuthoredSource(item('policy'), MEMBER)).toEqual({ admitted: true }); + expect(await svc.admitAuthoredSource(item('chapter'), MEMBER)).toEqual({ admitted: true }); + }); + + it('a documentBy that metadataFields does not list is left to the parse, which names that fix', async () => { + expect(await saveSetup().admitAuthoredSource(item('title', ['policy']), MEMBER)).toEqual({ admitted: true }); + }); + + it('a documentBy naming no field is the "does not exist" arm, as before', async () => { + const verdict = (await saveSetup().admitAuthoredSource(item('poilcy'), MEMBER)) as Refusal; + expect(verdict).toMatchObject({ admitted: false, status: 400, code: 'VALIDATION_ERROR', field: 'poilcy' }); + expect(verdict.message).toContain('knowledge-source-field-unknown'); + }); + + it('the system context is admitted, as every gate admits it', async () => { + expect(await saveSetup().admitAuthoredSource(item('title'), { positions: [], permissions: [], isSystem: true })).toEqual({ admitted: true }); + }); +}); 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 index 1b27a6c8b84..dafdfc22399 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts @@ -10,7 +10,9 @@ import { SEARCH_SCOPE_MAX_ENTRIES, SEARCH_SCOPE_MAX_IDS, SEARCH_VISIBLE_IDS_MAX, + documentUnitOf, narrowToVisible, + parentLinkRule, readSearchScope, scopeCheck, scopeTermsFor, @@ -178,6 +180,48 @@ describe('scopeTermsFor — the terms a source is handed', () => { }); +describe('parentLinkRule — the one parent-link rule, read by the scope and by the document unit', () => { + const clause = { name: 'clause', fields: { ...CLAUSE_FIELDS, cited_policies: { type: 'lookup', reference: 'policy', multiple: true } } }; + + it('a lookup or master_detail field, not withheld, with a readable target, is a link to that target', () => { + const linkOf = parentLinkRule(clause)!; + expect(linkOf('policy')).toEqual({ link: true, target: 'policy', type: 'lookup', multiple: false }); + expect(linkOf('chapter')).toEqual({ link: true, target: 'chapter', type: 'master_detail', multiple: false }); + expect(linkOf('cited_policies')).toEqual({ link: true, target: 'policy', type: 'lookup', multiple: true }); + }); + + it('names why anything else is no link', () => { + const linkOf = parentLinkRule({ name: 'clause', fields: { ...CLAUSE_FIELDS, no_target: { type: 'lookup', reference: { object: 'policy' } } } })!; + expect(linkOf('body')).toEqual({ link: false, reason: 'not-a-link', type: 'textarea' }); + expect(linkOf('owner')).toEqual({ link: false, reason: 'not-a-link', type: 'user' }); + expect(linkOf('supersedes')).toEqual({ link: false, reason: 'not-a-link', type: 'tree' }); + expect(linkOf('audit_policy')).toEqual({ link: false, reason: 'withheld', type: 'lookup' }); + expect(linkOf('no_target')).toEqual({ link: false, reason: 'no-target', type: 'lookup' }); + expect(linkOf('created_by')).toEqual({ link: false, reason: 'undeclared' }); + }); + + it('draws no verdict without fields to read', () => { + expect(parentLinkRule(undefined)).toBeUndefined(); + expect(parentLinkRule({ name: 'clause' })).toBeUndefined(); + }); + + it('documentUnitOf: a single-valued parent link only; a multiple lookup is refused by name', () => { + expect(documentUnitOf('policy', clause)).toEqual({ unit: true, target: 'policy' }); + expect(documentUnitOf('chapter', clause)).toEqual({ unit: true, target: 'chapter' }); + expect(documentUnitOf('cited_policies', clause)).toEqual({ unit: false, reason: 'multiple', type: 'lookup' }); + expect(documentUnitOf('owner', clause)).toEqual({ unit: false, reason: 'not-a-link', type: 'user' }); + expect(documentUnitOf('audit_policy', clause)).toEqual({ unit: false, reason: 'withheld', type: 'lookup' }); + expect(documentUnitOf('policy', undefined)).toBeUndefined(); + }); + + it('the scope still takes a multiple lookup as a parent link: only the document unit refuses it', () => { + const source = clauseSource(['cited_policies']); + expect(scopeTermsFor(source, [{ object: 'policy', ids: ['p1'] }], () => clause).terms).toEqual([ + { kind: 'metadata', field: 'cited_policies', ids: ['p1'] }, + ]); + }); +}); + 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: '', diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index b844b115a60..8d3bf84cbd8 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -382,6 +382,7 @@ "ai/ModelSelectionCriteria:tags", "ai/ObjectKnowledgeSource:content", "ai/ObjectKnowledgeSource:contentFields [RETIRED]", + "ai/ObjectKnowledgeSource:documentBy", "ai/ObjectKnowledgeSource:kind", "ai/ObjectKnowledgeSource:metadataFields", "ai/ObjectKnowledgeSource:object", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 9f4220e664d..63e60a519b3 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -77,6 +77,16 @@ "runtimeFilter.lazy" ] }, + "ai/KnowledgeSource": { + "sites": [ + "source" + ] + }, + "ai/ObjectKnowledgeSource": { + "sites": [ + "" + ] + }, "ai/ObjectQuerySource": { "sites": [ "filter.lazy" @@ -188,6 +198,7 @@ "manifest.hooks.element.texts.valueType", "manifest.jobs.element", "manifest.jobs.element.schedule.options[0].timezone", + "manifest.knowledgeSources.element.source", "manifest.mappings.element", "manifest.mappings.element.connectorSource.paging", "manifest.navigationContributions.element.items.element.lazy", @@ -387,6 +398,7 @@ "data.options[1].manifest.hooks.element.texts.valueType", "data.options[1].manifest.jobs.element", "data.options[1].manifest.jobs.element.schedule.options[0].timezone", + "data.options[1].manifest.knowledgeSources.element.source", "data.options[1].manifest.mappings.element", "data.options[1].manifest.mappings.element.connectorSource.paging", "data.options[1].manifest.objectExtensions.element", @@ -571,6 +583,7 @@ "options[1].manifest.hooks.element.texts.valueType", "options[1].manifest.jobs.element", "options[1].manifest.jobs.element.schedule.options[0].timezone", + "options[1].manifest.knowledgeSources.element.source", "options[1].manifest.mappings.element", "options[1].manifest.mappings.element.connectorSource.paging", "options[1].manifest.objectExtensions.element", @@ -679,6 +692,7 @@ "data.packages.element.options[1].manifest.hooks.element.texts.valueType", "data.packages.element.options[1].manifest.jobs.element", "data.packages.element.options[1].manifest.jobs.element.schedule.options[0].timezone", + "data.packages.element.options[1].manifest.knowledgeSources.element.source", "data.packages.element.options[1].manifest.mappings.element", "data.packages.element.options[1].manifest.mappings.element.connectorSource.paging", "data.packages.element.options[1].manifest.objectExtensions.element", From 2cabc4e3f4abac48d10ef59996f463f329162f41 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:43:07 +0000 Subject: [PATCH 04/12] chore(spec): liveness ledger row and changeset for source.documentBy Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .changeset/38537-knowledge-document-by.md | 15 +++++++++++++++ packages/spec/liveness/knowledge_source.json | 8 ++++++++ 2 files changed, 23 insertions(+) create mode 100644 .changeset/38537-knowledge-document-by.md diff --git a/.changeset/38537-knowledge-document-by.md b/.changeset/38537-knowledge-document-by.md new file mode 100644 index 00000000000..c9435a22ae0 --- /dev/null +++ b/.changeset/38537-knowledge-document-by.md @@ -0,0 +1,15 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-knowledge': patch +--- + +feat(knowledge): a knowledge source declares its document unit, `source.documentBy`; record-level search answers one hit per parent for it + +Clause-②: yes (widening) +Metadata-protocol: none + +A `knowledge_source` may now name the field that links each indexed record to the parent record it is part of: `source: { kind: 'object', object: 'policy_clause', content: ['body'], metadataFields: ['policy'], documentBy: 'policy' }`. For such a source, `search` / `search_knowledge` with `granularity: 'record'` and no `groupBy` returns one hit per parent (that parent's best passage) instead of one per record; the hit's `groupValue` is the parent id. A record with no parent is still its own hit, and two sources never share a parent. An explicit `groupBy`, `granularity: 'chunk'`, and every source without `documentBy` answer exactly as before. + +The index does not change: still one document per record. `documentBy` enters neither the index fingerprint nor the recipe hash, so adding it rebuilds nothing. + +`documentBy` must be listed in `metadataFields`, or the parse refuses it and says to add it there. Saving a source through Studio, the metadata API or MCP also refuses a field that is not a single-valued parent link: it must be a `lookup` or `master_detail` field, not `multiple: true`, and neither a credential nor an `internal` field. A `text` or `user` field is refused, with a message naming the fix. diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index cac97160911..6dd4e79b535 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -79,6 +79,14 @@ "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#recordToDocument — each listed field's value is carried in the document's metadata; packages/services/service-knowledge/src/knowledge-index-fingerprint.ts#computeRecipeHash — a change to the list changes the recipe hash and starts one rebuild; packages/services/service-knowledge/src/knowledge-search-scope.ts — a parent scope and `groupBy` resolve against the listed fields.", "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload)." }, + "documentBy": { + "status": "live", + "verifiedAt": "2026-11-29", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-knowledge/src/knowledge-service.ts#documentKeyOf — a record-level search with no `groupBy` groups each hit of the source by the parent the field holds (read from the hit's stored metadata), one hit per parent; packages/services/service-knowledge/src/knowledge-tools.ts#hitOf — the `search_knowledge` hit carries that parent as `groupValue`; packages/services/service-knowledge/src/knowledge-service.ts#admitAuthoredSource — the save refuses a field that is not a single-valued parent link (`documentUnitOf`, the parent-link rule of knowledge-search-scope.ts).", + "producer": "packages/metadata/src/plugin.ts — the stack's `knowledgeSources` collection reaches the metadata service as `knowledge_source` items; packages/services/service-knowledge/src/knowledge-service-plugin.ts#readPublishedSources reads the published items back and packages/services/service-knowledge/src/knowledge-source-loader.ts#KnowledgeSourceLoader registers each as a source (boot, a published change, a metadata reload).", + "note": "Must be one of `metadataFields` (refused at parse otherwise). Enters neither the index fingerprint nor the recipe hash: adding it rebuilds nothing." + }, "where": { "status": "live", "verifiedAt": "2026-11-26", From 494c378d5ea6b530c80ae45dc7ce5000690300ab Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:46:24 +0000 Subject: [PATCH 05/12] chore(spec): regenerate the reference page and liveness counts for source.documentBy Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- content/docs/references/ai/knowledge-source.mdx | 2 ++ packages/spec/liveness/state-counts/knowledge_source.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 4fde03217e8..dd87a25e817 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -78,6 +78,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | | **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **metadataFields** | `string[]` | optional (default: `[]`) | | +| **documentBy** | `string` | optional | Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | @@ -126,6 +127,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data); | **content** | `string[]` | ✅ | Fields whose text is indexed, in order; every name is listed (no wildcard) | | **contentFields** | `never` | optional | [REMOVED] `knowledge_source.source.contentFields` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — the key is spelled `content` now that a source is a metadata item; use `content`. Rename the key; the value (a list of field names) is unchanged, except that a `'*'` member is no longer accepted and is replaced by the field names it stood for. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **metadataFields** | `string[]` | optional (default: `[]`) | | +| **documentBy** | `string` | optional | Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent | | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index 0f1b3f9d841..2164603fe91 100644 --- a/packages/spec/liveness/state-counts/knowledge_source.md +++ b/packages/spec/liveness/state-counts/knowledge_source.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `knowledge_source` | 21 | 0 | 0 | 6 | 0 | 27 | +| `knowledge_source` | 22 | 0 | 0 | 6 | 0 | 28 | From f36580dde33397a98db3050c45c6db4b459ad7bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:48:55 +0000 Subject: [PATCH 06/12] chore(spec): the dropped-refinements ledger header counts the two new sites' schemas Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- packages/spec/dropped-refinements.baseline.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 63e60a519b3..a6408ee88e9 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 281, - "droppedRefinementSites": 1239, + "publishedSchemasWithDroppedRefinements": 283, + "droppedRefinementSites": 1245, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, From 03c7f54211d4a190fc4d88ec7156f53580dc595f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:16:21 +0000 Subject: [PATCH 07/12] chore(platform-objects): regenerate the metadata-form translation bundles for the knowledge source's document unit row Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .../src/apps/translations/ar.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/ar.source-hashes.generated.ts | 2 ++ .../src/apps/translations/de.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/de.source-hashes.generated.ts | 2 ++ .../src/apps/translations/en.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/es-ES.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/es-ES.source-hashes.generated.ts | 2 ++ .../src/apps/translations/fr.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/fr.source-hashes.generated.ts | 2 ++ .../src/apps/translations/ja-JP.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/ja-JP.source-hashes.generated.ts | 2 ++ .../src/apps/translations/ko.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/ko.source-hashes.generated.ts | 2 ++ .../src/apps/translations/pt-BR.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/pt-BR.source-hashes.generated.ts | 2 ++ .../src/apps/translations/ru.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/ru.source-hashes.generated.ts | 2 ++ .../src/apps/translations/zh-CN.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/zh-Hant.metadata-forms.generated.ts | 4 ++++ .../src/apps/translations/zh-Hant.source-hashes.generated.ts | 2 ++ 20 files changed, 62 insertions(+) diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 7f75b36eefb..e6f31b3d59c 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const arMetadataForms: NonNullable = { label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index 1bced799c77..a836fbcb84a 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -66,6 +66,8 @@ export const arGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "metadataForms.knowledge_source.fields.source.helpText": "0b648dbc7af2f85c", "metadataForms.knowledge_source.fields.source.kind.helpText": "98e903260393800d", "metadataForms.knowledge_source.fields.source.kind.label": "3acd2ee4b0e7f2cf", diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index c9182fceb96..29dbd2f0fb0 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const deMetadataForms: NonNullable = { label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 35b8e9d2293..28ac339ebc5 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -101,6 +101,8 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "metadataForms.knowledge_source.fields.source.helpText": "0b648dbc7af2f85c", "metadataForms.knowledge_source.fields.source.kind.helpText": "98e903260393800d", "metadataForms.knowledge_source.fields.source.kind.label": "3acd2ee4b0e7f2cf", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index a763af9ea39..af17169a096 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const enMetadataForms: NonNullable = { label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 9a2b081c5b8..dd8c3bf47d0 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const esESMetadataForms: NonNullable = label: "Campos de filtro", helpText: "Campos que se guardan junto a cada pasaje, para que una búsqueda pueda filtrar por ellos (por ejemplo, un estado o un propietario). Cada uno debe ser un campo que usted pueda consultar." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Registros que indexar", helpText: "Un filtro ObjectQL sobre el objeto, por ejemplo {\"status\": {\"$ne\": \"done\"}}. Solo se indexan los registros que coinciden. En blanco: todos los registros." diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts index 7824b427eaa..00cb88b4c43 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const esESGeneratedSourceHashes: Readonly> = { + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "objects.sys_email.fields.cc_addresses.label": "02946d952cf15623", "objects.sys_email.fields.error.label": "786fed84bd8d5a32", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index bd5845ad4af..c1b916cc638 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const frMetadataForms: NonNullable = { label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index af51a64f0b8..20b9153766f 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -122,6 +122,8 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "metadataForms.knowledge_source.fields.source.helpText": "0b648dbc7af2f85c", "metadataForms.knowledge_source.fields.source.kind.helpText": "98e903260393800d", "metadataForms.knowledge_source.fields.source.kind.label": "3acd2ee4b0e7f2cf", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index e25daa66cc5..37f039dfe69 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const jaJPMetadataForms: NonNullable = label: "フィルターフィールド", helpText: "各パッセージの横に保持されるフィールドで、検索でこれらによる絞り込みができます(例:ステータスや所有者)。それぞれ、あなたがクエリできるフィールドである必要があります。" }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "インデックス化するレコード", helpText: "オブジェクトに対する ObjectQL フィルター。例:{\"status\": {\"$ne\": \"done\"}}。一致するレコードだけがインデックス化されます。空欄:すべてのレコード。" diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts index 601a8fc4340..f1e7e841f72 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const jaJPGeneratedSourceHashes: Readonly> = { + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "objects.sys_email.fields.bcc_addresses.label": "8674899b7b6d5126", "objects.sys_email.fields.cc_addresses.label": "02946d952cf15623", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 69e0936fcc0..4efc74483ed 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const koMetadataForms: NonNullable = { label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index bcca80a75c0..821ea0c5048 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -66,6 +66,8 @@ export const koGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "metadataForms.knowledge_source.fields.source.helpText": "0b648dbc7af2f85c", "metadataForms.knowledge_source.fields.source.kind.helpText": "98e903260393800d", "metadataForms.knowledge_source.fields.source.kind.label": "3acd2ee4b0e7f2cf", diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index dfca7b34b03..6236c748675 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const ptBRMetadataForms: NonNullable = label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index 07292e81d0f..e49643f4ed4 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -78,6 +78,8 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "metadataForms.knowledge_source.fields.source.helpText": "0b648dbc7af2f85c", "metadataForms.knowledge_source.fields.source.kind.helpText": "98e903260393800d", "metadataForms.knowledge_source.fields.source.kind.label": "3acd2ee4b0e7f2cf", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 545c5158f16..2b772bbc273 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const ruMetadataForms: NonNullable = { label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 5c50c2a2711..e5e166a1f7d 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -66,6 +66,8 @@ export const ruGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "metadataForms.knowledge_source.fields.source.helpText": "0b648dbc7af2f85c", "metadataForms.knowledge_source.fields.source.kind.helpText": "98e903260393800d", "metadataForms.knowledge_source.fields.source.kind.label": "3acd2ee4b0e7f2cf", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 2c819d343d7..c9d1f5ce434 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const zhCNMetadataForms: NonNullable = label: "筛选字段", helpText: "保存在每个段落旁边的字段,使检索可以按它们筛选(例如状态或负责人)。每个字段都必须是你可以查询的字段。" }, + "source.documentBy": { + label: "文档单位", + helpText: "可选。把每条记录关联到它所属父记录的字段(例如条款所属的制度):须是单值的查找或主从字段,并且同时列在筛选字段中。按记录检索时,每个父记录只返回一条命中,而不是每条记录一条;没有父记录的记录单独作为一条命中。索引不变,不会重建。" + }, "source.where": { label: "要索引的记录", helpText: "对该对象的 ObjectQL 筛选条件,例如 {\"status\": {\"$ne\": \"done\"}}。只有匹配的记录会被索引。留空:所有记录。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 3ce8c1442ec..716c3804ae6 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -3553,6 +3553,10 @@ export const zhHantMetadataForms: NonNullable label: "Filter fields", helpText: "Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query." }, + "source.documentBy": { + label: "Document unit", + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index 24b354e83db..56b23425f36 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -64,6 +64,8 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.fields.refresh.onRecordChange.label": "53a3285b7bcfb91f", "metadataForms.knowledge_source.fields.source.content.helpText": "a58391e05d69ffe7", "metadataForms.knowledge_source.fields.source.content.label": "fb33868fefbf74b3", + "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", + "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "metadataForms.knowledge_source.fields.source.helpText": "0b648dbc7af2f85c", "metadataForms.knowledge_source.fields.source.kind.helpText": "98e903260393800d", "metadataForms.knowledge_source.fields.source.kind.label": "3acd2ee4b0e7f2cf", From a92874657e2f8bfb3c14f52ac103933d9163f23a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 09:33:10 +0000 Subject: [PATCH 08/12] chore(platform-objects): author the document unit row in ja-JP and es-ES, and count its label in the catalog's positive control Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .../src/apps/translations/es-ES.metadata-forms.generated.ts | 4 ++-- .../src/apps/translations/es-ES.source-hashes.generated.ts | 2 -- .../src/apps/translations/ja-JP.metadata-forms.generated.ts | 4 ++-- .../src/apps/translations/ja-JP.source-hashes.generated.ts | 2 -- .../object-lifecycle-panel-echo-decisions.test.ts | 4 +++- 5 files changed, 7 insertions(+), 9 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index dd8c3bf47d0..cf58c91a608 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3554,8 +3554,8 @@ export const esESMetadataForms: NonNullable = helpText: "Campos que se guardan junto a cada pasaje, para que una búsqueda pueda filtrar por ellos (por ejemplo, un estado o un propietario). Cada uno debe ser un campo que usted pueda consultar." }, "source.documentBy": { - label: "Document unit", - helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + label: "Unidad de documento", + helpText: "Opcional. El campo que vincula cada registro con el registro padre del que forma parte (una cláusula con su política): un campo de búsqueda o maestro-detalle, de un solo valor, que también figure en Campos de filtro. Una búsqueda por registros devuelve entonces un resultado por padre en lugar de uno por registro; un registro sin padre es su propio resultado. El índice no cambia y no se reconstruye nada." }, "source.where": { label: "Registros que indexar", diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts index 00cb88b4c43..7824b427eaa 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts @@ -18,8 +18,6 @@ */ export const esESGeneratedSourceHashes: Readonly> = { - "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", - "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "objects.sys_email.fields.cc_addresses.label": "02946d952cf15623", "objects.sys_email.fields.error.label": "786fed84bd8d5a32", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 37f039dfe69..fc7a6e67182 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3554,8 +3554,8 @@ export const jaJPMetadataForms: NonNullable = helpText: "各パッセージの横に保持されるフィールドで、検索でこれらによる絞り込みができます(例:ステータスや所有者)。それぞれ、あなたがクエリできるフィールドである必要があります。" }, "source.documentBy": { - label: "Document unit", - helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + label: "ドキュメント単位", + helpText: "任意。各レコードを、それが属する親レコードに結び付けるフィールド(例:条項が属する規程)。単一値の参照または主従フィールドで、フィルターフィールドにも含める必要があります。レコード単位の検索では、レコードごとではなく親レコードごとに 1 件のヒットを返します。親のないレコードはそれ自体で 1 件のヒットになります。インデックスは変わらず、再構築も行われません。" }, "source.where": { label: "インデックス化するレコード", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts index f1e7e841f72..601a8fc4340 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts @@ -18,8 +18,6 @@ */ export const jaJPGeneratedSourceHashes: Readonly> = { - "metadataForms.knowledge_source.fields.source.documentBy.helpText": "e389b429286eb1a8", - "metadataForms.knowledge_source.fields.source.documentBy.label": "b28af31bc5593158", "objects.sys_email.fields.bcc_addresses.label": "8674899b7b6d5126", "objects.sys_email.fields.cc_addresses.label": "02946d952cf15623", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 4be5a90cb63..242ac01424d 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1355,7 +1355,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 866 since #37309: the `knowledge_source` form (ADR-0161 K4 clause 2) // — twenty of its section and row labels, authored in all three // locales. - expect(translated.length, `${locale} positive control`).toBe(866); + // 867: the `knowledge_source` form's `documentBy` row (the document + // unit) — one row label, authored in all three locales. + expect(translated.length, `${locale} positive control`).toBe(867); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From 231e7c63390ecf2f58574a8a853604add8b1352e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:06:58 +0000 Subject: [PATCH 09/12] chore(changeset): the document unit is an added authorable key, minor on the packages it moves Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .changeset/38537-knowledge-document-by.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.changeset/38537-knowledge-document-by.md b/.changeset/38537-knowledge-document-by.md index c9435a22ae0..1336232d9f8 100644 --- a/.changeset/38537-knowledge-document-by.md +++ b/.changeset/38537-knowledge-document-by.md @@ -1,15 +1,18 @@ --- -'@objectstack/spec': patch -'@objectstack/service-knowledge': patch +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +'@objectstack/platform-objects': minor --- feat(knowledge): a knowledge source declares its document unit, `source.documentBy`; record-level search answers one hit per parent for it Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added A `knowledge_source` may now name the field that links each indexed record to the parent record it is part of: `source: { kind: 'object', object: 'policy_clause', content: ['body'], metadataFields: ['policy'], documentBy: 'policy' }`. For such a source, `search` / `search_knowledge` with `granularity: 'record'` and no `groupBy` returns one hit per parent (that parent's best passage) instead of one per record; the hit's `groupValue` is the parent id. A record with no parent is still its own hit, and two sources never share a parent. An explicit `groupBy`, `granularity: 'chunk'`, and every source without `documentBy` answer exactly as before. The index does not change: still one document per record. `documentBy` enters neither the index fingerprint nor the recipe hash, so adding it rebuilds nothing. `documentBy` must be listed in `metadataFields`, or the parse refuses it and says to add it there. Saving a source through Studio, the metadata API or MCP also refuses a field that is not a single-valued parent link: it must be a `lookup` or `master_detail` field, not `multiple: true`, and neither a credential nor an `internal` field. A `text` or `user` field is refused, with a message naming the fix. + +Studio's knowledge source form offers the key as a "Document unit" field picker beside the filter fields (its label and help translated in the platform's metadata-form bundles). From 12cd7dc8a6f7ac508ff7254a0075c5b1a88103c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:58:00 +0000 Subject: [PATCH 10/12] fix(knowledge): the document unit's contract text states what this head does The documentBy docblock names the save refusal alone (a packaged or code-registered source is not judged yet) and where each surface carries the parent: metadata[documentBy] on IKnowledgeService.search, groupValue on the search_knowledge hit. The form help and changeset say that listing the parent in Filter fields for the first time does rebuild. hitOf serves the parent only for a source that lists documentBy in metadataFields, as its groupBy arm does, with a pin over a stub service. The granularity and groupBy contract TSDoc and the search_knowledge description name the document unit. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .changeset/38537-knowledge-document-by.md | 4 ++-- .../src/__tests__/document-by-38537.test.ts | 24 ++++++++++++++++++- .../service-knowledge/src/knowledge-tools.ts | 10 +++++--- .../src/ai/knowledge-source.metadata-form.ts | 2 +- packages/spec/src/ai/knowledge-source.zod.ts | 18 +++++++------- .../spec/src/contracts/knowledge-service.ts | 9 +++++-- 6 files changed, 50 insertions(+), 17 deletions(-) diff --git a/.changeset/38537-knowledge-document-by.md b/.changeset/38537-knowledge-document-by.md index 1336232d9f8..020e42641c7 100644 --- a/.changeset/38537-knowledge-document-by.md +++ b/.changeset/38537-knowledge-document-by.md @@ -9,9 +9,9 @@ feat(knowledge): a knowledge source declares its document unit, `source.document Clause-②: yes (widening) Metadata-protocol: added -A `knowledge_source` may now name the field that links each indexed record to the parent record it is part of: `source: { kind: 'object', object: 'policy_clause', content: ['body'], metadataFields: ['policy'], documentBy: 'policy' }`. For such a source, `search` / `search_knowledge` with `granularity: 'record'` and no `groupBy` returns one hit per parent (that parent's best passage) instead of one per record; the hit's `groupValue` is the parent id. A record with no parent is still its own hit, and two sources never share a parent. An explicit `groupBy`, `granularity: 'chunk'`, and every source without `documentBy` answer exactly as before. +A `knowledge_source` may now name the field that links each indexed record to the parent record it is part of: `source: { kind: 'object', object: 'policy_clause', content: ['body'], metadataFields: ['policy'], documentBy: 'policy' }`. For such a source, `search` / `search_knowledge` with `granularity: 'record'` and no `groupBy` returns one hit per parent (that parent's best passage) instead of one per record. The parent id is in the hit's `metadata[documentBy]` on `search`, and also in `groupValue` on a `search_knowledge` hit. A record with no parent is still its own hit, and two sources never share a parent. An explicit `groupBy`, `granularity: 'chunk'`, and every source without `documentBy` answer exactly as before. -The index does not change: still one document per record. `documentBy` enters neither the index fingerprint nor the recipe hash, so adding it rebuilds nothing. +The index does not change: still one document per record. `documentBy` enters neither the index fingerprint nor the recipe hash, so setting it rebuilds nothing (listing the parent field in `metadataFields` for the first time does, as any new metadata field does). `documentBy` must be listed in `metadataFields`, or the parse refuses it and says to add it there. Saving a source through Studio, the metadata API or MCP also refuses a field that is not a single-valued parent link: it must be a `lookup` or `master_detail` field, not `multiple: true`, and neither a credential nor an `internal` field. A `text` or `user` field is refused, with a message naming the fix. diff --git a/packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts b/packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts index 5ed067c0b3b..2f8bb41fcb6 100644 --- a/packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts +++ b/packages/services/service-knowledge/src/__tests__/document-by-38537.test.ts @@ -17,11 +17,12 @@ */ import { describe, expect, it, vi } from 'vitest'; -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 { KnowledgeService, recordToDocument } from '../knowledge-service.js'; import { computeIndexFingerprint, computeRecipeHash } from '../knowledge-index-fingerprint.js'; +import { createKnowledgeTools } from '../knowledge-tools.js'; const MEMBER: ExecutionContext = { userId: 'u1', positions: ['member'], permissions: [], isSystem: false }; @@ -189,6 +190,27 @@ describe("documentBy — a record-level search with no groupBy answers one hit p const byChunk = await svc.knowledgeTools().searchKnowledge({ query: 'q', topK: 10 }, MEMBER); for (const hit of byChunk.hits) expect(hit).not.toHaveProperty('groupValue'); }); + + it('search_knowledge over any service: a documentBy its source does not list in metadataFields serves no groupValue', async () => { + const stored: KnowledgeHit = { + chunkId: 'policy_clause:c1#0', sourceId: 'clauses', documentId: 'policy_clause:c1', sourceRecordId: 'c1', snippet: 's', score: 0.9, + metadata: { policy: 'P_leave', hidden_parent: 'H_1' }, + }; + const toolsOver = (source: KnowledgeSource) => createKnowledgeTools({ + listSources: () => [source], + search: async () => [stored], + } as unknown as IKnowledgeService); + // A stub service that never parsed its source: `hidden_parent` is not listed. + const unlisted = await toolsOver(clauseSource('clauses', { metadataFields: ['policy'], documentBy: 'hidden_parent' })) + .searchKnowledge({ query: 'q', granularity: 'record' }, MEMBER); + expect(unlisted.hits).toHaveLength(1); + expect(unlisted.hits[0]).not.toHaveProperty('groupValue'); + expect(JSON.stringify(unlisted)).not.toContain('H_1'); + // Positive control: the same hit under a listed documentBy carries its parent. + const listed = await toolsOver(clauseSource('clauses', { metadataFields: ['policy'], documentBy: 'policy' })) + .searchKnowledge({ query: 'q', granularity: 'record' }, MEMBER); + expect(listed.hits[0]?.groupValue).toBe('P_leave'); + }); }); describe('documentBy — no index change: neither hash reads it', () => { diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index 15a3e675a82..e49165a005f 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -222,7 +222,10 @@ const SEARCH_KNOWLEDGE_DESCRIPTION = + '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. ' + '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 ' + + '`granularity: "record"`: one hit per record, its best passage, and `topK` counts records; for a source that ' + + 'declares a document unit (`documentBy`, the field linking each record to its parent, a clause to its policy), ' + + 'one hit per parent instead, which the hit carries as `groupValue` (a record with no parent is its own hit). ' + + '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 that does not index that field ' @@ -525,8 +528,8 @@ function declaredMetadataOf( * (`metadata`, {@link declaredMetadataOf}) and, under `groupBy`, that field's * value (`groupValue`), only for a source that lists that field — or, under * `granularity: 'record'` with no `groupBy`, the parent its source's - * `documentBy` names ({@link documentUnitValueOf}), a field the parse holds in - * `metadataFields`. Neither + * `documentBy` names ({@link documentUnitValueOf}), likewise 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`). @@ -547,6 +550,7 @@ function hitOf( const groupValue = groupBy !== undefined ? (objSource?.metadataFields?.includes(groupBy) ? hit.metadata?.[groupBy] : undefined) : granularity === 'record' && objSource?.documentBy !== undefined + && objSource.metadataFields?.includes(objSource.documentBy) ? documentUnitValueOf(hit.metadata, objSource.documentBy) : undefined; const metadata = declaredMetadataOf(hit.metadata, objSource?.metadataFields); diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index bd478aed378..cacab98090b 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -72,7 +72,7 @@ export const knowledgeSourceForm = defineMetadataForm({ helpText: 'The fields whose text is indexed, in order. Each field is named: there is no wildcard. Embedding is egress, and a build costs money: the first build reads every record the filter matches and sends the text of each listed field to your embedding provider, which bills for it, and that text is kept in an index outside the record store. A rebuild after you change the embedding model or the split sends all of it again. A field added to the object later is not indexed until you add it here. Credential and internal fields are never indexed, even when listed.', }, { field: 'metadataFields', label: 'Filter fields', widget: 'field-multi', dependsOn: 'object', helpText: 'Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query.' }, - { field: 'documentBy', label: 'Document unit', widget: 'field-ref', dependsOn: 'object', helpText: 'Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt.' }, + { field: 'documentBy', label: 'Document unit', widget: 'field-ref', dependsOn: 'object', helpText: 'Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. Setting it rebuilds nothing; adding the field to Filter fields does.' }, { field: 'where', label: 'Records to index', widget: 'json', helpText: 'An ObjectQL filter on the object, for example {"status": {"$ne": "done"}}. Only the records it matches are indexed. Blank: every record.' }, { field: 'split', diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 211cb6dc13a..8281b04e505 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -230,16 +230,18 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( * * Read by a record-level search (`granularity: 'record'`) that names no * `groupBy`: the hits of this source are grouped by the parent the field - * holds, one hit per parent (its best passage), and the hit carries that - * parent as its `groupValue`. A record with no parent is its own hit, as - * before. Two sources never share a group, whatever their parents. An - * explicit `groupBy` is answered as before. + * holds, one hit per parent (its best passage). The parent reaches the + * caller as the hit's `metadata[documentBy]` on `IKnowledgeService.search`, + * and also as `groupValue` on a `search_knowledge` tool hit. A record with + * no parent is its own hit, as before. Two sources never share a group, + * whatever their parents. An explicit `groupBy` is answered as before. * * Must be one of {@link metadataFields}: grouping reads the value the - * index stores beside each passage. Saving and `os validate` also refuse - * a field that is not a single-valued parent link: a `lookup` or - * `master_detail` field (never `multiple: true`), not credential-class or - * `internal`. + * index stores beside each passage. Saving a source also refuses a field + * that is not a single-valued parent link: a `lookup` or `master_detail` + * field (never `multiple: true`), not credential-class or `internal`. A + * source registered in code or installed with a package meets no save, + * so that rule does not judge it yet. */ documentBy: z.string().optional() .describe('Field linking each record to its parent document (a lookup or master_detail listed in metadataFields); record-level search answers one hit per parent'), diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index b22e8c76224..50d9f3fd00e 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -37,7 +37,11 @@ export interface KnowledgeSearchOptions { * * - `'chunk'` (the default): one hit per matching passage, as before. * - `'record'`: one hit per record — the best-scoring passage of the - * record, so `topK` counts records. Each hit returned is checked against + * record, so `topK` counts records. For a source that declares + * `documentBy` (its document unit), one hit per parent record instead — + * the best passage among that parent's records, the parent read from the + * hit's `metadata[documentBy]` — and a record with no parent is its own + * hit; two sources never share a parent. Each hit returned is checked against * the record as it reads now: a record that was deleted, left the * source's `where`, or changed since it was indexed is not returned, and * its document is repaired in the background — except in a source with @@ -56,7 +60,8 @@ export interface KnowledgeSearchOptions { * passing an empty name, or an unknown `granularity`) is refused with * `code: 'VALIDATION_ERROR'`, `status: 400`. An `object` source that does not list the field in its * `metadataFields` answers no hits for this search (never ungrouped), and - * neither does a record with no value for it. + * neither does a record with no value for it. An explicit `groupBy` takes + * the place of a source's `documentBy` for this search. */ groupBy?: string; /** Adapter-specific filter (passed opaquely). */ From e0ebb9ad8eb6c996ad6fa73fb9bd91951e3d3979 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:59:02 +0000 Subject: [PATCH 11/12] chore(i18n): regenerate the metadata-form bundles for the document unit's help Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .../src/apps/translations/en.metadata-forms.generated.ts | 2 +- .../src/apps/translations/es-ES.metadata-forms.generated.ts | 2 +- .../src/apps/translations/ja-JP.metadata-forms.generated.ts | 2 +- .../src/apps/translations/zh-CN.metadata-forms.generated.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index af17169a096..c8a96098508 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3555,7 +3555,7 @@ export const enMetadataForms: NonNullable = { }, "source.documentBy": { label: "Document unit", - helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. The index is unchanged and nothing is rebuilt." + helpText: "Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. Setting it rebuilds nothing; adding the field to Filter fields does." }, "source.where": { label: "Records to index", diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index cf58c91a608..15aac59cbd3 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3555,7 +3555,7 @@ export const esESMetadataForms: NonNullable = }, "source.documentBy": { label: "Unidad de documento", - helpText: "Opcional. El campo que vincula cada registro con el registro padre del que forma parte (una cláusula con su política): un campo de búsqueda o maestro-detalle, de un solo valor, que también figure en Campos de filtro. Una búsqueda por registros devuelve entonces un resultado por padre en lugar de uno por registro; un registro sin padre es su propio resultado. El índice no cambia y no se reconstruye nada." + helpText: "Opcional. El campo que vincula cada registro con el registro padre del que forma parte (una cláusula con su política): un campo de búsqueda o maestro-detalle, de un solo valor, que también figure en Campos de filtro. Una búsqueda por registros devuelve entonces un resultado por padre en lugar de uno por registro; un registro sin padre es su propio resultado. Definirlo no reconstruye nada; añadir el campo a Campos de filtro sí lo hace." }, "source.where": { label: "Registros que indexar", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index fc7a6e67182..62ac863d396 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3555,7 +3555,7 @@ export const jaJPMetadataForms: NonNullable = }, "source.documentBy": { label: "ドキュメント単位", - helpText: "任意。各レコードを、それが属する親レコードに結び付けるフィールド(例:条項が属する規程)。単一値の参照または主従フィールドで、フィルターフィールドにも含める必要があります。レコード単位の検索では、レコードごとではなく親レコードごとに 1 件のヒットを返します。親のないレコードはそれ自体で 1 件のヒットになります。インデックスは変わらず、再構築も行われません。" + helpText: "任意。各レコードを、それが属する親レコードに結び付けるフィールド(例:条項が属する規程)。単一値の参照または主従フィールドで、フィルターフィールドにも含める必要があります。レコード単位の検索では、レコードごとではなく親レコードごとに 1 件のヒットを返します。親のないレコードはそれ自体で 1 件のヒットになります。この設定だけでは再構築されませんが、フィールドをフィルターフィールドに新たに追加すると再構築されます。" }, "source.where": { label: "インデックス化するレコード", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index c9d1f5ce434..dd72f013647 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -3555,7 +3555,7 @@ export const zhCNMetadataForms: NonNullable = }, "source.documentBy": { label: "文档单位", - helpText: "可选。把每条记录关联到它所属父记录的字段(例如条款所属的制度):须是单值的查找或主从字段,并且同时列在筛选字段中。按记录检索时,每个父记录只返回一条命中,而不是每条记录一条;没有父记录的记录单独作为一条命中。索引不变,不会重建。" + helpText: "可选。把每条记录关联到它所属父记录的字段(例如条款所属的制度):须是单值的查找或主从字段,并且同时列在筛选字段中。按记录检索时,每个父记录只返回一条命中,而不是每条记录一条;没有父记录的记录单独作为一条命中。设置它不会触发重建;把该字段首次加入筛选字段则会。" }, "source.where": { label: "要索引的记录", From 43de68d58f094661a1f28d332f5becd486fe02bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 11:16:25 +0000 Subject: [PATCH 12/12] docs(knowledge): every record-level unit statement names the document unit The topK TSDoc in the knowledge-service contract, and in search_knowledge the topK, granularity and groupBy input descriptions, the matching input and output TSDoc and the granularity refusal, say that for a source that declares documentBy (its document unit) a record-level result counts one hit per parent record instead. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb --- .../service-knowledge/src/knowledge-tools.ts | 23 +++++++++++++------ .../spec/src/contracts/knowledge-service.ts | 10 ++++---- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index e49165a005f..5bc9ef1545d 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -111,9 +111,16 @@ export interface SearchKnowledgeInput { 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). */ + /** + * One hit per passage (`chunk`, the default) or per record (`record`) + * (ADR-0161 K1); under `record`, for a source that declares `documentBy` (its document unit), one hit per parent record instead. + */ granularity?: SearchKnowledgeGranularity; - /** One hit per value of this metadata field instead of per record; implies `granularity: 'record'`. */ + /** + * One hit per value of this metadata field instead of per record (or per + * parent record, for a source that declares `documentBy`); implies + * `granularity: 'record'`. + */ groupBy?: string; } @@ -178,7 +185,9 @@ export interface SearchKnowledgeRefusedSource { export interface SearchKnowledgeOutput { /** * The hits, most relevant first, at most `topK`: passages, or one per - * record under `granularity: 'record'`, or one per group under `groupBy`. + * record under `granularity: 'record'` (one per parent record, for a source + * that declares `documentBy`, its document unit), 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). */ @@ -260,7 +269,7 @@ const SEARCH_KNOWLEDGE_PARAMETERS: Record = Object.freeze({ type: 'integer', minimum: 1, maximum: SEARCH_KNOWLEDGE_MAX_TOP_K, - description: `At most this many hits (default ${SEARCH_KNOWLEDGE_DEFAULT_TOP_K}): passages, or records or groups under \`granularity: "record"\` or \`groupBy\``, + description: `At most this many hits (default ${SEARCH_KNOWLEDGE_DEFAULT_TOP_K}): passages, or records (parent records, for a source that declares \`documentBy\`, its document unit) or groups under \`granularity: "record"\` or \`groupBy\``, }, scope: { type: 'array', @@ -286,11 +295,11 @@ const SEARCH_KNOWLEDGE_PARAMETERS: Record = Object.freeze({ granularity: { type: 'string', enum: ['chunk', 'record'], - description: 'One hit per passage (`chunk`, the default) or per record (`record`)', + description: 'One hit per passage (`chunk`, the default) or per record (`record`); under `record`, for a source that declares `documentBy` (its document unit), one hit per parent record instead', }, groupBy: { ...NAME_SCHEMA, - description: 'One hit per value of this indexed field instead of per record; not with `granularity: "chunk"`', + description: 'One hit per value of this indexed field instead of per record (or per parent record, for a source that declares `documentBy`); not with `granularity: "chunk"`', }, }, required: ['query'], @@ -438,7 +447,7 @@ function parseInput(input: unknown): SearchKnowledgeInput { 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).'); + throw refusal('VALIDATION_ERROR', 400, '`granularity` is "chunk" (one hit per passage) or "record" (one hit per record, or per parent record for a source that declares `documentBy`).'); } parsed.granularity = record.granularity; } diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index 50d9f3fd00e..e4a6b8348a1 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -29,7 +29,8 @@ export interface KnowledgeSearchOptions { /** * Max number of hits to return. Adapters may cap further. Under * `granularity: 'record'` it counts records (or `groupBy` groups), not - * passages. + * passages. For a source that declares `documentBy` (its document unit), + * it counts parent records instead. */ topK?: number; /** @@ -40,8 +41,8 @@ export interface KnowledgeSearchOptions { * record, so `topK` counts records. For a source that declares * `documentBy` (its document unit), one hit per parent record instead — * the best passage among that parent's records, the parent read from the - * hit's `metadata[documentBy]` — and a record with no parent is its own - * hit; two sources never share a parent. Each hit returned is checked against + * hit's `metadata[documentBy]`, so `topK` counts parent records — and a + * record with no parent is its own hit; two sources never share a parent. Each hit returned is checked against * the record as it reads now: a record that was deleted, left the * source's `where`, or changed since it was indexed is not returned, and * its document is repaired in the background — except in a source with @@ -53,7 +54,8 @@ export interface KnowledgeSearchOptions { granularity?: 'chunk' | 'record'; /** * Group record-level hits by the value of this metadata field instead of by - * record — "which policies", not "which clauses" — keeping the best hit of + * record (or by parent record, for a source that declares `documentBy`) — + * "which policies", not "which clauses" — keeping the best hit of * each group; the group value is the hit's `metadata[groupBy]`, and hits * with the same value form one group whichever source they come from. Implies * `granularity: 'record'`; passing it with `granularity: 'chunk'` (or