diff --git a/.changeset/37432-ai-context-field-unprovisioned.md b/.changeset/37432-ai-context-field-unprovisioned.md new file mode 100644 index 00000000000..babf206c806 --- /dev/null +++ b/.changeset/37432-ai-context-field-unprovisioned.md @@ -0,0 +1,10 @@ +--- +'@objectstack/lint': patch +--- + +fix(lint): a context pack is warned when it reads an injected column with no storage on an external object + +Clause-②: yes (widening) +Metadata-protocol: none + +A new advisory rule, `ai-context-field-unprovisioned` (a `warning`), reports a context pack (`ai_context`) that names a system column the platform injects (`owner_id`, `created_at`, `created_by`, …) on an ADR-0015 `external` object. The name resolves, so `ai-context-field-unknown` stays silent, but the remote database owns the table and the platform provisions no column behind it. The rule judges the names in the root's `fields`, `body.field`, and each `related` entry's `fields`, `where`, `orderBy` and link field. Its message names the cost for each position: an empty value on every record, no body, no rows, or an arbitrary order. A column the author declares on the external object is never reported. The provenance answer is the spec's `unprovisionedInjectedColumns`, which every other unprovisioned-anchor rule reads too. `os explain ai-context-field-unprovisioned` states the cause and the remedy, and `os explain ai-context-field-unknown` now says that injected columns count as defined. diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 36a3bc2161b..a31a7b2c2ef 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -382,6 +382,7 @@ export { validateAiContext, AI_CONTEXT_OBJECT_UNKNOWN, AI_CONTEXT_FIELD_UNKNOWN, + AI_CONTEXT_FIELD_UNPROVISIONED, AI_CONTEXT_RELATED_LINK_UNKNOWN, AI_CONTEXT_BODY_NOT_LONG_TEXT, AI_CONTEXT_SORT_FIELD_UNSORTABLE, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index b1ecdda2b4e..04383c4a59a 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -443,7 +443,8 @@ const DASHBOARD_FILTER_FIELD_NOT_INCLUDED_EXPLANATION: RuleExplanation = { * What an unprovisioned anchor is — the cause half of every read-side anchor * id (`dashboard-filter-field-unprovisioned`, `react-chart-field-unprovisioned`, * `sort-field-unprovisioned`, `searchable-field-unprovisioned`, - * `page-field-unprovisioned`, `flow-template-field-unprovisioned`). + * `page-field-unprovisioned`, `flow-template-field-unprovisioned`, + * `ai-context-field-unprovisioned`). * The rule files share its verdict clause, `unprovisionedAnchorVerdict()`, or * its long form, `unprovisionedAnchorCause()`. */ @@ -458,7 +459,8 @@ const UNPROVISIONED_ANCHOR_CAUSE = * the converted anchor ids (`unprovisionedAnchorFix()`) names without the how: * `sort-field-unprovisioned`, `searchable-field-unprovisioned`, * `react-chart-field-unprovisioned`, `dashboard-filter-field-unprovisioned`, - * `page-field-unprovisioned`, `flow-template-field-unprovisioned` and the hook, + * `page-field-unprovisioned`, `flow-template-field-unprovisioned`, + * `ai-context-field-unprovisioned` and the hook, * action and flow-node write-anchor ids write it out. */ const UNPROVISIONED_ANCHOR_REMEDY = @@ -5992,8 +5994,37 @@ const AI_CONTEXT_FIELD_UNKNOWN_EXPLANATION: RuleExplanation = { rule: 'ai-context-field-unknown', covers: 'why each field a context pack lists must exist on its object', paragraphs: [ - 'A pack lists the root\'s `fields`, each related list\'s `fields`, and a `body.field`. A name the object ' + - 'does not define is left out of every answer: the assistant reads less about the record than the pack says.', + 'A pack lists the root\'s `fields`, each related list\'s `fields`, and a `body.field`; a related list\'s ' + + '`where` and `orderBy` name fields too. A name the object does not define is left out of every answer: ' + + 'the assistant reads less about the record than the pack says. In a `where` or `orderBy` the whole list ' + + 'is left out, since a filter or an order is never read with one of its fields removed.', + 'Defined means declared in the object\'s `fields` or injected by the platform: the system columns it ' + + 'adds without the author declaring them (`owner_id`, `created_at`, `created_by` and the rest) are ' + + 'fields of the published definition `get_record_context` reads, so a pack naming one is not reported. ' + + 'A column the platform does not inject on that object is still unknown: for example `owner_id` ' + + 'under `ownership: \'org\'`, or any of them under `systemFields: false`. On an ' + + '`external` object an injected column resolves but has no storage; that is ' + + '`ai-context-field-unprovisioned`.', + AI_CONTEXT_PACK_SILENCE, + ], +}; + +const AI_CONTEXT_FIELD_UNPROVISIONED_EXPLANATION: RuleExplanation = { + rule: 'ai-context-field-unprovisioned', + covers: 'why a context pack reads nothing of an external anchor', + paragraphs: [ + UNPROVISIONED_ANCHOR_CAUSE, + 'A context pack naming such an anchor reads a column that holds nothing, at the cost the message ' + + 'names for its position: in the root\'s or a related list\'s `fields` the answer carries it empty on ' + + 'every record; as `body.field` the answer carries no body; in a related list\'s `where`, or as the ' + + 'reference field that links the list to its root, the condition can never match a real value (on ' + + 'SQLite it degrades to constant-false) and the list reads no rows; in its `orderBy` the order finds ' + + 'no column, so the list is read in an arbitrary order and its row cap keeps an arbitrary slice.', + 'Only a name that resolved BECAUSE it is injected is judged: an author-declared column of the same ' + + 'name is one the author vouches for. A name the object does not define at all is ' + + '`ai-context-field-unknown`. A warning, because the rule cannot see the remote table, only that the ' + + 'platform provisions no storage.', + UNPROVISIONED_ANCHOR_REMEDY, AI_CONTEXT_PACK_SILENCE, ], }; @@ -7095,6 +7126,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION.rule]: PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION, [AI_CONTEXT_OBJECT_UNKNOWN_EXPLANATION.rule]: AI_CONTEXT_OBJECT_UNKNOWN_EXPLANATION, [AI_CONTEXT_FIELD_UNKNOWN_EXPLANATION.rule]: AI_CONTEXT_FIELD_UNKNOWN_EXPLANATION, + [AI_CONTEXT_FIELD_UNPROVISIONED_EXPLANATION.rule]: AI_CONTEXT_FIELD_UNPROVISIONED_EXPLANATION, [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, diff --git a/packages/lint/src/validate-ai-context.test.ts b/packages/lint/src/validate-ai-context.test.ts index 951d5c0c4aa..fee08a789c1 100644 --- a/packages/lint/src/validate-ai-context.test.ts +++ b/packages/lint/src/validate-ai-context.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest'; import { AI_CONTEXT_BODY_NOT_LONG_TEXT, AI_CONTEXT_FIELD_UNKNOWN, + AI_CONTEXT_FIELD_UNPROVISIONED, AI_CONTEXT_OBJECT_UNKNOWN, AI_CONTEXT_RELATED_LINK_UNKNOWN, AI_CONTEXT_SORT_FIELD_UNSORTABLE, @@ -166,7 +167,7 @@ describe('validateAiContext — ADR-0160 D1 author defects', () => { // and `get_record_context` answers both in the root's `fields`, a related // list's `fields`, its `where` and its `orderBy`. On an `ownership: 'org'` // object the platform injects no `owner_id` and the tool leaves it out. - // `service-record-context`'s injected-system-columns test pins the + // `service-record-context`'s shared harness (`record-context-tools.test.ts`) pins the // executor's half over a door serving the same registry-injected shape. it('an injected system column the object does not declare is no unknown field (owner_id, created_at)', () => { const stack = { @@ -230,10 +231,107 @@ describe('validateAiContext — ADR-0160 D1 author defects', () => { it('every verdict is a warning, and every rule it emits has an `os explain` entry', () => { const findings = validateAiContext({ objects, aiContexts: [pack({ fields: ['nope'], body: { field: 'title' } })] }); expect(findings.every((f) => f.severity === 'warning')).toBe(true); - for (const id of [AI_CONTEXT_OBJECT_UNKNOWN, AI_CONTEXT_FIELD_UNKNOWN, AI_CONTEXT_RELATED_LINK_UNKNOWN, AI_CONTEXT_BODY_NOT_LONG_TEXT, AI_CONTEXT_SORT_FIELD_UNSORTABLE]) { + for (const id of [AI_CONTEXT_OBJECT_UNKNOWN, AI_CONTEXT_FIELD_UNKNOWN, AI_CONTEXT_FIELD_UNPROVISIONED, AI_CONTEXT_RELATED_LINK_UNKNOWN, AI_CONTEXT_BODY_NOT_LONG_TEXT, AI_CONTEXT_SORT_FIELD_UNSORTABLE]) { expect(explainRule(id), id).toBeTruthy(); } }); + + it('the `ai-context-field-unknown` explanation counts injected columns as defined, and names the external case', () => { + const text = explainRule(AI_CONTEXT_FIELD_UNKNOWN)?.paragraphs.join(' ') ?? ''; + expect(text).toContain('injected'); + expect(text).toContain('owner_id'); + expect(text).toContain(AI_CONTEXT_FIELD_UNPROVISIONED); + }); +}); + +/** + * [ADR-0015] An `external` object's injected columns resolve — the published + * definition carries them, so `ai-context-field-unknown` stays silent — but + * the platform provisions no column behind them. The provenance answer is the + * spec's (`unprovisionedInjectedColumnsFor`), the one every unprovisioned-anchor + * rule here reads; an author-declared column of the same name is the author's. + */ +describe('validateAiContext — an injected column with no storage on an external object (ADR-0015)', () => { + const external = (names: string[]) => + objects.map((o) => (names.includes(o.name) ? { ...o, external: { remoteName: `${o.name}s` } } : o)); + const injectedPack = pack({ + fields: ['title', 'owner_id', 'created_at'], + related: [{ + object: 'policy_revision', + field: 'policy', + fields: ['version', 'created_by'], + where: { owner_id: 'usr_1' }, + orderBy: [{ field: 'created_at', order: 'desc' }], + }], + }); + + it('warns at every name the pack reads off an injected column, on the root and a related list', () => { + const findings = validateAiContext({ objects: external(['policy', 'policy_revision']), aiContexts: [injectedPack] }); + expect(findings.map((f) => [f.rule, f.path])).toEqual([ + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].fields[1]'], + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].fields[2]'], + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].related[0].fields[1]'], + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].related[0].where'], + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].related[0].orderBy[0].field'], + ]); + expect(findings.every((f) => f.severity === 'warning')).toBe(true); + // Each finding names its object and column, the shared anchor fix beside it. + const [rootOwner, , childCreator] = findings; + expect(rootOwner?.message).toContain("'owner_id'"); + expect(rootOwner?.message).toContain("external object 'policy'"); + expect(childCreator?.message).toContain("external object 'policy_revision'"); + expect(rootOwner?.hint).toContain('columnMap'); + }); + + it('the same pack on objects that are not external is clean', () => { + expect(validateAiContext({ objects, aiContexts: [injectedPack] })).toEqual([]); + }); + + it('judges each object by its own provenance: an external child under a local root', () => { + expect(rulesOf({ objects: external(['policy_revision']), aiContexts: [injectedPack] })).toEqual([ + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].related[0].fields[1]'], + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].related[0].where'], + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].related[0].orderBy[0].field'], + ]); + }); + + it('a column the author declares on the external object is theirs, and never judged', () => { + const declared = external(['policy']).map((o) => + o.name === 'policy' ? { ...o, fields: { ...o.fields, owner_id: { type: 'text', label: 'Remote owner' } } } : o); + expect(rulesOf({ objects: declared, aiContexts: [pack({ fields: ['title', 'owner_id'] })] })).toEqual([]); + }); + + it('a body on an injected column carries no body twice over: not long text, and no storage', () => { + expect(rulesOf({ objects: external(['policy']), aiContexts: [pack({ body: { field: 'created_at' } })] })).toEqual([ + [AI_CONTEXT_BODY_NOT_LONG_TEXT, 'aiContexts[0].body.field'], + [AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].body.field'], + ]); + }); + + it('a related list linked through an injected reference of an external child reads no rows', () => { + const withUser = [ + ...objects, + { name: 'sys_user', fields: { name: { type: 'text' } } }, + { name: 'task', fields: { subject: { type: 'text' } } }, + ]; + const userPack = { name: 'user_brief', object: 'sys_user', fields: ['name'], related: [{ object: 'task', field: 'owner_id' }] }; + const local = validateAiContext({ objects: withUser, aiContexts: [userPack] }); + expect(local).toEqual([]); + const externalTask = withUser.map((o) => (o.name === 'task' ? { ...o, external: { remoteName: 'tasks' } } : o)); + const [finding, ...rest] = validateAiContext({ objects: externalTask, aiContexts: [userPack] }); + expect(rest).toEqual([]); + expect([finding?.rule, finding?.path]).toEqual([AI_CONTEXT_FIELD_UNPROVISIONED, 'aiContexts[0].related[0].field']); + expect(finding?.message).toContain("external object 'task'"); + }); + + it('has an `os explain` entry that states the cause, the cost per position and the remedy', () => { + const entry = explainRule(AI_CONTEXT_FIELD_UNPROVISIONED); + expect(entry?.rule).toBe(AI_CONTEXT_FIELD_UNPROVISIONED); + const text = entry?.paragraphs.join(' ') ?? ''; + for (const fact of ['ADR-0015', 'external', '`fields`', '`body.field`', '`where`', '`orderBy`', 'columnMap', AI_CONTEXT_FIELD_UNKNOWN]) { + expect(text, fact).toContain(fact); + } + }); }); /** diff --git a/packages/lint/src/validate-ai-context.ts b/packages/lint/src/validate-ai-context.ts index c2119a56ce9..67957ee3b5f 100644 --- a/packages/lint/src/validate-ai-context.ts +++ b/packages/lint/src/validate-ai-context.ts @@ -11,7 +11,7 @@ * wrong — and is exactly why the author has to hear it here instead: a typo in * a pack ships as a pack that quietly reads less than it says. * - * Five verdicts, each a `warning` (the pack loads and reads what resolves): + * Six verdicts, each a `warning` (the pack loads and reads what resolves): * * - `ai-context-field-unknown`: a name in `fields`, a `related` entry's * `fields`, `where` or `orderBy`, or `body.field` that the object does not @@ -20,6 +20,13 @@ * any field (a `where` or `orderBy` field the child lacks leaves the whole list * out of every answer, ADR-0160 D1/D3 second amendment — the tool never * runs a filter with one of its conditions removed); + * - `ai-context-field-unprovisioned`: a name in any of those positions, or a + * related list's link field, that resolves only BECAUSE it is an injected + * system column, on an ADR-0015 `external` object: the platform registers + * the anchor without provisioning a column (`unprovisionedInjectedColumnsFor`, + * the spec's provenance derivation every unprovisioned-anchor rule here + * reads), so the name resolves and the read finds no value behind it. An + * author-declared column of the same name is the author's and never judged; * - `ai-context-sort-field-unsortable`: a `related` entry's `orderBy` field * the child does not offer as a sort — the sortability projection's * `sortable: false` (`resolveObjectSortability`): a formula, or a field @@ -54,7 +61,12 @@ import { AI_CONTEXT_BODY_FIELD_TYPES, aiContextWhereFields } from '@objectstack/ import { resolveObjectSortability } from '@objectstack/spec/api'; import { REFERENCE_VALUE_TYPES, referenceTargetOf } from '@objectstack/spec/data'; import { closureDependencyRemedy, recordsOf } from './object-graph.js'; -import { injectedColumnDefsFor } from './system-fields.js'; +import { + injectedColumnDefsFor, + unprovisionedAnchorFix, + unprovisionedAnchorVerdict, + unprovisionedInjectedColumnsFor, +} from './system-fields.js'; export type AiContextSeverity = 'warning'; @@ -71,6 +83,7 @@ export interface AiContextFinding { export const AI_CONTEXT_OBJECT_UNKNOWN = 'ai-context-object-unknown'; export const AI_CONTEXT_FIELD_UNKNOWN = 'ai-context-field-unknown'; +export const AI_CONTEXT_FIELD_UNPROVISIONED = 'ai-context-field-unprovisioned'; export const AI_CONTEXT_RELATED_LINK_UNKNOWN = 'ai-context-related-link-unknown'; export const AI_CONTEXT_BODY_NOT_LONG_TEXT = 'ai-context-body-not-long-text'; export const AI_CONTEXT_SORT_FIELD_UNSORTABLE = 'ai-context-sort-field-unsortable'; @@ -121,6 +134,28 @@ export function validateAiContext( const out: AiContextFinding[] = []; const objects = new Map(); for (const o of recordsOf(stack.objects)) if (str(o.name)) objects.set(str(o.name), o); + // [ADR-0015] Each object's injected columns with no storage behind them — + // empty on every object whose storage the platform provisions. Existence + // (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>(); + const unprovisionedOf = (object: string): ReadonlySet => { + let anchors = anchorsOf.get(object); + if (!anchors) anchorsOf.set(object, (anchors = unprovisionedInjectedColumnsFor(objects.get(object)))); + return anchors; + }; + /** The finding for a name that resolves on an unprovisioned anchor of `object`. */ + const unprovisioned = (object: string, name: string, where: string, path: string, subject: string, consequence: string) => + out.push({ + severity: 'warning', + rule: AI_CONTEXT_FIELD_UNPROVISIONED, + where, + path, + // One verdict sentence, the shared short anchor clause; why the anchor + // has no storage and how to vouch for it is `os explain ai-context-field-unprovisioned`. + message: `${subject}: ${unprovisionedAnchorVerdict(object, name)}, so ${consequence}`, + hint: unprovisionedAnchorFix(object, name), + }); const packs = Array.isArray(stack.aiContexts) ? (stack.aiContexts as unknown[]) : []; packs.forEach((raw, i) => { @@ -161,7 +196,12 @@ export function validateAiContext( }; const unknownFields = (names: string[], fields: Map, object: string, where: string, path: string) => { names.forEach((name, k) => { - if (fields.has(name)) return; + if (fields.has(name)) { + if (unprovisionedOf(object).has(name)) { + unprovisioned(object, name, where, `${path}[${k}]`, `names field '${name}'`, 'the pack reads it empty on every record'); + } + return; + } out.push({ severity: 'warning', rule: AI_CONTEXT_FIELD_UNKNOWN, @@ -201,6 +241,11 @@ export function validateAiContext( hint: `Name a long-text field of '${root}' as the body, or list '${bodyField}' in \`fields\` instead`, }); } + // Type and storage are separate questions: no injected column is long + // text, so this finding rides beside the one above, naming the cause. + if (def && unprovisionedOf(root).has(bodyField)) { + unprovisioned(root, bodyField, `${at} · body`, `aiContexts[${i}].body.field`, `\`body.field\` names '${bodyField}'`, 'the pack carries no body'); + } } } @@ -228,8 +273,10 @@ export function validateAiContext( hint: `Name a field of '${child}' (check the spelling), or remove it from \`${key}\``, }); }; + 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`); + 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[]) : []; // Judged by the projection the doors refuse by, never by a second reading of `type` or `sortable`. @@ -241,6 +288,10 @@ export function validateAiContext( listLeftOut(name, 'orderBy', `${path}.orderBy[${k}].field`); return; } + if (unprovisionedOf(child).has(name)) { + unprovisioned(child, name, where, `${path}.orderBy[${k}].field`, `\`orderBy\` sorts by field '${name}'`, + 'the order finds no column and the list is read in an arbitrary order'); + } const verdict = sortability[name]; if (verdict?.sortable !== false) return; const why = verdict.reason === 'virtual-type' ? 'is a formula, computed on read' : 'declares `sortable: false`'; @@ -258,7 +309,15 @@ export function validateAiContext( if (!root || !objects.has(root)) return; const named = str(entry.field); const links = [...childFields.keys()].filter((name) => referenceOf(childFields.get(name)) === root); - if (named ? referenceOf(childFields.get(named)) === root : links.length === 1) return; + const link = named ? (referenceOf(childFields.get(named)) === root ? named : undefined) : links.length === 1 ? links[0] : undefined; + if (link !== undefined) { + // The link is a name the rule reads too: an injected reference to the + // root (`owner_id` → `sys_user`) on an external child matches no row. + if (unprovisionedOf(child).has(link)) { + unprovisioned(child, link, where, named ? `${path}.field` : path, `the list links to '${root}' through '${link}'`, noRows); + } + return; + } out.push({ severity: 'warning', rule: AI_CONTEXT_RELATED_LINK_UNKNOWN, diff --git a/packages/services/service-record-context/src/__tests__/injected-system-columns.test.ts b/packages/services/service-record-context/src/__tests__/injected-system-columns.test.ts deleted file mode 100644 index b1405218b2b..00000000000 --- a/packages/services/service-record-context/src/__tests__/injected-system-columns.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [ADR-0160 D1/D3] A context pack that names a system column the platform - * injects (`owner_id`, `created_at`) on an object that does not declare it. - * - * The executor judges every name against the definitions its door hands it. - * The real doors hand the registry's definition, which carries the injected - * columns: measured over one real kernel (the `/mcp` door, the real protocol, - * `SqlDriver`, `sys_user` registered), the served listing of an object that - * declares neither column carries both, and `get_record_context` answers - * `owner_id` and `created_at` in the root's `fields` and a related list's - * `fields`, filters the list by a `where` on `owner_id` and orders it by - * `created_at`. The door below serves that shape (the spec's - * `injectedSystemColumnDefs`, the tables the registry's `applySystemFields` - * spreads, a declared field winning), and the executor reads every injected - * name as a field. `@objectstack/lint`'s `ai-context-field-unknown` judges - * the same names against the same injected map, so it does not warn on them. - */ - -import { describe, expect, it } from 'vitest'; -import { injectedSystemColumnDefs } from '@objectstack/spec/data'; -import { executeGetRecordContext } from '../index.js'; -import { fakeDoor, policyApp, type FakeApp } from './fake-door.js'; - -type Def = Record; - -/** The definition as the registry serves it: the injected columns it carries, a declared field winning. */ -const registered = (def: Def): Def => ({ - ...def, - fields: { ...injectedSystemColumnDefs(def), ...(def.fields as Def) }, -}); - -const PACK = { - name: 'policy_brief', - label: 'Policy brief', - object: 'policy', - fields: ['title', 'owner_id', 'created_at'], - related: [{ - object: 'policy_revision', - field: 'policy', - fields: ['version', 'owner_id', 'created_at'], - where: { owner_id: 'u1' }, - orderBy: [{ field: 'created_at', order: 'desc' as const }], - }], -}; - -/** The fixture app with the system columns on its rows, `sys_user` beside it, and {@link PACK}. */ -function app(injected: boolean): FakeApp { - const base = policyApp(); - const objects: FakeApp['objects'] = { - ...base.objects, - sys_user: { name: 'sys_user', label: 'User', nameField: 'name', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }, - }; - if (injected) for (const name of ['policy', 'policy_revision']) objects[name] = registered(objects[name]); - return { - ...base, - objects, - records: { - ...base.records, - sys_user: [{ id: 'u1', name: 'Ann' }, { id: 'u2', name: 'Bo' }], - policy: base.records.policy.map((r) => ({ ...r, owner_id: 'u1', created_at: '2026-01-01T00:00:00Z' })), - policy_revision: [ - { id: 'r1', version: 'v1', policy: 'p1', owner_id: 'u1', created_at: '2026-01-02T00:00:00Z' }, - { id: 'r2', version: 'v2', policy: 'p1', owner_id: 'u1', created_at: '2026-01-03T00:00:00Z' }, - { id: 'r3', version: 'v3', policy: 'p1', owner_id: 'u2', created_at: '2026-01-04T00:00:00Z' }, - ], - }, - packs: [PACK], - }; -} - -const CALL = { objectName: 'policy', recordId: 'p1', context: 'policy_brief' }; - -describe('get_record_context — an injected system column the object does not declare (ADR-0160 D1/D3)', () => { - it('the fixture declares neither column; the registered definition carries both', () => { - const declared = policyApp().objects; - for (const name of ['policy', 'policy_revision']) { - expect(Object.keys(declared[name].fields as Def)).not.toContain('owner_id'); - expect(Object.keys(declared[name].fields as Def)).not.toContain('created_at'); - expect(Object.keys(registered(declared[name]).fields as Def)).toEqual(expect.arrayContaining(['owner_id', 'created_at'])); - } - }); - - it('is read as a field: in the root\'s fields, a related list\'s fields, its where and its orderBy', async () => { - const out = await executeGetRecordContext(CALL, fakeDoor(app(true))); - expect(out.data.fields).toEqual([ - { name: 'title', label: 'Title', value: 'Fire cover' }, - { name: 'owner_id', label: 'Owner', value: 'u1', display: 'Ann' }, - { name: 'created_at', label: 'Created At', value: '2026-01-01T00:00:00Z' }, - ]); - expect(out.data.related?.[0]?.rows.map((r) => [r.id, r.fields.map((f) => [f.name, f.value])])).toEqual([ - ['r2', [['version', 'v2'], ['owner_id', 'u1'], ['created_at', '2026-01-03T00:00:00Z']]], - ['r1', [['version', 'v1'], ['owner_id', 'u1'], ['created_at', '2026-01-02T00:00:00Z']]], - ]); - expect(out.notes).toEqual([]); - }); - - it('a door serving the declared fields alone leaves every such name out, silently: the executor reads what the door serves', async () => { - const out = await executeGetRecordContext(CALL, fakeDoor(app(false))); - expect(out.data.fields.map((f) => f.name)).toEqual(['title']); - expect(out.data.related ?? []).toEqual([]); - expect(out.notes).toEqual([]); - }); -}); diff --git a/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts b/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts index 3bc1997b8a4..f09869dbd9e 100644 --- a/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts +++ b/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { mapDataError } from '@objectstack/types'; +import { injectedSystemColumnDefs } from '@objectstack/spec/data'; import { AI_CONTEXT_MAX_FIELDS, AI_CONTEXT_MAX_RELATED, @@ -1283,3 +1284,151 @@ describe('get_record_context — pack selection by (package, name) (ADR-0150 add expect(await recordContextReadSet({ objectName: 'policy', context: 'brief' }, door)).toEqual({ objects: ['policy'] }); }); }); + +/** + * [ADR-0160 D1/D3] A context pack that names a system column the platform + * injects (`owner_id`, `created_at`) on an object that does not declare it. + * + * The executor judges every name against the definitions its door hands it. + * The real doors hand the registry's definition, which carries the injected + * columns: measured over one real kernel (the `/mcp` door, the real protocol, + * `SqlDriver`, `sys_user` registered), the served listing of an object that + * declares neither column carries both, and `get_record_context` answers + * `owner_id` and `created_at` in the root's `fields` and a related list's + * `fields`, filters the list by a `where` on `owner_id` and orders it by + * `created_at`. The door below serves that shape (the spec's + * `injectedSystemColumnDefs`, the tables the registry's `applySystemFields` + * spreads, a declared field winning), and the executor reads every injected + * name as a field. `@objectstack/lint`'s `ai-context-field-unknown` judges + * the same names against the same injected map, so it does not warn on them. + */ +describe('get_record_context — an injected system column the object does not declare (ADR-0160 D1/D3)', () => { + type Def = Record; + + /** The definition as the registry serves it: the injected columns it carries, a declared field winning. */ + const registered = (def: Def): Def => ({ + ...def, + fields: { ...injectedSystemColumnDefs(def), ...(def.fields as Def) }, + }); + + const SYS_USER = { name: 'sys_user', label: 'User', nameField: 'name', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }; + + const PACK = { + name: 'policy_brief', + label: 'Policy brief', + object: 'policy', + fields: ['title', 'owner_id', 'created_at'], + related: [{ + object: 'policy_revision', + field: 'policy', + fields: ['version', 'owner_id', 'created_at'], + where: { owner_id: 'u1' }, + orderBy: [{ field: 'created_at', order: 'desc' as const }], + }], + }; + + /** The fixture app with the system columns on its rows, `sys_user` beside it, and {@link PACK}. */ + function app(injected: boolean): FakeApp { + const base = policyApp(); + const objects: FakeApp['objects'] = { ...base.objects, sys_user: SYS_USER }; + if (injected) for (const name of ['policy', 'policy_revision']) objects[name] = registered(objects[name]); + return { + ...base, + objects, + records: { + ...base.records, + sys_user: [{ id: 'u1', name: 'Ann' }, { id: 'u2', name: 'Bo' }], + policy: base.records.policy.map((r) => ({ ...r, owner_id: 'u1', created_at: '2026-01-01T00:00:00Z' })), + policy_revision: [ + { id: 'r1', version: 'v1', policy: 'p1', owner_id: 'u1', created_at: '2026-01-02T00:00:00Z' }, + { id: 'r2', version: 'v2', policy: 'p1', owner_id: 'u1', created_at: '2026-01-03T00:00:00Z' }, + { id: 'r3', version: 'v3', policy: 'p1', owner_id: 'u2', created_at: '2026-01-04T00:00:00Z' }, + ], + }, + packs: [PACK], + }; + } + + const BRIEF_CALL = { objectName: 'policy', recordId: 'p1', context: 'policy_brief' }; + + it('the fixture declares neither column; the registered definition carries both', () => { + const declared = policyApp().objects; + for (const name of ['policy', 'policy_revision']) { + expect(Object.keys(declared[name].fields as Def)).not.toContain('owner_id'); + expect(Object.keys(declared[name].fields as Def)).not.toContain('created_at'); + expect(Object.keys(registered(declared[name]).fields as Def)).toEqual(expect.arrayContaining(['owner_id', 'created_at'])); + } + }); + + it('is read as a field: in the root\'s fields, a related list\'s fields, its where and its orderBy', async () => { + const out = await executeGetRecordContext(BRIEF_CALL, fakeDoor(app(true))); + expect(out.data.fields).toEqual([ + { name: 'title', label: 'Title', value: 'Fire cover' }, + { name: 'owner_id', label: 'Owner', value: 'u1', display: 'Ann' }, + { name: 'created_at', label: 'Created At', value: '2026-01-01T00:00:00Z' }, + ]); + expect(out.data.related?.[0]?.rows.map((r) => [r.id, r.fields.map((f) => [f.name, f.value])])).toEqual([ + ['r2', [['version', 'v2'], ['owner_id', 'u1'], ['created_at', '2026-01-03T00:00:00Z']]], + ['r1', [['version', 'v1'], ['owner_id', 'u1'], ['created_at', '2026-01-02T00:00:00Z']]], + ]); + expect(out.notes).toEqual([]); + }); + + it('a door serving the declared fields alone leaves every such name out, silently: the executor reads what the door serves', async () => { + const out = await executeGetRecordContext(BRIEF_CALL, fakeDoor(app(false))); + expect(out.data.fields.map((f) => f.name)).toEqual(['title']); + expect(out.data.related ?? []).toEqual([]); + expect(out.notes).toEqual([]); + }); + + // The link resolution `@objectstack/lint`'s `ai-context-related-link-unknown` + // mirrors: `resolveRelatedLink` over the child's PUBLISHED definition, where + // the injected `owner_id` / `created_by` / `updated_by` each point at + // `sys_user`. Named, one of them is the link; omitted, the child has several + // and the list is an author defect, left out with nothing stated. + describe('a related list rooted on a sys_* object, linked through the child\'s injected references', () => { + const TASK = { name: 'task', label: 'Task', nameField: 'subject', fields: { subject: { name: 'subject', type: 'text', label: 'Subject' } } }; + const userApp = (injected: boolean, field?: string): FakeApp => ({ + objects: { sys_user: SYS_USER, task: injected ? registered(TASK) : TASK }, + records: { + sys_user: [{ id: 'u1', name: 'Ann' }, { id: 'u2', name: 'Bo' }], + task: [ + { id: 't1', subject: 'Call', owner_id: 'u1', created_by: 'u2', updated_by: 'u2' }, + { id: 't2', subject: 'Mail', owner_id: 'u2', created_by: 'u1', updated_by: 'u2' }, + ], + }, + packs: [{ + name: 'user_brief', + label: 'User brief', + object: 'sys_user', + fields: ['name'], + related: [{ object: 'task', ...(field !== undefined ? { field } : {}), fields: ['subject'] }], + }], + }); + const USER_CALL = { objectName: 'sys_user', recordId: 'u1', context: 'user_brief' }; + const rowsOf = async (a: FakeApp) => { + const out = await executeGetRecordContext(USER_CALL, fakeDoor(a)); + expect(out.notes).toEqual([]); + return (out.data.related ?? []).map((r) => r.rows.map((row) => row.id)); + }; + + it('the registered child carries the three injected references to sys_user; the declared one carries none', () => { + const fields = registered(TASK).fields as Record; + for (const name of ['owner_id', 'created_by', 'updated_by']) expect(fields[name]?.reference, name).toBe('sys_user'); + expect(Object.keys(TASK.fields)).toEqual(['subject']); + }); + + it('a named injected reference is the link: each one reads its own rows', async () => { + expect(await rowsOf(userApp(true, 'owner_id'))).toEqual([['t1']]); + expect(await rowsOf(userApp(true, 'created_by'))).toEqual([['t2']]); + }); + + it('omitted, the child\'s several injected references leave the list out, silently', async () => { + expect(await rowsOf(userApp(true))).toEqual([]); + }); + + it('a door serving the declared fields alone has no link to resolve: the list is left out, silently', async () => { + expect(await rowsOf(userApp(false, 'owner_id'))).toEqual([]); + }); + }); +});