Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/38503-validate-affinity-target.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 5 additions & 1 deletion content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
7 changes: 5 additions & 2 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions packages/lint/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
2 changes: 2 additions & 0 deletions packages/lint/src/rule-explanations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -693,6 +694,7 @@ export const RULE_EXPLANATIONS: Readonly<Record<string, RuleExplanation>> = 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,
Expand Down
21 changes: 21 additions & 0 deletions packages/lint/src/rule-explanations/knowledge-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
],
};
230 changes: 230 additions & 0 deletions packages/lint/src/validate-knowledge-source.affinity.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>) => {
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<string, unknown>) =>
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');
});
});
Loading
Loading