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..0a85899015e --- /dev/null +++ b/.changeset/37361-record-context-left-out-queryable-doors.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-record-context': patch +'@objectstack/runtime': patch +'@objectstack/mcp': patch +'@objectstack/spec': 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-②: no +Metadata-protocol: none + +ADR-0160 D3 "Object level", as amended, and its second amendment. No pack, key or code changes. + +- **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 now says a list is cut at its entry's `limit`, at the row cap, or at the door's page cap. diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 85529bba0e6..00821ed4607 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 { resolveQueryReadLimits, 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. @@ -192,6 +192,21 @@ import { type ObjectSchemaReadDelegateSource, } from '@objectstack/metadata-core'; +/** + * [ADR-0160 D3] The most rows one record-context read may ask for, offset 0: + * the smaller of the deployment's maximum page size and its query row budget + * (`resolveQueryReadLimits`), `undefined` when neither is set. This + * transport's engine read plans no read window of its own, but the limits are + * one value per deployment, which the `/mcp` door's data door refuses past and + * `query_records` probes within on this transport too; asked of both doors, a + * principal's pack is cut at the same row on each, and the cut is stated. + */ +function recordContextPageCap(): number | undefined { + const { maxPageSize, rowBudget } = resolveQueryReadLimits(); + const caps = [maxPageSize, rowBudget].filter((n): n is number => n !== undefined); + return caps.length > 0 ? Math.min(...caps) : undefined; +} + /** * [#25138] The object reads this transport asks of the `protocol` service, * and the data door's internal-field gate beside them. Every member is optional: the slot is filled by name from a host-owned @@ -250,8 +265,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 +1936,19 @@ 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 ({@link recordContextPageCap}). + pageCap: () => recordContextPageCap(), 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..ca3a7009c44 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, resolveQueryReadLimits } 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: () => recordContextPageCap(), })); } return bridge; @@ -1778,6 +1796,20 @@ export async function resolveMcpRecordContextToolsService( return service && typeof service.recordContextTools === 'function' ? (service as McpRecordContextToolsService) : undefined; } +/** + * [ADR-0160 D3] The most rows one record-context read may ask the data door + * for, offset 0: the smaller of the deployment's maximum page size and its + * query row budget, `undefined` when neither is set. The data door refuses, + * never clamps, a read over either (`resolveQueryReadLimits`), so a related + * list asked for more would refuse the whole call instead of being cut and + * stated. + */ +function recordContextPageCap(): number | undefined { + const { maxPageSize, rowBudget } = resolveQueryReadLimits(); + const caps = [maxPageSize, rowBudget].filter((n): n is number => n !== undefined); + return caps.length > 0 ? Math.min(...caps) : undefined; +} + /** * [ADR-0160 D3/D4] The bridge's two record-context members. The door handed * to the executor is built per call from the bridge's own members — `get`, @@ -1795,6 +1827,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..8226ac80f85 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(); + } + }); }); /** @@ -368,6 +392,8 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: let dispatcher: HttpDispatcher; let caller: ExecutionContext; 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 +427,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 the caller's capability lifts: the security service lists it as + // queryable for this caller, where the contract's fallback never would. + 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 +453,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,10 +498,20 @@ 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({ - name: 'rc_member', label: 'Member', isDefault: true, + name: 'rc_member', label: 'Member', isDefault: true, systemPermissions: ['rc_unmask'], 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' }], @@ -462,6 +536,7 @@ 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); @@ -627,11 +702,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 +730,78 @@ 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] 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..13d669a1c54 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, amendment 4). */ 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..0d805ebd44f 100644 --- a/packages/spec/src/ai/record-context-tools.zod.ts +++ b/packages/spec/src/ai/record-context-tools.zod.ts @@ -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). */