Skip to content
Merged
8 changes: 8 additions & 0 deletions .changeset/ai-context-save-time-advisories.md
Original file line number Diff line number Diff line change
@@ -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
22 changes: 17 additions & 5 deletions packages/lint/src/authoring-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions packages/lint/src/runtime-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,16 @@ const TYPE_TO_STACK_KEY: Readonly<Record<string, string>> = {
// 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',
};

/**
Expand Down
83 changes: 83 additions & 0 deletions packages/lint/src/validate-ai-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
{
Expand Down Expand Up @@ -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<string, unknown>) =>
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<string, unknown>) =>
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, unknown>, 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([]);
});
});
46 changes: 36 additions & 10 deletions packages/lint/src/validate-ai-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<string, AnyRec>();
for (const o of recordsOf(stack.objects)) if (str(o.name)) objects.set(str(o.name), o);
Expand All @@ -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);
Expand Down
Loading
Loading