Skip to content
Merged
29 changes: 29 additions & 0 deletions .changeset/37203-ai-context-related-where-orderby-limit.md
Original file line number Diff line number Diff line change
@@ -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`.

21 changes: 17 additions & 4 deletions content/docs/references/ai/ai-context.mdx
Original file line number Diff line number Diff line change
@@ -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/. */}
Expand All @@ -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);
Expand All @@ -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. |
Expand All @@ -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`

Expand Down Expand Up @@ -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<string, any> & { $and?: any[]; $or?: any[]; $not?: any }`


---
Expand Down
10 changes: 5 additions & 5 deletions content/docs/references/index.mdx
Original file line number Diff line number Diff line change
@@ -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/. */}
Expand All @@ -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. |
Expand All @@ -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` |
Expand Down
18 changes: 14 additions & 4 deletions examples/app-showcase/src/ai/record-context.ai-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,31 @@ 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',
label: 'Project brief',
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,
},
],
};

Expand Down
2 changes: 1 addition & 1 deletion examples/app-showcase/src/coverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ export const KIND_COVERAGE: Record<MetadataType, KindCoverage> = {
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',
Expand Down
1 change: 1 addition & 0 deletions packages/lint/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
14 changes: 14 additions & 0 deletions packages/lint/src/rule-explanations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -7049,6 +7062,7 @@ export const RULE_EXPLANATIONS: Readonly<Record<string, RuleExplanation>> = 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,
Expand Down
Loading
Loading