Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/37415-ai-context-injected-columns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/lint': patch
---

fix(lint): a context pack may name a system column the platform injects

Clause-②: no
Metadata-protocol: none

`ai-context-field-unknown` no longer warns on a system column the platform adds to an object without the author declaring it (`owner_id`, `created_at`, `created_by`, `updated_at`, `updated_by`, `organization_id`, …) when a context pack names it in `fields`, in a `related` entry's `fields`, `where` or `orderBy`, or in `body.field`. `get_record_context` reads the object's published definition, which carries those columns, and serves them like any field: the warning was false, and an author who followed it removed a field the assistant reads. A column the platform does not add to that object is still reported: `owner_id` on an object with `ownership: 'org'` or `'none'`, and every system column on an object with `systemFields: false`. A `body.field` naming an injected column is now judged by that column's type (`ai-context-body-not-long-text`), and a `related` entry's `orderBy` on one is judged by its sortability. On a related list whose root is a `sys_*` object, the child's injected references to it (`created_by`, `updated_by` and `owner_id` to `sys_user`) count as links, as they do for `get_record_context`: a child with one declared reference to that root and no `field` is now reported as having several.
67 changes: 67 additions & 0 deletions packages/lint/src/validate-ai-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,73 @@ describe('validateAiContext — ADR-0160 D1 author defects', () => {
]);
});

// The runtime answer this verdict matches, measured over one real kernel (the
// `/mcp` door, the real protocol, `SqlDriver`): on an object that declares
// neither `owner_id` nor `created_at`, the served definition carries both,
// 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
// 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 = {
objects,
aiContexts: [pack({
fields: ['title', 'owner_id', 'created_at'],
related: [{
object: 'policy_revision',
fields: ['version', 'owner_id', 'created_by'],
where: { owner_id: 'usr_1' },
orderBy: [{ field: 'created_at', order: 'desc' }],
}],
})],
};
expect(objects.flatMap((o) => Object.keys(o.fields))).not.toContain('owner_id');
expect(validateAiContext(stack)).toEqual([]);
});

it('a column the platform does not inject on the object is still unknown: owner_id under ownership org', () => {
const orgOwned = objects.map((o) => (o.name === 'policy' || o.name === 'policy_revision' ? { ...o, ownership: 'org' } : o));
const stack = {
objects: orgOwned,
aiContexts: [pack({
fields: ['title', 'owner_id', 'created_at'],
related: [{ object: 'policy_revision', fields: ['owner_id'], where: { owner_id: 'usr_1' }, orderBy: [{ field: 'owner_id' }] }],
})],
};
expect(rulesOf(stack)).toEqual([
[AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].fields[1]'],
[AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].related[0].fields[0]'],
[AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].related[0].where'],
[AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].related[0].orderBy[0].field'],
]);
// And `systemFields: false` withholds every injected column, `created_at` included.
const optedOut = objects.map((o) => (o.name === 'policy' ? { ...o, systemFields: false } : o));
expect(rulesOf({ objects: optedOut, aiContexts: [pack({ fields: ['created_at'], related: undefined })] })).toEqual([
[AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].fields[0]'],
]);
});

it('a body naming an injected column is judged by the injected definition, not reported unknown', () => {
expect(rulesOf({ objects, aiContexts: [pack({ body: { field: 'created_at' } })] })).toEqual([
[AI_CONTEXT_BODY_NOT_LONG_TEXT, 'aiContexts[0].body.field'],
]);
});

it('on a sys_ root, the child\'s injected references to it are links, as get_record_context resolves them', () => {
const withUser = [
...objects,
{ name: 'sys_user', fields: { name: { type: 'text' } } },
{ name: 'task', fields: { subject: { type: 'text' }, assignee: { type: 'lookup', reference: 'sys_user' } } },
];
const userPack = { name: 'user_brief', object: 'sys_user', fields: ['name'] };
const [finding] = validateAiContext({ objects: withUser, aiContexts: [{ ...userPack, related: [{ object: 'task' }] }] });
expect([finding?.rule, finding?.path]).toEqual([AI_CONTEXT_RELATED_LINK_UNKNOWN, 'aiContexts[0].related[0]']);
expect(finding?.message).toContain('assignee');
expect(finding?.message).toContain('owner_id');
expect(validateAiContext({ objects: withUser, aiContexts: [{ ...userPack, related: [{ object: 'task', field: 'assignee' }] }] })).toEqual([]);
});

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);
Expand Down
23 changes: 19 additions & 4 deletions packages/lint/src/validate-ai-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
*
* - `ai-context-field-unknown`: a name in `fields`, a `related` entry's
* `fields`, `where` or `orderBy`, or `body.field` that the object does not
* define (a `where` or `orderBy` field the child lacks leaves the whole list
* define — neither declares nor carries as an injected system column, which
* the published definition the tool reads carries and the tool serves like
* 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-sort-field-unsortable`: a `related` entry's `orderBy` field
Expand Down Expand Up @@ -52,6 +54,7 @@ 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';

export type AiContextSeverity = 'warning';

Expand All @@ -77,11 +80,23 @@ type AnyRec = Record<string, unknown>;
const str = (v: unknown): string => (typeof v === 'string' ? v : '');
const strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []);

/** An object's fields as a name → definition map, or `undefined` when it declares no readable map. */
/**
* An object's fields as a name → definition map, or `undefined` when it declares no readable map.
*
* The EFFECTIVE map: the declared fields plus the system columns the registry
* injects without the author declaring them (`owner_id`, `created_at`, …;
* {@link injectedColumnDefsFor}, the tables `applySystemFields` and the served
* read's `applyInjectedSystemColumns` spread), a declared field winning over
* the injected one of its name. `get_record_context` judges a pack against
* the published definition, which carries those columns, and reads them: a
* verdict over the declared fields alone warns on a name the tool serves.
*/
function fieldMapOf(object: AnyRec): Map<string, AnyRec> | 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 !== ''));
const fields = new Map(recordsOf(raw).map((f) => [str(f.name), f] as const).filter(([name]) => name !== ''));
for (const [name, def] of injectedColumnDefsFor(object)) if (!fields.has(name)) fields.set(name, { ...def });
return fields;
}

/** The object a reference field points at, or `undefined` for any other field. */
Expand Down Expand Up @@ -218,7 +233,7 @@ export function validateAiContext(
}
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`.
const sortability = orderBy.length > 0 ? resolveObjectSortability({ fields: objects.get(child)?.fields }).fields : {};
const sortability = orderBy.length > 0 ? resolveObjectSortability({ fields: Object.fromEntries(childFields) }).fields : {};
orderBy.forEach((node, k) => {
const name = node && typeof node === 'object' ? str((node as AnyRec).field) : '';
if (!name) return;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// 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<string, unknown>;

/** 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([]);
});
});
Loading