diff --git a/.changeset/37307-knowledge-source-references.md b/.changeset/37307-knowledge-source-references.md new file mode 100644 index 00000000000..58a4a847802 --- /dev/null +++ b/.changeset/37307-knowledge-source-references.md @@ -0,0 +1,38 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': patch +--- + +fix(lint)!: a knowledge source is checked for its object, its fields and the search gates that need no caller, in `os validate` and at publish + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up owed — skills/objectstack-ai/SKILL.md + + + +ADR-0161 K4, row 4. + +**BREAKING** for the publish of a knowledge source that carries one of the four errors below: it was accepted before and is refused now (422, the finding's rule id, path, message and fix), and `os validate` / `lint` / `compile` / `build` refuse the same source. The schema is unchanged, and stored sources are not rewritten or refused at boot. + +A new rule, `validateKnowledgeSource`, exported from `@objectstack/lint` with its five rule id constants. It runs on all three CLI commands and on the runtime publish gate for a `knowledge_source` write, with one set of rule ids and messages. Four errors: a source over a missing object has nothing to index, a missing field indexes no text for that member, and a gated object is never searched for a caller the service judges: + +- `knowledge-source-object-unknown`: `source.object` names an object that the stack, a package of its artifact, or (at the publish gate) the host does not define. Under the package closure the publish gate states, an object outside it is worded for the closure with the remedy to declare the dependency. On the CLI, while the manifest declares a dependency the artifact does not carry, the build cannot see that package's objects, so the finding is a warning that clears when the dependency defines the object (the publish gate judges it against the closure, which holds them); with no such dependency it is an error. A platform object a known package registers is not judged when the stack does not carry it; a platform-prefixed name no known package registers is a warning. +- `knowledge-source-field-unknown`: a `source.content` or `source.metadataFields` member names no field of the object, declared (the stack's own object extensions included) or addressable without a declaration (`id`, which the driver provisions, and the injected system columns `owner_id`, `created_at`, …). +- `knowledge-source-object-not-searchable`: the object's API exposure does not serve `search` (`canServeApiOperation(enable, 'search')`): `enable.apiEnabled: false`, an `enable.apiMethods` list that does not grant `list` (search derives from it; `search` itself is a retired list value the parse strips), or a list that grants `list` beside `enable.searchable: false`. With no `apiMethods` list, `searchable: false` does not refuse it. +- `knowledge-source-system-object-not-ai-readable`: a `sys_` object that does not declare `enable.aiReadable: true` (`isAiReadExposed`). + +One warning, which refuses nothing: + +- `knowledge-source-field-never-indexed`: a member names a credential-class field or a field declared `internal: true`; the index never carries either, even when named, so the member is skipped. + +The two gates are the knowledge service's own search-time gates that need no caller, asked through the same spec predicates. The disabled-package gate and the field-queryable gate need an environment or a caller and stay at save, judged for the author. `os explain` answers each of the five ids. + +## FROM → TO + +- `source: { object: 'kb_artcle', … }` → `source: { object: 'kb_article', … }`, an object the stack defines. An object a dependency defines clears at publish once the package's manifest declares that dependency in `dependencies`; on the CLI it stays a warning while the artifact does not carry the dependency. +- `content: ['title', 'bdy']` → `content: ['title', 'body']`. +- a source over an object with `enable: { apiEnabled: false }` → serve the object (`apiEnabled: true` and, where it declares `apiMethods`, a list that includes `list`, with `searchable` not false), or index another object. +- a source over `sys_audit_note` → index a business object, or declare `enable.aiReadable: true` on the system object's own definition. + +`@objectstack/spec` adds only the upgrade-guide entry `knowledge-source-publish-refuses-missing-references-and-gated-objects`. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 2b316444236..41cd378dcef 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (86)... + → Running author-time rules (87)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 72c0ea627a1..82a596aa35c 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -870,7 +870,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (86)... + → Running author-time rules (87)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index e6e21789448..a26c39899eb 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -318,7 +318,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (86)... + → Running author-time rules (87)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 7d50343038e..a72f727df16 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (86)... + → Running author-time rules (87)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index d91276cdd06..4e381b1047e 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -140,6 +140,7 @@ import { validateFormConsumers, validateFormPublicAddresses } from './validate-f import { validateThankYouRecordFields } from './validate-thank-you-record-fields.js'; import { validateAssignmentRules } from './validate-assignment-rules.js'; import { validateAiContext } from './validate-ai-context.js'; +import { validateKnowledgeSource } from './validate-knowledge-source.js'; import { validateSeedStateMachine } from './validate-seed-state-machine.js'; import { validateVisibilityPredicates } from './validate-visibility-predicates.js'; import { validatePredicatePathRefs } from './validate-predicate-path-refs.js'; @@ -2084,6 +2085,46 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ runtimeTypes: ['ai_context'], run: (stack, ctx) => validateAiContext(stack, ctx.packageScope ? { packageScope: ctx.packageScope } : {}), }, + // [ADR-0161 K4, row 4] Knowledge sources whose object or a listed field the + // stack does not have, whose object the API does not serve for `search`, or + // that index a system object which does not opt into AI reads (the gates of + // the knowledge service's admission that need no principal), and a listed + // credential-class or `internal` field, which the index never carries. + // + // GATING, and on the runtime publish door for `knowledge_source`: ADR-0161 + // K4 says an item "is refused when the object or a named field does not + // exist" and that "a packaged item meets the gates that need no principal in + // `os validate` and at publish". That is the departure from the + // `validateAiContext` row above, which only advises at publish because a + // context pack still reads what resolves; a source that fails one of these + // has nothing to index (a missing object), indexes no text for a member (a + // missing field), or is never searched for a caller the service judges (a + // gated object). The rule reads `knowledgeSources`, `objects` (and the + // stack's own extensions), `manifest.dependencies` and no other collection; + // `objects` is the context every per-write snapshot carries, and the + // written source is the sole member of its own collection. Under a stated + // package scope that `objects` is the write's closure, so the scope is + // passed through and an object outside it is worded for the closure with + // `closureDependencyRemedy`. With no scope `objects` is the whole + // collection the host serves (`wholeCollection`), so an unresolved object + // is an error there too; only the CLI, where a manifest dependency the + // artifact does not carry may define it, hedges it as a warning (the + // `flow-trigger-unknown-object` split). An `error` refuses the publish + // (422), the `warning`s ride the 2xx `advisories`. + { + name: 'validateKnowledgeSource', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-knowledge-source.ts', + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['knowledge_source'], + run: (stack, ctx) => + validateKnowledgeSource(stack, { + ...(ctx.packageScope ? { packageScope: ctx.packageScope } : {}), + wholeCollection: ctx.runtimeWriteType !== undefined && !ctx.packageScope, + }), + }, // [#34613] `validateSeedReplaySafety` (framework#3434, the `insert`-mode // replay warning) is retired: `SeedMode` itself refuses `insert` and // `replace` at parse (ruling 6942780880), so no stack this rule could flag diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 988e574abb5..85b0c888de3 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -407,6 +407,16 @@ export { } from './validate-ai-context.js'; export type { AiContextFinding, AiContextSeverity } from './validate-ai-context.js'; +export { + validateKnowledgeSource, + KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + KNOWLEDGE_SOURCE_FIELD_UNKNOWN, + KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, + KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE, + KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, +} from './validate-knowledge-source.js'; +export type { KnowledgeSourceFinding, KnowledgeSourceSeverity } from './validate-knowledge-source.js'; + export { validateAssignmentRules, ASSIGNMENT_RULE_USER_TARGET, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index d877ce13c05..53643e00f0b 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -6188,6 +6188,99 @@ const AI_CONTEXT_SORT_FIELD_UNSORTABLE_EXPLANATION: RuleExplanation = { ], }; +// ── Knowledge sources (`validate-knowledge-source.ts`) ── + +const KNOWLEDGE_SOURCE_DOORS = + 'Judged by `os validate`, `os build` and `os lint`, and at the runtime publish gate for a ' + + '`knowledge_source` write (Studio, the metadata API, MCP), with the same rule id and message. An error ' + + 'refuses the publish (ADR-0161 K4): a source over a missing object has nothing to index, a missing field ' + + 'indexes no text for that member, and a gated object is never searched for a caller the service judges.'; + +const KNOWLEDGE_SOURCE_OBJECT_UNKNOWN_EXPLANATION: RuleExplanation = { + rule: 'knowledge-source-object-unknown', + covers: 'why a knowledge source must name an existing object', + paragraphs: [ + 'A knowledge source (`knowledgeSources`, ADR-0161 K4) indexes the records of one object, `source.object`. ' + + '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 ' + + '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.', + 'On the command line a package the manifest declares in `dependencies` but the artifact does not carry ' + + 'is out of sight: its objects cannot be read there. So while the manifest declares such a dependency, ' + + 'an object the stack does not define is a warning, which clears when that dependency defines it (the ' + + 'publish gate judges the source against the package\'s closure, which holds the dependency\'s objects). ' + + 'With no such dependency it is an error, which clears only by naming an object that exists.', + KNOWLEDGE_SOURCE_DOORS, + ], +}; + +const KNOWLEDGE_SOURCE_FIELD_UNKNOWN_EXPLANATION: RuleExplanation = { + rule: 'knowledge-source-field-unknown', + covers: 'why each listed field must exist on the object', + paragraphs: [ + 'A source lists the fields whose text becomes each document (`source.content`) and the fields projected ' + + 'into a hit\'s metadata (`source.metadataFields`). A name the object does not define reads nothing on ' + + 'every record: the document is built without that text, or the metadata without that value.', + 'Defined means declared in the object\'s `fields` (an object extension of the same stack included) or ' + + 'addressable without a declaration: `id`, which the driver provisions, and the system columns the ' + + 'platform injects (`owner_id`, `created_at` and the rest) are read like any field. An object whose ' + + 'definition carries no readable field map is not judged.', + KNOWLEDGE_SOURCE_DOORS, + ], +}; + +const KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE_EXPLANATION: RuleExplanation = { + rule: 'knowledge-source-object-not-searchable', + covers: 'why the API must serve the object for search', + paragraphs: [ + 'A knowledge search is a search over the object\'s records, so the knowledge service searches a source ' + + 'only when the API exposure serves its object for `search`: the decision `canServeApiOperation` in ' + + '`@objectstack/spec/data` answers, the one every door serving object rows asks. `enable.apiEnabled: ' + + 'false` refuses it. So does an `enable.apiMethods` list that does not grant `list`, from which search ' + + 'derives (`search` itself is a retired list value the parse strips), or one that grants `list` beside ' + + '`enable.searchable: false`. With no `apiMethods` list, `searchable: false` does not refuse it.', + 'To clear it, keep `enable.apiEnabled` true and, where the object declares `enable.apiMethods`, include ' + + '`list` with `enable.searchable` not false; or index another object.', + 'This gate needs no caller, so it is judged here. The gates that need one (the object\'s package is not ' + + 'disabled, and the author may query every field the source serves) are asked when the source is saved, ' + + 'as its author.', + KNOWLEDGE_SOURCE_DOORS, + ], +}; + +const KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE_EXPLANATION: RuleExplanation = { + rule: 'knowledge-source-system-object-not-ai-readable', + covers: 'why a system object source must opt into AI reads', + paragraphs: [ + 'A system object (a `sys_` name) is indexed and searched only when its own definition opts into AI reads ' + + 'with `enable.aiReadable: true`, the posture the MCP record tools take (`isAiReadExposed` in ' + + '`@objectstack/spec/data`). The objects that store serialized metadata bodies are never opened, ' + + 'whatever they declare.', + 'The declaration belongs to the system object\'s author, not to the source: index a business object, or a ' + + 'system object that declares it.', + KNOWLEDGE_SOURCE_DOORS, + ], +}; + +const KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED_EXPLANATION: RuleExplanation = { + rule: 'knowledge-source-field-never-indexed', + covers: 'why a credential-class or internal field is skipped', + paragraphs: [ + 'Embedding is egress: the text of every listed field is sent to the embedding provider and kept in an ' + + 'index outside the row store. So the index never carries a credential-class field (a `secret`, or a ' + + '`password` the platform masks on read) or a field declared `internal: true`, even when the source ' + + 'names it (ADR-0161 K5). The member is skipped, and the documents read less than the list says.', + 'A warning, not a refusal: the rest of the source is indexed. Remove the member from `content` or ' + + '`metadataFields`. Judged by `os validate`, `os build` and `os lint`, and at the runtime publish gate ' + + 'for a `knowledge_source` write, where it rides the advisories.', + ], +}; + // ── Assignment rules (`validate-assignment-rules.ts`) ── const ASSIGNMENT_RULE_USER_TARGET_EXPLANATION: RuleExplanation = { @@ -7271,6 +7364,11 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [AI_CONTEXT_RELATED_LINK_UNKNOWN_EXPLANATION.rule]: AI_CONTEXT_RELATED_LINK_UNKNOWN_EXPLANATION, [AI_CONTEXT_BODY_NOT_LONG_TEXT_EXPLANATION.rule]: AI_CONTEXT_BODY_NOT_LONG_TEXT_EXPLANATION, [AI_CONTEXT_SORT_FIELD_UNSORTABLE_EXPLANATION.rule]: AI_CONTEXT_SORT_FIELD_UNSORTABLE_EXPLANATION, + [KNOWLEDGE_SOURCE_OBJECT_UNKNOWN_EXPLANATION.rule]: KNOWLEDGE_SOURCE_OBJECT_UNKNOWN_EXPLANATION, + [KNOWLEDGE_SOURCE_FIELD_UNKNOWN_EXPLANATION.rule]: KNOWLEDGE_SOURCE_FIELD_UNKNOWN_EXPLANATION, + [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, [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/runtime-gate.ts b/packages/lint/src/runtime-gate.ts index 1ee5ef9e59d..5706700cc16 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -311,6 +311,17 @@ const TYPE_TO_STACK_KEY: Readonly> = { // pack's names into `objects`, which every snapshot carries, and nothing // into a sibling pack. ai_context: 'aiContexts', + // [ADR-0161 K4, row 4] `knowledge_source` — `allowRuntimeCreate: true`, so + // Studio, REST `/meta` and an MCP/AI author mint sources at runtime, and the + // ADR says a packaged item meets the gates that need no principal at + // publish as in `os validate`. ⛔ NOT a mapping ahead of its rule: + // `validateKnowledgeSource` crosses with this row and opens on + // `stack.knowledgeSources`, the key `ObjectStackDefinitionSchema` gives the + // collection. Not a context row either, for the `position` / `app` reason + // above: the rule resolves a source's names into `objects`, which every + // snapshot carries, and nothing into a sibling source. Unlike the + // `ai_context` row, its errors refuse the publish (the rule is gating). + knowledge_source: 'knowledgeSources', }; /** diff --git a/packages/lint/src/validate-knowledge-source.test.ts b/packages/lint/src/validate-knowledge-source.test.ts new file mode 100644 index 00000000000..354f533e183 --- /dev/null +++ b/packages/lint/src/validate-knowledge-source.test.ts @@ -0,0 +1,276 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { + KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, + KNOWLEDGE_SOURCE_FIELD_UNKNOWN, + KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, + KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE, + validateKnowledgeSource, +} from './validate-knowledge-source.js'; +import { explainRule } from './rule-explanations.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor, stackKeyForType } from './runtime-gate.js'; + +const objects = [ + { + name: 'kb_article', + fields: { + title: { type: 'text' }, + body: { type: 'markdown' }, + status: { type: 'select' }, + api_token: { type: 'secret' }, + triage_note: { type: 'text', internal: true }, + }, + }, + { name: 'private_note', enable: { apiEnabled: false }, fields: { body: { type: 'text' } } }, + { name: 'get_only', enable: { apiMethods: ['get'] }, fields: { body: { type: 'text' } } }, + { name: 'unsearchable', enable: { apiMethods: ['get', 'list'], searchable: false }, fields: { body: { type: 'text' } } }, + { name: 'sys_audit_note', fields: { body: { type: 'text' } } }, + { name: 'sys_help_topic', enable: { aiReadable: true }, fields: { body: { type: 'text' } } }, +]; + +/** A source over `kb_article` that names only what the object defines; `source` overrides the source keys. */ +const kbSource = (source: Record = {}, name = 'support_kb') => ({ + name, + label: 'Support KB', + source: { kind: 'object', object: 'kb_article', content: ['title', 'body'], metadataFields: ['status'], ...source }, +}); + +const KS_RULE = /^knowledge-source-/; + +/** `os validate`'s verdict on one source: the CLI command's own registry entry over the stack. */ +const atValidate = (source: Record, extra: Record = {}) => { + const stack = { objects, knowledgeSources: [source], ...extra }; + return runAuthoringRules('validate', { parsed: stack, normalized: stack }).filter((f) => KS_RULE.test(f.rule)); +}; + +/** The runtime publish door's verdict on one source written against `objects` as the live context. */ +const atPublish = (source: Record) => + runRuntimeAuthoringRules({ type: 'knowledge_source', item: source, context: { objects } }); + +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 }); + +/** + * The card's acceptance families: each prints exactly one finding, with the + * rule id, the path, and the object or field named in its message. + */ +const FAMILIES: ReadonlyArray<[string, Record, string, 'error' | 'warning', string, string]> = [ + ['a missing object', kbSource({ object: 'kb_artcle' }), KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'error', 'knowledgeSources[0].source.object', "'kb_artcle'"], + ['a missing content field', kbSource({ content: ['title', 'bdy'] }), KNOWLEDGE_SOURCE_FIELD_UNKNOWN, 'error', 'knowledgeSources[0].source.content[1]', "'bdy'"], + ['a missing metadata field', kbSource({ metadataFields: ['stage'] }), KNOWLEDGE_SOURCE_FIELD_UNKNOWN, 'error', 'knowledgeSources[0].source.metadataFields[0]', "'stage'"], + ['an object with apiEnabled: false', kbSource({ object: 'private_note', content: ['body'], metadataFields: [] }), KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, 'error', 'knowledgeSources[0].source.object', "'private_note'"], + ['an object whose apiMethods do not grant search', kbSource({ object: 'get_only', content: ['body'], metadataFields: [] }), KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, 'error', 'knowledgeSources[0].source.object', "'get_only'"], + ['an object that lists but declares searchable: false', kbSource({ object: 'unsearchable', content: ['body'], metadataFields: [] }), KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, 'error', 'knowledgeSources[0].source.object', "'unsearchable'"], + ['a sys_ object without enable.aiReadable', kbSource({ object: 'sys_audit_note', content: ['body'], metadataFields: [] }), KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE, 'error', 'knowledgeSources[0].source.object', "'sys_audit_note'"], + ['a credential-class content field', kbSource({ content: ['title', 'api_token'] }), KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, 'warning', 'knowledgeSources[0].source.content[1]', "'api_token'"], + ['an internal metadata field', kbSource({ metadataFields: ['triage_note'] }), KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, 'warning', 'knowledgeSources[0].source.metadataFields[0]', "'triage_note'"], +]; + +describe('validateKnowledgeSource in os validate (ADR-0161 K4, row 4)', () => { + for (const [what, source, rule, severity, path, named] of FAMILIES) { + it(`${what} prints one ${severity} ${rule}, naming ${named}`, () => { + const findings = atValidate(source); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([[rule, severity, path]]); + expect(findings[0]!.message).toContain(named); + expect(findings[0]!.where).toBe('knowledge source "support_kb"'); + }); + } + + it('a clean source prints nothing', () => { + expect(atValidate(kbSource())).toEqual([]); + }); + + it('an apiMethods list that grants list grants search, as the exposure decision derives it', () => { + const withList = [...objects, { name: 'listed', enable: { apiMethods: ['get', 'list'] }, fields: { body: { type: 'text' } } }]; + const stack = { objects: withList, knowledgeSources: [kbSource({ object: 'listed', content: ['body'], metadataFields: [] })] }; + expect(validateKnowledgeSource(stack)).toEqual([]); + }); + + it('a sys_ object that declares enable.aiReadable: true passes the system-object gate', () => { + expect(atValidate(kbSource({ object: 'sys_help_topic', content: ['body'], metadataFields: [] }))).toEqual([]); + }); + + it('a system column the platform injects is a field the source may name', () => { + expect(atValidate(kbSource({ metadataFields: ['owner_id', 'created_at'] }))).toEqual([]); + }); + + it('`id`, which the driver provisions without a declaration, resolves like a declared field', () => { + expect(atValidate(kbSource({ metadataFields: ['id', 'status'] }))).toEqual([]); + expect(atValidate(kbSource({ content: ['id', 'title'] }))).toEqual([]); + expect(atPublish(kbSource({ metadataFields: ['id'] })).errors).toEqual([]); + }); + + it('`enable.searchable: false` with no `apiMethods` list does not refuse search', () => { + const open = { name: 'open_note', enable: { searchable: false }, fields: { body: { type: 'text' } } }; + const source = kbSource({ object: 'open_note', content: ['body'], metadataFields: [] }); + expect(validateKnowledgeSource({ objects: [open], knowledgeSources: [source] })).toEqual([]); + }); + + it('a field an object extension of the stack adds resolves', () => { + const extension = { extend: 'kb_article', fields: { product: { type: 'text' } } }; + expect(atValidate(kbSource({ metadataFields: ['product'] }), { objectExtensions: [extension] })).toEqual([]); + expect(atValidate(kbSource({ metadataFields: ['product'] })).map((f) => f.rule)).toEqual([KNOWLEDGE_SOURCE_FIELD_UNKNOWN]); + }); + + it('an object a package of the same artifact ships resolves, and is judged', () => { + const packages = [{ manifest: { id: 'com.acme.kb', objects: [{ name: 'faq_entry', fields: { answer: { type: 'text' } } }] } }]; + expect(atValidate(kbSource({ object: 'faq_entry', content: ['answer'], metadataFields: [] }), { packages })).toEqual([]); + expect(atValidate(kbSource({ object: 'faq_entry', content: ['answr'], metadataFields: [] }), { packages }).map((f) => f.rule)) + .toEqual([KNOWLEDGE_SOURCE_FIELD_UNKNOWN]); + }); + + it('a platform object a known package registers is not judged when the stack does not carry it', () => { + expect(atValidate(kbSource({ object: 'sys_user', content: ['name'], metadataFields: [] }))).toEqual([]); + }); + + it('a platform-prefixed name no known package registers is a warning, not an error', () => { + const findings = atValidate(kbSource({ object: 'sys_kb_article', content: ['body'], metadataFields: [] })); + expect(findings.map((f) => [f.rule, f.severity])).toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'warning']]); + }); + + it('on the CLI, a missing object is a warning while the manifest declares a dependency the artifact does not carry', () => { + const manifest = { id: 'app.kb', dependencies: { 'com.acme.faq': '^1.0.0' } }; + const source = kbSource({ object: 'faq_entry', content: ['answer'], metadataFields: [] }); + const findings = atValidate(source, { manifest }); + expect(findings.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'warning', 'knowledgeSources[0].source.object'], + ]); + expect(findings[0]!.message).toContain('"com.acme.faq"'); + expect(findings[0]!.hint).toContain('Ignore this if a declared dependency defines the object'); + }); + + it('on the CLI, a missing object stays an error when every declared dependency is carried, or none is declared', () => { + const carried = [{ manifest: { id: 'com.acme.faq', objects: [{ name: 'faq_topic', fields: { title: { type: 'text' } } }] } }]; + const manifest = { id: 'app.kb', dependencies: { 'com.acme.faq': '^1.0.0' } }; + const source = kbSource({ object: 'faq_entry', content: ['answer'], metadataFields: [] }); + expect(atValidate(source, { manifest, packages: carried }).map((f) => [f.rule, f.severity])) + .toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'error']]); + expect(atValidate(source, { manifest: { id: 'app.kb' } }).map((f) => [f.rule, f.severity])) + .toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'error']]); + }); + + it('a missing object is reported once, and its fields are not judged', () => { + const findings = atValidate(kbSource({ object: 'nothing_here', content: ['a', 'b'], metadataFields: ['c'] })); + expect(findings.map((f) => f.rule)).toEqual([KNOWLEDGE_SOURCE_OBJECT_UNKNOWN]); + }); + + it('the error refuses os validate, not only os lint', () => { + for (const command of ['validate', 'build', 'lint'] as const) { + const stack = { objects, knowledgeSources: [kbSource({ object: 'kb_artcle' })] }; + const errors = runAuthoringRules(command, { parsed: stack, normalized: stack }) + .filter((f) => f.rule === KNOWLEDGE_SOURCE_OBJECT_UNKNOWN && f.severity === 'error'); + expect(errors, command).toHaveLength(1); + } + }); +}); + +/** + * ADR-0161 K4: "a packaged item meets the gates that need no principal in + * `os validate` and at publish". The runtime publish door answers the rule + * ids and messages `os validate` prints for the same source; its errors + * refuse the publish, unlike the `ai_context` row's advisories. + */ +describe('validateKnowledgeSource on the runtime publish door', () => { + it('the door dispatches a knowledge_source write to the rule, into the knowledgeSources collection', () => { + expect(runtimeAuthoringRulesFor('knowledge_source').map((r) => r.name)).toContain('validateKnowledgeSource'); + expect(stackKeyForType('knowledge_source')).toBe('knowledgeSources'); + }); + + for (const [what, source, rule, severity] of FAMILIES) { + it(`${what} is reported at publish as ${rule}, in the words os validate prints${severity === 'error' ? ', and refuses the publish' : ''}`, () => { + const verdict = atPublish(source); + expect(verdict.rulesRun).toContain('validateKnowledgeSource'); + const refused = verdict.errors.filter((f) => KS_RULE.test(f.rule)); + const advised = verdict.advisories.filter((f) => KS_RULE.test(f.rule)); + expect((severity === 'error' ? refused : advised).map((f) => f.rule)).toEqual([rule]); + expect((severity === 'error' ? advised : refused)).toEqual([]); + expect([...refused, ...advised].map(face)).toEqual(atValidate(source).map(face)); + }); + } + + it('a clean source is published with nothing to report', () => { + const verdict = atPublish(kbSource()); + expect(verdict.rulesRun).toContain('validateKnowledgeSource'); + expect(verdict.errors).toEqual([]); + expect(verdict.advisories).toEqual([]); + }); + + it('under a stated package scope, an object outside the closure is refused with the closure remedy', () => { + const scoped = objects.map((o) => ({ ...o, _packageId: o.name === 'kb_article' ? 'com.other' : 'app.kb' })); + const verdict = runRuntimeAuthoringRules({ + type: 'knowledge_source', + item: kbSource(), + context: { objects: scoped }, + packageScope: { packageId: 'app.kb', dependencies: [] }, + }); + expect(verdict.errors.map((f) => [f.rule, f.path])).toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, expect.stringContaining('source.object')]]); + const [finding] = verdict.errors; + expect(finding!.message).toContain('outside the closure of package "app.kb"'); + expect(finding!.hint).toBe( + 'Declare a dependency on the package that defines "kb_article" in the `dependencies` of "app.kb"\'s manifest, ' + + 'or name an object inside that closure', + ); + // Non-vacuous: declaring the dependency brings the object into the closure, and the source is clean. + expect(runRuntimeAuthoringRules({ + type: 'knowledge_source', + item: kbSource(), + context: { objects: scoped }, + packageScope: { packageId: 'app.kb', dependencies: ['com.other'] }, + }).errors).toEqual([]); + }); + + it('with no scope the object verdict keeps the words os validate prints', () => { + const [finding] = validateKnowledgeSource({ objects, knowledgeSources: [kbSource({ object: 'kb_artcle' })] }); + expect(finding!.message).toContain("`source.object` names 'kb_artcle', which this stack does not define"); + expect(finding!.hint).toBe( + 'Name an object the stack defines (check the spelling) or a platform object by its full name; for an object ' + + 'another package defines, declare that package in the manifest\'s `dependencies` and install it', + ); + }); + + it('against the whole collection the host serves, a missing object is an error even beside an unseen declared dependency', () => { + const stack = { + objects, + manifest: { id: 'app.kb', dependencies: { 'com.acme.faq': '^1.0.0' } }, + knowledgeSources: [kbSource({ object: 'faq_entry', content: ['answer'], metadataFields: [] })], + }; + expect(validateKnowledgeSource(stack, { wholeCollection: true }).map((f) => [f.rule, f.severity])) + .toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'error']]); + // Non-vacuous: the same stack on the CLI is the hedged warning. + expect(validateKnowledgeSource(stack).map((f) => [f.rule, f.severity])) + .toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'warning']]); + }); + + it('the door passes the whole-collection reading when no package scope is stated', () => { + const item = kbSource({ object: 'faq_entry', content: ['answer'], metadataFields: [] }); + // An empty served collection is no universe at the door: no object verdict is drawn from it. + expect(runRuntimeAuthoringRules({ type: 'knowledge_source', item, context: { objects: [] } }).errors).toEqual([]); + // Non-vacuous: a served collection that lacks the object refuses it. + expect(runRuntimeAuthoringRules({ type: 'knowledge_source', item, context: { objects } }).errors + .map((f) => [f.rule, f.severity])).toEqual([[KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, 'error']]); + }); + + 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([]); + }); +}); + +describe('os explain for the knowledge source rules', () => { + for (const rule of [ + KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + KNOWLEDGE_SOURCE_FIELD_UNKNOWN, + KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, + KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE, + KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, + ]) { + it(`answers ${rule}`, () => { + const entry = explainRule(rule); + expect(entry?.rule).toBe(rule); + expect(entry?.paragraphs.length).toBeGreaterThan(0); + }); + } +}); diff --git a/packages/lint/src/validate-knowledge-source.ts b/packages/lint/src/validate-knowledge-source.ts new file mode 100644 index 00000000000..9c1420a636a --- /dev/null +++ b/packages/lint/src/validate-knowledge-source.ts @@ -0,0 +1,347 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0161 K4, row 4] Knowledge sources (`knowledgeSources`, the governed + * type `knowledge_source`) that reference what the stack does not have, or an + * object the knowledge service never searches for a caller it judges: + * reported by `os validate` / `build` / `lint` and by the runtime publish + * gate, with one set of rule ids and messages. + * + * ADR-0161 K4 states both halves: an item "is refused when the object or a + * named field does not exist (the lint and `os validate` checks are row 4)", + * and "a packaged item meets the gates that need no principal in `os validate` + * and at publish (row 4)". So those findings are errors, and the publish door + * refuses them. What each one costs differs: a missing object leaves the + * source nothing to index, a missing field indexes no text for that member, + * and a gated object is never searched for any caller the service judges. + * That is the one point where this rule departs from its precedent, + * `validateAiContext`, which only advises at publish (ADR-0160 D1: a context + * pack still reads what resolves); K4 orders the refusal here. + * + * Five 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 + * door, of the objects the host serves. An `error` where the snapshot is + * enough to know: under the package closure the door states (worded for + * the closure with {@link closureDependencyRemedy}), at the door with no + * closure (the whole collection the host serves), and on the CLI for a + * stack whose manifest declares no dependency the artifact does not carry. + * A `warning` with the hedge on the CLI when the manifest declares such a + * dependency: the build cannot see that package's objects, and the publish + * door judges the source against its closure, which holds them (the + * `flow-trigger-unknown-object` split). The ladder + * `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. + * - `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 + * a column addressable on it without being declared + * ({@link injectedColumnsFor}: `id`, which the driver provisions, and the + * system columns the registry injects). The index reads that member off + * every record and finds nothing. + * - `knowledge-source-object-not-searchable` (`error`): the object's API + * exposure refuses `search`: `canServeApiOperation(enable, 'search')`, the + * decision and operation the knowledge service's admission asks + * (`knowledge-source-admission.ts` in `@objectstack/service-knowledge`, + * gate 2). `enable.apiEnabled: false` refuses it, and so does an + * `enable.apiMethods` list that does not grant `list` (search derives from + * `list`; `search` itself is a retired list value the parse strips) or that + * grants `list` beside `enable.searchable: false`. With no `apiMethods` + * list, `searchable: false` does not refuse it. + * - `knowledge-source-system-object-not-ai-readable` (`error`): a system + * object (a `sys_` name, the admission's gate 3) that does not opt into AI + * reads — `isAiReadExposed`, the spec's one reading of + * `enable.aiReadable`. + * - `knowledge-source-field-never-indexed` (`warning`): a member names a + * credential-class field (`isMaskedOnReadFieldType`, the spec's + * 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). + * + * 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, + * as the authoring principal (`authoredKnowledgeSourceRefusal` in + * `@objectstack/metadata-core`). The fields a `where` reads are judged there + * too. The predicates are the spec's own, asked as the admission module asks + * them: no gate is restated here. + * + * An object the stack does not define is reported once and its fields are not + * judged; an object with no readable field map is not field-judged. Both gates + * are judged on every object whose definition is in hand. + */ + +import { canServeApiOperation, isAiReadExposed, isMaskedOnReadFieldType, 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'; +import { injectedColumnsFor } from './system-fields.js'; + +export type KnowledgeSourceSeverity = 'error' | 'warning'; + +export interface KnowledgeSourceFinding { + severity: KnowledgeSourceSeverity; + rule: string; + /** Human-readable location, e.g. `knowledge source "support_kb"`. */ + where: string; + /** Config path, e.g. `knowledgeSources[0].source.content[1]`. */ + path: string; + message: string; + hint: string; +} + +export const KNOWLEDGE_SOURCE_OBJECT_UNKNOWN = 'knowledge-source-object-unknown'; +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'; + +/** The operation a knowledge search is judged as — the admission module's `KNOWLEDGE_SEARCH_OPERATION`. */ +const SEARCH_OPERATION = 'search'; + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); +const str = (v: unknown): string => (typeof v === 'string' ? v : ''); + +/** + * The admission module's system-object reading (gate 3): a `sys_` name, the + * predicate the MCP record tools refuse by. + */ +const isSystemObjectName = (name: string): boolean => /^sys_/i.test(name); + +/** + * The object's declared fields as a name → definition map, or `undefined` + * when it declares no readable map. Existence also admits the columns + * addressable without a declaration ({@link injectedColumnsFor}), which carry + * no credential and no `internal` flag, so they need no definition here. + */ +function declaredFieldsOf(object: AnyRec): Map | undefined { + const raw = object.fields; + if (!raw || typeof raw !== 'object') return undefined; + return new Map(recordsOf(raw).map((f) => [str(f.name), f] as const).filter(([name]) => name !== '')); +} + +/** + * The ids of the packages the stack's manifest declares in `dependencies` + * that its artifact (`packages[]`) does not carry: packages whose objects the + * build cannot see, and the publish door's closure holds. + */ +function unseenDeclaredDependencies(stack: AnyRec): string[] { + const manifest = stack.manifest; + if (!isRec(manifest)) return []; + const declared = manifest.dependencies; + const ids = Array.isArray(declared) + ? declared.filter((d): d is string => typeof d === 'string' && d !== '') + : isRec(declared) + ? Object.keys(declared) + : []; + if (ids.length === 0) return []; + const carried = new Set(); + for (const entry of packagesOf(stack)) { + const id = isRec(entry.manifest) ? str(entry.manifest.id) : ''; + if (id) carried.add(id); + } + return ids.filter((id) => !carried.has(id) && id !== str(manifest.id)); +} + +/** + * Report every knowledge source of `stack` whose object or fields the stack + * does not have, whose object the knowledge service never searches for a + * caller it judges, or that names a field the index never carries. Reads + * `stack.knowledgeSources`, `stack.manifest.dependencies`, `stack.objects` + * (with the stack's own `objectExtensions` folded in) and the objects of + * `stack.packages[]`; safe on any shape. + * + * @param options.packageScope The package closure the runtime publish gate + * narrowed `stack.objects` to (`AuthoringRuleContext.packageScope`), present + * only when one was in force. An unresolved object is then outside the + * package's reach, and the verdict says so with the closure remedy. + * @param options.wholeCollection `true` when `stack.objects` is the whole + * collection a runtime host serves (a gated write that names no package), + * as the list-view and form members read it: an unresolved object exists + * nowhere, and the declared-dependency hedge does not apply. + */ +export function validateKnowledgeSource( + stack: AnyRec, + options: { + packageScope?: { readonly packageId: string; readonly dependencies: readonly string[] }; + wholeCollection?: boolean; + } = {}, +): KnowledgeSourceFinding[] { + const out: KnowledgeSourceFinding[] = []; + if (!isRec(stack)) return out; + const sources = collectionEntries(stack.knowledgeSources, 'knowledgeSources'); + if (sources.length === 0) return out; + const closure = options.packageScope; + const atDoor = !!closure || options.wholeCollection === true; + + // The stack's own objects as served, then what a package of its artifact + // ships (ADR-0130 D4: the release artifact is the co-ownership boundary, so + // the per-package pass of `os build` resolves a sibling's object). + const objects = new Map(); + for (const o of objectsAsServed(stack).objects) if (str(o.name)) objects.set(str(o.name), o); + for (const entry of packagesOf(stack)) { + const body = entry.manifest; + if (!isRec(body)) continue; + for (const o of recordsOf(body.objects)) if (str(o.name) && !objects.has(str(o.name))) objects.set(str(o.name), o); + } + // An empty whole collection means the host supplied no universe (a failed + // 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; + const unseen = atDoor ? [] : unseenDeclaredDependencies(stack); + + for (const { rec, path } of sources) { + const where = `knowledge source "${str(rec.name) || path}"`; + const source = rec.source; + if (!isRec(source)) continue; + const objectName = str(source.object); + if (!objectName) continue; + const objectPath = `${path}.source.object`; + const def = objects.get(objectName); + + if (!def) { + 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; + if (closure) { + out.push({ + severity: 'error', + rule: KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + where, + path: objectPath, + message: + `\`source.object\` names '${objectName}', which is outside the closure of package "${closure.packageId}" ` + + '(the package, the packages its manifest declares in `dependencies`, and platform objects), so the ' + + 'source indexes nothing where the package is installed without that dependency.' + + suggestName(objectName, objects.keys()), + hint: closureDependencyRemedy(objectName, closure.packageId, 'name an object inside that closure'), + }); + } else if (hasPlatformObjectPrefix(objectName)) { + out.push({ + severity: 'warning', + rule: KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + where, + path: objectPath, + message: + `\`source.object\` names '${objectName}', which has a platform prefix, but no known package registers it ` + + 'and this stack does not define it, so the source likely indexes nothing.' + + suggestName(objectName, objects.keys()), + hint: 'Check the spelling against the object the providing package registers, or ignore this if a third-party package provides it', + }); + } else if (unseen.length > 0) { + out.push({ + severity: 'warning', + rule: KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + where, + path: objectPath, + message: + `\`source.object\` names '${objectName}', which this stack does not define. The manifest declares ` + + `${unseen.map((id) => `"${id}"`).join(', ')} in \`dependencies\`, whose objects this build cannot see; ` + + 'if none of them defines it, the source indexes nothing, and the publish is refused.' + + suggestName(objectName, objects.keys()), + hint: + 'Ignore this if a declared dependency defines the object (the publish checks it against the package\'s ' + + 'closure); otherwise name an object the stack defines (check the spelling)', + }); + } else { + out.push({ + severity: 'error', + rule: KNOWLEDGE_SOURCE_OBJECT_UNKNOWN, + where, + path: objectPath, + message: + `\`source.object\` names '${objectName}', which this stack does not define, so the source indexes nothing ` + + 'and no search ever returns a hit from it.' + + suggestName(objectName, objects.keys()), + hint: + 'Name an object the stack defines (check the spelling) or a platform object by its full name; for an ' + + 'object another package defines, declare that package in the manifest\'s `dependencies` and install it', + }); + } + continue; + } + + // [ADR-0161 K4] The gates that need no principal, in the admission's order. + const enable = (isRec(def.enable) ? def.enable : undefined) as EnableLike | undefined; + if (!canServeApiOperation(enable, SEARCH_OPERATION)) { + out.push({ + severity: 'error', + rule: KNOWLEDGE_SOURCE_OBJECT_NOT_SEARCHABLE, + where, + path: objectPath, + message: + `the API does not serve object '${objectName}' 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`), so the knowledge service never searches this source for a caller it judges.', + hint: + `Serve '${objectName}' for search: keep \`enable.apiEnabled\` true and, where it declares ` + + '`enable.apiMethods`, include `list` with `enable.searchable` not false; or index another object', + }); + } + if (isSystemObjectName(objectName) && !isAiReadExposed(def)) { + out.push({ + severity: 'error', + rule: KNOWLEDGE_SOURCE_SYSTEM_OBJECT_NOT_AI_READABLE, + where, + path: objectPath, + message: + `'${objectName}' is a system object that does not opt into AI reads (\`enable.aiReadable: true\`), so ` + + 'the knowledge service never searches this source for a caller it judges.', + hint: 'Index a business object, or a system object whose definition declares `enable.aiReadable: true`', + }); + } + + const fields = declaredFieldsOf(def); + if (!fields) continue; + const addressable = injectedColumnsFor(def); + const known = (): string[] => [...fields.keys(), ...[...addressable].filter((n) => !fields.has(n))]; + const managedBy = def.managedBy; + const judgeMembers = (key: 'content' | 'metadataFields') => { + const members = source[key]; + if (!Array.isArray(members)) return; + members.forEach((member, k) => { + if (typeof member !== 'string' || member === '') return; + const memberPath = `${path}.source.${key}[${k}]`; + const field = fields.get(member); + if (!field) { + if (addressable.has(member)) return; + out.push({ + severity: 'error', + rule: KNOWLEDGE_SOURCE_FIELD_UNKNOWN, + where, + path: memberPath, + message: + `\`source.${key}\` names field '${member}', which object '${objectName}' does not define, so the ` + + 'index reads nothing for it on any record.' + + suggestName(member, known()), + hint: `Name a field of '${objectName}' (check the spelling), or remove it from \`${key}\``, + }); + return; + } + const credential = isMaskedOnReadFieldType(field.type, managedBy); + if (credential || field.internal === true) { + out.push({ + severity: 'warning', + rule: KNOWLEDGE_SOURCE_FIELD_NEVER_INDEXED, + where, + path: memberPath, + message: + `\`source.${key}\` names field '${member}' of '${objectName}', which is ` + + (credential ? `a credential-class field (\`${str(field.type)}\`)` : 'declared `internal: true`') + + ', and the index never carries it, so the member is skipped.', + hint: `Remove '${member}' from \`${key}\``, + }); + } + }); + }; + judgeMembers('content'); + judgeMembers('metadataFields'); + } + return out; +} diff --git a/packages/spec/src/migrations/entries/semantic/19.knowledge-source-publish-refuses-missing-references-and-gated-objects.ts b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-publish-refuses-missing-references-and-gated-objects.ts new file mode 100644 index 00000000000..394edc62a2c --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.knowledge-source-publish-refuses-missing-references-and-gated-objects.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// ADR-0161 K4 (row 4) — the D3 entry of the author-time rule that judges a +// `knowledge_source` against the objects it names, at publish and in +// `os validate` / `build` / `lint`. Notice only: no key is removed and no D2 +// conversion exists, because each fix is a choice only the author can make +// (which object or field the source meant, whether to serve the object for +// search or opt a system object into AI reads, or which object to index). +export const entry: SemanticMigration = { + id: 'knowledge-source-publish-refuses-missing-references-and-gated-objects', + surface: + 'Four author-time errors on a knowledge source (`knowledgeSources`, the `knowledge_source` type), run by the ' + + 'runtime publish gate and by `os validate` / `lint` / `compile` / `build`: `source.object` names an object that ' + + 'does not exist (`knowledge-source-object-unknown`; a warning for a platform-prefixed name no known package ' + + 'registers, and on the CLI while the manifest declares a dependency the artifact does not carry); a `source.content` or `source.metadataFields` member names no field of the object, declared or ' + + 'injected (`knowledge-source-field-unknown`); the object\'s API exposure does not serve `search` ' + + '(`knowledge-source-object-not-searchable`); the object is a system object without `enable.aiReadable: true` ' + + '(`knowledge-source-system-object-not-ai-readable`). And one warning: a member names a credential-class or ' + + '`internal` field, which the index never carries (`knowledge-source-field-never-indexed`)', + replacement: + 'Point `source.object` at an object the stack, its artifact or the host defines; an object a dependency defines ' + + 'clears at publish once the package\'s manifest declares that dependency in `dependencies` (on the CLI it stays ' + + 'a warning while the artifact does not carry the dependency). Name fields the object defines, or `id` and the ' + + 'injected system columns, in `content` and `metadataFields`. Serve the object for `search`: keep ' + + '`enable.apiEnabled` true and, where it declares `enable.apiMethods`, include `list` with `enable.searchable` ' + + 'not false (`search` is a retired list value the parse strips); or index another object. Index a business ' + + 'object, or a system object whose definition declares `enable.aiReadable: true`', + reason: + 'Each one parses and publishes, then fails at search: an object nothing defines leaves nothing to index, a field ' + + 'it does not define indexes no text for that member on any record, and the knowledge service never searches a ' + + 'source whose object the API does not serve for search or a system object that does not opt into AI reads, for ' + + 'any caller it judges. The save door already ' + + 'refused the last two for an author it judges; a publish no author judgement reaches (where no knowledge ' + + 'service is mounted) is now refused too, and so is a missing object or field. Stored metadata is ' + + 'not rewritten or refused at boot. The next publish of a source that carries one of these is refused with the ' + + 'fix named.', + acceptanceCriteria: + 'os validate reports none of the four errors; a publish of every knowledge source the package carries succeeds.', +};