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
21 changes: 21 additions & 0 deletions .changeset/38019-knowledge-source-review-follow-ups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/lint': minor
'@objectstack/service-knowledge': patch
'@objectstack/spec': patch
---

fix(lint)!: a knowledge source naming an absent platform object is refused at publish; `ai_context` accepts `id`; the save door's search refusal names `list`

Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: follow-up #37310

<!-- adr-0087: not-required (already-registered knowledge-source-publish-refuses-missing-references-and-gated-objects) the entry that registered this rule's publish refusal landed with the rule itself; this change extends its surface to an absent platform object name judged against the whole collection the host serves, says the platform-name warning is the command line's, and lists the entry only for a stack that declares knowledge sources. No id is added and no key is added, removed or re-shaped. -->

ADR-0161 K4, row 4.

**BREAKING** for the publish of a knowledge source whose `source.object` is a platform name the host does not serve: when the publish gate judges the source against the whole collection the host serves (a write that names no package), a platform-prefixed name no package registers there, and a known platform object (`sys_user`) the host does not serve, are now `knowledge-source-object-unknown` errors (422), as an unprefixed name already was. Before, the first was a warning and the second was not judged. FROM a source over such an object TO a source over an object the host serves: name the object by its full name, or install the package that registers it. On the command line nothing changes: a platform-prefixed name no known package registers stays a warning, and a known platform object the stack does not carry is not judged.

