diff --git a/.changeset/ai-context-save-time-advisories.md b/.changeset/ai-context-save-time-advisories.md new file mode 100644 index 00000000000..dabc16bca55 --- /dev/null +++ b/.changeset/ai-context-save-time-advisories.md @@ -0,0 +1,8 @@ +--- +'@objectstack/lint': patch +--- + +A context pack (`ai_context`) saved at runtime is now judged by `validateAiContext` on the publish door (ADR-0160 D1: author defects are "reported at save and by `os validate`"). A pack that names a field or object the live objects do not define, a related list with no link to the root, or a body that is not a long-text field is saved and told so on the save response's existing `advisories`, with the same rule ids (`ai-context-field-unknown`, `ai-context-object-unknown`, `ai-context-related-link-unknown`, `ai-context-body-not-long-text`) and, for a write that names no package, the messages `os validate` prints; under a package, an object outside the package's closure (the package, its declared `dependencies` and platform objects) is told so, with the remedy to declare the dependency. The save is never refused for them, as for every advisory rule on that door; a draft save is not judged. + +Clause-②: no +Metadata-protocol: none diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 49c01c5d2b7..4f3cbcedc0b 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -1966,17 +1966,29 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // [ADR-0160 D1] Context packs that name an object or field the stack does not // define, a related list with no link to the root, or a body that is not // long text. Advisory: the tool reads what resolves and states nothing about - // the rest, so the author hears it here. CLI-only — every verdict reads the - // stack's `objects` beside its `aiContexts`. + // the rest, so the author hears it here. + // + // [ADR-0160 D1] "Reported at save and by `os validate`": on the runtime + // publish door for `ai_context`, the door a Studio / REST `/meta` / MCP + // author of a pack has. The rule reads `aiContexts` and `objects` and no + // other collection; `objects` is the context every per-write snapshot + // carries, and the written pack is the sole member of its own collection. + // Under a stated package scope that `objects` is the write's closure, not + // every installed object, so the scope is passed through and an object + // outside it is worded for the closure with `closureDependencyRemedy`, as + // every save-door rule judging an object name under a scope does. The + // findings ride the 2xx `advisories`; with no scope they carry the rule ids + // and messages `os validate` prints. The save is never refused for them, as + // for every advisory rule on this door. { name: 'validateAiContext', tier: 'advisory', input: 'parsed', commands: ALL, source: 'packages/lint/src/validate-ai-context.ts', - surfaces: CLI_ONLY, - surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, - run: (stack) => validateAiContext(stack), + surfaces: CLI_AND_RUNTIME, + runtimeTypes: ['ai_context'], + run: (stack, ctx) => validateAiContext(stack, ctx.packageScope ? { packageScope: ctx.packageScope } : {}), }, // [#34613] `validateSeedReplaySafety` (framework#3434, the `insert`-mode // replay warning) is retired: `SeedMode` itself refuses `insert` and diff --git a/packages/lint/src/runtime-gate.ts b/packages/lint/src/runtime-gate.ts index de37ecbeb90..881be5b4d18 100644 --- a/packages/lint/src/runtime-gate.ts +++ b/packages/lint/src/runtime-gate.ts @@ -300,6 +300,16 @@ const TYPE_TO_STACK_KEY: Readonly> = { // entry onto its target in `objects` (as served, without the written // package's own extension), so it needs no context collection either. object_extension: 'objectExtensions', + // [ADR-0160 D1] `ai_context` — `allowRuntimeCreate: true`, so Studio, REST + // `/meta` and an MCP/AI author mint context packs at runtime, and the ADR + // says a pack's author defects are reported at save as well as by + // `os validate`. ⛔ NOT a mapping ahead of its rule: `validateAiContext` + // crosses with this row and opens on `stack.aiContexts`, the key + // `ObjectStackDefinitionSchema` gives the collection. Not a context row + // either, for the `position` / `app` reason above: the rule resolves a + // pack's names into `objects`, which every snapshot carries, and nothing + // into a sibling pack. + ai_context: 'aiContexts', }; /** diff --git a/packages/lint/src/validate-ai-context.test.ts b/packages/lint/src/validate-ai-context.test.ts index 31c2120885b..a452d4f67d8 100644 --- a/packages/lint/src/validate-ai-context.test.ts +++ b/packages/lint/src/validate-ai-context.test.ts @@ -9,6 +9,8 @@ import { validateAiContext, } from './validate-ai-context.js'; import { explainRule } from './rule-explanations.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor, stackKeyForType } from './runtime-gate.js'; const objects = [ { @@ -104,3 +106,84 @@ describe('validateAiContext — ADR-0160 D1 author defects', () => { } }); }); + +/** + * ADR-0160 D1: "reported at save and by `os validate`". The runtime publish + * door judges a written `ai_context` against the live objects, and answers + * the same rule ids, `where`, messages and hints `os validate` prints for the + * same pack — as advisories, never a refusal (the tier every advisory rule on + * that door keeps). + */ +describe('validateAiContext on the runtime publish door (ADR-0160 D1)', () => { + /** One pack written at the door, judged against `objects` as the live context. */ + const atSave = (body: Record) => + runRuntimeAuthoringRules({ type: 'ai_context', item: body, context: { objects } }); + /** The same pack as `os validate` judges it: the CLI command's own entry over the stack. */ + const atValidate = (body: Record) => + runAuthoringRules('validate', { parsed: { objects, aiContexts: [body] }, normalized: { objects, aiContexts: [body] } }) + .filter((f) => f.rule.startsWith('ai-context-')); + const face = (f: { rule: string; where: string; path: string; message: string; hint?: string; severity: string }) => + ({ rule: f.rule, severity: f.severity, where: f.where, path: f.path, message: f.message, hint: f.hint }); + + it('the door dispatches an ai_context write to the rule, into the aiContexts collection', () => { + expect(runtimeAuthoringRulesFor('ai_context').map((r) => r.name)).toContain('validateAiContext'); + expect(stackKeyForType('ai_context')).toBe('aiContexts'); + }); + + const FAMILIES: ReadonlyArray<[string, Record, string, string]> = [ + ['a misspelled field', pack({ fields: ['title', 'titel'] }), AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].fields[1]'], + ['an unknown related object', pack({ related: [{ object: 'policy_revison' }] }), AI_CONTEXT_OBJECT_UNKNOWN, 'aiContexts[0].related[0].object'], + ['a related list with no link', pack({ related: [{ object: 'account' }] }), AI_CONTEXT_RELATED_LINK_UNKNOWN, 'aiContexts[0].related[0]'], + ['a body that is not long text', pack({ body: { field: 'title' } }), AI_CONTEXT_BODY_NOT_LONG_TEXT, 'aiContexts[0].body.field'], + ]; + + for (const [what, body, rule, path] of FAMILIES) { + it(`${what} is reported at save as ${rule}, in the words os validate prints, and the save is not refused`, () => { + const verdict = atSave(body); + expect(verdict.rulesRun).toContain('validateAiContext'); + expect(verdict.errors, 'an advisory rule never refuses the write').toEqual([]); + expect(verdict.advisories.map((f) => [f.rule, f.path])).toEqual([[rule, path]]); + expect(verdict.advisories.map(face)).toEqual(atValidate(body).map(face)); + }); + } + + it('under a stated package scope, an installed object outside the closure is worded for the closure, with the closure remedy', () => { + const scoped = objects.map((o) => ({ ...o, _packageId: o.name === 'account' ? 'com.other' : 'app.policy' })); + const body = pack({ related: [{ object: 'account' }] }); + const verdict = runRuntimeAuthoringRules({ + type: 'ai_context', + item: body, + context: { objects: scoped }, + packageScope: { packageId: 'app.policy', dependencies: [] }, + }); + expect(verdict.errors, 'an advisory rule never refuses the write').toEqual([]); + expect(verdict.advisories.map((f) => [f.rule, f.path])).toEqual([[AI_CONTEXT_OBJECT_UNKNOWN, 'aiContexts[0].related[0].object']]); + const [finding] = verdict.advisories; + expect(finding!.message).toContain('outside the closure of package "app.policy"'); + expect(finding!.message).not.toContain('this stack does not define'); + expect(finding!.hint).toBe( + 'Declare a dependency on the package that defines "account" in the `dependencies` of "app.policy"\'s manifest, ' + + 'or name an object inside that closure', + ); + // Non-vacuous: declaring the dependency brings the object into the closure, and the pack is clean. + expect(runRuntimeAuthoringRules({ + type: 'ai_context', + item: body, + context: { objects: scoped }, + packageScope: { packageId: 'app.policy', dependencies: ['com.other'] }, + }).advisories.filter((f) => f.rule === AI_CONTEXT_OBJECT_UNKNOWN)).toEqual([]); + }); + + it('with no scope the object verdict keeps the words os validate prints', () => { + const [finding] = validateAiContext({ objects, aiContexts: [pack({ object: 'polcy', related: undefined, body: undefined })] }); + expect(finding!.message).toBe("names object 'polcy', which this stack does not define, so the pack reads nothing of it"); + expect(finding!.hint).toBe('Name an object the stack defines (check the spelling), or remove the entry'); + }); + + it('a pack that names only what the live objects define earns nothing at save', () => { + const verdict = atSave(pack()); + expect(verdict.rulesRun).toContain('validateAiContext'); + expect(verdict.advisories).toEqual([]); + expect(verdict.errors).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-ai-context.ts b/packages/lint/src/validate-ai-context.ts index 437102a8f97..689cc794b80 100644 --- a/packages/lint/src/validate-ai-context.ts +++ b/packages/lint/src/validate-ai-context.ts @@ -27,11 +27,21 @@ * the stack does not define is reported once (the root, or the related entry) * and its fields are not judged; an object with no readable field map is not * judged; a `sys_*` object is the platform's and is not judged here. + * + * Under a package closure the runtime publish gate states (`options.packageScope`, + * ruling #9612) the snapshot's `objects` ARE that closure, so an object missing + * from it may be installed and read by `get_record_context` here, yet is out of + * the package's reach wherever it is installed without that dependency. The + * object verdict is then worded for the closure and carries the remedy every + * save-door rule judging an object name under a scope prints + * ({@link closureDependencyRemedy}). Still a `warning`: the tier never refuses. + * With no closure (`os validate`, a write naming no package) the wording is + * unchanged. */ import { AI_CONTEXT_BODY_FIELD_TYPES } from '@objectstack/spec/ai'; import { REFERENCE_VALUE_TYPES, referenceTargetOf } from '@objectstack/spec/data'; -import { recordsOf } from './object-graph.js'; +import { closureDependencyRemedy, recordsOf } from './object-graph.js'; export type AiContextSeverity = 'warning'; @@ -77,7 +87,11 @@ function referenceOf(def: AnyRec | undefined): string | undefined { * Report the names every context pack of `stack` gives that the stack does not * define. Reads `stack.aiContexts` and `stack.objects`; safe on any shape. */ -export function validateAiContext(stack: AnyRec): AiContextFinding[] { +export function validateAiContext( + stack: AnyRec, + options: { packageScope?: { readonly packageId: string; readonly dependencies: readonly string[] } } = {}, +): AiContextFinding[] { + const closure = options.packageScope; const out: AiContextFinding[] = []; const objects = new Map(); for (const o of recordsOf(stack.objects)) if (str(o.name)) objects.set(str(o.name), o); @@ -95,14 +109,26 @@ export function validateAiContext(stack: AnyRec): AiContextFinding[] { if (!object || object.startsWith('sys_')) return undefined; const def = objects.get(object); if (!def) { - out.push({ - severity: 'warning', - rule: AI_CONTEXT_OBJECT_UNKNOWN, - where, - path, - message: `names object '${object}', which this stack does not define, so the pack reads nothing of it`, - hint: 'Name an object the stack defines (check the spelling), or remove the entry', - }); + out.push(closure + ? { + severity: 'warning', + rule: AI_CONTEXT_OBJECT_UNKNOWN, + where, + path, + message: + `names object '${object}', which is outside the closure of package "${closure.packageId}" ` + + '(the package, the packages its manifest declares in `dependencies`, and platform objects), so ' + + 'the pack reads nothing of it where the package is installed without that dependency', + hint: closureDependencyRemedy(object, closure.packageId, 'name an object inside that closure'), + } + : { + severity: 'warning', + rule: AI_CONTEXT_OBJECT_UNKNOWN, + where, + path, + message: `names object '${object}', which this stack does not define, so the pack reads nothing of it`, + hint: 'Name an object the stack defines (check the spelling), or remove the entry', + }); return undefined; } return fieldMapOf(def); diff --git a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts index 3d3ff843c0f..4ac24333c66 100644 --- a/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts +++ b/packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts @@ -5615,3 +5615,143 @@ describe('runtime authoring gate — an object list view sort the list door refu } }); }); + +/** + * ADR-0160 D1 — a context pack's author defects are "reported at save and by + * `os validate`". `validateAiContext` crosses to this door for `ai_context`: + * a runtime-created pack (Studio, REST `/meta`, an MCP/AI author) that names + * what the live objects lack is told so on the save it makes, in the rule ids + * and messages `os validate` prints. + * + * Saved with warnings, never refused: the door's precedent for every advisory + * rule (`protocol-save.ts`, the gate call's `[#4717]` note and the receipt's + * conditional `advisories` key) — the gate's errors are thrown as the 422 and + * its advisories ride the 2xx this write earns. + */ +describe('ai_context author defects at save (ADR-0160 D1)', () => { + let warn: ReturnType; + beforeEach(() => { + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + delete process.env.OS_ALLOW_UNLINTED_METADATA_WRITES; + }); + afterEach(() => { + warn.mockRestore(); + }); + + /** The live objects the pack is judged against, as the registry serves them. */ + const POLICY_OBJECTS = [ + { + name: 'policy', + fields: { + title: { type: 'text' }, + status: { type: 'select' }, + content: { type: 'markdown' }, + }, + }, + { name: 'policy_revision', fields: { version: { type: 'text' }, policy: { type: 'lookup', reference: 'policy' } } }, + { name: 'account', fields: { name: { type: 'text' } } }, + ]; + + function makePackProtocol() { + const { engine, rows } = makeStubEngine(); + engine.registry.listItems = (type: string) => (type === 'object' ? POLICY_OBJECTS : []); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test'); + return { protocol: protocol as any, rows }; + } + + const pack = (over: Record = {}) => ({ + name: 'policy_document', + label: 'Policy document', + object: 'policy', + fields: ['title', 'status'], + related: [{ object: 'policy_revision', fields: ['version'] }], + body: { field: 'content' }, + ...over, + }); + + const savePack = (protocol: any, item: unknown, extra: Record = {}) => + protocol.saveMetaItem({ type: 'ai_context', name: 'policy_document', item, ...extra }); + + const packRows = (rows: Map) => Array.from(rows.values()).filter((r) => r.type === 'ai_context'); + + /** What `os validate` prints for the same pack over the same objects: the CLI command's own entry. */ + const validateFindings = (item: Record) => + runAuthoringRules('validate', { normalized: { objects: POLICY_OBJECTS, aiContexts: [item] } }) + .filter((f) => f.rule.startsWith('ai-context-')) + .map((f) => ({ rule: f.rule, where: f.where, message: f.message, hint: f.hint })); + + const FAMILIES: ReadonlyArray<[string, Record, string]> = [ + ['a misspelled field', pack({ fields: ['title', 'titel'] }), 'ai-context-field-unknown'], + ['an unknown related object', pack({ related: [{ object: 'policy_revison' }] }), 'ai-context-object-unknown'], + ['a related list with no link', pack({ related: [{ object: 'account' }] }), 'ai-context-related-link-unknown'], + ['a body that is not long text', pack({ body: { field: 'title' } }), 'ai-context-body-not-long-text'], + ]; + + for (const [what, item, rule] of FAMILIES) { + it(`a runtime-created pack with ${what} is saved and told ${rule}, in os validate's words`, async () => { + const { protocol, rows } = makePackProtocol(); + + const result = await savePack(protocol, item); + + expect(result.success).toBe(true); + expect(packRows(rows)).toHaveLength(1); + const advisories = (result.advisories ?? []) as Array>; + expect(advisories.map((a) => a.rule), `advisories: ${JSON.stringify(advisories)}`).toEqual([rule]); + expect(advisories[0]!.severity).toBe('warning'); + expect(advisories.map((a) => ({ rule: a.rule, where: a.where, message: a.message, hint: a.hint }))) + .toEqual(validateFindings(item)); + }); + } + + it('a pack saved under a package scope naming an installed object outside the closure is told so, with the closure remedy', async () => { + const { engine, rows } = makeStubEngine(); + // `app.fx` is installed with no dependencies; `account` belongs to another installed package. + engine.registry.listItems = (type: string) => (type === 'object' + ? POLICY_OBJECTS.map((o) => ({ ...o, _packageId: o.name === 'account' ? 'com.example.pages' : 'app.fx' })) + : []); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_test') as any; + + const result = await savePack(protocol, pack({ related: [{ object: 'account' }] }), { packageId: 'app.fx' }); + + expect(result.success).toBe(true); + expect(packRows(rows)).toHaveLength(1); + const advisories = (result.advisories ?? []) as Array>; + expect(advisories.map((a) => [a.rule, a.path]), `advisories: ${JSON.stringify(advisories)}`) + .toEqual([['ai-context-object-unknown', 'aiContexts[0].related[0].object']]); + expect(advisories[0]!.message).toContain('outside the closure of package "app.fx"'); + expect(advisories[0]!.message).not.toContain('this stack does not define'); + expect(advisories[0]!.hint).toBe( + 'Declare a dependency on the package that defines "account" in the `dependencies` of "app.fx"\'s manifest, ' + + 'or name an object inside that closure', + ); + }); + + it('with no package, an unknown object keeps the os validate words', async () => { + const { protocol } = makePackProtocol(); + const item = pack({ related: [{ object: 'polcy_revision' }] }); + const result = await savePack(protocol, item); + const advisories = (result.advisories ?? []) as Array>; + expect(advisories.map((a) => ({ rule: a.rule, where: a.where, message: a.message, hint: a.hint }))) + .toEqual(validateFindings(item)); + expect(advisories[0]!.message).toContain('this stack does not define'); + }); + + it('a clean pack carries no advisories key at all', async () => { + const { protocol, rows } = makePackProtocol(); + const result = await savePack(protocol, pack()); + expect(result.success).toBe(true); + expect('advisories' in result, `advisories leaked: ${JSON.stringify(result.advisories)}`).toBe(false); + expect(packRows(rows)).toHaveLength(1); + }); + + it('a DRAFT save of a defective pack is not judged; its publish is', async () => { + const { protocol } = makePackProtocol(); + const item = pack({ fields: ['title', 'titel'] }); + const draft = await savePack(protocol, item, { mode: 'draft' }); + expect(draft.success).toBe(true); + expect('advisories' in draft, `a draft is allowed to be half-finished: ${JSON.stringify(draft.advisories)}`).toBe(false); + // Non-vacuous: the same body saved active is told. + const active = await savePack(protocol, item); + expect((active.advisories ?? []).map((a: any) => a.rule)).toEqual(['ai-context-field-unknown']); + }); +});