diff --git a/.changeset/38537-knowledge-document-by-validate.md b/.changeset/38537-knowledge-document-by-validate.md new file mode 100644 index 00000000000..49809a598f3 --- /dev/null +++ b/.changeset/38537-knowledge-document-by-validate.md @@ -0,0 +1,12 @@ +--- +'@objectstack/lint': patch +--- + +fix(lint): `os validate` and the publish gate refuse a knowledge source whose `documentBy` is not a single-valued parent link + +Clause-②: no +Metadata-protocol: none + +A knowledge source's `source.documentBy` (its document unit, new in this release) must name a `lookup` or `master_detail` field of the indexed object that points at each record's parent record: declared by the object, with a readable `reference`, not `multiple: true`, and neither credential-class nor `internal`. The metadata API's save door already refused any other field. New rule `knowledge-source-document-by-not-parent-link` (`error`) now refuses it in `os validate`, `os build` and `os lint`, and at the runtime publish gate, which is what judges a source a package ships or code registers. The message names the field, why it cannot be the document unit, and the fix: name the parent lookup, or remove `documentBy`. + +A `documentBy` that `metadataFields` does not list is still refused by the schema, and a field the object does not have is still reported once, as `knowledge-source-field-unknown`. `os explain knowledge-source-document-by-not-parent-link` describes the rule. diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index 35e41d627a2..3f63af95796 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -322,6 +322,11 @@ const CALLERS: Record = { kind: 'not-a-served-read', reason: 'authoring-time static analysis of metadata; reads no record', }, + // [#38537] A knowledge source's `documentBy` judged as a parent link: asks only whether a target is declared. + 'packages/lint/src/validate-knowledge-source.ts': { + kind: 'not-a-served-read', + reason: 'authoring-time static analysis of metadata; reads no record', + }, // [#35146] The post-publish build probes' two landed-data checks. 'packages/metadata-protocol/src/build-probes.ts': { kind: 'not-a-served-read', diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 77aa5a13a74..393cc6b4dca 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -418,6 +418,7 @@ export { KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE, KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, + KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK, } from './validate-knowledge-source.js'; export type { KnowledgeSourceFinding, KnowledgeSourceSeverity } from './validate-knowledge-source.js'; diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index d0046777dd1..c05de677490 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -6422,6 +6422,24 @@ const KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED_EXPLANATION: RuleExplanation = { ], }; +const KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK_EXPLANATION: RuleExplanation = { + rule: 'knowledge-source-document-by-not-parent-link', + covers: 'why a document unit must be a single parent link', + paragraphs: [ + 'A source\'s `documentBy` names its document unit: the field that links each indexed record to the parent ' + + 'record it is part of, such as the policy a clause belongs to. Record-level search then answers one hit ' + + 'per parent instead of one per record, read from the parent value each passage carries in its metadata.', + 'So the field must be a single-valued parent link: declared by the object, a `lookup` or `master_detail` ' + + 'field (a `user` field names a person, not a document), with a target the platform can read (its ' + + '`reference`), not `multiple: true` (a record that names several parents belongs to no one document), and ' + + 'neither credential-class nor `internal`, because the index never stores such a field. It must also be ' + + 'listed in `metadataFields`; the schema refuses it otherwise.', + 'To clear it, name the lookup or master_detail field that points at each record\'s parent record, or remove ' + + '`documentBy`. The same rule refuses the source when it is saved through the metadata API.', + KNOWLEDGE_SOURCE_DOORS, + ], +}; + // ── Assignment rules (`validate-assignment-rules.ts`) ── const ASSIGNMENT_RULE_USER_TARGET_EXPLANATION: RuleExplanation = { @@ -7519,6 +7537,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE_EXPLANATION.rule]: KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE_EXPLANATION, [KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE_EXPLANATION.rule]: KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE_EXPLANATION, [KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED_EXPLANATION.rule]: KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED_EXPLANATION, + [KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK_EXPLANATION.rule]: KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK_EXPLANATION, [ASSIGNMENT_RULE_USER_TARGET_EXPLANATION.rule]: ASSIGNMENT_RULE_USER_TARGET_EXPLANATION, [ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION.rule]: ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION, [SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION.rule]: SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION, diff --git a/packages/lint/src/validate-knowledge-source.document-by.test.ts b/packages/lint/src/validate-knowledge-source.document-by.test.ts new file mode 100644 index 00000000000..1bea27d2432 --- /dev/null +++ b/packages/lint/src/validate-knowledge-source.document-by.test.ts @@ -0,0 +1,173 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// [ADR-0161 K4] `source.documentBy`, a knowledge source's document unit, must +// be a single-valued parent link of the indexed object. The knowledge service's +// save door refuses any other field for a source written through the metadata +// API; this file pins the same verdict for `os validate` and the runtime +// publish gate, which judge the sources a package ships or code registers. + +import { describe, expect, it } from 'vitest'; +import { + KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK, + KNOWLEDGE_SOURCE_FIELD_UNKNOWN, + validateKnowledgeSource, +} from './validate-knowledge-source.js'; +import { KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK as FROM_BARREL } from './index.js'; +import { explainRule } from './rule-explanations.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +const objects = [ + { name: 'policy', fields: { title: { type: 'text' } } }, + { + name: 'policy_clause', + fields: { + body: { type: 'markdown' }, + clause_hash: { type: 'text' }, + policy: { type: 'lookup', reference: 'policy' }, + master_policy: { type: 'master_detail', reference: 'policy' }, + reviewer: { type: 'user' }, + hidden_policy: { type: 'lookup', reference: 'policy', internal: true }, + vault_key: { type: 'secret' }, + policies: { type: 'lookup', reference: 'policy', multiple: true }, + dangling: { type: 'lookup' }, + }, + }, +]; + +/** A source over `policy_clause` whose document unit is `documentBy`, listed in `metadataFields`. */ +const clauseSource = (documentBy: string | undefined, metadataFields: string[] = documentBy ? [documentBy] : []) => ({ + name: 'policy_kb', + label: 'Policy KB', + source: { + kind: 'object', + object: 'policy_clause', + content: ['body'], + metadataFields, + ...(documentBy === undefined ? {} : { documentBy }), + }, +}); + +const DOC_RULE = KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK; + +/** `os validate`'s verdict: the CLI command's own registry entry over the stack. */ +const atValidate = (source: Record) => { + const stack = { objects, knowledgeSources: [source] }; + return runAuthoringRules('validate', { parsed: stack, normalized: stack }).filter((f) => + f.rule.startsWith('knowledge-source-'), + ); +}; + +/** The runtime publish door's verdict on one source written against `objects`. */ +const atPublish = (source: Record) => + runRuntimeAuthoringRules({ type: 'knowledge_source', item: source, context: { objects } }); + +/** [what, documentBy, words the message must carry, words the hint must carry] */ +const REFUSED: ReadonlyArray<[string, string, string, string]> = [ + ['a text field', 'clause_hash', 'a `text` field', 'lookup or master_detail'], + ['a user field', 'reviewer', 'a user field names a person', 'lookup or master_detail'], + ['an internal lookup', 'hidden_policy', 'a credential or internal field', 'neither credential-class nor internal'], + ['a credential-class field', 'vault_key', 'a credential or internal field', 'neither credential-class nor internal'], + ['a multiple lookup', 'policies', '`multiple: true`', 'not `multiple`'], + ['a lookup with no readable target', 'dangling', 'target object cannot be read', "Declare the field's `reference`"], + ['a system column the platform adds', 'owner_id', 'does not declare', 'lookup or master_detail'], +]; + +describe('validateKnowledgeSource: source.documentBy (os validate)', () => { + for (const [what, documentBy, inMessage, inHint] of REFUSED) { + it(`refuses ${what} as the document unit, naming the field and the fix`, () => { + const findings = atValidate(clauseSource(documentBy)).filter((f) => f.rule === DOC_RULE); + expect(findings.map((f) => [f.severity, f.path, f.where])).toEqual([ + ['error', 'knowledgeSources[0].source.documentBy', 'knowledge source "policy_kb"'], + ]); + expect(findings[0]!.message).toContain(`\`source.documentBy\` names '${documentBy}'`); + expect(findings[0]!.message).toContain(inMessage); + expect(findings[0]!.hint).toContain(inHint); + expect(findings[0]!.hint).toContain('remove `documentBy`'); + }); + } + + it('CONTROL: a lookup and a master_detail to the parent are admitted', () => { + expect(atValidate(clauseSource('policy'))).toEqual([]); + expect(atValidate(clauseSource('master_policy'))).toEqual([]); + }); + + it('CONTROL: a source without documentBy is judged as before', () => { + expect(atValidate(clauseSource(undefined, ['clause_hash']))).toEqual([]); + }); + + it('a documentBy that metadataFields does not list is left to the parse, which names that fix', () => { + const findings = atValidate(clauseSource('clause_hash', ['policy'])); + expect(findings.filter((f) => f.rule === DOC_RULE)).toEqual([]); + }); + + it('a member the object does not have is reported once, as an unknown field', () => { + const findings = atValidate(clauseSource('polcy')); + expect(findings.map((f) => [f.rule, f.path])).toEqual([ + [KNOWLEDGE_SOURCE_FIELD_UNKNOWN, 'knowledgeSources[0].source.metadataFields[0]'], + ]); + }); + + it('an object with no readable field map is not judged', () => { + const stack = { + objects: [{ name: 'policy_clause' }], + knowledgeSources: [clauseSource('clause_hash')], + }; + expect(validateKnowledgeSource(stack).filter((f) => f.rule === DOC_RULE)).toEqual([]); + }); + + it('a fields array is read like a field map', () => { + const stack = { + objects: [ + { + name: 'policy_clause', + fields: [ + { name: 'body', type: 'markdown' }, + { name: 'clause_hash', type: 'text' }, + { name: 'policy', type: 'lookup', reference: 'policy' }, + ], + }, + ], + knowledgeSources: [clauseSource('clause_hash'), clauseSource('policy')], + }; + expect(validateKnowledgeSource(stack).map((f) => [f.rule, f.path])).toEqual([ + [DOC_RULE, 'knowledgeSources[0].source.documentBy'], + ]); + }); +}); + +describe('validateKnowledgeSource: source.documentBy (runtime publish door)', () => { + it('refuses the publish with the words os validate prints', () => { + const source = clauseSource('clause_hash'); + const verdict = atPublish(source); + expect(verdict.rulesRun).toContain('validateKnowledgeSource'); + const refused = verdict.errors.filter((f) => f.rule === DOC_RULE); + expect(refused).toHaveLength(1); + const face = (f: { rule: string; severity: string; where: string; message: string; hint?: string }) => ({ + rule: f.rule, + severity: f.severity, + where: f.where, + message: f.message, + hint: f.hint, + }); + expect(refused.map(face)).toEqual(atValidate(source).filter((f) => f.rule === DOC_RULE).map(face)); + }); + + it('CONTROL: a single-valued parent link publishes with nothing to report', () => { + const verdict = atPublish(clauseSource('policy')); + expect(verdict.errors).toEqual([]); + expect(verdict.advisories.filter((f) => f.rule.startsWith('knowledge-source-'))).toEqual([]); + }); +}); + +describe('the document-unit rule id is published and explained', () => { + it('the root barrel re-exports it', () => { + expect(FROM_BARREL).toBe('knowledge-source-document-by-not-parent-link'); + }); + + it('os explain answers it', () => { + const entry = explainRule(DOC_RULE); + expect(entry?.rule).toBe(DOC_RULE); + expect(entry?.paragraphs.join(' ')).toContain('single-valued parent link'); + }); +}); diff --git a/packages/lint/src/validate-knowledge-source.ts b/packages/lint/src/validate-knowledge-source.ts index e64700f3d1a..d9f63681062 100644 --- a/packages/lint/src/validate-knowledge-source.ts +++ b/packages/lint/src/validate-knowledge-source.ts @@ -18,7 +18,7 @@ * `validateAiContext`, which only advises at publish (ADR-0160 D1: a context * pack still reads what resolves); K4 orders the refusal here. * - * Five verdicts: + * Six verdicts: * * - `knowledge-source-object-unknown`: `source.object` names no object of the * stack or of a package of its artifact (`packages[]`), or, at the publish @@ -74,6 +74,20 @@ * declaration the service's withheld set asks) or an `internal` field. The * index never carries either, even when named (ADR-0161 K5), so the author * hears that the member is skipped (ADR-0078). + * - `knowledge-source-document-by-not-parent-link` (`error`): `source.documentBy`, + * the source's document unit, names a member of `metadataFields` that is not a + * single-valued parent link of the object. The rule is the one the knowledge + * service's save door asks (`documentUnitOf` in + * `@objectstack/service-knowledge`'s `knowledge-search-scope.ts`), composed + * here from the same spec predicates, because this package never depends on + * a runtime: the field is declared, is neither credential-class nor + * `internal` (the reading the never-indexed verdict above takes), is a + * `lookup` or `master_detail`, has a target `referenceTargetOf` can read, and + * is not `multiple: true`. The save door judges a source written through the + * metadata API; this verdict is what judges one a package ships or code + * registers. A `documentBy` that `metadataFields` does not list is left to + * the parse, which names that fix; a member the object does not have at all + * is reported once, by `knowledge-source-field-unknown`. * * Not judged here, because they need an environment or a principal: the * disabled-package gate and the field-queryable gate. Both are asked at save, @@ -87,7 +101,13 @@ * are judged on every object whose definition is in hand. */ -import { canServeApiOperation, isAiReadExposed, isMaskedOnReadFieldType, type EnableLike } from '@objectstack/spec/data'; +import { + canServeApiOperation, + isAiReadExposed, + isMaskedOnReadFieldType, + referenceTargetOf, + type EnableLike, +} from '@objectstack/spec/data'; import { hasPlatformObjectPrefix, isPlatformProvidedObjectName } from '@objectstack/spec/system'; import { collectionEntries } from './collection-entries.js'; import { closureDependencyRemedy, objectsAsServed, packagesOf, recordsOf, suggestName } from './object-graph.js'; @@ -112,6 +132,7 @@ export const KNOWLEDGE_SOURCE_FIELD_UNKNOWN = 'knowledge-source-field-unknown'; export const KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE = 'knowledge-source-object-not-searchable'; export const KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE = 'knowledge-source-system-object-not-ai-readable'; export const KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED = 'knowledge-source-field-never-indexed'; +export const KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK = 'knowledge-source-document-by-not-parent-link'; /** The operation a knowledge search is judged as — the admission module's `KNOWLEDGE_SEARCH_OPERATION`. */ const SEARCH_OPERATION = 'search'; @@ -139,6 +160,100 @@ function declaredFieldsOf(object: AnyRec): Map | undefined { return new Map(recordsOf(raw).map((f) => [str(f.name), f] as const).filter(([name]) => name !== '')); } +/** The field types that link a record to a parent record (never `user`, never `tree`). */ +const PARENT_LINK_TYPES: ReadonlySet = new Set(['lookup', 'master_detail']); + +/** Why `source.documentBy` cannot be the source's document unit. */ +type DocumentUnitRefusal = 'undeclared' | 'withheld' | 'not-a-link' | 'no-target' | 'multiple'; + +/** + * Why `field` cannot be the document unit of a source over `object`, or + * `undefined` when it can: a single-valued parent link. The same answer, in + * the same order, as the save door's `documentUnitOf` + * (`@objectstack/service-knowledge`, `knowledge-search-scope.ts`): declared, + * not withheld from the index, a parent-link type, a readable target, one + * parent. `fields` is {@link declaredFieldsOf} over `object`. + */ +function documentUnitRefusal( + field: string, + object: AnyRec, + fields: ReadonlyMap, +): { reason: DocumentUnitRefusal; type?: string } | undefined { + const def = fields.get(field); + if (!def) return { reason: 'undeclared' }; + const type = typeof def.type === 'string' ? def.type : undefined; + const typed = type ? { type } : {}; + if (isMaskedOnReadFieldType(def.type, object.managedBy) || def.internal === true) { + return { reason: 'withheld', ...typed }; + } + if (type === undefined || !PARENT_LINK_TYPES.has(type)) return { reason: 'not-a-link', ...typed }; + let target: string | undefined; + try { + target = referenceTargetOf(def); + } catch { + target = undefined; + } + if (target === undefined) return { reason: 'no-target', type }; + if (def.multiple === true) return { reason: 'multiple', type }; + return undefined; +} + +/** + * The finding's sentence, one per reason: the wording the save door refuses + * with (`documentUnitRefusalText`), so an author hears one explanation at + * either door. + */ +function documentUnitRefusalText( + object: string, + field: string, + refusal: { reason: DocumentUnitRefusal; type?: string }, +): { message: string; hint: string } { + const hint = + `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 = refusal.type === undefined ? 'a field' : `a \`${refusal.type}\` field`; + switch (refusal.reason) { + case 'undeclared': + return { + message: + `${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.', + hint, + }; + case 'withheld': + return { + message: + `${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.', + hint: `${hint}; it must be neither credential-class nor internal`, + }; + case 'not-a-link': + return { + message: + `${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' + + (refusal.type === 'user' ? ' (a user field names a person, not the document a record is part of)' : '') + + '.', + hint, + }; + case 'no-target': + return { + message: + `${named}, ${typed} of object '${object}' whose target object cannot be read (it declares no ` + + '`reference`), so the parent it holds is not known.', + hint: `Declare the field's \`reference\`, or ${hint.charAt(0).toLowerCase()}${hint.slice(1)}`, + }; + case 'multiple': + return { + message: + `${named}, ${typed} of object '${object}' declared \`multiple: true\`: a record that names several ` + + 'parents belongs to no one document.', + hint: `${hint}; it must hold one parent (not \`multiple\`)`, + }; + } +} + /** * The ids of the packages the stack's manifest declares in `dependencies` * that its artifact (`packages[]`) does not carry: packages whose objects the @@ -395,6 +510,26 @@ export function validateKnowledgeSource( }; judgeMembers('content'); judgeMembers('metadataFields'); + + // [ADR-0161 K4] The document unit: a single-valued parent link. Judged + // only when `metadataFields` lists it (otherwise the parse refuses it, and + // names that fix), and not for a member no column answers to (the + // field-unknown verdict above already reported it). + const documentBy = source.documentBy; + const listed = Array.isArray(source.metadataFields) && source.metadataFields.includes(documentBy); + const judged = typeof documentBy === 'string' && documentBy !== '' && listed; + if (judged && (fields.has(documentBy) || addressable.has(documentBy))) { + const refusal = documentUnitRefusal(documentBy, def, fields); + if (refusal) { + out.push({ + severity: 'error', + rule: KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK, + where, + path: `${path}.source.documentBy`, + ...documentUnitRefusalText(objectName, documentBy, refusal), + }); + } + } } return out; }