- `ai_context`: a field named `id` (in `fields`, a related list's `fields`, `where` or `orderBy`) is no longer reported as `ai-context-field-unknown`. The driver provisions it, so it exists on every object; existence is now asked through the same column set the other existence rules use. A `body.field` of `id` is reported as not long text, never as unknown.
- `@objectstack/service-knowledge`: the save refusal for an object the API does not serve for search names the cause and fix in the words of `knowledge-source-object-not-searchable`: `enable.apiEnabled` false, an `enable.apiMethods` list that does not grant `list` (from which search derives), or `list` beside `enable.searchable: false`; the fix is to include `list` with `enable.searchable` not false. It no longer tells the author to grant `search`, a retired list value the parse strips.
- `@objectstack/spec`: the upgrade entry `knowledge-source-publish-refuses-missing-references-and-gated-objects` is listed by `os migrate meta` only for a stack that declares `knowledgeSources` (`--all` still lists it), and its surface states that the platform-name warning is the CLI's.
8 changes: 5 additions & 3 deletions packages/lint/src/rule-explanations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6204,9 +6204,11 @@ const KNOWLEDGE_SOURCE_OBJECT_UNKNOWN_EXPLANATION: RuleExplanation = {
'An object nothing defines has no records, so the source is built empty and every search over it ' +
'answers nothing, with no error anywhere.',
'Defined means an object of this stack, of a package in the same artifact (`packages[]`), or, at the ' +
'publish gate, an object the host serves. A platform object a known package registers (`sys_user`) is ' +
'not judged when the stack does not carry its definition. A name with a platform prefix that no known ' +
'package registers is a warning, because a third-party package may still provide it. When the publish ' +
'publish gate, an object the host serves. On the command line a platform object a known package ' +
'registers (`sys_user`) is not judged when the stack does not carry its definition, and a name with a ' +
'platform prefix that no known package registers is a warning, because a third-party package may still ' +
'provide it. At the publish gate with no package stated, the source is judged against every object the ' +
'host serves, so either one is an error there when the host does not serve it. When the publish ' +
'gate states the package\'s closure (the package, the packages its manifest declares in ' +
'`dependencies`, and platform objects), an object outside it is reported with the remedy to declare the ' +
'dependency.',
Expand Down
27 changes: 27 additions & 0 deletions packages/lint/src/validate-ai-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,33 @@ describe('validateAiContext — ADR-0160 D1 author defects', () => {
expect(validateAiContext(stack)).toEqual([]);
});

// `id` is provisioned by the driver, not the injection pass, so no injected
// definition carries it; existence resolves through `injectedColumnsFor`.
it('`id` is no unknown field, in fields, related fields, where and orderBy', () => {
const stack = {
objects,
aiContexts: [pack({
fields: ['title', 'id'],
related: [{ object: 'policy_revision', fields: ['version', 'id'], where: { id: 'rev_1' }, orderBy: [{ field: 'id' }] }],
})],
};
expect(objects.flatMap((o) => Object.keys(o.fields))).not.toContain('id');
expect(validateAiContext(stack)).toEqual([]);
// Through the CLI tier too (`os validate`).
expect(runAuthoringRules('validate', { parsed: stack, normalized: stack }).filter((f) => f.rule.startsWith('ai-context-')))
.toEqual([]);
// CONTROL: a misspelling beside it is still reported.
expect(rulesOf({ objects, aiContexts: [pack({ fields: ['idd'], related: undefined })] })).toEqual([
[AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].fields[0]'],
]);
});

it('a body naming `id` exists and is judged not long text, never unknown', () => {
expect(rulesOf({ objects, aiContexts: [pack({ body: { field: 'id' } })] })).toEqual([
[AI_CONTEXT_BODY_NOT_LONG_TEXT, 'aiContexts[0].body.field'],
]);
});

it('a column the platform does not inject on the object is still unknown: owner_id under ownership org', () => {
const orgOwned = objects.map((o) => (o.name === 'policy' || o.name === 'policy_revision' ? { ...o, ownership: 'org' } : o));
const stack = {
Expand Down
31 changes: 25 additions & 6 deletions packages/lint/src/validate-ai-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import { REFERENCE_VALUE_TYPES, referenceTargetOf } from '@objectstack/spec/data
import { closureDependencyRemedy, recordsOf } from './object-graph.js';
import {
injectedColumnDefsFor,
injectedColumnsFor,
unprovisionedAnchorFix,
unprovisionedAnchorVerdict,
unprovisionedInjectedColumnsFor,
Expand Down Expand Up @@ -103,6 +104,12 @@ const strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is
* the injected one of its name. `get_record_context` judges a pack against
* the published definition, which carries those columns, and reads them: a
* verdict over the declared fields alone warns on a name the tool serves.
*
* This map answers what a field IS (its type, its reference target). Whether
* a name EXISTS is asked through {@link injectedColumnsFor} as well
* (`fieldExists` in the rule), as `system-fields.ts` prescribes for an
* existence check: `id`, which the driver provisions, has no definition table
* and so is absent from this map, yet the pack reads it.
*/
function fieldMapOf(object: AnyRec): Map<string, AnyRec> | undefined {
const raw = object.fields;
Expand Down Expand Up @@ -139,6 +146,18 @@ export function validateAiContext(
// (the field map above) and provenance are separate questions: a name this
// set holds resolves, and is judged here instead of as unknown.
const anchorsOf = new Map<string, ReadonlySet<string>>();
/**
* Does `name` exist on `object`: a field of its effective map, or a column
* addressable without a declaration ({@link injectedColumnsFor}, which also
* holds the driver's `id`).
*/
const addressable = new Map<string, ReadonlySet<string>>();
const fieldExists = (object: string, fields: Map<string, AnyRec>, name: string): boolean => {
if (fields.has(name)) return true;
let names = addressable.get(object);
if (!names) addressable.set(object, (names = injectedColumnsFor(objects.get(object))));
return names.has(name);
};
const unprovisionedOf = (object: string): ReadonlySet<string> => {
let anchors = anchorsOf.get(object);
if (!anchors) anchorsOf.set(object, (anchors = unprovisionedInjectedColumnsFor(objects.get(object))));
Expand Down Expand Up @@ -196,7 +215,7 @@ export function validateAiContext(
};
const unknownFields = (names: string[], fields: Map<string, AnyRec>, object: string, where: string, path: string) => {
names.forEach((name, k) => {
if (fields.has(name)) {
if (fieldExists(object, fields, name)) {
if (unprovisionedOf(object).has(name)) {
unprovisioned(object, name, where, `${path}[${k}]`, `names field '${name}'`, 'the pack reads it empty on every record');
}
Expand All @@ -220,7 +239,7 @@ export function validateAiContext(
const bodyField = str(body?.field);
if (bodyField) {
const def = rootFields.get(bodyField);
if (!def) {
if (!fieldExists(root, rootFields, bodyField)) {
out.push({
severity: 'warning',
rule: AI_CONTEXT_FIELD_UNKNOWN,
Expand All @@ -229,14 +248,14 @@ export function validateAiContext(
message: `\`body.field\` names '${bodyField}', which object '${root}' does not define, so the pack carries no body`,
hint: `Name a long-text field of '${root}' (check the spelling)`,
});
} else if (!(AI_CONTEXT_BODY_FIELD_TYPES as readonly string[]).includes(str(def.type))) {
} else if (!(AI_CONTEXT_BODY_FIELD_TYPES as readonly string[]).includes(str(def?.type))) {
out.push({
severity: 'warning',
rule: AI_CONTEXT_BODY_NOT_LONG_TEXT,
where: `${at} · body`,
path: `aiContexts[${i}].body.field`,
message:
`\`body.field\` names '${bodyField}', a ${str(def.type) || 'untyped'} field; a body is a long-text ` +
`\`body.field\` names '${bodyField}', a ${str(def?.type) || 'untyped'} field; a body is a long-text ` +
`field (${AI_CONTEXT_BODY_FIELD_TYPES.join(', ')}), so the pack carries no body`,
hint: `Name a long-text field of '${root}' as the body, or list '${bodyField}' in \`fields\` instead`,
});
Expand Down Expand Up @@ -275,7 +294,7 @@ export function validateAiContext(
};
const noRows = 'a condition on it can never match a real value and the list reads no rows';
for (const name of aiContextWhereFields(entry.where)) {
if (!childFields.has(name)) listLeftOut(name, 'where', `${path}.where`);
if (!fieldExists(child, childFields, name)) listLeftOut(name, 'where', `${path}.where`);
else if (unprovisionedOf(child).has(name)) unprovisioned(child, name, where, `${path}.where`, `\`where\` names field '${name}'`, noRows);
}
const orderBy = Array.isArray(entry.orderBy) ? (entry.orderBy as unknown[]) : [];
Expand All @@ -284,7 +303,7 @@ export function validateAiContext(
orderBy.forEach((node, k) => {
const name = node && typeof node === 'object' ? str((node as AnyRec).field) : '';
if (!name) return;
if (!childFields.has(name)) {
if (!fieldExists(child, childFields, name)) {
listLeftOut(name, 'orderBy', `${path}.orderBy[${k}].field`);
return;
}
Expand Down
22 changes: 22 additions & 0 deletions packages/lint/src/validate-knowledge-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,28 @@ describe('validateKnowledgeSource on the runtime publish door', () => {
.map((f) => [f.rule, f.severity])).toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'error']]);
});

it('against the whole collection, an absent platform name, prefixed or known, is refused as an unprefixed one is', () => {
for (const object of ['sys_kb_article', 'sys_user']) {
const item = kbSource({ object, content: ['body'], metadataFields: [] });
const verdict = runRuntimeAuthoringRules({ type: 'knowledge_source', item, context: { objects } });
expect(verdict.errors.map((f) => [f.rule, f.severity, f.path]), object)
.toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'error', 'knowledgeSources[0].source.object']]);
expect(verdict.errors[0]!.message, object).toContain(`'${object}', which this stack does not define`);
expect(verdict.advisories.filter((f) => KS_RULE.test(f.rule)), object).toEqual([]);
}
// The CLI arms stay: a prefixed name no known package registers warns, a known platform name is not judged.
expect(atValidate(kbSource({ object: 'sys_kb_article', content: ['body'], metadataFields: [] })).map((f) => f.severity))
.toEqual(['warning']);
expect(atValidate(kbSource({ object: 'sys_user', content: ['name'], metadataFields: [] }))).toEqual([]);
// CONTROL: a served platform object is no unknown object at the door.
const served = [...objects, { name: 'sys_kb_article', enable: { aiReadable: true }, fields: { body: { type: 'text' } } }];
expect(runRuntimeAuthoringRules({
type: 'knowledge_source',
item: kbSource({ object: 'sys_kb_article', content: ['body'], metadataFields: [] }),
context: { objects: served },
}).errors).toEqual([]);
});

it('an empty whole collection at the door is no universe, and judges no object', () => {
const stack = { objects: [], knowledgeSources: [kbSource({ object: 'faq_entry' })] };
expect(validateKnowledgeSource(stack, { wholeCollection: true })).toEqual([]);
Expand Down
16 changes: 12 additions & 4 deletions packages/lint/src/validate-knowledge-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,11 @@
* `validateObjectReferences` resolves object names by also applies: a
* platform object a known package registers is not judged when the stack
* does not carry it (its declaration is not in hand), and a
* platform-prefixed name no known package registers is a `warning`. An
* empty whole collection at the door is no universe, and judges nothing.
* platform-prefixed name no known package registers is a `warning`; both
* on the CLI and under a closure. Against the whole collection at the door
* either one is absent from every package the host serves, so it is an
* `error` as an unprefixed name is. An empty whole collection at the door
* is no universe, and judges nothing.
* - `knowledge-source-field-unknown` (`error`): a `source.content` or
* `source.metadataFields` member names no field of the object: neither one
* it declares (its own stack's extensions folded in, `objectsAsServed`) nor
Expand Down Expand Up @@ -193,6 +196,10 @@ export function validateKnowledgeSource(
// registry read), as the list-view and form members read it: no object
// verdict is drawn from it.
const noUniverse = !closure && options.wholeCollection === true && objects.size === 0;
// The whole collection the host serves holds every platform object a
// package registers there, so an absent platform name, known or merely
// prefixed, exists nowhere: judged as an unprefixed name is (K4).
const whole = !closure && options.wholeCollection === true;
const unseen = atDoor ? [] : unseenDeclaredDependencies(stack);

for (const { rec, path } of sources) {
Expand All @@ -208,7 +215,8 @@ export function validateKnowledgeSource(
if (noUniverse) continue;
// A platform object a known package registers: its declaration is not
// in this stack, so neither its fields nor its gates can be read here.
if (isPlatformProvidedObjectName(objectName)) continue;
// Against the whole collection it is in hand, and its absence is final.
if (!whole && isPlatformProvidedObjectName(objectName)) continue;
if (closure) {
out.push({
severity: 'error',
Expand All @@ -222,7 +230,7 @@ export function validateKnowledgeSource(
suggestName(objectName, objects.keys()),
hint: closureDependencyRemedy(objectName, closure.packageId, 'name an object inside that closure'),
});
} else if (hasPlatformObjectPrefix(objectName)) {
} else if (!whole && hasPlatformObjectPrefix(objectName)) {
out.push({
severity: 'warning',
rule: KNOWLEDGE_SOURCE_OBJECT_UNKNOWN,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -891,6 +891,7 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
});
const sealed: ObjectDef = { ...TICKET, name: 'sealed', enable: { apiEnabled: false } };
const getOnly: ObjectDef = { ...TICKET, name: 'get_only', enable: { apiMethods: ['get'] } };
const unsearchable: ObjectDef = { ...TICKET, name: 'unsearchable', enable: { apiMethods: ['list'], searchable: false } };
const sysClosed: ObjectDef = { ...TICKET, name: 'sys_closed_note' };
const sysOpen: ObjectDef = { ...TICKET, name: 'sys_open_note', enable: { aiReadable: true } };

Expand Down Expand Up @@ -971,7 +972,8 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
it.each([
['an object of a disabled package', { objects: [TICKET], disabled: ['ticket'] }, 'ticket', 'disabled package'],
['an object the API does not serve at all', { objects: [sealed] }, 'sealed', 'does not serve object'],
['an object whose `apiMethods` do not grant `search`', { objects: [getOnly] }, 'get_only', 'does not serve object'],
['an object whose `apiMethods` do not grant `list`', { objects: [getOnly] }, 'get_only', 'does not serve object'],
['an object granting `list` beside `searchable: false`', { objects: [unsearchable] }, 'unsearchable', 'does not serve object'],
['a system object without `enable.aiReadable`', { objects: [sysClosed] }, 'sys_closed_note', 'does not opt into AI reads'],
])('%s is refused PERMISSION_DENIED / 403, naming the object', async (_label, opts, object, said) => {
const { svc } = setup({ sources: [], ...opts });
Expand All @@ -983,6 +985,20 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri
expect(await svc.admitAuthoredSource(item(object, ['body']), SYSTEM)).toEqual({ admitted: true });
});

it('the not-served refusal names `list` and `searchable` as cause and fix, never a `search` grant', async () => {
for (const object of ['sealed', 'get_only', 'unsearchable']) {
const { svc } = setup({ sources: [], objects: [sealed, getOnly, unsearchable] });
const verdict = await svc.admitAuthoredSource(item(object, ['body']), MANAGER);
expect(verdict).toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, object });
const message = (verdict as { message: string }).message;
expect(message).toContain('does not grant `list`');
expect(message).toContain('include `list` with `enable.searchable` not false');
// `search` is a retired `apiMethods` value the parse strips: never prescribed as a grant.
expect(message).not.toMatch(/(include|grant)s? `search`/);
expect(message).not.toContain('Serve the object for `search`');
}
});

it('CONTROL: a served object, and a system object that opts into AI reads, are admitted', async () => {
const { svc } = setup({ sources: [], objects: [TICKET, sysOpen] });
expect(await svc.admitAuthoredSource(item('ticket', ['body']), MANAGER)).toEqual({ admitted: true });
Expand Down
8 changes: 5 additions & 3 deletions packages/services/service-knowledge/src/knowledge-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3190,9 +3190,11 @@ export class KnowledgeService implements IKnowledgeService {
return refuse(
403,
'PERMISSION_DENIED',
`${named}: the API does not serve object '${object}' for \`search\` (\`enable.apiEnabled\` is false, or ` +
"its `enable.apiMethods` list does not include `search`), and a knowledge search is a search over the " +
"object's records. Serve the object for `search`, or index another object.",
`${named}: the API does not serve object '${object}' for \`search\` (\`enable.apiEnabled\` is false, its ` +
'`enable.apiMethods` list does not grant `list`, from which search derives, or it grants `list` beside ' +
"`enable.searchable: false`), and a knowledge search is a search over the object's records. " +
`Serve '${object}' for search: keep \`enable.apiEnabled\` true and, where it declares ` +
'`enable.apiMethods`, include `list` with `enable.searchable` not false; or index another object.',
);
case 'system-object-not-ai-readable':
return refuse(
Expand Down
Loading
Loading