diff --git a/.changeset/37203-ai-context-related-where-orderby-limit.md b/.changeset/37203-ai-context-related-where-orderby-limit.md new file mode 100644 index 00000000000..d06663133a1 --- /dev/null +++ b/.changeset/37203-ai-context-related-where-orderby-limit.md @@ -0,0 +1,29 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-record-context': minor +'@objectstack/lint': minor +--- + +feat(ai): a context pack's related list takes `where`, `orderBy` and `limit` (ADR-0160 second amendment) + +Clause-②: yes +Metadata-protocol: added + +A `related` entry of an `ai_context` pack may now choose, order and cut the child rows it carries: + +```yaml +related: + - object: policy_revision + field: policy + fields: [version, published_at] + where: { is_current: { $eq: true } } + orderBy: [{ field: sort_no, order: asc }] + limit: 5 +``` + +- **`where`** is the object filter form on the child's own fields: `$eq`, `$ne`, `$in`, `$nin`, `$gt`, `$gte`, `$lt`, `$lte`, `$null` and `$exists` (`AI_CONTEXT_WHERE_OPERATORS`), joined by `$and` / `$or` nested at most `AI_CONTEXT_WHERE_MAX_DEPTH` (32) deep. A bare value reads as `$eq`. Refused at parse: any other operator (`$not`, `$between`, `$contains`, …), a dotted path or a condition on a lookup's target, a field-to-field comparand (`{ $field }`), a `$now` anchor, a formula, and a comparand that is one whole `{…}` placeholder (`{today}`, `{current_user_id}`, `${record_id}`, or an unknown one), and `$and` / `$or` nested deeper than the bound. +- **`orderBy`** is `{ field, order }[]` (the sort node; `direction` is refused by name) on the child's own fields. +- **`limit`** is a positive integer, at most `AI_CONTEXT_MAX_RELATED_ROWS` (20). Over it the pack is refused at parse, never lowered at call time. `RECORD_CONTEXT_RELATED_MAX_ROWS` in `@objectstack/service-record-context` is now this one number. + +`get_record_context` reads such a list in the one capped child query, as the caller: the link filter and `where` joined with `$and`, ordered by `orderBy`, cut at `limit` (else the row cap), and a cut is stated in the notes. The filter grants nothing: a row the caller's row rules hide stays absent. A `where` or `orderBy` field the caller cannot query on (outside the security service's `getQueryableFields`; without that answer, any field that declares a `maskingRule`, or that the caller's schema hides or field-level security withholds) drops the whole section with the one "some material is not visible" statement, and the field is never named. A field the child does not define leaves the section out and states nothing; `os validate` and the save-time check report it as `ai-context-field-unknown`. So does an `orderBy` field the child does not offer as a sort (a formula, or a field that declares `sortable: false`, which the record doors refuse with `INVALID_SORT`): the section is left out and nothing is stated, and `os validate` and the save-time check report it as the new warning `ai-context-sort-field-unsortable`. The call's read set does not change. A door may hand the executor the caller's queryable fields through the new optional `RecordContextDoor.queryableFieldsOf`. + diff --git a/content/docs/references/ai/ai-context.mdx b/content/docs/references/ai/ai-context.mdx index 9da0f13aa8f..bc8159d77a3 100644 --- a/content/docs/references/ai/ai-context.mdx +++ b/content/docs/references/ai/ai-context.mdx @@ -1,7 +1,7 @@ --- title: Ai Context schema — AI Protocol reference navTitle: Ai Context -description: "Ai Context schemas of the ObjectStack AI Protocol: AiContext, AiContextBody, AiContextRelated — each property with its type, default and a TypeScript example." +description: "Ai Context schemas of the ObjectStack AI Protocol: AiContext, AiContextBody and 2 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Ai Context schemas of the ObjectStack AI Protocol: AiContext, AiCo ## TypeScript Usage ```typescript -import { AiContextSchema, AiContextBodySchema, AiContextRelatedSchema } from '@objectstack/spec/ai'; -import type { AiContext, AiContextBody, AiContextRelated } from '@objectstack/spec/ai'; +import { AiContextSchema, AiContextBodySchema, AiContextRelatedSchema, AiContextRelatedWhereSchema } from '@objectstack/spec/ai'; +import type { AiContext, AiContextBody, AiContextRelated, AiContextRelatedWhere } from '@objectstack/spec/ai'; // Validate data const result = AiContextSchema.parse(data); @@ -32,7 +32,7 @@ const result = AiContextSchema.parse(data); | **label** | `string` | ✅ | Pack display name — the header of the tool answer | | **object** | `string` | ✅ | The root object: a pack reads one record of it | | **fields** | `string[]` | optional | The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at | -| **related** | `{ object: string; field?: string; fields?: string[] }[]` | optional | Child lists that point at the record (at most 3), one level deep | +| **related** | `{ object: string; field?: string; fields?: string[]; where?: any; … }[]` | optional | Child lists that point at the record (at most 3), one level deep | | **body** | `{ field: string }` | optional | The one long-text field read as the record's body | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -49,6 +49,9 @@ const result = AiContextSchema.parse(data); | **object** | `string` | ✅ | A child object with a reference field (lookup, master-detail, user or tree) that points at the pack's root object | | **field** | `string` | optional | The child's reference field that points at the root. Required when the child has several such fields; with one, it may be omitted. Resolved once, on the published definition | | **fields** | `string[]` | optional | The columns read for each row, in order (at most 10). A lookup among them is answered with the name of the record it points at. Omit to read the row's name only | +| **where** | `any` | optional | Which child rows the list carries: a filter on the child's own fields, in the object filter form. A bare value is `$eq`; the operators are $eq, $ne, $in, $nin, $gt, $gte, $lt, $lte, $null, $exists, joined by $and / $or nested at most 32 deep. Comparands are literal values: no dotted path, no field-to-field comparand, no $now anchor and no `{…}` placeholder. Joined to the link with $and and read as the caller, so it grants nothing | +| **orderBy** | `{ field: string; order?: Enum<'asc' \| 'desc'> }[]` | optional | The order of the rows: `{ field, order }[]` on the child's own fields, `order` `asc` (the default) or `desc`. Without it the rows come in the data engine's order. A field the child does not offer as a sort (it declares `sortable: false`, or is a formula) leaves the list out of every answer | +| **limit** | `integer` | optional | The most rows the list carries (at most 20, the default). A list cut at it says so in the answer | ### Nested Shape: `AiContext.body` @@ -79,6 +82,16 @@ const result = AiContextSchema.parse(data); | **object** | `string` | ✅ | A child object with a reference field (lookup, master-detail, user or tree) that points at the pack's root object | | **field** | `string` | optional | The child's reference field that points at the root. Required when the child has several such fields; with one, it may be omitted. Resolved once, on the published definition | | **fields** | `string[]` | optional | The columns read for each row, in order (at most 10). A lookup among them is answered with the name of the record it points at. Omit to read the row's name only | +| **where** | `any` | optional | Which child rows the list carries: a filter on the child's own fields, in the object filter form. A bare value is `$eq`; the operators are $eq, $ne, $in, $nin, $gt, $gte, $lt, $lte, $null, $exists, joined by $and / $or nested at most 32 deep. Comparands are literal values: no dotted path, no field-to-field comparand, no $now anchor and no `{…}` placeholder. Joined to the link with $and and read as the caller, so it grants nothing | +| **orderBy** | `{ field: string; order?: Enum<'asc' \| 'desc'> }[]` | optional | The order of the rows: `{ field, order }[]` on the child's own fields, `order` `asc` (the default) or `desc`. Without it the rows come in the data engine's order. A field the child does not offer as a sort (it declares `sortable: false`, or is a formula) leaves the list out of every answer | +| **limit** | `integer` | optional | The most rows the list carries (at most 20, the default). A list cut at it says so in the answer | + + +--- + +## AiContextRelatedWhere + +**Type:** `Record & { $and?: any[]; $or?: any[]; $not?: any }` --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 4b17f8699a1..2264223dc58 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1732 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1733 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -20,7 +20,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 16 | 99 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 16 | 100 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -34,20 +34,20 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 184 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **221** | **1732** | 14 protocol modules | +| **Total** | **221** | **1733** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **16 pages, 99 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **16 pages, 100 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | File | Schemas | | :--- | :--- | | [`agent.zod.ts`](/docs/references/ai/agent) | `AIModelConfig`, `Agent`, `StructuredOutputConfig`, `StructuredOutputFormat`, `TransformPipelineStep` | -| [`ai-context.zod.ts`](/docs/references/ai/ai-context) | `AiContext`, `AiContextBody`, `AiContextRelated` | +| [`ai-context.zod.ts`](/docs/references/ai/ai-context) | `AiContext`, `AiContextBody`, `AiContextRelated`, `AiContextRelatedWhere` | | [`build-progress.zod.ts`](/docs/references/ai/build-progress) | `BuildProgressFrame`, `BuildProgressPhase` | | [`conversation.zod.ts`](/docs/references/ai/conversation) | `CodeContent`, `ConversationAnalytics`, `ConversationContext`, `ConversationMessage`, `ConversationSession`, `ConversationSummary`, `FileContent`, `FunctionCall`, `ImageContent`, `MessageContent`, `MessageContentType`, `MessagePruningEvent`, `MessageRole`, `TextContent`, `TokenBudgetConfig`, `TokenBudgetStrategy`, `TokenUsageStats`, `ToolCall` | | [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | diff --git a/examples/app-showcase/src/ai/record-context.ai-context.ts b/examples/app-showcase/src/ai/record-context.ai-context.ts index 82c5ba27d67..36550831942 100644 --- a/examples/app-showcase/src/ai/record-context.ai-context.ts +++ b/examples/app-showcase/src/ai/record-context.ai-context.ts @@ -8,13 +8,16 @@ import type { AiContext } from '@objectstack/spec/ai'; * * `showcase_project_brief` is the full shape: the project's own fields (one * of them a lookup, so the account's display name is read through it), and - * its tasks as a related list capped by the service. `showcase_task_notes` + * its open tasks as a related list: filtered (`where`, on the task's own + * fields), ordered by due date and cut at ten (`limit`), all inside the one + * child query read as the caller. `showcase_task_notes` * adds a body: a long `notes` text comes back whole, or as an outline whose * sections are read one at a time by anchor. * * A pack never widens a read: a field the caller may not read is left out - * and the answer says so, and a related object the caller may not read - * refuses the whole call. + * and the answer says so, a related object the caller may not read + * refuses the whole call, and a `where` grants nothing — the caller's row + * rules still decide which rows arrive. */ export const ShowcaseProjectBriefContext: AiContext = { name: 'showcase_project_brief', @@ -22,7 +25,14 @@ export const ShowcaseProjectBriefContext: AiContext = { object: 'showcase_project', fields: ['name', 'account', 'status', 'health', 'budget', 'spent', 'end_date', 'owner'], related: [ - { object: 'showcase_task', field: 'project', fields: ['title', 'status', 'priority', 'due_date', 'assignee'] }, + { + object: 'showcase_task', + field: 'project', + fields: ['title', 'status', 'priority', 'due_date', 'assignee'], + where: { status: { $ne: 'done' } }, + orderBy: [{ field: 'due_date', order: 'asc' }], + limit: 10, + }, ], }; diff --git a/examples/app-showcase/src/coverage.ts b/examples/app-showcase/src/coverage.ts index 6d471433705..b983ccc0c06 100644 --- a/examples/app-showcase/src/coverage.ts +++ b/examples/app-showcase/src/coverage.ts @@ -217,7 +217,7 @@ export const KIND_COVERAGE: Record = { status: 'demonstrated', files: ['src/ai/record-context.ai-context.ts'], notes: - 'Two context packs (ADR-0160): a project brief (own fields, a lookup read through to the account, tasks as a related list) and a task with its notes as a body (whole, or an outline read by anchor). Read by `get_record_context` over MCP; the service is wired in objectstack.config.ts plugins.', + 'Two context packs (ADR-0160): a project brief (own fields, a lookup read through to the account, its open tasks as a related list, filtered, ordered by due date and cut by `where` / `orderBy` / `limit`) and a task with its notes as a body (whole, or an outline read by anchor). Read by `get_record_context` over MCP; the service is wired in objectstack.config.ts plugins.', }, skill: { status: 'waived', diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 8880a48921c..5497d2f3854 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -384,6 +384,7 @@ export { AI_CONTEXT_FIELD_UNKNOWN, AI_CONTEXT_RELATED_LINK_UNKNOWN, AI_CONTEXT_BODY_NOT_LONG_TEXT, + AI_CONTEXT_SORT_FIELD_UNSORTABLE, } from './validate-ai-context.js'; export type { AiContextFinding, AiContextSeverity } from './validate-ai-context.js'; diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 34b8b040634..cb9e9433373 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -6060,6 +6060,19 @@ const AI_CONTEXT_BODY_NOT_LONG_TEXT_EXPLANATION: RuleExplanation = { ], }; +const AI_CONTEXT_SORT_FIELD_UNSORTABLE_EXPLANATION: RuleExplanation = { + rule: 'ai-context-sort-field-unsortable', + covers: 'which fields may order a related list of a context pack', + paragraphs: [ + 'A related list\'s `orderBy` runs in the one query that reads the list. A field the object does not offer as ' + + 'a sort, a formula (computed on read, no column to order by) or a field whose author declared ' + + '`sortable: false`, is refused by the record doors (`INVALID_SORT`), so `get_record_context` leaves the whole ' + + 'list out of every answer rather than read it in another order.', + 'Order the list by a field that is offered as a sort, or remove the field from `orderBy`.', + AI_CONTEXT_PACK_SILENCE, + ], +}; + // ── Assignment rules (`validate-assignment-rules.ts`) ── const ASSIGNMENT_RULE_USER_TARGET_EXPLANATION: RuleExplanation = { @@ -7049,6 +7062,7 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [AI_CONTEXT_FIELD_UNKNOWN_EXPLANATION.rule]: AI_CONTEXT_FIELD_UNKNOWN_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, [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/validate-ai-context.test.ts b/packages/lint/src/validate-ai-context.test.ts index a452d4f67d8..0528192de0d 100644 --- a/packages/lint/src/validate-ai-context.test.ts +++ b/packages/lint/src/validate-ai-context.test.ts @@ -6,6 +6,7 @@ import { AI_CONTEXT_FIELD_UNKNOWN, AI_CONTEXT_OBJECT_UNKNOWN, AI_CONTEXT_RELATED_LINK_UNKNOWN, + AI_CONTEXT_SORT_FIELD_UNSORTABLE, validateAiContext, } from './validate-ai-context.js'; import { explainRule } from './rule-explanations.js'; @@ -24,7 +25,7 @@ const objects = [ }, { name: 'policy_revision', - fields: { version: { type: 'text' }, policy: { type: 'lookup', reference: 'policy' } }, + fields: { version: { type: 'text' }, policy: { type: 'lookup', reference: 'policy' }, rank: { type: 'number', sortable: false } }, }, { name: 'policy_link', @@ -69,6 +70,67 @@ describe('validateAiContext — ADR-0160 D1 author defects', () => { ]); }); + it('reports a where or orderBy field the child does not define (ADR-0160 second amendment): the list is left out', () => { + const stack = { + objects, + aiContexts: [pack({ + related: [{ + object: 'policy_revision', + fields: ['version'], + where: { $or: [{ version: 'v1' }, { is_curent: true }] }, + orderBy: [{ field: 'version', order: 'asc' }, { field: 'sortno', order: 'desc' }], + limit: 5, + }], + })], + }; + expect(rulesOf(stack)).toEqual([ + [AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].related[0].where'], + [AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].related[0].orderBy[1].field'], + ]); + const [whereFinding] = validateAiContext(stack); + expect(whereFinding.message).toContain("'is_curent'"); + expect(whereFinding.message).toContain('left out'); + // Control: the same keys on fields the child defines are clean. + expect(rulesOf({ + objects, + aiContexts: [pack({ related: [{ object: 'policy_revision', where: { version: { $ne: 'v0' } }, orderBy: [{ field: 'version' }] }] })], + })).toEqual([]); + }); + + it('reports an orderBy field the child does not offer as a sort (sortable: false, a formula): the list is left out', () => { + const ranked = objects.map((o) => o.name !== 'policy_revision' ? o : { + ...o, + fields: { + ...o.fields, + score: { type: 'formula', expression: 'rank * 2' }, + seq: { type: 'number' }, + }, + }); + const stack = { + objects: ranked, + aiContexts: [pack({ + related: [{ + object: 'policy_revision', + where: { rank: { $gt: 0 } }, + orderBy: [{ field: 'seq' }, { field: 'rank', order: 'desc' }, { field: 'score' }], + }], + })], + }; + expect(rulesOf(stack)).toEqual([ + [AI_CONTEXT_SORT_FIELD_UNSORTABLE, 'aiContexts[0].related[0].orderBy[1].field'], + [AI_CONTEXT_SORT_FIELD_UNSORTABLE, 'aiContexts[0].related[0].orderBy[2].field'], + ]); + const [declared, formula] = validateAiContext(stack); + expect(declared.severity).toBe('warning'); + expect(declared.message).toContain("'rank'"); + expect(declared.message).toContain('`sortable: false`'); + expect(declared.message).toContain('left out'); + expect(formula.message).toContain('formula'); + // Control: the same fields in `where` and a sortable order are clean. + expect(rulesOf({ objects: ranked, aiContexts: [pack({ related: [{ object: 'policy_revision', where: { rank: 1, score: 2 }, orderBy: [{ field: 'seq' }] }] })] })) + .toEqual([]); + }); + it('reports an object the stack does not define once, without judging its fields; a sys_ object is not judged', () => { expect(rulesOf({ objects, aiContexts: [pack({ object: 'polcy', related: undefined, body: undefined })] })).toEqual([ [AI_CONTEXT_OBJECT_UNKNOWN, 'aiContexts[0].object'], @@ -101,7 +163,7 @@ 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]) { + 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]) { expect(explainRule(id), id).toBeTruthy(); } }); @@ -132,6 +194,8 @@ describe('validateAiContext on the runtime publish door (ADR-0160 D1)', () => { const FAMILIES: ReadonlyArray<[string, Record, string, string]> = [ ['a misspelled field', pack({ fields: ['title', 'titel'] }), AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].fields[1]'], + ['a misspelled where field', pack({ related: [{ object: 'policy_revision', where: { verison: 'v1' } }] }), AI_CONTEXT_FIELD_UNKNOWN, 'aiContexts[0].related[0].where'], + ['an order on a field not offered as a sort', pack({ related: [{ object: 'policy_revision', orderBy: [{ field: 'rank' }] }] }), AI_CONTEXT_SORT_FIELD_UNSORTABLE, 'aiContexts[0].related[0].orderBy[0].field'], ['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'], diff --git a/packages/lint/src/validate-ai-context.ts b/packages/lint/src/validate-ai-context.ts index 689cc794b80..93ef6a59145 100644 --- a/packages/lint/src/validate-ai-context.ts +++ b/packages/lint/src/validate-ai-context.ts @@ -11,10 +11,19 @@ * 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. * - * Four verdicts, each a `warning` (the pack loads and reads what resolves): + * Five verdicts, each a `warning` (the pack loads and reads what resolves): * * - `ai-context-field-unknown`: a name in `fields`, a `related` entry's - * `fields`, or `body.field` that the object does not define; + * `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 + * 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 + * the child does not offer as a sort — the sortability projection's + * `sortable: false` (`resolveObjectSortability`): a formula, or a field + * whose author declared `sortable: false`. Both MCP doors refuse such an + * order with `INVALID_SORT`, so `get_record_context` leaves the list out of + * every answer instead and states nothing (ADR-0160 D1: an author defect); * - `ai-context-related-link-unknown`: a `related` entry with no reference * field to the root — `field` names none that points at it, or, omitted, the * child has none or several (then `field` must say which); @@ -39,7 +48,8 @@ * unchanged. */ -import { AI_CONTEXT_BODY_FIELD_TYPES } from '@objectstack/spec/ai'; +import { AI_CONTEXT_BODY_FIELD_TYPES, aiContextWhereFields } from '@objectstack/spec/ai'; +import { resolveObjectSortability } from '@objectstack/spec/api'; import { REFERENCE_VALUE_TYPES, referenceTargetOf } from '@objectstack/spec/data'; import { closureDependencyRemedy, recordsOf } from './object-graph.js'; @@ -60,6 +70,7 @@ export const AI_CONTEXT_OBJECT_UNKNOWN = 'ai-context-object-unknown'; export const AI_CONTEXT_FIELD_UNKNOWN = 'ai-context-field-unknown'; 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'; type AnyRec = Record; @@ -188,6 +199,47 @@ export function validateAiContext( const childFields = judged(child, where, `${path}.object`); if (!childFields) return; unknownFields(strings(entry.fields), childFields, child, where, `${path}.fields`); + // [ADR-0160 D1, second amendment] The fields `where` and `orderBy` name. + // One the child lacks is no condition dropped: the list is left out. + const listLeftOut = (name: string, key: 'where' | 'orderBy', at: string) => { + out.push({ + severity: 'warning', + rule: AI_CONTEXT_FIELD_UNKNOWN, + where, + path: at, + message: + `\`${key}\` names field '${name}', which object '${child}' does not define, so the list is left out of ` + + 'every answer (a filter or an order is never read with one of its fields removed)', + hint: `Name a field of '${child}' (check the spelling), or remove it from \`${key}\``, + }); + }; + for (const name of aiContextWhereFields(entry.where)) { + if (!childFields.has(name)) listLeftOut(name, 'where', `${path}.where`); + } + 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 : {}; + orderBy.forEach((node, k) => { + const name = node && typeof node === 'object' ? str((node as AnyRec).field) : ''; + if (!name) return; + if (!childFields.has(name)) { + listLeftOut(name, 'orderBy', `${path}.orderBy[${k}].field`); + return; + } + const verdict = sortability[name]; + if (verdict?.sortable !== false) return; + const why = verdict.reason === 'virtual-type' ? 'is a formula, computed on read' : 'declares `sortable: false`'; + out.push({ + severity: 'warning', + rule: AI_CONTEXT_SORT_FIELD_UNSORTABLE, + where, + path: `${path}.orderBy[${k}].field`, + message: + `\`orderBy\` sorts by field '${name}' of object '${child}', which ${why}, so it is not offered as a sort ` + + 'and the list is left out of every answer (an order is never read with one of its fields removed)', + hint: `Order the list by a field of '${child}' that is offered as a sort, or remove '${name}' from \`orderBy\``, + }); + }); if (!root || !objects.has(root)) return; const named = str(entry.field); const links = [...childFields.keys()].filter((name) => referenceOf(childFields.get(name)) === root); diff --git a/packages/services/service-record-context/src/__tests__/fake-door.ts b/packages/services/service-record-context/src/__tests__/fake-door.ts index 856a8ac5605..cda24b09a9d 100644 --- a/packages/services/service-record-context/src/__tests__/fake-door.ts +++ b/packages/services/service-record-context/src/__tests__/fake-door.ts @@ -1,5 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { resolveObjectSortability } from '@objectstack/spec/api'; import type { RecordContextDoor } from '../door.js'; /** @@ -15,8 +16,19 @@ import type { RecordContextDoor } from '../door.js'; * - `unreadableRows` are filtered out by row-level security; * - `unpublishedObjects` make the published-definition read THROW a coded * error naming the object, as a door's package gate renders it; - * - a `where` is equality, or `{ $contains: id }` on an array value; any - * other operator or combinator is refused, never read as a field; + * - a `where` is read as the engine reads it: a bare value is equality, + * `$and` / `$or` combine, and the operators are a related list's ten plus + * `$contains` on an array value; any other operator or combinator is + * refused, never read as a field; `orderBy` sorts the rows; + * - `unqueryableFields` are served and readable but not queryable (served + * masked, say): `queryableFieldsOf` leaves them out, and a `where` or + * `orderBy` naming one — or any field the caller cannot query on — is + * refused by the read, as the security plugin's engine guard refuses it; + * `noQueryableAnswer` makes the door carry no `queryableFieldsOf`; + * - an `orderBy` on a field the object's sortability projection calls + * unsortable (a formula, or `sortable: false`) refuses the read with + * `INVALID_SORT`, as the Data API ingress (`assertSortFieldsExist`, the + * HTTP MCP door) and the stdio door (`unofferedSortRefusal`) refuse it; * - a lookup is expanded to `{ id, name }` when its target is readable and the * target row is readable, else left as the bare id. */ @@ -31,6 +43,8 @@ export interface FakeApp { unexposedObjects?: string[]; unreadableRows?: string[]; unpublishedObjects?: string[]; + unqueryableFields?: Record; + noQueryableAnswer?: boolean; narrowed?: Record; locales?: string[]; /** @@ -50,6 +64,44 @@ export interface FakeDoor extends RecordContextDoor { const coded = (code: string, status: number, message: string) => Object.assign(new Error(message), { code, status }); +/** One operator applied to a stored value, as the engine applies it. */ +function applies(value: unknown, op: string, comparand: unknown): boolean { + switch (op) { + case '$eq': return value === comparand; + case '$ne': return value !== comparand; + case '$in': return (comparand as unknown[]).includes(value); + case '$nin': return !(comparand as unknown[]).includes(value); + case '$gt': return (value as number) > (comparand as number); + case '$gte': return (value as number) >= (comparand as number); + case '$lt': return (value as number) < (comparand as number); + case '$lte': return (value as number) <= (comparand as number); + case '$null': return (value == null) === comparand; + case '$exists': return (value !== undefined) === comparand; + case '$contains': return Array.isArray(value) && value.includes(comparand); + default: throw new Error(`fake door: unsupported where operator '${op}'`); + } +} + +/** Whether `row` matches `where`. */ +function matches(row: Record, where: Record): boolean { + return Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as Array>).every((m) => matches(row, m)); + if (k === '$or') return (v as Array>).some((m) => matches(row, m)); + if (k.startsWith('$')) throw new Error(`fake door: unsupported where combinator '${k}'`); + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { + return Object.entries(v as Record).every(([op, c]) => applies(row[k], op, c)); + } + return row[k] === v; + }); +} + +/** The field keys a `where` names, through `$and` / `$or`. */ +function whereKeys(where: Record): string[] { + return Object.entries(where).flatMap(([k, v]) => + k === '$and' || k === '$or' ? (v as Array>).flatMap(whereKeys) : [k], + ); +} + export function fakeDoor(app: FakeApp): FakeDoor { const hidden = (o: string) => new Set(app.hiddenFields?.[o] ?? []); const withheld = (o: string) => new Set(app.withheldFields?.[o] ?? []); @@ -69,6 +121,12 @@ export function fakeDoor(app: FakeApp): FakeDoor { const readableRow = (object: string, row: Record) => Object.fromEntries(Object.entries(row).filter(([k]) => !hidden(object).has(k) && !withheld(object).has(k))); const canRead = (object: string) => !guarded.has(object) && served(object) !== null; + const queryable = (object: string): string[] => { + const def = served(object); + if (!def) return []; + const out = new Set(app.unqueryableFields?.[object] ?? []); + return Object.keys(def.fields as Record).filter((n) => !withheld(object).has(n) && !out.has(n)); + }; const door: FakeDoor = { asked: [], @@ -112,18 +170,28 @@ export function fakeDoor(app: FakeApp): FakeDoor { door.reads.push({ member: 'query', object, opts }); const def = served(object); if (!def) throw coded('OBJECT_NOT_FOUND', 404, `Object '${object}' not found`); + const sortability = resolveObjectSortability(app.objects[object]).fields; + for (const { field } of opts.orderBy ?? []) { + if (sortability[field]?.sortable === false) { + throw coded('INVALID_SORT', 400, `Query parameter 'orderBy' sorts by '${field}', a field on '${object}' that is not offered as a sort`); + } + } + // The security plugin's engine guard: a filter or sort on a field the + // caller cannot query on is refused, naming it. + const allowed = new Set(['id', ...queryable(object)]); + for (const f of [...whereKeys(opts.where), ...(opts.orderBy ?? []).map((n) => n.field)]) { + if (!allowed.has(f)) throw coded('PERMISSION_DENIED', 403, `Field '${f}' cannot be filtered or sorted on`); + } let rows = (app.records[object] ?? []).filter((r) => !unreadable.has(String(r.id))); - rows = rows.filter((r) => - Object.entries(opts.where).every(([k, v]) => { - if (k.startsWith('$')) throw new Error(`fake door: unsupported where combinator '${k}'`); - if (v !== null && typeof v === 'object') { - const ops = Object.keys(v); - if (ops.length !== 1 || ops[0] !== '$contains') throw new Error(`fake door: unsupported where operator on '${k}'`); - return Array.isArray(r[k]) && (r[k] as unknown[]).includes((v as { $contains: unknown }).$contains); - } - return r[k] === v; - }), - ); + rows = rows.filter((r) => matches(r, opts.where)); + for (const { field, order } of [...(opts.orderBy ?? [])].reverse()) { + const sign = order === 'desc' ? -1 : 1; + rows = [...rows].sort((a, b) => { + const x = a[field] as number | string; + const y = b[field] as number | string; + return x === y ? 0 : x < y ? -sign : sign; + }); + } const out = rows.slice(0, opts.limit ?? rows.length).map((r) => { const row = readableRow(object, r); for (const f of opts.expand ?? []) { @@ -146,6 +214,13 @@ export function fakeDoor(app: FakeApp): FakeDoor { const names = Object.keys(def.fields as Record); return { served: names, readable: names.filter((n) => !withheld(object).has(n)) }; }, + ...(app.noQueryableAnswer + ? {} + : { + async queryableFieldsOf(object: string) { + return served(object) ? queryable(object) : undefined; + }, + }), async diagnoseDelegation(object) { const statement = app.narrowed?.[object]; return statement ? { narrowed: true, statement } : { narrowed: false }; 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 6f2997bf0a4..4c1303a05fc 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 @@ -424,6 +424,181 @@ describe('get_record_context — row level (ADR-0160 D3)', () => { }); }); +/** + * [ADR-0160 D1/D3/D4, second amendment] A related list's `where`, `orderBy` + * and `limit`: run inside the one capped child query, as the caller; a field + * they name that the caller cannot query on drops the section, stated and + * never named; one the definition lacks leaves it out silently; the read set + * does not move. + */ +describe('get_record_context — a related list\'s where, orderBy and limit (ADR-0160 second amendment)', () => { + /** policy_revision with `is_current`, `sort_no` and a masked `reviewer_email`; three rows on p1, one on p2. */ + function filteredApp(entry: Record, overrides: Partial = {}): FakeApp { + const app = policyApp(overrides); + const revision = app.objects.policy_revision as { fields: Record> }; + revision.fields.is_current = { name: 'is_current', type: 'boolean', label: 'Current' }; + revision.fields.sort_no = { name: 'sort_no', type: 'number', label: 'Sort number' }; + revision.fields.reviewer_email = { + name: 'reviewer_email', type: 'email', label: 'Reviewer email', maskingRule: { strategy: 'partial' }, + }; + app.records.policy_revision = [ + { id: 'r1', version: 'v1', policy: 'p1', is_current: true, sort_no: 2, reviewer_email: 'a@x.io' }, + { id: 'r2', version: 'v2', policy: 'p1', is_current: true, sort_no: 1, reviewer_email: 'b@x.io' }, + { id: 'r3', version: 'v3', policy: 'p1', is_current: false, sort_no: 3, reviewer_email: 'c@x.io' }, + { id: 'r9', version: 'v9', policy: 'p2', is_current: true, sort_no: 0, reviewer_email: 'd@x.io' }, + ]; + app.packs = [{ + name: 'policy_document', + label: 'Policy document', + object: 'policy', + fields: ['title'], + related: [{ object: 'policy_revision', field: 'policy', fields: ['version'], ...entry }], + }]; + return app; + } + const listReads = (door: ReturnType) => + door.reads.filter((r) => r.member === 'query' && r.object === 'policy_revision'); + + it('filter and order applied in ONE capped query, cut at the limit, and the cut is stated', async () => { + const where = { is_current: { $eq: true } }; + const door = fakeDoor(filteredApp({ where, orderBy: [{ field: 'sort_no', order: 'asc' }], limit: 1 })); + const out = await executeGetRecordContext(CALL, door); + const list = out.data.related![0]; + expect(list.rows.map((r) => r.id)).toEqual(['r2']); + expect(list.truncated).toBe(true); + expect(out.notes).toEqual([ + { kind: 'related_truncated', object: 'policy_revision', text: sentencesFor([]).relatedTruncated('policy_revision', 1) }, + ]); + const reads = listReads(door); + expect(reads).toHaveLength(1); + expect(reads[0].opts).toMatchObject({ + where: { $and: [{ policy: 'p1' }, where] }, + orderBy: [{ field: 'sort_no', order: 'asc' }], + limit: 2, + }); + }); + + it('a bare value reads as $eq; a list within its limit is not cut; descending order is kept', async () => { + const out = await run(filteredApp({ where: { is_current: true }, orderBy: [{ field: 'sort_no', order: 'desc' }], limit: 5 })); + expect(out.data.related![0].rows.map((r) => r.id)).toEqual(['r1', 'r2']); + expect(out.data.related![0].truncated).toBeUndefined(); + expect(out.notes).toEqual([]); + }); + + it('the filter grants nothing: a row the caller\'s row rules hide stays absent though it matches', async () => { + const out = await run(filteredApp({ where: { is_current: true } }, { unreadableRows: ['r2'] })); + expect(out.data.related![0].rows.map((r) => r.id)).toEqual(['r1']); + expect(JSON.stringify(out)).not.toContain('r2'); + }); + + it('no where reaches another root\'s rows: it is joined to the link with $and', async () => { + const out = await run(filteredApp({ where: { $or: [{ is_current: true }, { version: 'v9' }] } })); + expect(out.data.related![0].rows.map((r) => r.id)).toEqual(['r1', 'r2']); + }); + + it.each<[string, Record, Partial]>([ + ['a where field outside the caller\'s queryable fields', { where: { sort_no: { $gt: 0 } } }, { unqueryableFields: { policy_revision: ['sort_no'] } }], + ['an orderBy field outside the caller\'s queryable fields', { orderBy: [{ field: 'sort_no', order: 'asc' }] }, { unqueryableFields: { policy_revision: ['sort_no'] } }], + ['a where field the caller\'s schema hides', { where: { $and: [{ is_current: true }, { sort_no: 1 }] } }, { hiddenFields: { policy_revision: ['sort_no'] } }], + ['an orderBy field field-level security withholds', { orderBy: [{ field: 'sort_no', order: 'desc' }] }, { withheldFields: { policy_revision: ['sort_no'] } }], + ])('%s drops the whole section with the one not-visible statement, never naming it and never refusing', async (_label, entry, overrides) => { + const door = fakeDoor(filteredApp(entry, overrides)); + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related).toBeUndefined(); + expect(out.notes).toEqual([{ kind: 'not_visible', text: sentencesFor([]).notVisible }]); + const text = JSON.stringify(out); + expect(text).not.toContain('sort_no'); + expect(text).not.toContain('Sort number'); + expect(listReads(door)).toEqual([]); + }); + + it('control: the same where and orderBy on fields the caller can query on read the list', async () => { + const out = await run(filteredApp({ where: { sort_no: { $gt: 0 } }, orderBy: [{ field: 'sort_no', order: 'asc' }] })); + expect(out.data.related![0].rows.map((r) => r.id)).toEqual(['r2', 'r1', 'r3']); + expect(out.notes).toEqual([]); + }); + + it('with no queryable answer, a field that declares a masking rule is never filtered or sorted on (the contract\'s fallback)', async () => { + const door = fakeDoor(filteredApp({ orderBy: [{ field: 'reviewer_email', order: 'asc' }] }, { noQueryableAnswer: true })); + expect(door.queryableFieldsOf).toBeUndefined(); + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related).toBeUndefined(); + expect(out.notes.map((n) => n.kind)).toEqual(['not_visible']); + expect(JSON.stringify(out)).not.toContain('reviewer_email'); + expect(listReads(door)).toEqual([]); + // Control: an unmasked field under the same fallback reads. + const control = await run(filteredApp({ orderBy: [{ field: 'sort_no', order: 'asc' }] }, { noQueryableAnswer: true })); + expect(control.data.related![0].rows.map((r) => r.id)).toEqual(['r2', 'r1', 'r3']); + }); + + it('a queryable-fields probe that throws judges nothing: the section is dropped and stated, never read on a guess', async () => { + const door = fakeDoor(filteredApp({ where: { is_current: true } })); + door.queryableFieldsOf = async () => { throw new Error('security service down'); }; + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related).toBeUndefined(); + expect(out.notes.map((n) => n.kind)).toEqual(['not_visible']); + expect(listReads(door)).toEqual([]); + }); + + it.each<[string, Record]>([ + ['a where field', { where: { is_curent: true } }], + ['an orderBy field', { orderBy: [{ field: 'sortno', order: 'asc' }] }], + ])('%s the definition lacks is an author defect: the section is left out, nothing stated, never read without it', async (_label, entry) => { + const door = fakeDoor(filteredApp(entry)); + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related).toBeUndefined(); + expect(out.notes).toEqual([]); + expect(listReads(door)).toEqual([]); + }); + + it.each<[string, Record]>([ + ['declares `sortable: false`', { name: 'notes_rank', type: 'number', label: 'Notes rank', sortable: false }], + ['is a formula', { name: 'notes_rank', type: 'formula', label: 'Notes rank', expression: 'sort_no * 2' }], + ])('an orderBy field that %s is not offered as a sort: an author defect, the section left out, nothing stated, the door never asked', async (_label, def) => { + const app = filteredApp({ orderBy: [{ field: 'notes_rank', order: 'asc' }] }); + (app.objects.policy_revision as { fields: Record }).fields.notes_rank = def; + const door = fakeDoor(app); + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related).toBeUndefined(); + expect(out.notes).toEqual([]); + expect(JSON.stringify(out)).not.toContain('notes_rank'); + expect(listReads(door)).toEqual([]); + // The door this judgement keeps the call from: the same order handed to it is refused whole. + await expect(door.query('policy_revision', { where: { policy: 'p1' }, orderBy: [{ field: 'notes_rank', order: 'asc' }] })) + .rejects.toMatchObject({ code: 'INVALID_SORT', status: 400 }); + // The root's own answer is untouched. + expect(out.data.fields.map((f) => f.name)).toEqual(['title']); + }); + + it('control: a where on a field that is not offered as a sort still reads; only an order on it is judged', async () => { + const app = filteredApp({ where: { notes_rank: { $gt: 0 } }, orderBy: [{ field: 'sort_no', order: 'asc' }] }); + (app.objects.policy_revision as { fields: Record }).fields.notes_rank = { + name: 'notes_rank', type: 'number', label: 'Notes rank', sortable: false, + }; + app.records.policy_revision = app.records.policy_revision.map((r) => ({ ...r, notes_rank: r.sort_no })); + const out = await run(app); + expect(out.data.related![0].rows.map((r) => r.id)).toEqual(['r2', 'r1', 'r3']); + expect(out.notes).toEqual([]); + }); + + it('the read set is the same with and without the three keys', async () => { + const metadataOf = (app: FakeApp) => ({ + listContextPacks: async () => app.packs, + publishedObjectDefinitionOf: async (name: string) => app.objects[name] ?? null, + }); + const plain = filteredApp({ fields: ['version', 'reviewer'] }); + const keyed = filteredApp({ + fields: ['version', 'reviewer'], + where: { $or: [{ is_current: true }, { sort_no: { $in: [1, 2] } }] }, + orderBy: [{ field: 'sort_no', order: 'desc' }], + limit: 3, + }); + const without = await recordContextReadSet({ objectName: 'policy' }, metadataOf(plain)); + expect(without).toEqual({ pack: 'policy_document', objects: ['policy', 'policy_revision', 'account'] }); + expect(await recordContextReadSet({ objectName: 'policy' }, metadataOf(keyed))).toEqual(without); + }); +}); + describe('get_record_context — the body (ADR-0160 D3)', () => { const withBody = (content: string) => { const app = policyApp(); diff --git a/packages/services/service-record-context/src/door.ts b/packages/services/service-record-context/src/door.ts index 039bd10f575..c100e57e269 100644 --- a/packages/services/service-record-context/src/door.ts +++ b/packages/services/service-record-context/src/door.ts @@ -47,16 +47,36 @@ export interface RecordContextDoor { listContextPacks(): Promise; /** The record, read as the caller; `null` (or a throw) when the caller cannot read it. */ get(objectName: string, id: string): Promise; - /** A list read as the caller, `query_records`' read (with its one-level `expand`). */ + /** + * A list read as the caller, `query_records`' read (with its one-level + * `expand`). A related list with a `where` is read with the link filter and + * that `where` joined under `$and`, and with its `orderBy` (ADR-0160 D3, + * second amendment): still one query. + */ query( objectName: string, - opts: { where: Record; fields?: string[]; limit?: number; expand?: string[] }, + opts: { + where: Record; + fields?: string[]; + limit?: number; + expand?: string[]; + orderBy?: Array<{ field: string; order: 'asc' | 'desc' }>; + }, ): Promise; /** * [#35137] The served-schema field names and the readable ones, both asked * as the caller. OPTIONAL: absent, or `undefined`, names no withheld field. */ fieldVisibilityOf?(objectName: string): Promise<{ served: readonly string[]; readable: readonly string[] } | undefined>; + /** + * [ADR-0160 D3, second amendment] The fields the caller may QUERY ON in + * `objectName` — filter or sort by — the security service's + * `getQueryableFields` for the caller. OPTIONAL: absent, or `undefined`, + * the executor takes that contract's fallback (a field that declares a + * `maskingRule` is never queryable, and neither is one the caller's served + * schema hides or field-level security withholds). + */ + queryableFieldsOf?(objectName: string): Promise; /** * [ADR-0090 D10] Whether a read on `objectName` is narrowed by the agent * ceiling, with the security service's sentence. OPTIONAL: a door with no diff --git a/packages/services/service-record-context/src/record-context-tools.ts b/packages/services/service-record-context/src/record-context-tools.ts index e71b4e2cb9e..9925919192d 100644 --- a/packages/services/service-record-context/src/record-context-tools.ts +++ b/packages/services/service-record-context/src/record-context-tools.ts @@ -3,6 +3,8 @@ import { recordNotFoundError, wrapRecordMaterial } from '@objectstack/core'; import { AI_CONTEXT_BODY_FIELD_TYPES, + AI_CONTEXT_MAX_RELATED_ROWS, + aiContextWhereFields, GET_RECORD_CONTEXT_TOOL_NAME, GetRecordContextInputSchema, getRecordContextToolJsonSchemas, @@ -16,6 +18,7 @@ import { type RecordContextRelatedList, type RecordContextRelatedRow, } from '@objectstack/spec/ai'; +import { resolveObjectSortability } from '@objectstack/spec/api'; import type { AIToolDefinition } from '@objectstack/spec/contracts'; import { isMultiValueField, resolveDisplayField, resolveRecordDisplayName } from '@objectstack/spec/data'; import { boundedOutline, boundedText, headingsOf, isHtmlBodyType, sectionOf, RECORD_CONTEXT_BODY_MAX_CHARS } from './body-outline.js'; @@ -66,10 +69,28 @@ import { sentencesFor, type Sentences } from './sentences.js'; * schema shows and field-level security withholds keeps its name and label, * carries no value and is marked `withheld` (#35137). A name the published * definition lacks is an author defect and states nothing. + * + * ## A related list's `where`, `orderBy` and `limit` (D1, D3: second amendment) + * + * They run inside the one capped child query, as the caller: `where` joined + * to the link filter with `$and`, `orderBy` as the order, `limit` (else the + * row cap) as the cut, stated when it cuts. Before that query, each field + * they name is judged: one the child's published definition lacks, or an + * `orderBy` field that definition does not offer as a sort (the sortability + * projection's `sortable: false`: a formula, or `sortable: false` declared by + * its author, which the doors refuse with `INVALID_SORT`), is an author + * defect, and the section is left out with nothing stated (a filter or an + * order is never read with one of its fields removed); one the caller cannot + * query on ({@link queryableAmong}) drops the section with the one + * not-visible statement, and is never named. Neither is ever a refusal. */ -/** The most rows one related list of a pack carries. A list with more is cut and says so. */ -export const RECORD_CONTEXT_RELATED_MAX_ROWS = 20; +/** + * The most rows one related list of a pack carries. A list with more is cut + * and says so. The spec's `AI_CONTEXT_MAX_RELATED_ROWS`, which also bounds a + * `related` entry's `limit` at parse: one number, read by both. + */ +export const RECORD_CONTEXT_RELATED_MAX_ROWS: number = AI_CONTEXT_MAX_RELATED_ROWS; const DESCRIPTION = 'Read one record through its context pack: the fields, related lists and body text the app author chose for ' @@ -212,10 +233,67 @@ function rowsOf(read: unknown): Record[] { return Array.isArray(rows) ? rows.filter((r): r is Record => !!r && typeof r === 'object') : []; } +/** + * [ADR-0160 D3, second amendment] Whether the caller can query on every one + * of `names` — filter or sort by it — on `object`. + * + * The answer is the door's `queryableFieldsOf` (the security service's + * `getQueryableFields` for the caller). Where the door has no such answer — + * the member is absent, or it answers `undefined` — the contract's fallback + * holds (`ISecurityService.getQueryableFields`): a field is queryable only + * when the caller's served schema shows it, field-level security does not + * withhold it (`fieldVisibilityOf`), and it declares no `maskingRule` on + * either definition. A probe that throws judges nothing, so it answers no: + * the section is dropped and stated, never read on a guess. + */ +async function queryableAmong( + door: RecordContextDoor, + object: string, + names: readonly string[], + served: Map>, + published: Map>, +): Promise { + if (names.length === 0) return true; + if (typeof door.queryableFieldsOf === 'function') { + let answer: readonly string[] | undefined; + try { + answer = await door.queryableFieldsOf(object); + } catch { + return false; + } + if (Array.isArray(answer)) { + const queryable = new Set(answer); + return names.every((n) => served.has(n) && queryable.has(n)); + } + } + if (!names.every((n) => served.has(n))) return false; + const declaresMasking = (def: Record | undefined) => def?.maskingRule != null; + if (names.some((n) => declaresMasking(served.get(n)) || declaresMasking(published.get(n)))) return false; + if (typeof door.fieldVisibilityOf === 'function') { + let visibility: { served: readonly string[]; readable: readonly string[] } | undefined; + try { + visibility = await door.fieldVisibilityOf(object); + } catch { + return false; + } + if (visibility) { + const readable = new Set(visibility.readable); + if (!names.every((n) => readable.has(n))) return false; + } + } + return true; +} + /** One `related` entry, planned after projection. */ interface RelatedPlan { object: string; link: string; + /** The entry's `where`, joined to the link filter with `$and` in the one child query. */ + where?: Record; + /** The entry's `orderBy`, the order of the one child query. */ + orderBy?: Array<{ field: string; order: 'asc' | 'desc' }>; + /** The most rows the list carries: the entry's `limit`, else the row cap. */ + cap: number; /** The link holds an array of ids (`multiple: true`): matched with `$contains`, as `get_record` matches it. */ multiValueLink: boolean; columns: string[]; @@ -285,6 +363,10 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex ); }; + // Whether something the pack covers was left out for this caller: the one + // not-visible statement, whatever was removed. + let hidden = false; + // 4a. Each related child at object level, before anything of it is read, // its published definition included: a child the caller is refused is // never asked about by name. @@ -323,7 +405,6 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex const planned = new Set(await planObjectsOf(pack, publishedOf)); // 4b. Field-level projection onto the definitions as the caller is served them. - let hidden = false; const rootServedFields = fieldMapOf(rootServed); const rootPublishedFields = fieldMapOf(await publishedOf(root)); const project = ( @@ -354,7 +435,8 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex for (const entry of pack.related ?? []) { const served = childServed.get(entry.object); if (!served) continue; - const childPublished = fieldMapOf(await publishedOf(entry.object)); + const childPublishedDefinition = await publishedOf(entry.object); + const childPublished = fieldMapOf(childPublishedDefinition); const link = resolveRelatedLink(entry, childPublished, root); if (link === undefined) continue; // author defect, reported on author surfaces const servedFields = fieldMapOf(served); @@ -364,11 +446,31 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex hidden = true; continue; } + // [ADR-0160 D3, second amendment] The fields `where` and `orderBy` name, + // judged before the one query: one the published definition lacks, or an + // `orderBy` field it does not offer as a sort, is an author defect (left + // out, nothing stated, the same for every caller); one this caller cannot + // query on drops the section with the statement, never named, never refused. + const queried = [...new Set([...aiContextWhereFields(entry.where), ...(entry.orderBy ?? []).map((n) => n.field)])]; + if (!queried.every((name) => childPublished.has(name))) continue; + if (entry.orderBy?.length) { + const sortability = resolveObjectSortability(childPublishedDefinition).fields; + if (entry.orderBy.some((n) => sortability[n.field]?.sortable === false)) continue; + } + if (!(await queryableAmong(door, entry.object, queried, servedFields, childPublished))) { + hidden = true; + continue; + } const columns = project(entry.fields ?? [], servedFields, childPublished); const displayField = resolveDisplayField(served as Parameters[0]); relatedPlans.push({ object: entry.object, link, + ...(entry.where !== undefined ? { where: entry.where as Record } : {}), + ...(entry.orderBy !== undefined + ? { orderBy: entry.orderBy.map((n) => ({ field: n.field, order: n.order ?? ('asc' as const) })) } + : {}), + cap: entry.limit ?? RECORD_CONTEXT_RELATED_MAX_ROWS, multiValueLink: isMultiValueField({ type: String(servedFields.get(link)?.type ?? ''), multiple: servedFields.get(link)?.multiple === true }), columns, lookups: columns.filter((c) => lookupTargetOf(servedFields.get(c)) !== undefined), @@ -423,18 +525,23 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex const related: RecordContextRelatedList[] = []; for (const plan of relatedPlans) { - const probe = RECORD_CONTEXT_RELATED_MAX_ROWS + 1; + // The one capped query, as the caller: the link filter joined with the + // entry's `where` (so no `where` reaches another root's rows), its order, + // and one row past the cut to know whether the cut cut anything. + const probe = plan.cap + 1; const projection = [...new Set(['id', ...(plan.displayField ? [plan.displayField] : []), ...plan.columns])]; + const linkWhere = { [plan.link]: plan.multiValueLink ? { $contains: recordId } : recordId }; const rows = rowsOf( await door.query(plan.object, { - where: { [plan.link]: plan.multiValueLink ? { $contains: recordId } : recordId }, + where: plan.where !== undefined ? { $and: [linkWhere, plan.where] } : linkWhere, fields: projection, + ...(plan.orderBy ? { orderBy: plan.orderBy } : {}), ...(plan.lookups.length > 0 ? { expand: plan.lookups } : {}), limit: probe, }), ); - const truncated = rows.length > RECORD_CONTEXT_RELATED_MAX_ROWS; - const kept = truncated ? rows.slice(0, RECORD_CONTEXT_RELATED_MAX_ROWS) : rows; + const truncated = rows.length > plan.cap; + const kept = truncated ? rows.slice(0, plan.cap) : rows; const childWithheld = await withheldAmong(door, plan.object, plan.columns); for (const c of plan.columns) if (childWithheld.has(c)) withheldNames.push(`${plan.object}.${c}`); const outRows: RecordContextRelatedRow[] = []; @@ -458,7 +565,7 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex ...(truncated ? { truncated: true as const } : {}), }); if (truncated) { - notes.push({ kind: 'related_truncated', object: plan.object, text: say.relatedTruncated(plan.object, RECORD_CONTEXT_RELATED_MAX_ROWS) }); + notes.push({ kind: 'related_truncated', object: plan.object, text: say.relatedTruncated(plan.object, plan.cap) }); } // [ADR-0090 D10] A list the agent ceiling narrowed carries the narrowing, // in the security service's own sentence. ⛔ The probe never fails the list. diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 94dcf301b0f..0da0ce0e2f0 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -9,6 +9,10 @@ "AI_CONTEXT_MAX_FIELDS (const)", "AI_CONTEXT_MAX_RELATED (const)", "AI_CONTEXT_MAX_RELATED_FIELDS (const)", + "AI_CONTEXT_MAX_RELATED_ROWS (const)", + "AI_CONTEXT_WHERE_COMBINATORS (const)", + "AI_CONTEXT_WHERE_MAX_DEPTH (const)", + "AI_CONTEXT_WHERE_OPERATORS (const)", "AI_FACE_NAME_CUT_LENGTH (const)", "AI_FACE_NAME_HASH_LENGTH (const)", "AI_FACE_NAME_MAX_LENGTH (const)", @@ -24,6 +28,9 @@ "AiContextRelated (type)", "AiContextRelatedParsed (type)", "AiContextRelatedSchema (const)", + "AiContextRelatedWhere (type)", + "AiContextRelatedWhereParsed (type)", + "AiContextRelatedWhereSchema (const)", "AiContextSchema (const)", "AiFaceAddress (interface)", "BUILD_PROGRESS_FRAME_TYPE (const)", @@ -274,6 +281,7 @@ "VectorStoreSchema (const)", "agentForm (const)", "aiContextForm (const)", + "aiContextWhereFields (function)", "defineAgent (function)", "defineSkill (function)", "defineSolutionBlueprint (function)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 21779ecab9b..33d080f6ceb 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -52,7 +52,10 @@ "ai/AiContextBody:field", "ai/AiContextRelated:field", "ai/AiContextRelated:fields", + "ai/AiContextRelated:limit", "ai/AiContextRelated:object", + "ai/AiContextRelated:orderBy", + "ai/AiContextRelated:where", "ai/BlueprintApp:icon", "ai/BlueprintApp:label", "ai/BlueprintApp:name", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index daf9026fe92..b45a72c56a2 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -12,6 +12,8 @@ "AiContextBodySchema": "ai/AiContextBody", "AiContextRelated": "ai/AiContextRelated", "AiContextRelatedSchema": "ai/AiContextRelated", + "AiContextRelatedWhere": "ai/AiContextRelatedWhere", + "AiContextRelatedWhereSchema": "ai/AiContextRelatedWhere", "AiContextSchema": "ai/AiContext", "BlueprintApp": "ai/BlueprintApp", "BlueprintAppSchema": "ai/BlueprintApp", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 1dbc51d97f3..8f4d14e7eea 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 276, - "droppedRefinementSites": 1188, + "publishedSchemasWithDroppedRefinements": 278, + "droppedRefinementSites": 1210, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -16,7 +16,26 @@ }, "ai/AiContext": { "sites": [ - "related" + "related", + "related.element.orderBy", + "related.element.where.lazy", + "related.element.where.lazy.lazy", + "related.element.where.lazy.lazy.right.$not.lazy" + ] + }, + "ai/AiContextRelated": { + "sites": [ + "orderBy", + "where.lazy", + "where.lazy.lazy", + "where.lazy.lazy.right.$not.lazy" + ] + }, + "ai/AiContextRelatedWhere": { + "sites": [ + "lazy", + "lazy.lazy", + "lazy.lazy.right.$not.lazy" ] }, "ai/BlueprintField": { @@ -122,6 +141,9 @@ "manifest.agents.element.memory", "manifest.agents.element.structuredOutput.schema", "manifest.aiContexts.element.related", + "manifest.aiContexts.element.related.element.orderBy", + "manifest.aiContexts.element.related.element.where.lazy", + "manifest.aiContexts.element.related.element.where.lazy.lazy", "manifest.analyticsCubes.element.measures.valueType", "manifest.apps.element", "manifest.assignmentRules.element", @@ -317,6 +339,9 @@ "data.options[1].manifest.agents.element.memory", "data.options[1].manifest.agents.element.structuredOutput.schema", "data.options[1].manifest.aiContexts.element.related", + "data.options[1].manifest.aiContexts.element.related.element.orderBy", + "data.options[1].manifest.aiContexts.element.related.element.where.lazy", + "data.options[1].manifest.aiContexts.element.related.element.where.lazy.lazy", "data.options[1].manifest.analyticsCubes.element.measures.valueType", "data.options[1].manifest.apps.element", "data.options[1].manifest.assignmentRules.element", @@ -491,6 +516,9 @@ "options[1].manifest.agents.element.memory", "options[1].manifest.agents.element.structuredOutput.schema", "options[1].manifest.aiContexts.element.related", + "options[1].manifest.aiContexts.element.related.element.orderBy", + "options[1].manifest.aiContexts.element.related.element.where.lazy", + "options[1].manifest.aiContexts.element.related.element.where.lazy.lazy", "options[1].manifest.analyticsCubes.element.measures.valueType", "options[1].manifest.apps.element", "options[1].manifest.assignmentRules.element", @@ -593,6 +621,8 @@ "data.packages.element.options[1].manifest.agents.element.memory", "data.packages.element.options[1].manifest.agents.element.structuredOutput.schema", "data.packages.element.options[1].manifest.aiContexts.element.related", + "data.packages.element.options[1].manifest.aiContexts.element.related.element.orderBy", + "data.packages.element.options[1].manifest.aiContexts.element.related.element.where.lazy", "data.packages.element.options[1].manifest.analyticsCubes.element.measures.valueType", "data.packages.element.options[1].manifest.apps.element", "data.packages.element.options[1].manifest.assignmentRules.element", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index b1d78d10a4f..a9376d6b33e 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -9,6 +9,10 @@ "AI_CONTEXT_MAX_FIELDS": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_FIELDS (const)", "AI_CONTEXT_MAX_RELATED": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_RELATED (const)", "AI_CONTEXT_MAX_RELATED_FIELDS": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_RELATED_FIELDS (const)", + "AI_CONTEXT_MAX_RELATED_ROWS": "src/ai/ai-context.zod.ts#AI_CONTEXT_MAX_RELATED_ROWS (const)", + "AI_CONTEXT_WHERE_COMBINATORS": "src/ai/ai-context.zod.ts#AI_CONTEXT_WHERE_COMBINATORS (const)", + "AI_CONTEXT_WHERE_MAX_DEPTH": "src/ai/ai-context.zod.ts#AI_CONTEXT_WHERE_MAX_DEPTH (const)", + "AI_CONTEXT_WHERE_OPERATORS": "src/ai/ai-context.zod.ts#AI_CONTEXT_WHERE_OPERATORS (const)", "AI_FACE_NAME_CUT_LENGTH": "src/ai/face-name.ts#AI_FACE_NAME_CUT_LENGTH (const)", "AI_FACE_NAME_HASH_LENGTH": "src/ai/face-name.ts#AI_FACE_NAME_HASH_LENGTH (const)", "AI_FACE_NAME_MAX_LENGTH": "src/ai/face-name.ts#AI_FACE_NAME_MAX_LENGTH (const)", @@ -24,6 +28,9 @@ "AiContextRelated": "src/ai/ai-context.zod.ts#AiContextRelated (type)", "AiContextRelatedParsed": "src/ai/ai-context.zod.ts#AiContextRelatedParsed (type)", "AiContextRelatedSchema": "src/ai/ai-context.zod.ts#AiContextRelatedSchema (const)", + "AiContextRelatedWhere": "src/ai/ai-context.zod.ts#AiContextRelatedWhere (type)", + "AiContextRelatedWhereParsed": "src/ai/ai-context.zod.ts#AiContextRelatedWhereParsed (type)", + "AiContextRelatedWhereSchema": "src/ai/ai-context.zod.ts#AiContextRelatedWhereSchema (const)", "AiContextSchema": "src/ai/ai-context.zod.ts#AiContextSchema (const)", "AiFaceAddress": "src/ai/face-name.ts#AiFaceAddress (interface)", "BUILD_PROGRESS_FRAME_TYPE": "src/ai/build-progress.zod.ts#BUILD_PROGRESS_FRAME_TYPE (const)", @@ -271,6 +278,7 @@ "VectorStoreSchema": "src/ai/embedding.zod.ts#VectorStoreSchema (const)", "agentForm": "src/ai/agent.form.ts#agentForm (const)", "aiContextForm": "src/ai/ai-context.form.ts#aiContextForm (const)", + "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", "defineAgent": "src/ai/agent.zod.ts#defineAgent (function)", "defineSkill": "src/ai/skill.zod.ts#defineSkill (function)", "defineSolutionBlueprint": "src/ai/solution-blueprint.zod.ts#defineSolutionBlueprint (function)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 3cca2214894..52674e76eb5 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -8,6 +8,7 @@ "ai/AiContext", "ai/AiContextBody", "ai/AiContextRelated", + "ai/AiContextRelatedWhere", "ai/BlueprintApp", "ai/BlueprintCondition", "ai/BlueprintDashboard", diff --git a/packages/spec/liveness/ai_context.json b/packages/spec/liveness/ai_context.json index 01d25e63242..ce6154af03b 100644 --- a/packages/spec/liveness/ai_context.json +++ b/packages/spec/liveness/ai_context.json @@ -54,6 +54,42 @@ "evidenceScope": "in-repo", "evidence": "packages/services/service-record-context/src/record-context-tools.ts#executeGetRecordContext — the list's columns, projected onto the child as the caller is served it; packages/services/service-record-context/src/read-set.ts#planObjectsOf — a lookup among them adds its target to the read set.", "producer": "packages/objectql/src/engine-top-level.ts#METADATA_ARRAY_KEYS — the stack's `aiContexts` reach the registry as `ai_context` items with their package stamped; packages/runtime/src/domains/mcp.ts#recordContextMembers and packages/mcp/src/stdio-data-bridge.ts#createStdioDataBridge read them back (`listContextPacks`) for the executor." + }, + "where": { + "status": "live", + "verifiedAt": "2026-11-25", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-record-context/src/record-context-tools.ts#executeGetRecordContext — joined to the link filter with `$and` in the one capped child query, read as the caller; each field it names (`aiContextWhereFields`) is judged first: one the child lacks leaves the list out, one the caller cannot query on (`queryableAmong`) drops it with the not-visible statement.", + "producer": "packages/objectql/src/engine-top-level.ts#METADATA_ARRAY_KEYS — the stack's `aiContexts` reach the registry as `ai_context` items with their package stamped; packages/runtime/src/domains/mcp.ts#recordContextMembers and packages/mcp/src/stdio-data-bridge.ts#createStdioDataBridge read them back (`listContextPacks`) for the executor.", + "note": "ADR-0160 second amendment (row 11). Parse-time subset of the object filter form: AI_CONTEXT_WHERE_OPERATORS joined by $and / $or, literal comparands only." + }, + "orderBy": { + "children": { + "field": { + "status": "live", + "verifiedAt": "2026-11-25", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-record-context/src/record-context-tools.ts#executeGetRecordContext — the sort key of the one capped child query, read as the caller; judged first, as `where`'s fields are: one the child lacks leaves the list out, one the caller cannot query on (`queryableAmong`) drops it with the not-visible statement.", + "producer": "packages/objectql/src/engine-top-level.ts#METADATA_ARRAY_KEYS — the stack's `aiContexts` reach the registry as `ai_context` items with their package stamped; packages/runtime/src/domains/mcp.ts#recordContextMembers and packages/mcp/src/stdio-data-bridge.ts#createStdioDataBridge read them back (`listContextPacks`) for the executor.", + "note": "ADR-0160 second amendment (row 11). The child's own field only: a dotted path is refused at parse." + }, + "order": { + "status": "live", + "verifiedAt": "2026-11-25", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-record-context/src/record-context-tools.ts#executeGetRecordContext — the direction of that sort key in the one child query (`asc` when omitted).", + "producer": "packages/objectql/src/engine-top-level.ts#METADATA_ARRAY_KEYS — the stack's `aiContexts` reach the registry as `ai_context` items with their package stamped; packages/runtime/src/domains/mcp.ts#recordContextMembers and packages/mcp/src/stdio-data-bridge.ts#createStdioDataBridge read them back (`listContextPacks`) for the executor.", + "note": "SortNodeSchema's `order`; `direction` is refused by name." + } + } + }, + "limit": { + "status": "live", + "verifiedAt": "2026-11-25", + "evidenceScope": "in-repo", + "evidence": "packages/services/service-record-context/src/record-context-tools.ts#executeGetRecordContext — the cut of the one child query (asked for one row past it), marked `truncated` and stated in the notes when it cuts; absent, the row cap RECORD_CONTEXT_RELATED_MAX_ROWS (= AI_CONTEXT_MAX_RELATED_ROWS) applies.", + "producer": "packages/objectql/src/engine-top-level.ts#METADATA_ARRAY_KEYS — the stack's `aiContexts` reach the registry as `ai_context` items with their package stamped; packages/runtime/src/domains/mcp.ts#recordContextMembers and packages/mcp/src/stdio-data-bridge.ts#createStdioDataBridge read them back (`listContextPacks`) for the executor.", + "note": "ADR-0160 second amendment (row 11). Bounded at parse by AI_CONTEXT_MAX_RELATED_ROWS, never lowered at call time." } } }, diff --git a/packages/spec/liveness/state-counts/ai_context.md b/packages/spec/liveness/state-counts/ai_context.md index 894fd0845d9..dc0b412323c 100644 --- a/packages/spec/liveness/state-counts/ai_context.md +++ b/packages/spec/liveness/state-counts/ai_context.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `ai_context` | 15 | 0 | 0 | 0 | 0 | 15 | +| `ai_context` | 19 | 0 | 0 | 0 | 0 | 19 | diff --git a/packages/spec/src/ai/ai-context.zod.test.ts b/packages/spec/src/ai/ai-context.zod.test.ts new file mode 100644 index 00000000000..6fb90260a7f --- /dev/null +++ b/packages/spec/src/ai/ai-context.zod.test.ts @@ -0,0 +1,128 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { + AI_CONTEXT_MAX_RELATED_ROWS, + AI_CONTEXT_WHERE_MAX_DEPTH, + AI_CONTEXT_WHERE_OPERATORS, + AiContextRelatedSchema, + AiContextSchema, + aiContextWhereFields, +} from './ai-context.zod'; +import { FILTER_OPERATORS } from '../data/filter.zod'; + +/** + * [ADR-0160 D1, second amendment] A `related` entry's `where`, `orderBy` and + * `limit`, as the parse admits and refuses them. The render service's reader + * is pinned in `@objectstack/service-record-context`. + */ +const entry = (extra: Record) => ({ object: 'policy_revision', field: 'policy', ...extra }); +const parse = (extra: Record) => AiContextRelatedSchema.safeParse(entry(extra)); +const messages = (extra: Record): string => { + const parsed = parse(extra); + expect(parsed.success).toBe(false); + return parsed.success ? '' : parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('\n'); +}; + +describe('ai_context related — where, orderBy and limit (ADR-0160 D1, second amendment)', () => { + it('admits the ten operators, joined by $and / $or, with literal comparands', () => { + expect(AI_CONTEXT_WHERE_OPERATORS).toEqual(['$eq', '$ne', '$in', '$nin', '$gt', '$gte', '$lt', '$lte', '$null', '$exists']); + for (const op of AI_CONTEXT_WHERE_OPERATORS) expect(FILTER_OPERATORS).toContain(op); + const where = { + is_current: { $eq: true }, + $or: [ + { status: { $in: ['active', 'draft'] }, sort_no: { $gte: 1, $lt: 10 } }, + { $and: [{ note: { $ne: 'x' } }, { archived_at: { $null: true } }, { tag: { $exists: false } }] }, + { kind: { $nin: ['a', 'b'] }, score: { $gt: 0.5, $lte: 99 } }, + ], + }; + const parsed = parse({ where, orderBy: [{ field: 'sort_no', order: 'asc' }], limit: 5 }); + expect(parsed.success).toBe(true); + expect(parsed.data?.where).toEqual(where); + }); + + it('a bare value is admitted (read as $eq), and a string that only contains braces is a literal', () => { + expect(parse({ where: { is_current: true, title: 'a {b} c', owner_id: null } }).success).toBe(true); + }); + + it.each<[string, Record, RegExp]>([ + ['an operator outside the set', { status: { $contains: 'act' } }, /`\$contains` is not admitted on 'status'/], + ['$between', { sort_no: { $between: [1, 2] } }, /`\$between` is not admitted/], + ['$not', { $not: { status: 'x' } }, /`\$not` is not admitted here/], + ['a dotted path', { 'account.industry': 'tech' }, /'account\.industry' is a dotted path/], + ['a condition on a lookup\'s target', { account: { industry: 'tech' } }, /condition on the record its lookup points at/], + ['a field-to-field comparand', { sort_no: { $gt: { $field: 'version' } } }, /field-to-field comparand/], + ['a bare field-to-field comparand', { sort_no: { $field: 'version' } }, /field-to-field comparand/], + ['a $now anchor', { effective_at: { $lt: { $now: { offset: '-P1D' } } } }, /\$now anchor is not admitted/], + ['a whole {token} comparand', { owner_id: '{current_user_id}' }, /whole \{…\} placeholder/], + ['a whole ${token} comparand', { effective_at: { $lt: '${today}' } }, /whole \{…\} placeholder/], + ['a whole token the platform does not know', { status: { $eq: '{nope}' } }, /whole \{…\} placeholder/], + ['a whole token in an $in list', { status: { $in: ['a', '{record_id}'] } }, /whole \{…\} placeholder/], + ['a formula comparand', { sort_no: { $gt: { $expr: 'a + b' } } }, /a comparand is a literal value/], + ['$null with a non-boolean', { note: { $null: 'yes' } }, /takes true or false/], + ['$in with a non-list', { status: { $in: 'a' } }, /takes a list of literal values/], + ])('refuses at parse: %s', (_label, where, expected) => { + expect(messages({ where })).toMatch(expected); + }); + + it('orderBy is SortNodeSchema[]: { field, order }, `direction` refused by name, the child\'s own fields only', () => { + const parsed = parse({ orderBy: [{ field: 'sort_no' }, { field: 'version', order: 'desc' }] }); + expect(parsed.data?.orderBy).toEqual([{ field: 'sort_no', order: 'asc' }, { field: 'version', order: 'desc' }]); + expect(messages({ orderBy: [{ field: 'sort_no', direction: 'desc' }] })).toMatch(/direction/); + expect(messages({ orderBy: [{ field: 'account.name', order: 'asc' }] })).toMatch(/not one of the child's own fields/); + expect(messages({ orderBy: [] })).toMatch(/orderBy/); + }); + + it('limit is a positive integer, at most the row cap; over the cap it is refused, never lowered', () => { + expect(AI_CONTEXT_MAX_RELATED_ROWS).toBe(20); + expect(parse({ limit: AI_CONTEXT_MAX_RELATED_ROWS }).success).toBe(true); + expect(messages({ limit: AI_CONTEXT_MAX_RELATED_ROWS + 1 })).toMatch(/at most 20 rows/); + expect(parse({ limit: 0 }).success).toBe(false); + expect(parse({ limit: 2.5 }).success).toBe(false); + }); + + it('points the near-miss spellings at the declared keys', () => { + expect(messages({ filter: { status: 'x' } })).toMatch(/where/); + expect(messages({ sort: [{ field: 'sort_no' }] })).toMatch(/orderBy/); + }); + + it('a whole pack carrying the three keys parses', () => { + const parsed = AiContextSchema.safeParse({ + name: 'policy_document', + label: 'Policy document', + object: 'policy', + related: [entry({ where: { is_current: { $eq: true } }, orderBy: [{ field: 'sort_no', order: 'asc' }], limit: 5 })], + }); + expect(parsed.success).toBe(true); + }); + + it('aiContextWhereFields names each field once, through $and / $or, and nothing for a non-condition', () => { + expect(aiContextWhereFields({ a_1: 1, $or: [{ b_2: { $gt: 1 } }, { $and: [{ a_1: 2 }, { c_3: null }] }] })).toEqual([ + 'a_1', + 'b_2', + 'c_3', + ]); + expect(aiContextWhereFields(undefined)).toEqual([]); + expect(aiContextWhereFields('x')).toEqual([]); + }); + + it('nesting is bounded at parse at the depth aiContextWhereFields walks: every field of a where that parsed is named', () => { + // `deep` sits beneath `levels` $and / $or lists, with `top` beside the outermost. + const nested = (levels: number) => { + let node: Record = { deep: { $eq: 1 } }; + for (let i = 0; i < levels; i++) node = { [i % 2 ? '$or' : '$and']: [node] }; + return { top: true, ...node }; + }; + expect(AI_CONTEXT_WHERE_MAX_DEPTH).toBe(32); + const atBound = parse({ where: nested(AI_CONTEXT_WHERE_MAX_DEPTH) }); + expect(atBound.success).toBe(true); + expect(aiContextWhereFields(atBound.data?.where)).toEqual(['top', 'deep']); + const past = messages({ where: nested(AI_CONTEXT_WHERE_MAX_DEPTH + 1) }); + expect(past).toContain(`nests $and / $or at most ${AI_CONTEXT_WHERE_MAX_DEPTH} levels deep`); + // Refused once, at the list that would carry a condition past the bound. + expect(past.split('\n')).toHaveLength(1); + expect(past.split(':')[0].split('.')).toHaveLength(2 + 2 * AI_CONTEXT_WHERE_MAX_DEPTH); + // The walker stops where parse stops: a field past the bound is in no list. + expect(aiContextWhereFields(nested(AI_CONTEXT_WHERE_MAX_DEPTH + 1))).toEqual(['top']); + }); +}); diff --git a/packages/spec/src/ai/ai-context.zod.ts b/packages/spec/src/ai/ai-context.zod.ts index 74f7c3fdb04..26b936dae0b 100644 --- a/packages/spec/src/ai/ai-context.zod.ts +++ b/packages/spec/src/ai/ai-context.zod.ts @@ -33,10 +33,25 @@ import { z } from 'zod'; * - each `related[].fields` holds at most {@link AI_CONTEXT_MAX_RELATED_FIELDS} * columns, its lookups expanded in the one read of that list. * - * The rows of a list are capped by the render service, not by the pack: the - * cap is a service constant, stated in the answer when it cuts. + * - a related list carries at most {@link AI_CONTEXT_MAX_RELATED_ROWS} rows: the + * render service's row cap, and the bound of the entry's own `limit` — one + * number, read by both, so a `limit` over the cap is refused here and never + * lowered at call time. + * + * ## Filter, order and limit on a related list (ADR-0160 D1, second amendment) + * + * A `related` entry may choose, order and cut its rows: `where` (the object + * filter form on the child's OWN fields, {@link AI_CONTEXT_WHERE_OPERATORS} + * joined by {@link AI_CONTEXT_WHERE_COMBINATORS} at most + * {@link AI_CONTEXT_WHERE_MAX_DEPTH} deep, literal comparands only), + * `orderBy` (`{ field, order }[]`) and `limit`. They run inside the one + * capped child query, as the caller, joined to the link filter with `$and`: + * they grant nothing and add no object to the call's read set (D4). */ +import { FILTER_TOKEN_WRAPPED_RE } from '../data/context-tokens.zod'; +import { FilterConditionSchema, type FilterCondition, type FilterOperatorKey } from '../data/filter.zod'; +import { SortNodeSchema } from '../data/query.zod'; import { lazySchema } from '../shared/lazy-schema'; import { strictObject } from '../shared/strict-object'; import { ROUTER_ADDRESSABLE_NAME_MESSAGE, ROUTER_ADDRESSABLE_NAME_PATTERN } from '../kernel/address-grammar'; @@ -53,6 +68,36 @@ export const AI_CONTEXT_MAX_RELATED = 3; /** The most columns one child list of a pack reads. */ export const AI_CONTEXT_MAX_RELATED_FIELDS = 10; +/** + * The most rows one related list of a pack carries: the render service's row + * cap (`RECORD_CONTEXT_RELATED_MAX_ROWS` in `@objectstack/service-record-context` + * is this number) and the bound of a `related` entry's `limit`. A list with + * more rows is cut and the answer says so (ADR-0160 D3). + */ +export const AI_CONTEXT_MAX_RELATED_ROWS = 20; + +/** + * The operators a related list's `where` admits on a field (ADR-0160 D1, + * second amendment). Every other operator of the object filter form is + * refused at parse. + */ +export const AI_CONTEXT_WHERE_OPERATORS = [ + '$eq', '$ne', '$in', '$nin', '$gt', '$gte', '$lt', '$lte', '$null', '$exists', +] as const satisfies readonly FilterOperatorKey[]; + +/** The combinators that join a related list's `where` conditions. `$not` is not admitted. */ +export const AI_CONTEXT_WHERE_COMBINATORS = ['$and', '$or'] as const; + +/** + * The most `$and` / `$or` lists a condition of a related list's `where` sits + * beneath (the top-level condition sits beneath none). Deeper nesting is + * refused at parse, like the pack's other bounds (ADR-0160 row 11), and + * {@link aiContextWhereFields} walks to exactly this depth, so every field a + * `where` that parsed names is judged by the render service and the author + * surfaces. 32 is the bound the platform's other filter walks keep. + */ +export const AI_CONTEXT_WHERE_MAX_DEPTH = 32; + /** * The field types a pack's `body` may name: the long-text types, the ones a * record's prose is written in. @@ -74,6 +119,172 @@ function distinctFieldNames(max: number, what: string) { .refine(UNIQUE_SCALAR_ITEMS, { message: `${what} names a field twice` }); } +/** A field name a `where` key or a sort node names: one of the child's own fields, never a dotted path. */ +const OWN_FIELD_NAME_RE = /^[a-z][a-z0-9_]*$/; + +const WHERE_OPERATOR_SET: ReadonlySet = new Set(AI_CONTEXT_WHERE_OPERATORS); +const WHERE_ADMITTED = + `a related list's \`where\` admits ${AI_CONTEXT_WHERE_OPERATORS.join(', ')} on the child's own fields, ` + + `joined by ${AI_CONTEXT_WHERE_COMBINATORS.join(' / ')}`; + +function isPlainNode(value: unknown): value is Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +/** Why `value` is not a literal comparand of a related list's `where`, or `undefined` when it is one. */ +function comparandRefusal(value: unknown): string | undefined { + if (value === null || typeof value === 'boolean' || value instanceof Date) return undefined; + if (typeof value === 'number') return Number.isFinite(value) ? undefined : 'a number comparand must be finite'; + if (typeof value === 'string') { + return FILTER_TOKEN_WRAPPED_RE.test(value) + ? `'${value}' is a whole {…} placeholder, which the data engine would resolve at call time; a related list's ` + + '`where` takes literal values only (placeholders resolved at call time are later work)' + : undefined; + } + if (Array.isArray(value)) return 'a list is a comparand of $in and $nin only, and its members are literal values'; + if (isPlainNode(value) && '$field' in value) { + return 'a field-to-field comparand ({ $field }) is not admitted: compare the field with a literal value'; + } + if (isPlainNode(value) && '$now' in value) { + return 'a $now anchor is not admitted: a related list\'s selection never reads the clock'; + } + return 'a comparand is a literal value (a string, number, boolean or null), never a formula, an anchor or a reference'; +} + +/** + * [ADR-0160 D1, second amendment] The one walk that holds a related list's + * `where` to its admitted subset of the object filter form: field keys that + * are the child's own fields (no dotted path, no condition on a lookup's + * target), the ten {@link AI_CONTEXT_WHERE_OPERATORS}, `$and` / `$or` nested + * at most {@link AI_CONTEXT_WHERE_MAX_DEPTH} deep, and literal comparands. A + * bare value is `$eq`, as the filter form reads it. `depth` is how many + * `$and` / `$or` lists `node` sits beneath. + */ +function checkRelatedWhere(node: unknown, ctx: z.RefinementCtx, path: (string | number)[], depth = 0): void { + if (!isPlainNode(node)) { + ctx.addIssue({ code: 'custom', path, message: `A condition is an object of field conditions; ${WHERE_ADMITTED}` }); + return; + } + for (const [key, value] of Object.entries(node)) { + const at = [...path, key]; + if ((AI_CONTEXT_WHERE_COMBINATORS as readonly string[]).includes(key)) { + if (!Array.isArray(value)) { + ctx.addIssue({ code: 'custom', path: at, message: `\`${key}\` takes a list of conditions` }); + continue; + } + if (depth + 1 > AI_CONTEXT_WHERE_MAX_DEPTH) { + ctx.addIssue({ + code: 'custom', + path: at, + message: `\`${key}\` nests too deep: a related list's \`where\` nests $and / $or at most ` + + `${AI_CONTEXT_WHERE_MAX_DEPTH} levels deep`, + }); + continue; + } + value.forEach((member, i) => checkRelatedWhere(member, ctx, [...at, i], depth + 1)); + continue; + } + if (key.startsWith('$')) { + ctx.addIssue({ code: 'custom', path: at, message: `\`${key}\` is not admitted here: ${WHERE_ADMITTED}` }); + continue; + } + if (!OWN_FIELD_NAME_RE.test(key)) { + ctx.addIssue({ + code: 'custom', + path: at, + message: key.includes('.') + ? `'${key}' is a dotted path: a related list's \`where\` reads the child's own fields only (reads through a ` + + 'lookup are later work)' + : `'${key}' is not a field name (lowercase snake_case)`, + }); + continue; + } + if (!isPlainNode(value)) { + // A bare value: read as `$eq`. + const why = comparandRefusal(value); + if (why) ctx.addIssue({ code: 'custom', path: at, message: `'${key}': ${why}` }); + continue; + } + const ops = Object.keys(value); + if (ops.length > 0 && !ops.some((op) => op.startsWith('$'))) { + ctx.addIssue({ + code: 'custom', + path: at, + message: `'${key}' holds a condition on the record its lookup points at: a related list's \`where\` reads the ` + + 'child\'s own fields only (relation traversal is later work)', + }); + continue; + } + if (ops.length === 0 || '$field' in value || '$now' in value) { + const why = ops.length === 0 ? 'a field condition names at least one operator' : comparandRefusal(value); + ctx.addIssue({ code: 'custom', path: at, message: `'${key}': ${why}` }); + continue; + } + for (const op of ops) { + const opAt = [...at, op]; + if (!WHERE_OPERATOR_SET.has(op)) { + ctx.addIssue({ code: 'custom', path: opAt, message: `\`${op}\` is not admitted on '${key}': ${WHERE_ADMITTED}` }); + continue; + } + const comparand = value[op]; + if (op === '$in' || op === '$nin') { + if (!Array.isArray(comparand)) { + ctx.addIssue({ code: 'custom', path: opAt, message: `\`${op}\` on '${key}' takes a list of literal values` }); + continue; + } + comparand.forEach((member, i) => { + const why = Array.isArray(member) ? 'a list member is a literal value, never a list' : comparandRefusal(member); + if (why) ctx.addIssue({ code: 'custom', path: [...opAt, i], message: `'${key}' ${op}: ${why}` }); + }); + continue; + } + if (op === '$null' || op === '$exists') { + if (typeof comparand !== 'boolean') { + ctx.addIssue({ code: 'custom', path: opAt, message: `\`${op}\` on '${key}' takes true or false` }); + } + continue; + } + const why = comparandRefusal(comparand); + if (why) ctx.addIssue({ code: 'custom', path: opAt, message: `'${key}' ${op}: ${why}` }); + } + } +} + +/** + * The child fields a related list's `where` names, each once, in first-named + * order — walked through `$and` / `$or` to {@link AI_CONTEXT_WHERE_MAX_DEPTH}, + * the depth parse admits, so on a `where` that parsed no field is missed. + * Safe on any shape: a value that is no condition names no field. The render service judges each one against + * the caller's queryable fields before it reads, and the author surfaces + * report one the child does not define (ADR-0160 D1, D3). + */ +export function aiContextWhereFields(where: unknown): string[] { + const out: string[] = []; + const walk = (node: unknown, depth: number) => { + if (depth > AI_CONTEXT_WHERE_MAX_DEPTH || !isPlainNode(node)) return; + for (const [key, value] of Object.entries(node)) { + if ((AI_CONTEXT_WHERE_COMBINATORS as readonly string[]).includes(key)) { + if (Array.isArray(value)) for (const member of value) walk(member, depth + 1); + } else if (!key.startsWith('$') && !out.includes(key)) { + out.push(key); + } + } + }; + walk(where, 0); + return out; +} + +/** + * [ADR-0160 D1, second amendment] A related list's `where`: the object filter + * form ({@link FilterConditionSchema}) held to its admitted subset by + * {@link checkRelatedWhere}. + */ +export const AiContextRelatedWhereSchema: z.ZodType = z.lazy(() => + FilterConditionSchema.superRefine((node, ctx) => checkRelatedWhere(node, ctx, [])), +); + /** * One child list of a pack: the records of `object` whose reference field * points at the pack's root record. One level, child lists only — the shape of @@ -83,7 +294,15 @@ export const AiContextRelatedSchema = lazySchema(() => strictObject( { surface: 'a context pack `related` entry', history: BORN_CLOSED, - aliases: { objectName: 'object', link: 'field', linkField: 'field', columns: 'fields' }, + aliases: { + objectName: 'object', + link: 'field', + linkField: 'field', + columns: 'fields', + filter: 'where', + sort: 'orderBy', + sortBy: 'orderBy', + }, }, { object: SnakeCaseIdentifierSchema.describe( @@ -97,6 +316,46 @@ export const AiContextRelatedSchema = lazySchema(() => strictObject( `The columns read for each row, in order (at most ${AI_CONTEXT_MAX_RELATED_FIELDS}). A lookup among them is ` + 'answered with the name of the record it points at. Omit to read the row\'s name only', ), + where: AiContextRelatedWhereSchema.optional().describe( + 'Which child rows the list carries: a filter on the child\'s own fields, in the object filter form. A bare ' + + `value is \`$eq\`; the operators are ${AI_CONTEXT_WHERE_OPERATORS.join(', ')}, joined by ` + + `${AI_CONTEXT_WHERE_COMBINATORS.join(' / ')} nested at most ${AI_CONTEXT_WHERE_MAX_DEPTH} deep. Comparands are literal values: no dotted path, no field-to-field ` + + 'comparand, no $now anchor and no {…} placeholder. Joined to the link with $and and read as the caller, so ' + + 'it grants nothing', + ), + orderBy: z + .array(SortNodeSchema) + .min(1) + .superRefine((nodes, ctx) => { + nodes.forEach((node, i) => { + if (typeof node?.field === 'string' && !OWN_FIELD_NAME_RE.test(node.field)) { + ctx.addIssue({ + code: 'custom', + path: [i, 'field'], + message: `'${node.field}' is not one of the child's own fields: \`orderBy\` names a field of the list's ` + + 'own object (lowercase snake_case, no dotted path)', + }); + } + }); + }) + .optional() + .describe( + 'The order of the rows: `{ field, order }[]` on the child\'s own fields, `order` `asc` (the default) or ' + + '`desc`. Without it the rows come in the data engine\'s order. A field the child does not offer as a sort ' + + '(it declares `sortable: false`, or is a formula) leaves the list out of every answer', + ), + limit: z + .number() + .int() + .min(1) + .max(AI_CONTEXT_MAX_RELATED_ROWS, { + message: `A related list carries at most ${AI_CONTEXT_MAX_RELATED_ROWS} rows (the render service's row cap)`, + }) + .optional() + .describe( + `The most rows the list carries (at most ${AI_CONTEXT_MAX_RELATED_ROWS}, the default). A list cut at it says ` + + 'so in the answer', + ), }, )); @@ -129,6 +388,9 @@ export const AiContextBodySchema = lazySchema(() => strictObject( * - object: policy_revision * field: policy * fields: [version, published_at] + * where: { is_current: { $eq: true } } + * orderBy: [{ field: sort_no, order: asc }] + * limit: 5 * body: * field: content * ``` @@ -149,8 +411,8 @@ export const AiContextSchema = lazySchema(() => strictObject( description: 'A context pack has no `description` in v1 (ADR-0160 D1): write the purpose in `label`.', filter: - 'A context pack reads one record by id; it takes no filter. A related list reads every child row the caller ' - + 'may read, up to the render service\'s row cap.', + 'A context pack reads one record by id; it takes no filter. To choose which rows a related list carries, ' + + 'give that `related` entry its own `where`.', }, }, { @@ -184,3 +446,5 @@ export type AiContextRelated = z.input; export type AiContextRelatedParsed = z.infer; export type AiContextBody = z.input; export type AiContextBodyParsed = z.infer; +export type AiContextRelatedWhere = z.input; +export type AiContextRelatedWhereParsed = z.infer;