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/38537-knowledge-document-by-validate.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 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.
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,11 @@ const CALLERS: Record<string, Classification> = {
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',
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 @@ -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';

Expand Down
19 changes: 19 additions & 0 deletions packages/lint/src/rule-explanations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -7519,6 +7537,7 @@ export const RULE_EXPLANATIONS: Readonly<Record<string, RuleExplanation>> = 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,
Expand Down
173 changes: 173 additions & 0 deletions packages/lint/src/validate-knowledge-source.document-by.test.ts
Original file line number Diff line number Diff line change
@@ -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<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 } });

/** [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');
});
});
Loading
Loading