diff --git a/.changeset/38503-validate-affinity-target.md b/.changeset/38503-validate-affinity-target.md new file mode 100644 index 00000000000..e7c048c3d55 --- /dev/null +++ b/.changeset/38503-validate-affinity-target.md @@ -0,0 +1,12 @@ +--- +'@objectstack/lint': patch +--- + +fix(lint): `os validate` and the publish gate refuse a knowledge source `affinity` entry whose field does not point at the object its caller fact names + +Clause-②: no +Metadata-protocol: none + +Each `source.affinity` entry of a knowledge source compares its `field` with a fact about the person asking, so the field must hold that kind of id: for `caller: 'user'` a `user` field or a lookup to `sys_user`, for `caller: 'business_unit'` a lookup to `sys_business_unit`. Any other field holds a value that is never the caller's, so the entry matches no hit and the source is ordered as if it had no `affinity`. The metadata API's save door already refused such an entry. New rule `knowledge-source-affinity-field-not-caller-target` (`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, with the save door's words: the message names the entry, the field and what it points at; the fix names a field of the right kind, or the `caller` that matches the field (for a `nearest` entry on a field that points at `sys_user`, a `boost` entry with `caller: 'user'` and `places`). + +Only a field that `metadataFields` lists and the object declares is judged: an unlisted field is still refused by the schema, a field the object does not have is still reported once as `knowledge-source-field-unknown`, and a system column the platform adds is not judged. `os explain knowledge-source-affinity-field-not-caller-target` describes the rule. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index c1f5293df30..ed1bf031ff7 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -218,7 +218,11 @@ their primary business unit with its parents up to the root, as far as they may read them), so no tool argument and no model supplies it. Only that source's hits move, by position: each keeps the `score` its store answered, nothing is dropped, and a source without `affinity` answers exactly as before. `places` is -a whole number from 1 to 20, and a source declares at most one `nearest`. The +a whole number from 1 to 20, and a source declares at most one `nearest`. Each +`field` must point at the object its `caller` names: a `user` field or a lookup +to `sys_user` for `user`, a lookup to `sys_business_unit` for `business_unit`; +any other is refused when the source is saved, and by `os validate` and the +publish gate (`knowledge-source-affinity-field-not-caller-target`). The rules, and every refusal, are in [the protocol](/docs/protocol/knowledge#ordering-for-the-asker). diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index d63c935f505..3a185fa4400 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -1201,8 +1201,11 @@ source: { `nearest` (`filter` is answered that narrowing is the search scope and visibility is sharing), a caller fact outside the two, a second `nearest`, `nearest` with `caller: 'user'`, `places` missing on a `boost`, present on a - `nearest`, or not a whole number from 1 to 20. Saving a source also refuses - a `field` that does not point at the object its `caller` names. A unit + `nearest`, or not a whole number from 1 to 20. A `field` that does not + point at the object its `caller` names (`sys_user` for `user`, a `user` + field included; `sys_business_unit` for `business_unit`) is refused at a + save in Studio, the metadata API or MCP, and by `os validate` and the + publish gate (`knowledge-source-affinity-field-not-caller-target`). A unit read that fails for a reason other than a refusal leaves the units out of that search, logged once at `warn`; its `business_unit` entries then match nothing, and its `user` entries still apply. diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 38b9e9dd671..aeb5360d7e1 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -420,6 +420,7 @@ export { KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE, KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK, + KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET, } 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 49523b776e5..79145162bca 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -388,6 +388,7 @@ import { KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE_EXPLANATION, KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED_EXPLANATION, KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK_EXPLANATION, + KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET_EXPLANATION, } from './rule-explanations/knowledge-source.js'; import { ASSIGNMENT_RULE_USER_TARGET_EXPLANATION, @@ -693,6 +694,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [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, + [KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET_EXPLANATION.rule]: KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET_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/rule-explanations/knowledge-source.ts b/packages/lint/src/rule-explanations/knowledge-source.ts index fd729c7f7b7..a6ddfd85403 100644 --- a/packages/lint/src/rule-explanations/knowledge-source.ts +++ b/packages/lint/src/rule-explanations/knowledge-source.ts @@ -119,3 +119,24 @@ export const KNOWLEDGE_SOURCE_DOCUMENT_BY_NOT_PARENT_LINK_EXPLANATION: RuleExpla KNOWLEDGE_SOURCE_DOORS, ], }; + +export const KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET_EXPLANATION: RuleExplanation = { + rule: 'knowledge-source-affinity-field-not-caller-target', + covers: 'why an affinity field must point at its caller fact', + paragraphs: [ + 'A source\'s `affinity` orders its hits for the person asking: each entry compares a field the index stores ' + + 'beside every passage with a fact about the caller, and moves the hits that match. `caller: \'user\'` compares ' + + 'the field with the caller\'s user id; `caller: \'business_unit\'` compares it with their primary business ' + + 'unit and each parent up to the root.', + 'So the field must hold that kind of id: for `user`, a `user` field or a lookup to `sys_user`; for ' + + '`business_unit`, a lookup to `sys_business_unit`. A field that points at another object, or at none, holds ' + + 'a value that is never the caller\'s, so the entry matches no hit and the source is ordered exactly as if ' + + 'it were absent, with no error anywhere else. Only a field the object declares and `metadataFields` lists is ' + + 'judged; the schema refuses an unlisted one.', + 'To clear it, name a field that points at the object the caller fact names, or change `caller` to match the ' + + 'field. `nearest` orders by business unit only, so a `nearest` entry on a field that points at `sys_user` ' + + 'becomes a `boost` entry with `caller: \'user\'` and `places`. The same rule refuses the source when it is ' + + 'saved through the metadata API.', + KNOWLEDGE_SOURCE_DOORS, + ], +}; diff --git a/packages/lint/src/validate-knowledge-source.affinity.test.ts b/packages/lint/src/validate-knowledge-source.affinity.test.ts new file mode 100644 index 00000000000..ce626c31e07 --- /dev/null +++ b/packages/lint/src/validate-knowledge-source.affinity.test.ts @@ -0,0 +1,230 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// [ADR-0161, the dated note of 2026-11-29 under K1] Each `source.affinity` +// entry compares its `field` with a fact about the caller, so the field must +// point at the object that fact names: `sys_user` for `caller: 'user'`, +// `sys_business_unit` for `caller: 'business_unit'`. 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_AFFINITY_FIELD_NOT_CALLER_TARGET, + KNOWLEDGE_SOURCE_FIELD_UNKNOWN, + validateKnowledgeSource, +} from './validate-knowledge-source.js'; +import { KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET 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: 'account', fields: { name: { type: 'text' } } }, + { + name: 'policy', + fields: { + title: { type: 'text' }, + body: { type: 'markdown' }, + region: { type: 'text' }, + owner: { type: 'user' }, + reviewer: { type: 'lookup', reference: 'sys_user' }, + business_unit: { type: 'lookup', reference: 'sys_business_unit' }, + account: { type: 'lookup', reference: 'account' }, + dangling: { type: 'lookup' }, + }, + }, +]; + +type Entry = { field: string; caller: string; mode: string; places?: number }; + +/** A source over `policy` whose `affinity` is `entries`; `metadataFields` lists every entry field unless given. */ +const policySource = (entries: Entry[] | undefined, metadataFields?: string[]) => ({ + name: 'policy_kb', + label: 'Policy KB', + source: { + kind: 'object', + object: 'policy', + content: ['title', 'body'], + metadataFields: metadataFields ?? [...new Set((entries ?? []).map((e) => e.field))], + ...(entries === undefined ? {} : { affinity: entries }), + }, +}); + +const RULE = KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET; + +/** `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 } }); + +const boost = (field: string, caller: string): Entry => ({ field, caller, mode: 'boost', places: 3 }); +const nearest = (field: string): Entry => ({ field, caller: 'business_unit', mode: 'nearest' }); + +/** [what, entry, words the message must carry, words the hint must carry] */ +const REFUSED: ReadonlyArray<[string, Entry, string, string]> = [ + [ + "caller 'user' on a lookup to another object", + boost('account', 'user'), + "with the caller's user id, but 'account' is a field that points at 'account'", + "write `caller: 'business_unit'` for a field that points at 'sys_business_unit'", + ], + [ + "caller 'user' on a text field", + boost('region', 'user'), + "'region' is a `text` field that points at no object", + "a `user` field, or a lookup to 'sys_user'", + ], + [ + "caller 'user' on a lookup to the business units", + boost('business_unit', 'user'), + "'business_unit' is a field that points at 'sys_business_unit'", + "write `caller: 'business_unit'`", + ], + [ + "caller 'business_unit' boost on a user field", + boost('owner', 'business_unit'), + "with the caller's business units, but 'owner' is a field that points at 'sys_user'", + "write `caller: 'user'` for a field that points at 'sys_user'", + ], + [ + 'a nearest entry on a lookup to sys_user', + nearest('reviewer'), + "'reviewer' is a field that points at 'sys_user'", + "write a `boost` entry with `caller: 'user'` and `places` for a field that points at 'sys_user' (`nearest` orders by business unit only)", + ], + [ + 'a nearest entry on a lookup with no readable target', + nearest('dangling'), + "'dangling' is a `lookup` field that points at no object", + "a lookup to 'sys_business_unit'", + ], +]; + +describe('validateKnowledgeSource: source.affinity field target (os validate)', () => { + for (const [what, entry, inMessage, inHint] of REFUSED) { + it(`refuses ${what}, naming the field and the fix`, () => { + const findings = atValidate(policySource([entry])); + expect(findings.map((f) => [f.rule, f.severity, f.path, f.where])).toEqual([ + [RULE, 'error', 'knowledgeSources[0].source.affinity[0].field', 'knowledge source "policy_kb"'], + ]); + expect(findings[0]!.message).toContain( + `\`source.affinity[0]\` compares field '${entry.field}' of object 'policy'`, + ); + expect(findings[0]!.message).toContain(inMessage); + expect(findings[0]!.message).toContain('the entry would match nothing'); + expect(findings[0]!.hint).toContain('also listed in `metadataFields`'); + expect(findings[0]!.hint).toContain(inHint); + }); + } + + it('CONTROL: each field that points at its caller fact\'s object is admitted', () => { + expect( + atValidate( + policySource([ + nearest('business_unit'), + boost('business_unit', 'business_unit'), + boost('owner', 'user'), + boost('reviewer', 'user'), + ]), + ), + ).toEqual([]); + }); + + it('CONTROL: a source without affinity is judged as before', () => { + expect(atValidate(policySource(undefined, ['account', 'region']))).toEqual([]); + }); + + it('reports each refused entry at its own index, and only those', () => { + const findings = atValidate( + policySource([nearest('business_unit'), boost('account', 'user'), boost('owner', 'user'), boost('region', 'business_unit')]), + ); + expect(findings.map((f) => [f.rule, f.path])).toEqual([ + [RULE, 'knowledgeSources[0].source.affinity[1].field'], + [RULE, 'knowledgeSources[0].source.affinity[3].field'], + ]); + expect(findings[1]!.message).toContain('`source.affinity[3]`'); + }); + + it('a field that metadataFields does not list is left to the parse, which names that fix', () => { + expect(atValidate(policySource([boost('account', 'user')], ['owner']))).toEqual([]); + }); + + it('a member the object does not have is reported once, as an unknown field', () => { + const findings = atValidate(policySource([boost('ownr', 'user')])); + expect(findings.map((f) => [f.rule, f.path])).toEqual([ + [KNOWLEDGE_SOURCE_FIELD_UNKNOWN, 'knowledgeSources[0].source.metadataFields[0]'], + ]); + }); + + it('a system column the platform adds is not judged, as at the save door', () => { + expect(atValidate(policySource([boost('owner_id', 'user'), boost('created_by', 'business_unit')]))).toEqual([]); + }); + + it('an entry whose caller the parse does not admit is left to the parse', () => { + expect(atValidate(policySource([{ field: 'account', caller: 'organization', mode: 'boost', places: 1 }]))).toEqual([]); + }); + + it('a fields array is read like a field map', () => { + const stack = { + objects: [ + { + name: 'policy', + fields: [ + { name: 'title', type: 'text' }, + { name: 'body', type: 'markdown' }, + { name: 'owner', type: 'user' }, + { name: 'account', type: 'lookup', reference: 'account' }, + ], + }, + ], + knowledgeSources: [policySource([boost('account', 'user'), boost('owner', 'user')])], + }; + expect(validateKnowledgeSource(stack).map((f) => [f.rule, f.path])).toEqual([ + [RULE, 'knowledgeSources[0].source.affinity[0].field'], + ]); + }); +}); + +describe('validateKnowledgeSource: source.affinity field target (runtime publish door)', () => { + it('refuses the publish with the words os validate prints', () => { + const source = policySource([nearest('reviewer')]); + const verdict = atPublish(source); + expect(verdict.rulesRun).toContain('validateKnowledgeSource'); + const refused = verdict.errors.filter((f) => f.rule === 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 === RULE).map(face)); + }); + + it('CONTROL: fields that point at the caller facts\' objects publish with nothing to report', () => { + const verdict = atPublish(policySource([nearest('business_unit'), boost('owner', 'user')])); + expect(verdict.errors).toEqual([]); + expect(verdict.advisories.filter((f) => f.rule.startsWith('knowledge-source-'))).toEqual([]); + }); +}); + +describe('the affinity target rule id is published and explained', () => { + it('the root barrel re-exports it', () => { + expect(FROM_BARREL).toBe('knowledge-source-affinity-field-not-caller-target'); + }); + + it('os explain answers it', () => { + const entry = explainRule(RULE); + expect(entry?.rule).toBe(RULE); + expect(entry?.paragraphs.join(' ')).toContain('the entry matches no hit'); + }); +}); diff --git a/packages/lint/src/validate-knowledge-source.ts b/packages/lint/src/validate-knowledge-source.ts index d9f63681062..995471fedaf 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. * - * Six verdicts: + * Seven 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 @@ -88,6 +88,20 @@ * 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`. + * - `knowledge-source-affinity-field-not-caller-target` (`error`): a + * `source.affinity` entry (ADR-0161, the dated note of 2026-11-29 under K1) + * whose `field` does not point at the object its `caller` names: `sys_user` + * for `user`, `sys_business_unit` for `business_unit`, read through the + * spec's one answer for a field's target (`referenceTargetOf`, so a `user` + * field points at `sys_user`). Its value is never the caller's, so the entry + * matches nothing and the source is ordered as if it were absent. The rule + * and its sentence are the save door's (`affinityTargetRefusalText` in + * `@objectstack/service-knowledge`'s `knowledge-source-admission.ts`), + * composed here from the same spec predicate for the reason above. Like the + * door, it judges only a `field` that `metadataFields` lists (otherwise the + * parse refuses it) and that the object declares (a member no column answers + * to is reported once, by `knowledge-source-field-unknown`; a system column + * the platform adds is not judged). * * 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, @@ -133,6 +147,7 @@ export const KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE = 'knowledge-source-object-n 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'; +export const KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET = 'knowledge-source-affinity-field-not-caller-target'; /** The operation a knowledge search is judged as — the admission module's `KNOWLEDGE_SEARCH_OPERATION`. */ const SEARCH_OPERATION = 'search'; @@ -254,6 +269,59 @@ function documentUnitRefusalText( } } +/** + * The object each `source.affinity` caller fact is compared with: the field + * must point at it. The save door's `AFFINITY_CALLER_TARGETS`. + */ +const AFFINITY_CALLER_TARGETS: Readonly> = Object.freeze({ + user: 'sys_user', + business_unit: 'sys_business_unit', +}); + +/** + * Why a `source.affinity` entry over `object` would match nothing, or + * `undefined` when its `field` points at the object its `caller` names, or + * when the entry names no `caller` the parse admits. The same answer and the + * same words as the save door's `affinityTargetRefusalText`, split into the + * finding's sentence and its fix. `def` is the declared definition of the + * entry's field ({@link declaredFieldsOf}); the caller skips an undeclared one. + */ +function affinityTargetRefusal( + object: string, + def: AnyRec, + entry: AnyRec, + index: number, +): { message: string; hint: string } | undefined { + const { field, caller, mode } = entry; + if (typeof field !== 'string' || (caller !== 'user' && caller !== 'business_unit')) return undefined; + const expected = AFFINITY_CALLER_TARGETS[caller]; + let target: string | undefined; + try { + target = referenceTargetOf(def); + } catch { + target = undefined; + } + if (target === expected) return undefined; + const what = target === undefined + ? `${typeof def.type === 'string' ? `a \`${def.type}\` field` : 'a field'} that points at no object` + : `a field that points at '${target}'`; + return { + message: + `\`source.affinity[${index}]\` compares field '${field}' of object '${object}' with the caller's ` + + `${caller === 'user' ? 'user id' : 'business units'}, but '${field}' is ${what}, so its value is never the ` + + "caller's and the entry would match nothing.", + hint: + `Name a field of '${object}' that points at '${expected}' ` + + `(${caller === 'user' ? "a `user` field, or a lookup to 'sys_user'" : "a lookup to 'sys_business_unit'"}), ` + + `also listed in \`metadataFields\`, or ${caller === 'user' + ? "write `caller: 'business_unit'` for a field that points at 'sys_business_unit'" + : mode === 'nearest' + ? "write a `boost` entry with `caller: 'user'` and `places` for a field that points at 'sys_user' " + + '(`nearest` orders by business unit only)' + : "write `caller: 'user'` for a field that points at 'sys_user'"}`, + }; +} + /** * The ids of the packages the stack's manifest declares in `dependencies` * that its artifact (`packages[]`) does not carry: packages whose objects the @@ -530,6 +598,30 @@ export function validateKnowledgeSource( }); } } + + // [ADR-0161, the dated note of 2026-11-29 under K1] Each affinity entry's + // field points at the object its caller fact names. Judged, as at the save + // door, only on a field `metadataFields` lists (otherwise the parse + // refuses it, and names that fix) and the object declares. + const affinity = source.affinity; + if (Array.isArray(affinity)) { + const metadataFields = Array.isArray(source.metadataFields) ? source.metadataFields : []; + affinity.forEach((entry, i) => { + if (!isRec(entry) || typeof entry.field !== 'string' || !metadataFields.includes(entry.field)) return; + const fieldDef = fields.get(entry.field); + if (!fieldDef) return; + const refusal = affinityTargetRefusal(objectName, fieldDef, entry, i); + if (refusal) { + out.push({ + severity: 'error', + rule: KNOWLEDGE_SOURCE_AFFINITY_FIELD_NOT_CALLER_TARGET, + where, + path: `${path}.source.affinity[${i}].field`, + ...refusal, + }); + } + }); + } } return out; }