diff --git a/.changeset/37361-record-context-left-out-queryable-doors.md b/.changeset/37361-record-context-left-out-queryable-doors.md new file mode 100644 index 00000000000..cfa4cef8539 --- /dev/null +++ b/.changeset/37361-record-context-left-out-queryable-doors.md @@ -0,0 +1,20 @@ +--- +'@objectstack/service-record-context': patch +'@objectstack/runtime': patch +'@objectstack/mcp': patch +'@objectstack/spec': patch +'@objectstack/types': patch +--- + +fix(service-record-context): get_record_context leaves out a related child the caller is not served, and both MCP doors hand over the caller's queryable fields and their page cap + +Clause-②: yes (widening) +Metadata-protocol: none + +ADR-0160 D3 "Object level", as amended, and its second amendment. No pack, key or code changes. The published surface widens by optional members only: `RecordContextDoor.pageCap?()`, and `StdioDataBridgeDeps.security` may carry `getQueryableFields`; `@objectstack/types` adds `resolveQueryReadPageCap`. + +- **A related child this caller is not served is left out, not refused.** The answer carries the root and every served section, with the one `not_visible` note, and names the child nowhere; nothing of the child is read after its object-level judgement, its published definition included. A child is still refused whole, as before, when a gate refuses it for everyone: the read guard, or API exposure — which is now asked before the served definition, so a child whose package is disabled (`OBJECT_PACKAGE_DISABLED`, which also serves its object to nobody) keeps its `PERMISSION_DENIED` refusal. A served-definition read that fails refuses the call, unnamed, and is never read as a narrowing. +- **Both doors supply `queryableFieldsOf`.** The `/mcp` door and the stdio door now hand the executor the security service's `getQueryableFields` answer for the caller they resolved, so a related list's `where` or `orderBy` is judged on that answer before the read. A field outside it drops the section with the note, and is never refused by the engine's guard; a masked field this caller is served whole (its unmask capability held) is now filtered and sorted on, where the fallback dropped the section. +- **A door's page cap is a stated cut.** A door may report its page cap (`pageCap`, optional); the executor then asks a related list for at most that many rows, cuts the list one row under it, and states the cut. Both doors report the deployment's smaller read limit (`OS_DATA_MAX_PAGE_SIZE`, `OS_DATA_QUERY_ROW_BUDGET`). Before, under a maximum page size below a list's cut plus its probe row, the `/mcp` door refused the whole call `MAX_RECORDS_EXCEEDED` and the stdio door read the full list. +- The `related_truncated` note kind's doc line, and the `rows` and `truncated` descriptions of a related list in the tool's output schema, now say a list is cut at its entry's `limit`, at the row cap, or below either at the door's page cap. +- `@objectstack/types` exports `resolveQueryReadPageCap()`: the smaller of `OS_DATA_MAX_PAGE_SIZE` and `OS_DATA_QUERY_ROW_BUDGET`, `undefined` when neither is set. Both doors answer `pageCap` from this one function, so they cut at the same row. diff --git a/content/docs/references/ai/record-context-tools.mdx b/content/docs/references/ai/record-context-tools.mdx index ca58dfa22bd..58b304f9b60 100644 --- a/content/docs/references/ai/record-context-tools.mdx +++ b/content/docs/references/ai/record-context-tools.mdx @@ -137,8 +137,8 @@ const result = GetRecordContextInputSchema.parse(data); | **object** | `string` | ✅ | The child object | | **label** | `string` | ✅ | The child object's plural label at the caller's locale | | **field** | `string` | ✅ | The child's field that points at the record | -| **rows** | `{ id?: string; displayName?: string; fields: object[] }[]` | ✅ | The rows the caller may read, up to the row cap | -| **truncated** | `true` | optional | Present when more rows existed past the row cap | +| **rows** | `{ id?: string; displayName?: string; fields: object[] }[]` | ✅ | The rows the caller may read, up to the list's `limit` (the row cap when it names none), or fewer when the door's page cap is lower | +| **truncated** | `true` | optional | Present when more rows existed past the rows given: at the list's `limit`, at the row cap, or below either at the door's page cap | ### Nested Shape: `RecordContextData.body` @@ -221,8 +221,8 @@ const result = GetRecordContextInputSchema.parse(data); | **object** | `string` | ✅ | The child object | | **label** | `string` | ✅ | The child object's plural label at the caller's locale | | **field** | `string` | ✅ | The child's field that points at the record | -| **rows** | `{ id?: string; displayName?: string; fields: object[] }[]` | ✅ | The rows the caller may read, up to the row cap | -| **truncated** | `true` | optional | Present when more rows existed past the row cap | +| **rows** | `{ id?: string; displayName?: string; fields: object[] }[]` | ✅ | The rows the caller may read, up to the list's `limit` (the row cap when it names none), or fewer when the door's page cap is lower | +| **truncated** | `true` | optional | Present when more rows existed past the rows given: at the list's `limit`, at the row cap, or below either at the door's page cap | ### Nested Shape: `RecordContextRelatedList.rows[number]` diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 85529bba0e6..095fb23ef4f 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -135,7 +135,7 @@ import { // context-pack listing before the record-context executor parses it. stripReadDecorations, } from '@objectstack/spec/kernel'; -import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import type { IDataEngine, IMetadataService, ISecurityService } from '@objectstack/spec/contracts'; import { resolveObjectSortability } from '@objectstack/spec/api'; // [#32442] The ONE reading of `enable.aiReadable` (ruling A, #32865). import { isAiReadExposed } from '@objectstack/spec/data'; @@ -172,7 +172,7 @@ import { diagnoseObjectListRead, type DiagnosedObjectListing, } from './metadata-completeness.js'; -import { staleSummaryRefusalOrThrow, withEarnedAnswer, type SummaryRecomputeRefusal } from '@objectstack/types'; +import { resolveQueryReadPageCap, staleSummaryRefusalOrThrow, withEarnedAnswer, type SummaryRecomputeRefusal } from '@objectstack/types'; // [ADR-0149 D2] The `/meta` list translation and its locale parse, the pair // the HTTP door's `loadDatasets` runs — imported, never restated, so both // transports localize a saved dataset with one function. @@ -250,8 +250,12 @@ export interface StdioDataBridgeDeps { * use and `undefined` when this host registers none — the deployment then * has no field-level posture, and the schema is served as declared, as on * every other object-schema exit. + * + * [ADR-0160 D3, second amendment] The same service answers the fields the + * principal may query on (`getQueryableFields`, feature-detected), which + * the record-context door hands its executor. */ - security?: () => ObjectSchemaMaskSecuritySurface | undefined; + security?: () => (ObjectSchemaMaskSecuritySurface & Pick, 'getQueryableFields'>) | undefined; /** * [decision 6840464379] Where the object-schema mask finds an object's * declared `schemaReadDelegate` ({@link CallerObjectViewDeps.schemaReadDelegates}). @@ -1917,6 +1921,20 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge get: (object: string, id: string) => self.get(object, id), query: (object: string, o: Parameters[1]) => self.query(object, o), fieldVisibilityOf: (object: string) => self.fieldVisibilityOf!(object), + // [ADR-0160 D3, second amendment] The fields the principal may query + // on: the security service's own answer (`getQueryableFields`), judged + // on the map its engine guard refuses a filter or sort with, so a + // related list's `where` or `orderBy` the guard would refuse is dropped + // and stated before the read. No security service, or one predating the + // method: `undefined`, and the executor takes the contract's fallback. + queryableFieldsOf: async (object: string) => { + const surface = security?.(); + if (typeof surface?.getQueryableFields !== 'function') return undefined; + return await surface.getQueryableFields(object, await resolvePrincipal()); + }, + // [ADR-0160 D3] The deployment's page cap (`resolveQueryReadPageCap`), the + // same value the `/mcp` door answers. + pageCap: () => resolveQueryReadPageCap(), userTextLocales: () => self.userTextLocales!(), }); bridge.recordContextToolDefinitions = () => service.recordContextTools().definitions; diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 0a6ac6f447a..4c4e1f94cb1 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -8,7 +8,7 @@ * Fetch-Request normalization ride along as family helpers. */ -import { isMcpServerEnabled } from '@objectstack/types'; +import { isMcpServerEnabled, resolveQueryReadPageCap } from '@objectstack/types'; import { MCP_OAUTH_SCOPES, MCP_OAUTH_SCOPE_DATA_READ, deriveAiFaceName } from '@objectstack/spec/ai'; import type { ErrorCode, MetadataProtocol } from '@objectstack/spec/api'; import type { ISecurityService } from '@objectstack/spec/contracts'; @@ -1739,6 +1739,24 @@ export function buildMcpBridge( // [ADR-0150 D6, addendum 2026-11-25] A package's pack is spelt by // its face `NS-NAME`, as a package-held skill's prompt name is. packageNamespace: (packageId: string) => packageNamespaceOf(contextPackEngine, packageId), + // [ADR-0160 D3, second amendment] The fields this caller may query + // on: THIS request's security service's own answer + // (`getQueryableFields`), judged on the map its engine guard + // refuses a filter or sort with, so a related list's `where` or + // `orderBy` the guard would refuse is dropped and stated before + // the read. No security service, or one predating the method: + // `undefined`, and the executor takes the contract's fallback. + queryableFieldsOf: async (object: string) => { + const security = await deps.resolveService(context, 'security', envId) as + Partial | undefined; + if (typeof security?.getQueryableFields !== 'function') return undefined; + return await security.getQueryableFields(object, ec); + }, + // [ADR-0160 D3] The data door's page cap: `findData` refuses a + // read asking for more rows than the deployment's maximum page + // size or its row budget (`@objectstack/types`' + // `query-read-limits.ts`), so the executor asks for no more. + pageCap: () => resolveQueryReadPageCap(), })); } return bridge; @@ -1795,6 +1813,8 @@ function recordContextMembers( publishedObjectDefinitionOf(name: string): Promise | null>; listContextPacks(): Promise; packageNamespace(packageId: string): string | undefined; + queryableFieldsOf(object: string): Promise; + pageCap(): number | undefined; }, ) { return { diff --git a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts index bf084dd46b9..005dc7e332f 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -116,12 +116,19 @@ describe('[ADR-0160 D4] the MCP bridge\'s record-context members', () => { 'get', 'listContextPacks', 'packageNamespace', + 'pageCap', 'publishedObjectDefinitionOf', 'query', + 'queryableFieldsOf', 'readGuard', 'servedObjectDefinitionOf', 'userTextLocales', ]); + // [ADR-0160 D3, second amendment] The queryable fields: this request's security service's own + // answer, for this request's caller; none (no service, or one without the method) is `undefined`. + expect(await door.queryableFieldsOf('policy')).toBeUndefined(); + // [ADR-0160 D3] The page cap: the deployment's read limits, unset here. + expect(door.pageCap()).toBeUndefined(); // The published packs: the protocol's merged listing, as `/meta/ai_context` reads it. expect(await door.listContextPacks()).toEqual([PACK]); expect(protocol.getMetaItems).toHaveBeenCalledWith({ type: 'ai_context' }); @@ -134,6 +141,23 @@ describe('[ADR-0160 D4] the MCP bridge\'s record-context members', () => { expect(query).toHaveBeenCalledWith('policy_revision', { where: { policy: 'p1' }, limit: 21 }); expect(await door.userTextLocales()).toEqual(await bridge.userTextLocales()); }); + + it('[ADR-0160 D3] the door\'s queryable fields are the security service\'s answer for the caller, and its page cap the deployment\'s smaller read limit', async () => { + const getQueryableFields = vi.fn(async () => ['title', 'status']); + const { ctx, deps, service, doors } = harness({ security: { getQueryableFields } }); + const bridge = buildMcpBridge(deps, ctx, { recordContextTools: service }); + await bridge.getRecordContext({ objectName: 'policy', recordId: 'p1' }, { readGuard: vi.fn(async () => undefined) }); + const [door] = doors; + expect(await door.queryableFieldsOf('policy')).toEqual(['title', 'status']); + expect(getQueryableFields).toHaveBeenCalledWith('policy', expect.objectContaining({ userId: EC.userId, tenantId: EC.tenantId })); + vi.stubEnv('OS_DATA_MAX_PAGE_SIZE', '40'); + vi.stubEnv('OS_DATA_QUERY_ROW_BUDGET', '12'); + try { + expect(door.pageCap()).toBe(12); + } finally { + vi.unstubAllEnvs(); + } + }); }); /** @@ -347,11 +371,13 @@ describe('[ADR-0160 D4] the /mcp route answers through a package pack the real p * real `SecurityPlugin` and the real protocol. Nothing of the metadata plane, * the data plane or the executor is a double. * - * The caller is one identity: the stdio session resolves its + * The caller is one identity per call: the stdio session resolves its * `OS_MCP_STDIO_API_KEY` through `resolveAuthzContext` and * `assembleExecutionContext`, and the `/mcp` request is handed the context * those same two calls assemble for the same key. Every case below asks both * doors the same call and requires the same bytes back, refusals included. + * The key's owner is `usr_member`; one case names `usr_plain` as its owner + * instead, the same user bar the capability that lifts a masking rule. * * Where `main` differs from ADR-0160 as amended 2026-11-25 (a related child * THIS caller is not served is left out and stated, not refused), the case @@ -367,7 +393,17 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: let protocol: ObjectStackProtocolImplementation; let dispatcher: HttpDispatcher; let caller: ExecutionContext; + /** + * A second caller of the same key's door, without the capability that lifts + * `rc_step.serial`'s masking rule: `usr_member` holds `rc_unmask` through + * its own grant of `rc_unmasker`; `usr_plain` holds the baseline only. + */ + let plainCaller: ExecutionContext; + /** Whom the key's owner row names on this call: the stdio door re-resolves it per call. */ + let keyOwner: 'usr_member' | 'usr_plain' = 'usr_member'; let rpc: (method: string, params?: unknown) => Promise; + /** The real `security` service both doors resolve. */ + let securityService: any; /** The execution context the stdio door handed the engine, per object read. */ const stdioReads: Array<{ object: string; context: any }> = []; @@ -401,6 +437,18 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: }, }, child('rc_revision', 'Revision'), + { + name: 'rc_step', label: 'Step', nameField: 'label', sharingModel: 'public_read_write', + fields: { + label: { name: 'label', type: 'text', label: 'Label' }, + stage: { name: 'stage', type: 'text', label: 'Stage' }, + rank: { name: 'rank', type: 'number', label: 'Rank' }, + policy: { name: 'policy', type: 'lookup', reference: 'rc_policy', label: 'Policy' }, + // A masking rule `rc_unmask` lifts: the security service lists it as queryable + // for `usr_member`, where the contract's fallback never would, and not for `usr_plain`. + serial: { name: 'serial', type: 'text', label: 'Serial', maskingRule: { keepHead: 1, keepTail: 1 }, requiredPermissions: ['rc_unmask'] }, + }, + }, child('rc_closed', 'Closed', { enable: { apiEnabled: false } }), child('rc_hidden', 'Hidden'), { @@ -415,7 +463,33 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: related: [{ object: 'rc_revision', fields: ['version'] }], body: { field: 'content' }, }, - { name: 'rc_unserved_child', label: 'Unserved child', object: 'rc_policy', fields: ['title'], related: [{ object: 'rc_hidden', fields: ['version'] }] }, + { + name: 'rc_unserved_child', label: 'Unserved child', object: 'rc_policy', fields: ['title'], + related: [{ object: 'rc_hidden', fields: ['version'] }, { object: 'rc_revision', fields: ['version'] }], + }, + { + name: 'rc_filtered', label: 'Filtered steps', object: 'rc_policy', fields: ['title'], + related: [{ object: 'rc_step', fields: ['label', 'rank'], where: { stage: { $eq: 'open' } }, orderBy: [{ field: 'rank', order: 'desc' }], limit: 2 }], + }, + { + name: 'rc_unqueryable_where', label: 'Unqueryable where', object: 'rc_policy', fields: ['title'], + related: [ + { object: 'rc_step', fields: ['label'], where: { stage: { $ne: 'closed' } } }, + { object: 'rc_revision', fields: ['version'] }, + ], + }, + { + name: 'rc_unmasked_order', label: 'Steps by serial', object: 'rc_policy', fields: ['title'], + related: [{ object: 'rc_step', fields: ['label'], orderBy: [{ field: 'serial', order: 'desc' }] }], + }, + { + name: 'rc_created_order', label: 'Steps by creation', object: 'rc_policy', fields: ['title'], + related: [{ object: 'rc_step', fields: ['label'], orderBy: [{ field: 'created_at', order: 'desc' }] }], + }, + { + name: 'rc_steps', label: 'Steps', object: 'rc_policy', fields: ['title'], + related: [{ object: 'rc_step', fields: ['label'], orderBy: [{ field: 'rank', order: 'asc' }] }], + }, { name: 'rc_exposure_child', label: 'Exposure child', object: 'rc_policy', fields: ['title'], related: [{ object: 'rc_closed', fields: ['version'] }] }, { name: 'rc_disabled_child', label: 'Disabled child', object: 'rc_policy', fields: ['title'], related: [{ object: 'rc_off', fields: ['version'] }] }, ], @@ -434,6 +508,16 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: await engine.insert('rc_revision', { id: 'r1', version: 'v1', policy: 'p1', owner_id: 'usr_member', organization_id: 'org_1' }, sys); await engine.insert('rc_revision', { id: 'r2', version: 'v2', policy: 'p1', owner_id: 'usr_other', organization_id: 'org_1' }, sys); await engine.insert('rc_hidden', { id: 'h1', version: 'h', policy: 'p1', organization_id: 'org_1' }, sys); + for (const [id, stage, rank, at] of [ + ['s1', 'open', 1, '2026-11-01T00:00:00.000Z'], + ['s2', 'open', 3, '2026-11-02T00:00:00.000Z'], + ['s3', 'open', 2, '2026-11-03T00:00:00.000Z'], + ['s4', 'closed', 5, '2026-11-04T00:00:00.000Z'], + ] as const) { + await engine.insert('rc_step', { + id, label: `Step ${id}`, stage, rank, policy: 'p1', serial: `N-${rank}`, created_at: at, organization_id: 'org_1', + }, sys); + } engine.registry.disablePackage(OFF_PKG); const sets = [PermissionSetSchema.parse({ @@ -441,6 +525,9 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: objects: { '*': READ_ALL, rc_hidden: READ_NONE }, fields: { 'rc_policy.secret_note': { readable: false, editable: false } }, rowLevelSecurity: [{ name: 'rc_own_revisions', object: 'rc_revision', operation: 'select', using: 'owner_id == current_user.id' }], + }), PermissionSetSchema.parse({ + // Granted to `usr_member` alone (its `sys_user_permission_set` row below). + name: 'rc_unmasker', label: 'Unmasker', systemPermissions: ['rc_unmask'], objects: {}, })]; const services: Record = { manifest: { register: vi.fn() }, @@ -462,13 +549,15 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: const security = new SecurityPlugin({ fallbackPermissionSet: 'rc_member' }); await security.init(ctx as never); await security.start(ctx as never); + securityService = services.security; await new RecordContextServicePlugin().init(ctx as never); protocol = new ObjectStackProtocolImplementation(engine as any); - // The key's auth tables (`sys_api_key`, `sys_user`, `sys_member`) are - // not part of this kernel: these answers stand in for them, for the one - // key (owner `usr_member`, active in `org_1`); every other read is the - // engine's, and the stdio door's are recorded with their context. + // The key's auth tables (`sys_api_key`, `sys_user`, `sys_member`, + // `sys_user_permission_set`) are not part of this kernel: these answers + // stand in for them, for the one key (owner {@link keyOwner}, active in + // `org_1`; `usr_member` alone granted `rc_unmasker`); every other read is + // the engine's, and the stdio door's are recorded with their context. const keyedQl = new Proxy(engine as any, { get(target, prop, receiver) { if (prop === 'update') { @@ -477,11 +566,21 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: } if (prop === 'find') { return async (object: string, query?: any, options?: any) => { + const users = ['usr_member', 'usr_plain']; if (object === 'sys_api_key') { - return [{ id: 'k1', user_id: 'usr_member', revoked: false, active_organization_id: 'org_1' }]; + return [{ id: 'k1', user_id: keyOwner, revoked: false, active_organization_id: 'org_1' }]; + } + if (object === 'sys_user') return users.includes(query?.where?.id) ? [{ id: query.where.id }] : []; + if (object === 'sys_member') { + const members = users.map((u, i) => ({ id: `m${i + 1}`, user_id: u, organization_id: 'org_1', role: 'member' })); + const who = query?.where?.user_id; + return who === undefined ? members : members.filter((m) => m.user_id === who); + } + if (object === 'sys_user_permission_set') { + return query?.where?.user_id === 'usr_member' + ? [{ id: 'g1', user_id: 'usr_member', permission_set: 'rc_unmasker', organization_id: 'org_1' }] + : []; } - if (object === 'sys_user') return query?.where?.id === 'usr_member' ? [{ id: 'usr_member' }] : []; - if (object === 'sys_member') return [{ id: 'm1', user_id: 'usr_member', organization_id: 'org_1', role: 'member' }]; if (object.startsWith('sys_') && !target.registry.getObject(object)) return []; stdioReads.push({ object, context: query?.context ?? options?.context }); return target.find(object, query, options); @@ -491,10 +590,13 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: return typeof value === 'function' ? value.bind(target) : value; }, }); - caller = assembleExecutionContext({ + const resolveCaller = async (): Promise => assembleExecutionContext({ authz: await resolveAuthzContext({ ql: keyedQl, headers: { 'x-api-key': KEY }, tenancyPosture: undefined, client: { transport: 'stdio' } } as never), oauth: undefined, localization: undefined, requestLocale: undefined, accessToken: undefined, } as never) as ExecutionContext; + caller = await resolveCaller(); + keyOwner = 'usr_plain'; + try { plainCaller = await resolveCaller(); } finally { keyOwner = 'usr_member'; } // The stdio door: the real plugin's long-lived session, over an in-process transport. const stdioServices = new Map(Object.entries({ @@ -556,7 +658,7 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: interface DoorAnswer { isError: boolean; text: string } - const overHttp = async (args: Record, tool = 'get_record_context'): Promise => { + const overHttp = async (args: Record, tool = 'get_record_context', executionContext: ExecutionContext = caller): Promise => { const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }; const res = await dispatcher.handleMcp(body, { request: new Request('http://localhost/api/v1/mcp', { @@ -566,7 +668,7 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: }), response: {}, environmentId: undefined, - executionContext: caller, + executionContext, } as any); expect(res.response?.status).toBe(200); const result = (res.response?.body as any)?.result; @@ -584,6 +686,19 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(stdio).toEqual(http); return { isError: http.isError, text: http.text, payload: JSON.parse(http.text) }; }; + /** {@link both}, as `usr_plain`: the /mcp request carries its context, and the key's owner row names it for the stdio call. */ + const bothAsPlain = async (args: Record, tool = 'get_record_context') => { + keyOwner = 'usr_plain'; + try { + const http = await overHttp(args, tool, plainCaller); + const stdio = await overStdio(args, tool); + expect(typeof http.text).toBe('string'); + expect(stdio).toEqual(http); + return { isError: http.isError, text: http.text, payload: JSON.parse(http.text) }; + } finally { + keyOwner = 'usr_member'; + } + }; it('precondition: the stdio session reads as the caller the /mcp request carries', async () => { expect(caller).toMatchObject({ userId: 'usr_member', tenantId: 'org_1' }); @@ -627,11 +742,17 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(answer.payload.error).toEqual(record.payload.error); }); - it('[today; ADR-0160 as amended says left out and stated] a related child this caller is not served refuses the call, unnamed', async () => { + it('[ADR-0160 D3 as amended] a related child this caller is not served is left out: the root and the served child, one not-visible statement, the child named nowhere', async () => { const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_unserved_child' }); - expect(answer.isError).toBe(true); - expect(answer.payload.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(answer.isError).toBe(false); + const { data, notes } = answer.payload; + expect(data.fields.map((f: { name: string }) => f.name)).toEqual(['title']); + // The served control: its section answers as the caller reads it. + expect(data.related.map((l: { object: string }) => l.object)).toEqual(['rc_revision']); + expect(data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['r1']); + expect(notes.map((n: { kind: string }) => n.kind)).toEqual(['not_visible']); expect(answer.text).not.toContain('rc_hidden'); + expect(answer.text).not.toContain('Hidden'); }); it('a related child its API exposure refuses refuses the call, named (the caller\'s schema shows it)', async () => { @@ -649,6 +770,101 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(answer.text).not.toContain('rc_off'); }); + it('[ADR-0160 D3, second amendment] where, orderBy and limit on a related list answer the same bytes on both doors: filtered, ordered, cut at the limit and stated', async () => { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_filtered' }); + expect(answer.isError).toBe(false); + const { data, notes } = answer.payload; + expect(data.related).toHaveLength(1); + expect(data.related[0]).toMatchObject({ object: 'rc_step', field: 'policy', truncated: true }); + expect(data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['s2', 's3']); + expect(notes).toEqual([{ kind: 'related_truncated', object: 'rc_step', text: expect.stringContaining('2') }]); + }); + + it('[ADR-0160 D3, second amendment] a where field outside the security service\'s queryable answer drops the section with the statement on both doors, never refusing, though the fallback would admit it', async () => { + // plugin-security's read projection already leaves out what its queryable answer leaves out, + // bar masked fields (which the fallback refuses for everyone), so the answer is narrowed here by + // one field the fallback admits: served, readable, declaring no masking rule. + expect(await securityService.getReadableFields('rc_step', caller)).toContain('stage'); + expect((engine.getSchema('rc_step') as any)?.fields?.stage?.maskingRule).toBeUndefined(); + const real = securityService.getQueryableFields.bind(securityService); + const narrowed = vi.spyOn(securityService, 'getQueryableFields').mockImplementation(async (object: any, ctx: any) => { + const fields = await real(object, ctx); + return object === 'rc_step' ? fields?.filter((f: string) => f !== 'stage') : fields; + }); + try { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_unqueryable_where' }); + expect(answer.isError).toBe(false); + const { data, notes } = answer.payload; + // The served control beside it still answers. + expect(data.related.map((l: { object: string }) => l.object)).toEqual(['rc_revision']); + expect(notes.map((n: { kind: string }) => n.kind)).toEqual(['not_visible']); + expect(answer.text).not.toContain('stage'); + expect(answer.text).not.toContain('rc_step'); + // Asked on both doors, for the caller each resolved. + const asked = narrowed.mock.calls.filter(([object]) => object === 'rc_step'); + expect(asked.length).toBeGreaterThanOrEqual(2); + for (const [, ctx] of asked) expect(ctx).toMatchObject({ userId: caller.userId, tenantId: caller.tenantId }); + } finally { + narrowed.mockRestore(); + } + }); + + it('[ADR-0160 D3, second amendment] an orderBy on a masked field this caller is served whole is read on both doors: the doors hand over the security service\'s answer, not the fallback', async () => { + expect(await securityService.getQueryableFields('rc_step', caller)).toContain('serial'); + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_unmasked_order' }); + expect(answer.isError).toBe(false); + expect(answer.payload.notes).toEqual([]); + expect(answer.payload.data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['s4', 's2', 's3', 's1']); + }); + + it('[ADR-0160 D3, second amendment] an orderBy on a masked field whose rule is NOT lifted for the caller drops the section with the statement on both doors, never refusing and naming nothing of it', async () => { + // Precondition: the two callers differ in the capability alone, and each door reads as its caller. + expect(plainCaller).toMatchObject({ userId: 'usr_plain', tenantId: 'org_1' }); + expect(caller.systemPermissions).toContain('rc_unmask'); + expect(plainCaller.systemPermissions ?? []).not.toContain('rc_unmask'); + expect(await securityService.getQueryableFields('rc_step', plainCaller)).not.toContain('serial'); + expect(await securityService.getQueryableFields('rc_step', caller)).toContain('serial'); + stdioReads.length = 0; + const answer = await bothAsPlain({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_unmasked_order' }); + expect(stdioReads.find((r) => r.object === 'rc_policy')?.context).toMatchObject({ userId: 'usr_plain', tenantId: 'org_1' }); + expect(answer.isError).toBe(false); + expect(answer.payload.data.record.id).toBe('p1'); + expect(answer.payload.data).not.toHaveProperty('related'); + expect(answer.payload.notes.map((n: { kind: string }) => n.kind)).toEqual(['not_visible']); + expect(answer.payload.notes[0]).not.toHaveProperty('object'); + // No section, row, count or field name of the child (the pack's own label, "Steps by serial", is the author's). + for (const word of ['rc_step', '"serial"', 'N-', 'Step s']) expect(answer.text).not.toContain(word); + // Control leg: the same pack, as the caller whose capability lifts the rule, reads the section. + const control = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_unmasked_order' }); + expect(control.payload.notes).toEqual([]); + expect(control.payload.data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['s4', 's2', 's3', 's1']); + }); + + it('[ADR-0160 D3] an orderBy on a registry-injected field (created_at) is accepted by the own-field check and by both doors', async () => { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_created_order' }); + expect(answer.isError).toBe(false); + expect(answer.payload.notes).toEqual([]); + expect(answer.payload.data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['s4', 's3', 's2', 's1']); + }); + + it('[ADR-0160 D3: every cut is stated] under a deployment page cap below the cut plus its probe row, both doors cut one row under the cap and state it', async () => { + const plain = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_steps' }); + expect(plain.payload.data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['s1', 's3', 's2', 's4']); + const saved = process.env.OS_DATA_MAX_PAGE_SIZE; + process.env.OS_DATA_MAX_PAGE_SIZE = '3'; + try { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_steps' }); + expect(answer.isError).toBe(false); + const { data, notes } = answer.payload; + expect(data.related[0].truncated).toBe(true); + expect(data.related[0].rows.map((r: { id: string }) => r.id)).toEqual(['s1', 's3']); + expect(notes).toEqual([{ kind: 'related_truncated', object: 'rc_step', text: expect.stringContaining('2') }]); + } finally { + if (saved === undefined) delete process.env.OS_DATA_MAX_PAGE_SIZE; + else process.env.OS_DATA_MAX_PAGE_SIZE = saved; + } + }); + it('an anchor the body does not resolve is one coded answer', async () => { const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main', anchor: 'nowhere' }); expect(answer.isError).toBe(true); 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 4c1303a05fc..53ace66a78f 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 @@ -242,15 +242,89 @@ describe('get_record_context — the order of judgement (ADR-0160 D4)', () => { }); }); -describe('get_record_context — object level: one refusal is the whole call\'s, within the naming bound (ADR-0160 D3/D4)', () => { - it('a child the caller is not served is refused PERMISSION_DENIED without naming it', async () => { - const refused = await refusalOf(run(policyApp({ unservedObjects: ['policy_revision'] }))); +describe('get_record_context — object level: a gate that refuses everyone refuses the whole call, within the naming bound (ADR-0160 D3/D4)', () => { + /** The fixture pack with a second, served related child (`claim`) beside `policy_revision`. */ + const twoChildren = (overrides: Partial = {}): FakeApp => { + const app = policyApp(overrides); + app.packs = [{ + name: 'policy_document', + label: 'Policy document', + object: 'policy', + fields: ['title'], + related: [ + { object: 'policy_revision', field: 'policy', fields: ['version'] }, + { object: 'claim', field: 'policy', fields: ['number'] }, + ], + }]; + return app; + }; + + it('[as amended] a child this caller is not served is left out: the root and the served child, ONE not-visible statement, the child named nowhere', async () => { + const door = fakeDoor(twoChildren({ unservedObjects: ['policy_revision'] })); + const out = await executeGetRecordContext(CALL, door); + expect(out.data.fields.map((f) => f.name)).toEqual(['title']); + expect(out.data.related!.map((l) => l.object)).toEqual(['claim']); + expect(out.data.related![0].rows.map((r) => r.id)).toEqual(['c1']); + expect(out.notes).toEqual([{ kind: 'not_visible', text: sentencesFor([]).notVisible }]); + const text = JSON.stringify(out); + expect(text).not.toContain('policy_revision'); + expect(text).not.toContain('Policy revision'); + // Nothing of the child is read after its object-level judgement, its published definition included. + expect(door.asked.filter((a) => a.object === 'policy_revision').map((a) => a.member)) + .toEqual(['readGuard', 'assertApiExposed', 'servedObjectDefinitionOf']); + // Control: served, both children answer and nothing is stated. + const control = await run(twoChildren()); + expect(control.data.related!.map((l) => l.object)).toEqual(['policy_revision', 'claim']); + expect(control.notes).toEqual([]); + }); + + it('[as amended] a lookup target reached only through a left-out child is not judged: it refuses nothing', async () => { + const app = twoChildren({ unservedObjects: ['policy_revision'], guardedObjects: ['account'] }); + (app.packs[0] as { related: Array<{ fields: string[] }> }).related[0].fields = ['version', 'reviewer']; + const door = fakeDoor(app); + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related!.map((l) => l.object)).toEqual(['claim']); + expect(door.asked).not.toContainEqual({ member: 'readGuard', object: 'account' }); + }); + + it('a child API exposure refuses whose caller is not served it either is refused unnamed (the naming bound)', async () => { + const refused = await refusalOf(run(twoChildren({ unexposedObjects: ['policy_revision'], unservedObjects: ['policy_revision'] }))); expect(refused).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); expect(refused.message).toContain('policy_document'); - expect(refused.message).toContain('policy'); expect(refused.message).not.toContain('policy_revision'); }); + it('a disabled-package child is refused whole, before its served definition is asked: a disabled package serves its object to nobody', async () => { + const door = fakeDoor(twoChildren({ unservedObjects: ['policy_revision'] })); + const exposedOf = door.assertApiExposed.bind(door); + door.assertApiExposed = async (object, action) => { + if (object === 'policy_revision') { + door.asked.push({ member: 'assertApiExposed', object }); + throw Object.assign(new Error(`Object '${object}' belongs to a disabled package`), { code: 'OBJECT_PACKAGE_DISABLED', status: 404 }); + } + return exposedOf(object, action); + }; + const refused = await refusalOf(executeGetRecordContext(CALL, door)); + expect(refused).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(refused.message).not.toContain('policy_revision'); + expect(refused.message).not.toContain('disabled package'); + expect(door.asked).not.toContainEqual({ member: 'servedObjectDefinitionOf', object: 'policy_revision' }); + expect(door.reads).toEqual([]); + }); + + it('a served-definition read that throws is no answer about this caller: it refuses the call unnamed, never left out', async () => { + const door = fakeDoor(twoChildren()); + const servedOf = door.servedObjectDefinitionOf.bind(door); + door.servedObjectDefinitionOf = async (object) => { + if (object === 'policy_revision') throw new Error('metadata store down: policy_revision'); + return servedOf(object); + }; + const refused = await refusalOf(executeGetRecordContext(CALL, door)); + expect(refused).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(refused.message).not.toContain('policy_revision'); + expect(door.reads).toEqual([]); + }); + it('a child the read guard refuses is refused with the same code, unnamed', async () => { const refused = await refusalOf(run(policyApp({ guardedObjects: ['policy_revision'] }))); expect(refused.code).toBe('PERMISSION_DENIED'); @@ -272,13 +346,16 @@ describe('get_record_context — object level: one refusal is the whole call\'s, it('a child\'s gates are judged before ANY read of its definition, the published one included', async () => { for (const app of [ policyApp({ guardedObjects: ['policy_revision'] }), - policyApp({ unservedObjects: ['policy_revision'] }), policyApp({ unexposedObjects: ['policy_revision'] }), ]) { const door = fakeDoor(app); await refusalOf(executeGetRecordContext(CALL, door)); expect(door.asked).not.toContainEqual({ member: 'publishedObjectDefinitionOf', object: 'policy_revision' }); } + // [as amended] A child left out for this caller is not read either. + const leftOut = fakeDoor(policyApp({ unservedObjects: ['policy_revision'] })); + await executeGetRecordContext(CALL, leftOut); + expect(leftOut.asked).not.toContainEqual({ member: 'publishedObjectDefinitionOf', object: 'policy_revision' }); const door = fakeDoor(policyApp()); await executeGetRecordContext(CALL, door); const at = (member: string) => door.asked.findIndex((a) => a.member === member && a.object === 'policy_revision'); @@ -418,6 +495,55 @@ describe('get_record_context — row level (ADR-0160 D3)', () => { expect((listRead?.opts as { limit: number }).limit).toBe(RECORD_CONTEXT_RELATED_MAX_ROWS + 1); }); + /** + * [ADR-0160 D3: every cut is stated] A door whose page cap is below the cut + * plus its probe row: this fake cuts a larger page silently, the way a door + * that clamps would, so without its cap the executor would carry a cut list + * as whole. + */ + const cappedDoor = (app: FakeApp, cap: number | undefined) => { + const door = fakeDoor(app); + const queryOf = door.query.bind(door); + door.query = async (object, opts) => + queryOf(object, { ...opts, ...(cap !== undefined && typeof opts.limit === 'number' ? { limit: Math.min(opts.limit, cap) } : {}) }); + door.pageCap = () => cap; + return door; + }; + const longApp = (rows: number) => { + const app = policyApp(); + app.records.policy_revision = Array.from({ length: rows }, (_, i) => ({ id: `r${i}`, version: `v${i}`, policy: 'p1', reviewer: 'a1', note: 'n' })); + return app; + }; + + it('a door whose page cap is below the cut plus its probe row is asked for at most its cap; the list is cut one row under it, and stated', async () => { + const door = cappedDoor(longApp(25), 5); + const out = await executeGetRecordContext(CALL, door); + const list = out.data.related![0]; + expect(list.rows).toHaveLength(4); + expect(list.truncated).toBe(true); + expect(out.notes).toEqual([ + { kind: 'related_truncated', object: 'policy_revision', text: sentencesFor([]).relatedTruncated('policy_revision', 4) }, + ]); + const listRead = door.reads.find((r) => r.member === 'query' && r.object === 'policy_revision'); + expect((listRead?.opts as { limit: number }).limit).toBe(5); + // A list that fits under the door's cap is carried whole, with nothing stated. + const short = await executeGetRecordContext(CALL, cappedDoor(longApp(4), 5)); + expect(short.data.related![0].rows).toHaveLength(4); + expect(short.data.related![0].truncated).toBeUndefined(); + expect(short.notes).toEqual([]); + }); + + it('a door cap at or above the cut plus its probe row, or no answer, changes nothing', async () => { + for (const cap of [RECORD_CONTEXT_RELATED_MAX_ROWS + 1, 500, undefined, 0, 2.5]) { + const door = fakeDoor(longApp(25)); + door.pageCap = () => cap; + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related![0].rows).toHaveLength(RECORD_CONTEXT_RELATED_MAX_ROWS); + const listRead = door.reads.find((r) => r.member === 'query' && r.object === 'policy_revision'); + expect((listRead?.opts as { limit: number }).limit).toBe(RECORD_CONTEXT_RELATED_MAX_ROWS + 1); + } + }); + it('a list the agent ceiling narrowed carries the security service\'s own sentence', async () => { const out = await run(policyApp({ narrowed: { policy_revision: 'Narrowed by the agent ceiling.' } })); expect(out.notes).toEqual([{ kind: 'narrowed', object: 'policy_revision', text: 'Narrowed by the agent ceiling.' }]); @@ -581,6 +707,19 @@ describe('get_record_context — a related list\'s where, orderBy and limit (ADR expect(out.notes).toEqual([]); }); + it('an orderBy on a registry-injected field (`created_at`) that both definitions carry reads the list in that order', async () => { + const app = filteredApp({ orderBy: [{ field: 'created_at', order: 'desc' }] }); + (app.objects.policy_revision as { fields: Record }).fields.created_at = { + name: 'created_at', type: 'datetime', label: 'Created at', readonly: true, + }; + app.records.policy_revision = app.records.policy_revision.map((r, i) => ({ ...r, created_at: `2026-11-0${i + 1}T00:00:00Z` })); + const door = fakeDoor(app); + const out = await executeGetRecordContext(CALL, door); + expect(out.data.related![0].rows.map((r) => r.id)).toEqual(['r3', 'r2', 'r1']); + expect(out.notes).toEqual([]); + expect(listReads(door)[0].opts).toMatchObject({ orderBy: [{ field: 'created_at', order: 'desc' }] }); + }); + it('the read set is the same with and without the three keys', async () => { const metadataOf = (app: FakeApp) => ({ listContextPacks: async () => app.packs, diff --git a/packages/services/service-record-context/src/door.ts b/packages/services/service-record-context/src/door.ts index c100e57e269..e0528b20552 100644 --- a/packages/services/service-record-context/src/door.ts +++ b/packages/services/service-record-context/src/door.ts @@ -51,7 +51,9 @@ export interface RecordContextDoor { * 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. + * second amendment): still one query. The door decides each expansion + * target's API exposure: a target it does not expose is left unexpanded, + * so the lookup carries no id and no name (ADR-0160 D3 "Object level"). */ query( objectName: string, @@ -83,6 +85,15 @@ export interface RecordContextDoor { * probe states no narrowing. */ diagnoseDelegation?(objectName: string): Promise<{ narrowed: boolean; statement?: string } | undefined>; + /** + * [ADR-0160 D3] The most rows one `query` of this door may ask for: the + * deployment's page limits where the door refuses (or cuts) a larger page. + * The executor never asks a related list for more: a list whose cut plus + * its probe row is above the cap is read with at most the cap and cut one + * row under it, and the cut is stated. OPTIONAL: absent, or `undefined`, + * the door caps nothing below the executor's own cut. + */ + pageCap?(): number | undefined | Promise; /** The caller's locale ladder for the executor's sentences. OPTIONAL: `en`. */ userTextLocales?(): Promise; /** 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 9925919192d..c4cd29690aa 100644 --- a/packages/services/service-record-context/src/record-context-tools.ts +++ b/packages/services/service-record-context/src/record-context-tools.ts @@ -53,19 +53,24 @@ import { sentencesFor, type Sentences } from './sentences.js'; * caller they refuse gets `get_record`'s answer, the same whether or not a * pack exists. * 3. Pack selection, with no fallback ({@link selectContextPack}). - * 4. Each `related` child at object level (the same three gates); then the - * field-level projection onto the definitions as the caller is served them; - * then the surviving lookups' targets (the read guard `query_records`' - * `expand` puts before an expansion); then the reads. + * 4. Each `related` child at object level (the read guard, API exposure, then + * whether this caller is served it); then the field-level projection onto + * the definitions as the caller is served them; then the surviving lookups' + * targets (the read guard `query_records`' `expand` puts before an + * expansion); then the reads. * - * ## Object level refuses the whole call; field level omits and states (D3) + * ## What refuses the whole call, and what omits and states (D3, as amended) * - * A refused child or lookup target refuses the call with `PERMISSION_DENIED` - * and no partial pack. The refusal names the pack and the root, and the - * refused object only when the caller's served schema shows it (the naming - * bound). A field the caller's served schema hides is not named: the entry, a - * related section whose link it is, or the body, is left out, and the notes - * carry one statement that some material is not visible. A field the served + * A gate that refuses everyone refuses the call with `PERMISSION_DENIED` and + * no partial pack: the read guard or API exposure (a disabled package + * included) on a related child, and any gate on a surviving lookup's target. + * The refusal names the pack and the root, and the refused object only when + * the caller's served schema shows it (the naming bound). A related child + * that passes both and that THIS caller is not served is left out: nothing of + * it is read again, its section is not named, and the notes carry the one + * not-visible statement. A field the caller's served schema hides is not + * named: the entry, a related section whose link it is, or the body, is left + * out, and the notes carry the same statement. A field the served * 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. @@ -74,7 +79,10 @@ import { sentencesFor, type Sentences } from './sentences.js'; * * 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 + * row cap) as the cut, stated when it cuts. A door whose page cap + * ({@link RecordContextDoor.pageCap}) is below that cut plus the probe row is + * asked for at most its cap, and the list is cut one row under it and stated, + * so no door cuts or refuses a list the answer does not say was cut. 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 @@ -284,6 +292,18 @@ async function queryableAmong( return true; } +/** + * [ADR-0160 D3] The door's page cap ({@link RecordContextDoor.pageCap}): a + * whole number of rows of at least one, else `undefined` (no member, no cap, + * or an answer that is no cap). A probe that throws fails the call, as the + * door's own read would. + */ +async function pageCapOf(door: RecordContextDoor): Promise { + if (typeof door.pageCap !== 'function') return undefined; + const cap = await door.pageCap(); + return typeof cap === 'number' && Number.isSafeInteger(cap) && cap >= 1 ? cap : undefined; +} + /** One `related` entry, planned after projection. */ interface RelatedPlan { object: string; @@ -368,33 +388,56 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex 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. + // its published definition included. [ADR-0160 D3 "Object level", as + // amended] The gates that apply to everyone come first and refuse the + // whole call: the read guard (the system-object refusal), then API + // exposure, whose refusals include a disabled package's + // `OBJECT_PACKAGE_DISABLED` (a disabled package's object is not served + // to anyone either, so judging exposure after the served definition + // would read it as this caller's narrowing). A child that passes both + // and that THIS caller is not served is left out: never named, never + // read again, with the one not-visible statement. const childServed = new Map>(); + const leftOut = new Set(); for (const entry of pack.related ?? []) { + if (childServed.has(entry.object) || leftOut.has(entry.object)) continue; const guarded = await door.readGuard(entry.object); if (guarded !== undefined) await refuseObject(entry.object, false); + try { + await door.assertApiExposed(entry.object, 'query'); + } catch (err) { + // Only API exposure's own refusal is about the object itself, and it is + // named only when the caller's served schema shows the object (the + // naming bound); any other failure (a package gate, an outage) names + // nothing. + let shown = false; + if (API_EXPOSURE_REFUSALS.has(String((err as { code?: unknown } | null)?.code))) { + shown = (await door.servedObjectDefinitionOf(entry.object).catch(() => null)) != null; + } + await refuseObject(entry.object, shown); + } let served: Record | null; try { served = await door.servedObjectDefinitionOf(entry.object); } catch { - served = null; + // A read that failed is no answer about this caller: it refuses, unnamed. + return refuseObject(entry.object, false); } - if (!served) await refuseObject(entry.object, false); - try { - await door.assertApiExposed(entry.object, 'query'); - } catch (err) { - // Only API exposure's own refusal is about an object the caller's schema - // shows; any other failure (a package gate, an outage) names nothing. - await refuseObject(entry.object, API_EXPOSURE_REFUSALS.has(String((err as { code?: unknown } | null)?.code))); + if (!served) { + leftOut.add(entry.object); + hidden = true; + continue; } - childServed.set(entry.object, served as Record); + childServed.set(entry.object, served); } // Every published-definition read from here on is of an object whose gates // already passed; one that still throws refuses the call unnamed, so no // door's own rendering of the failure can name what the caller is not shown. + // A child left out for this caller is never read, its definition included: + // the plan reads it as having no published definition. const publishedOf = async (name: string): Promise | null> => { + if (leftOut.has(name)) return null; try { return await door.publishedObjectDefinitionOf(name); } catch { @@ -523,12 +566,20 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex } for (const name of rootFields) if (rootWithheld.has(name)) withheldNames.push(name); + // [ADR-0160 D3] The door's page cap, asked once: a list is never read with + // more rows than one of the door's queries may ask for, so a door that would + // refuse or cut a larger page is asked for at most its cap, and the cut below + // it is stated like any other. + const doorCap = relatedPlans.length > 0 ? await pageCapOf(door) : undefined; + const related: RecordContextRelatedList[] = []; for (const plan of relatedPlans) { // 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; + // and one row past the cut to know whether the cut cut anything. Below the + // door's page cap, the cut is one row under it, so the probe row still fits. + const cap = doorCap !== undefined ? Math.min(plan.cap, doorCap - 1) : plan.cap; + const probe = 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( @@ -540,8 +591,8 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex limit: probe, }), ); - const truncated = rows.length > plan.cap; - const kept = truncated ? rows.slice(0, plan.cap) : rows; + const truncated = rows.length > cap; + const kept = truncated ? rows.slice(0, 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[] = []; @@ -565,7 +616,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, plan.cap) }); + notes.push({ kind: 'related_truncated', object: plan.object, text: say.relatedTruncated(plan.object, 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/src/ai/record-context-tools.zod.ts b/packages/spec/src/ai/record-context-tools.zod.ts index 8925e8c5375..7e880d08acf 100644 --- a/packages/spec/src/ai/record-context-tools.zod.ts +++ b/packages/spec/src/ai/record-context-tools.zod.ts @@ -120,8 +120,8 @@ export const RecordContextRelatedListSchema = lazySchema(() => z.object({ object: z.string().describe('The child object'), label: z.string().describe('The child object\'s plural label at the caller\'s locale'), field: z.string().describe('The child\'s field that points at the record'), - rows: z.array(RecordContextRelatedRowSchema).describe('The rows the caller may read, up to the row cap'), - truncated: z.literal(true).optional().describe('Present when more rows existed past the row cap'), + rows: z.array(RecordContextRelatedRowSchema).describe('The rows the caller may read, up to the list\'s `limit` (the row cap when it names none), or fewer when the door\'s page cap is lower'), + truncated: z.literal(true).optional().describe('Present when more rows existed past the rows given: at the list\'s `limit`, at the row cap, or below either at the door\'s page cap'), })); /** One heading of a body outline. */ @@ -175,7 +175,8 @@ export const RecordContextDataSchema = lazySchema(() => z.object({ * - `outline_truncated` — the outline was cut at the service's outline bounds: * its sentence says how many headings are not listed (every heading's anchor * still reads its section); - * - `related_truncated` — the related list on `object` was cut at the row cap; + * - `related_truncated` — the related list on `object` was cut: at its entry's + * `limit`, at the row cap, or below either at the door's page cap; * - `narrowed` — the agent ceiling narrows what the caller reads on `object` * (the security service's sentence, relayed as the probe returns it). */ diff --git a/packages/types/src/query-read-limits.test.ts b/packages/types/src/query-read-limits.test.ts index 781f06ae787..abbeec7cd72 100644 --- a/packages/types/src/query-read-limits.test.ts +++ b/packages/types/src/query-read-limits.test.ts @@ -22,6 +22,7 @@ import { assertQueryReadRows, planQueryReadWindow, resolveQueryReadLimits, + resolveQueryReadPageCap, type QueryReadRequest, } from './query-read-limits.js'; @@ -70,6 +71,26 @@ describe('resolveQueryReadLimits — host configuration', () => { }); }); +describe('resolveQueryReadPageCap — the most rows one offset-0 read may ask for', () => { + it('is undefined when neither limit is set', () => { + expect(resolveQueryReadPageCap({})).toBeUndefined(); + }); + + it('is the one limit that is set', () => { + expect(resolveQueryReadPageCap({ [DATA_MAX_PAGE_SIZE_ENV]: '40' })).toBe(40); + expect(resolveQueryReadPageCap({ [DATA_QUERY_ROW_BUDGET_ENV]: '12' })).toBe(12); + }); + + it('is the smaller of the two when both are set', () => { + expect(resolveQueryReadPageCap({ [DATA_MAX_PAGE_SIZE_ENV]: '40', [DATA_QUERY_ROW_BUDGET_ENV]: '12' })).toBe(12); + expect(resolveQueryReadPageCap({ [DATA_MAX_PAGE_SIZE_ENV]: '5', [DATA_QUERY_ROW_BUDGET_ENV]: '12' })).toBe(5); + }); + + it('throws on an unreadable value, as the limits do', () => { + expect(() => resolveQueryReadPageCap({ [DATA_MAX_PAGE_SIZE_ENV]: 'ten' })).toThrow(DATA_MAX_PAGE_SIZE_ENV); + }); +}); + describe('planQueryReadWindow — no limits configured leaves every read untouched', () => { it('returns the caller\'s own limit, or none', () => { expect(planQueryReadWindow(list(), {})).toEqual({}); diff --git a/packages/types/src/query-read-limits.ts b/packages/types/src/query-read-limits.ts index eaf3df6ed20..3f90354a30f 100644 --- a/packages/types/src/query-read-limits.ts +++ b/packages/types/src/query-read-limits.ts @@ -158,6 +158,22 @@ export function resolveQueryReadLimits( }; } +/** + * The most rows one read starting at offset 0 may ask for on this deployment: + * the smaller of {@link QueryReadLimits.maxPageSize} and + * {@link QueryReadLimits.rowBudget}, `undefined` when neither is set. The data + * door refuses, never clamps, a read past either, so a caller that cuts its + * own read to fit (ADR-0160 D3's record-context page cap) asks this one value + * on every door, and the doors cut at the same row. + */ +export function resolveQueryReadPageCap( + env: Record = typeof process !== 'undefined' ? process.env : {}, +): number | undefined { + const { maxPageSize, rowBudget } = resolveQueryReadLimits(env); + const caps = [maxPageSize, rowBudget].filter((n): n is number => n !== undefined); + return caps.length > 0 ? Math.min(...caps) : undefined; +} + /** One read, as the window planner sees it. */ export interface QueryReadRequest { readonly surface: QueryReadSurface;