From 32aba545983608ea7b5787ffeb82d95c829267e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:40:52 +0000 Subject: [PATCH 1/4] fix(record-context): a related object's read that fails is a failure, not a refusal At the reads of a related object get_record_context judges (step 4a's exposure check and served definition, a published definition, the child list query), one helper tells a coded refusal from a failure: a refusal answers as before, a failure fails the call SERVICE_UNAVAILABLE (503) naming the pack and the root only, with the original on cause. The citation verifier reads the same classifier. Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- .changeset/37463-record-context-outage.md | 12 ++ .../mcp-record-context-tools-bridge.test.ts | 23 ++++ .../__tests__/record-context-tools.test.ts | 96 +++++++++++++++- .../src/__tests__/verify-citations.test.ts | 27 +++++ .../src/record-context-tools.ts | 108 ++++++++++++++---- .../service-record-context/src/sentences.ts | 6 + .../src/verify-citations.ts | 37 ++---- 7 files changed, 255 insertions(+), 54 deletions(-) create mode 100644 .changeset/37463-record-context-outage.md diff --git a/.changeset/37463-record-context-outage.md b/.changeset/37463-record-context-outage.md new file mode 100644 index 00000000000..580d606cf3d --- /dev/null +++ b/.changeset/37463-record-context-outage.md @@ -0,0 +1,12 @@ +--- +'@objectstack/service-record-context': patch +--- + +fix(record-context): a related object's read that fails is answered as a failure, not as "no access" + +Clause-②: no +Metadata-protocol: none + +`get_record_context` reads each related object of a pack before it answers: the object's API exposure, its definition as the caller is served it, its published definition, and the related list itself. When one of those reads failed for a reason that is not a refusal (the database or the metadata store down, a bug), the call was refused `PERMISSION_DENIED` (403), as if the caller could not read the object. Such a failure now fails the call `SERVICE_UNAVAILABLE` (503). Its sentence names the pack and the root record's object only, never the related object, a field, a package or what the failed read said; the original error is on the thrown error's `cause` for the host. A coded refusal at the same reads, a disabled package's included, is refused `PERMISSION_DENIED` (403) as before. + +`verifyRecordCitations` therefore reports such a failure through `onError` (its citations are still dropped), where it used to drop them without a report. It reads the line between a refusal and a failure with the same rule as the executor: a refusal is a throw with a string `code` and a declared 4xx status. A host that retries or logs on `onError` now sees outages behind a pack with related lists. 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 fb9ccad51f2..4df2af8dc1b 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -776,6 +776,29 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(answer.text).not.toContain('rc_off'); }); + it('[ADR-0112] a related child whose list read fails (an outage, no coded refusal) fails the call SERVICE_UNAVAILABLE on both doors, naming nothing, never as a refusal', async () => { + const OUTAGE = 'disk I/O error reading rc_revision.version'; + const real = engine.find.bind(engine); + const failing = vi.spyOn(engine, 'find').mockImplementation(async (object: string, ...rest: any[]) => { + if (object === 'rc_revision') throw new Error(OUTAGE); + return (real as any)(object, ...rest); + }); + try { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + // Reached through each door, so the answer is the outage's on both. + expect(failing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(2); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word); + } finally { + failing.mockRestore(); + } + // Control: the same call reads once the list read answers. + const control = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(control.isError).toBe(false); + expect(control.payload.data.related[0]).toMatchObject({ object: 'rc_revision' }); + }); + 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); 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 6f1120d0680..399269ddc0e 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 @@ -314,11 +314,13 @@ describe('get_record_context — object level: a gate that refuses everyone refu 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 () => { + it('a served-definition read that throws a coded refusal 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'); + if (object === 'policy_revision') { + throw Object.assign(new Error(`Object '${object}' not found`), { code: 'OBJECT_NOT_FOUND', status: 404 }); + } return servedOf(object); }; const refused = await refusalOf(executeGetRecordContext(CALL, door)); @@ -402,6 +404,96 @@ describe('get_record_context — object level: a gate that refuses everyone refu }); }); +describe('get_record_context — a read of a related object that fails is a failure, not a refusal (ADR-0112, ADR-0160 D3 "Object level")', () => { + /** What the outage says: every name in it is one the caller is not shown. */ + const OUTAGE = 'store down: policy_revision.secret_note in package acme_private'; + const outage = () => new Error(OUTAGE); + + /** The thrown failure, with what it must not carry. */ + async function failureOf(promise: Promise): Promise<{ code: string; status: number; message: string; cause: unknown }> { + try { + await promise; + } catch (err) { + const e = err as { code: string; status: number; message: string; cause: unknown }; + return { code: e.code, status: e.status, message: e.message, cause: e.cause }; + } + throw new Error('expected a failure'); + } + + /** A door whose `member` throws `thrown()` for `policy_revision`, and answers as the fixture otherwise. */ + const throwingAt = ( + member: 'assertApiExposed' | 'servedObjectDefinitionOf' | 'publishedObjectDefinitionOf' | 'query', + thrown: () => unknown, + app: FakeApp = policyApp(), + ) => { + const door = fakeDoor(app); + const real = (door[member] as (...a: unknown[]) => Promise).bind(door); + (door as unknown as Record)[member] = async (object: string, ...rest: unknown[]) => { + if (object === 'policy_revision') throw thrown(); + return real(object, ...rest); + }; + return door; + }; + + /** The failure's answer: `SERVICE_UNAVAILABLE` 503, naming the pack and the root and nothing the outage said. */ + const expectFailureNamingNothing = (failed: Awaited>, original: unknown) => { + expect(failed).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(failed.message).toBe(sentencesFor([]).readFailed('policy_document', 'policy')); + for (const word of ['policy_revision', 'secret_note', 'acme_private', 'store down']) { + expect(failed.message).not.toContain(word); + } + // The original is the host's, on `cause` (which no door puts on the wire). + expect(failed.cause).toBe(original); + }; + + it.each([ + ['step 4a: the API-exposure check', 'assertApiExposed'], + ['step 4a: the served-definition read', 'servedObjectDefinitionOf'], + ['publishedOf: the published-definition read', 'publishedObjectDefinitionOf'], + ['the child list query', 'query'], + ] as const)('%s throwing an uncoded error fails the call SERVICE_UNAVAILABLE, naming nothing', async (_site, member) => { + const thrown = outage(); + const door = throwingAt(member, () => thrown); + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, door)), thrown); + }); + + it.each([ + ['step 4a: the API-exposure check', 'assertApiExposed'], + ['step 4a: the served-definition read', 'servedObjectDefinitionOf'], + ['publishedOf: the published-definition read', 'publishedObjectDefinitionOf'], + ] as const)('control, %s: a coded refusal (a disabled package\'s 404) stays PERMISSION_DENIED 403, unnamed', async (_site, member) => { + const door = throwingAt(member, () => + Object.assign(new Error("Object 'policy_revision' belongs to a disabled package"), { code: 'OBJECT_PACKAGE_DISABLED', status: 404 })); + const refused = await refusalOf(executeGetRecordContext(CALL, door)); + expect(refused).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(refused.message).toBe(sentencesFor([]).objectRefusedUnnamed('policy_document', 'policy')); + }); + + it('control, the child list query: the door\'s own coded refusal of a served child is answered as the door wrote it', async () => { + const refusal = Object.assign(new Error("Field 'version' cannot be filtered or sorted on"), { code: 'PERMISSION_DENIED', status: 403 }); + const door = throwingAt('query', () => refusal); + await expect(executeGetRecordContext(CALL, door)).rejects.toBe(refusal); + }); + + it.each<[string, () => unknown]>([ + ['a driver errno on `.code` with no status', () => Object.assign(new Error(OUTAGE), { code: 'SQLITE_BUSY' })], + ['a coded 5xx', () => Object.assign(new Error(OUTAGE), { code: 'SERVICE_UNAVAILABLE', status: 503 })], + ['a status with no code', () => Object.assign(new Error(OUTAGE), { status: 404 })], + ['a thrown value that is not an object', () => OUTAGE], + ])('%s is a failure too, not a refusal', async (_label, thrown) => { + let original: unknown; + const door = throwingAt('servedObjectDefinitionOf', () => (original = thrown())); + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, door)), original); + }); + + it('the failure sentence is written in the caller\'s locale', async () => { + const door = throwingAt('publishedObjectDefinitionOf', outage, policyApp({ locales: ['zh-CN'] })); + const failed = await failureOf(executeGetRecordContext(CALL, door)); + expect(failed.message).toBe(sentencesFor(['zh-CN']).readFailed('policy_document', 'policy')); + expect(failed.message).not.toBe(sentencesFor([]).readFailed('policy_document', 'policy')); + }); +}); + describe('get_record_context — field level: omit and state, or name the withheld (ADR-0160 D3)', () => { it('a field the caller\'s schema hides is not named, and the notes carry ONE not-visible statement', async () => { const out = await run(policyApp({ hiddenFields: { policy: ['secret_terms'], policy_revision: ['note'] } })); diff --git a/packages/services/service-record-context/src/__tests__/verify-citations.test.ts b/packages/services/service-record-context/src/__tests__/verify-citations.test.ts index de62cb0e7d9..9d4022e0301 100644 --- a/packages/services/service-record-context/src/__tests__/verify-citations.test.ts +++ b/packages/services/service-record-context/src/__tests__/verify-citations.test.ts @@ -217,6 +217,33 @@ describe('[ADR-0160 D9] a refusal and a failure', () => { expect((await run(throwingDoor(fault), [cite('Fire cover')])).reported.map((r) => r.error)).toEqual([fault]); }); + it('a related child\'s read that throws an uncoded error drops the citation and is reported; a coded refusal there is dropped and not reported', async () => { + /** A door whose served-definition read of the related child throws `err`. */ + const childThrows = (err: unknown): FakeDoor => { + const door = fakeDoor(policyApp()); + const servedOf = door.servedObjectDefinitionOf.bind(door); + door.servedObjectDefinitionOf = async (object) => { + if (object === 'policy_revision') throw err; + return servedOf(object); + }; + return door; + }; + // Control: the same citation verifies through a door whose child read answers. + expect((await run(fakeDoor(policyApp()), [cite('Fire cover')])).quotes).toEqual(['Fire cover']); + + const outage = new Error('metadata store down: policy_revision'); + const failed = await run(childThrows(outage), [cite('Fire cover')]); + expect(failed.quotes).toEqual([]); + expect(failed.reported).toHaveLength(1); + expect(failed.reported[0].call).toEqual({ object: 'policy', id: 'p1' }); + // The executor's failure, naming nothing, with the outage on its cause. + expect(failed.reported[0].error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, cause: outage }); + expect((failed.reported[0].error as Error).message).not.toContain('policy_revision'); + + const refusal = Object.assign(new Error("Object 'policy_revision' not found"), { code: 'OBJECT_NOT_FOUND', status: 404 }); + expect(await run(childThrows(refusal), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] }); + }); + it('reports a 4xx with no code, and a thrown value that is not an Error, as failures', async () => { for (const err of [Object.assign(new Error('gone'), { status: 404 }), 'socket hang up', undefined]) { const { quotes, reported } = await run(throwingDoor(err), [cite('Fire cover')]); 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 d953a7d334e..74d1834cb46 100644 --- a/packages/services/service-record-context/src/record-context-tools.ts +++ b/packages/services/service-record-context/src/record-context-tools.ts @@ -75,6 +75,11 @@ import { sentencesFor, type Sentences } from './sentences.js'; * carries no value and is marked `withheld` (#35137). A name the published * definition lacks is an author defect and states nothing. * + * A read of a related object that FAILS rather than refuses (a throw that is + * no coded refusal, {@link isCodedRefusal}: an outage, a bug) is no answer + * about the caller, so it is never answered as a refusal: the call fails + * `SERVICE_UNAVAILABLE` (503), naming the pack and the root only. + * * ## A related list's `where`, `orderBy` and `limit` (D1, D3: second amendment) * * They run inside the one capped child query, as the caller: `where` joined @@ -136,6 +141,31 @@ function refusal(code: string, status: number, message: string): Coded { return Object.assign(new Error(message), { code, status }); } +/** + * [ADR-0112] Whether a throw is a coded refusal: a non-empty string `code` + * and a declared 4xx status, read as ADR-0112's reader reads it + * (`resolveThrownHttpError`'s `declaredStatus`, `@objectstack/types`): + * `.status`, then `.statusCode`. Anything else is a failure, not an answer + * about the caller: no code, no status, a 5xx, a driver errno on `.code` + * with no status, a thrown value that is not an object (an outage, a bug). + * ADR-0112 names the status channel as the one structural signal between a + * refusal and a fault; a driver errno also arrives on `.code`, so the string + * alone cannot tell. + * + * The one line, drawn once for both of its readers: the executor asks it at + * every read of a related object it judges ({@link executeGetRecordContext}, + * step 4a, the published definitions, the child list query), and the + * citation verifier asks it of the executor's own throw + * (`verifyRecordCitations`). So what the executor refuses, the verifier + * drops without a report, and what fails, it reports. + */ +export function isCodedRefusal(err: unknown): boolean { + if (err == null || typeof err !== 'object') return false; + const { code, status, statusCode } = err as { code?: unknown; status?: unknown; statusCode?: unknown }; + const declared = typeof status === 'number' ? status : typeof statusCode === 'number' ? statusCode : undefined; + return typeof code === 'string' && code.length > 0 && declared !== undefined && declared >= 400 && declared < 500; +} + /** The call's arguments, or a `VALIDATION_ERROR` carrying the spec's own words. */ function parseInput(input: unknown): GetRecordContextInput { const parsed = GetRecordContextInputSchema.safeParse(input); @@ -387,6 +417,27 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex ); }; + // [ADR-0112, ADR-0160 D3 "Object level"] The one line between a refusal and + // a failure at the reads of a related object this executor judges: step + // 4a's exposure check and served definition, a published definition + // (`publishedOf`), and the child list query. A coded refusal + // ({@link isCodedRefusal}) answers as `refused` says, as it always has. Any + // other throw is a failure, which says nothing about what this caller may + // read, so it is not answered as a refusal: the call fails + // `SERVICE_UNAVAILABLE` (503) in the executor's own sentence, which names + // the pack and the root only. No door renders the original error, so + // nothing it says can name an object, a field or a package the caller is + // not shown; it rides on `cause`, which no door puts on the wire, for the + // host (the citation verifier hands it to `onError`). + const refusedOrFailed = async (err: unknown, refused: () => Promise): Promise => { + if (isCodedRefusal(err)) return refused(); + throw Object.assign(new Error(say.readFailed(pack.name, root)), { + code: 'SERVICE_UNAVAILABLE', + status: 503, + cause: err, + }); + }; + // Whether something the pack covers was left out for this caller: the one // not-visible statement, whatever was removed. let hidden = false; @@ -410,22 +461,25 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex 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); + // A coded refusal refuses the call. 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 refusal + // (a disabled package's) names nothing. A failure fails the call. + await refusedOrFailed(err, async () => { + let shown = false; + if (API_EXPOSURE_REFUSALS.has(String((err as { code?: unknown }).code))) { + shown = (await door.servedObjectDefinitionOf(entry.object).catch(() => null)) != null; + } + return refuseObject(entry.object, shown); + }); } let served: Record | null; try { served = await door.servedObjectDefinitionOf(entry.object); - } catch { - // A read that failed is no answer about this caller: it refuses, unnamed. - return refuseObject(entry.object, false); + } catch (err) { + // A coded refusal refuses, unnamed; a read that failed is no answer + // about this caller, so it fails the call, naming nothing. + return refusedOrFailed(err, () => refuseObject(entry.object, false)); } if (!served) { leftOut.add(entry.object); @@ -436,16 +490,17 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex } // 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. + // already passed; one that still throws a coded refusal refuses the call + // unnamed, and one that fails fails it, naming nothing, so no door's own + // rendering of either 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 { - return refuseObject(name, false); + } catch (err) { + return refusedOrFailed(err, () => refuseObject(name, false)); } }; // The read set is the plan: every object read below is one of these. @@ -586,15 +641,24 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex 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( - await door.query(plan.object, { + let read: unknown; + try { + read = await door.query(plan.object, { where: plan.where !== undefined ? { $and: [linkWhere, plan.where] } : linkWhere, fields: projection, ...(plan.orderBy ? { orderBy: plan.orderBy } : {}), ...(plan.lookups.length > 0 ? { expand: plan.lookups } : {}), limit: probe, - }), - ); + }); + } catch (err) { + // The child is one this caller is served (step 4a), so the door's own + // coded refusal of the query is answered as the door wrote it, as it + // always was; a query that failed fails the call, naming nothing. + return refusedOrFailed(err, async () => { + throw err; + }); + } + const rows = rowsOf(read); const truncated = rows.length > cap; const kept = truncated ? rows.slice(0, cap) : rows; const childWithheld = await withheldAmong(door, plan.object, plan.columns); diff --git a/packages/services/service-record-context/src/sentences.ts b/packages/services/service-record-context/src/sentences.ts index d985ac87671..81018cff360 100644 --- a/packages/services/service-record-context/src/sentences.ts +++ b/packages/services/service-record-context/src/sentences.ts @@ -103,6 +103,10 @@ const WRITTEN = { objectRefusedUnnamed: (pack: string, root: string) => `Context pack '${pack}' on '${root}' reads an object you cannot read, so the pack cannot be read for you. ` + 'Nothing was returned. Read the record with get_record.', + // A failure, not a refusal: it says nothing about what the caller may read. + readFailed: (pack: string, root: string) => + `Context pack '${pack}' on '${root}' could not be read just now: a read it needs failed. This says nothing ` + + 'about what you may read. Nothing was returned. Try again later, or read the record with get_record.', anchorUnresolved: (anchor: string) => `No section '${anchor}' can be read through this pack for this record. Call get_record_context without ` + '\'anchor\' to read the current outline.', @@ -146,6 +150,8 @@ const WRITTEN = { `'${root}' 上的资料包 '${pack}' 会读取对象 '${object}',而本入口不向你提供它,因此无法为你读取这个资料包。没有返回任何内容。请用 get_record 读取记录。`, objectRefusedUnnamed: (pack: string, root: string) => `'${root}' 上的资料包 '${pack}' 会读取一个你无权读取的对象,因此无法为你读取这个资料包。没有返回任何内容。请用 get_record 读取记录。`, + readFailed: (pack: string, root: string) => + `'${root}' 上的资料包 '${pack}' 暂时无法读取:它需要的一次读取失败了。这与你能读取什么无关。没有返回任何内容。请稍后再试,或用 get_record 读取记录。`, anchorUnresolved: (anchor: string) => `无法通过这个资料包为这条记录读取章节 '${anchor}'。请不带 'anchor' 调用 get_record_context 以读取当前大纲。`, outlineFromUnresolved: (from: number) => diff --git a/packages/services/service-record-context/src/verify-citations.ts b/packages/services/service-record-context/src/verify-citations.ts index 5d81d1ffbac..c27c13cccd3 100644 --- a/packages/services/service-record-context/src/verify-citations.ts +++ b/packages/services/service-record-context/src/verify-citations.ts @@ -10,7 +10,7 @@ import { } from '@objectstack/spec/ai'; import { isHtmlBodyType } from './body-outline.js'; import type { RecordContextDoor } from './door.js'; -import { executeGetRecordContext } from './record-context-tools.js'; +import { executeGetRecordContext, isCodedRefusal } from './record-context-tools.js'; /** * [ADR-0160 D9, third amendment] The citation verifier: which citations of an @@ -48,11 +48,11 @@ import { executeGetRecordContext } from './record-context-tools.js'; * refusal and a fault; a driver errno also arrives on `.code`, so the * string alone cannot tell. * - * That holds at this function's boundary only. The executor itself turns - * some failures into a refusal so that it names nothing: a related object's - * definition read, or a published-definition read, that throws arrives here - * as `PERMISSION_DENIED` 403, and is dropped without a report (#37463). - * The whole 4xx band is a refusal, so a door that declared a coded 408 or + * The executor draws the same line with the same reader + * (`isCodedRefusal`) at the reads of a related object it judges, so a + * failure there is no refusal either: it arrives here as + * `SERVICE_UNAVAILABLE` (503), naming nothing, with the original error on + * its `cause`, and is reported. The whole 4xx band is a refusal, so a door that declared a coded 408 or * 429 would have a transient condition dropped without a report; no door on * the read path declares one today. * - **What a quote is matched against** — the strings of the data member, and @@ -153,32 +153,9 @@ export interface VerifyingCall { anchor?: string; } -/** - * Whether a throw is an ADR-0112 refusal: a non-empty string `code` and a - * declared 4xx status. Anything else is a failure. - */ -function isRefusal(err: unknown): boolean { - if (err == null || typeof err !== 'object') return false; - const { code } = err as { code?: unknown }; - const status = declaredStatusOf(err); - return typeof code === 'string' && code.length > 0 && status !== undefined && status >= 400 && status < 500; -} - -/** - * The status a throw declares, read as ADR-0112's reader reads it: - * `.status`, then `.statusCode` (`resolveThrownHttpError`'s `declaredStatus`, - * `@objectstack/types`). Both spellings are produced in this repo. - */ -function declaredStatusOf(err: object): number | undefined { - const { status, statusCode } = err as { status?: unknown; statusCode?: unknown }; - if (typeof status === 'number') return status; - if (typeof statusCode === 'number') return statusCode; - return undefined; -} - /** Hand a failure to the host; a callback that throws changes nothing. */ function report(onError: VerifyRecordCitationsOptions['onError'], err: unknown, c: RecordCitationParsed): void { - if (onError === undefined || isRefusal(err)) return; + if (onError === undefined || isCodedRefusal(err)) return; const call: VerifyingCall = { object: c.object, id: c.id, From c8f14ddd91b10e6b806cf5b097924aca39c0d809 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:27:58 +0000 Subject: [PATCH 2/4] fix(record-context): an outage fails INTERNAL_ERROR and logs as a fault; door refusals at the list read stay A failure at a related object's read now answers INTERNAL_ERROR (500): SERVICE_UNAVAILABLE with a 5xx is a declared capability absence the doors log once per route at warn without the error. At the child list query the executor asks the /data door's own classifier (mapDataError), so a sandboxed hook's plain throw stays 400 HOOK_ABORTED and a status-less PERMISSION_DENIED stays 403; only a door fault fails. Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- .changeset/37463-record-context-outage.md | 10 ++- .../mcp-record-context-tools-bridge.test.ts | 50 ++++++++++++- .../service-record-context/package.json | 3 +- .../__tests__/record-context-tools.test.ts | 25 ++++++- .../src/__tests__/verify-citations.test.ts | 2 +- .../src/record-context-tools.ts | 74 ++++++++++++------- .../src/verify-citations.ts | 9 ++- pnpm-lock.yaml | 3 + 8 files changed, 137 insertions(+), 39 deletions(-) diff --git a/.changeset/37463-record-context-outage.md b/.changeset/37463-record-context-outage.md index 580d606cf3d..d6c8f6e9c37 100644 --- a/.changeset/37463-record-context-outage.md +++ b/.changeset/37463-record-context-outage.md @@ -7,6 +7,12 @@ fix(record-context): a related object's read that fails is answered as a failure Clause-②: no Metadata-protocol: none -`get_record_context` reads each related object of a pack before it answers: the object's API exposure, its definition as the caller is served it, its published definition, and the related list itself. When one of those reads failed for a reason that is not a refusal (the database or the metadata store down, a bug), the call was refused `PERMISSION_DENIED` (403), as if the caller could not read the object. Such a failure now fails the call `SERVICE_UNAVAILABLE` (503). Its sentence names the pack and the root record's object only, never the related object, a field, a package or what the failed read said; the original error is on the thrown error's `cause` for the host. A coded refusal at the same reads, a disabled package's included, is refused `PERMISSION_DENIED` (403) as before. +`get_record_context` reads each related object of a pack before it answers: the object's API exposure, its definition as the caller is served it, its published definition, and the related list itself. When one of the first three reads failed for a reason that is not a refusal (the database or the metadata store down, a bug), the call was refused `PERMISSION_DENIED` (403), as if the caller could not read the object. When the related-list read failed that way, the raw error left the executor and the MCP doors answered it `INTERNAL_ERROR` (500). Such a failure now fails the call `INTERNAL_ERROR` (500) at all four reads, and the thrown error carries the original on `cause`. -`verifyRecordCitations` therefore reports such a failure through `onError` (its citations are still dropped), where it used to drop them without a report. It reads the line between a refusal and a failure with the same rule as the executor: a refusal is a throw with a string `code` and a declared 4xx status. A host that retries or logs on `onError` now sees outages behind a pack with related lists. +What an MCP caller sees for it, on either door: `{ code: 'INTERNAL_ERROR', status: 500 }` with the message `Internal server error`. The doors withhold a 5xx's own sentence, so the executor's sentence (which names the pack and the root record's object only) is read in-process only, for example by the host of `verifyRecordCitations`. Nothing names the related object, a field, a package or what the failed read said. Each door logs the failure at `error` on every call, with the thrown error and its `cause`. + +A refusal at the same reads is answered as before. At the first three reads a coded refusal (a string `code` with a declared 4xx status, a disabled package's included) refuses `PERMISSION_DENIED` (403). At the related-list read, a throw the `/data` door answers below 500 is left to the door as before: a sandboxed `beforeFind` hook's plain throw still answers `400 HOOK_ABORTED`, and a `PERMISSION_DENIED` with no status still answers 403. + +`verifyRecordCitations` therefore reports such a failure through `onError` (its citations are still dropped), where at the first three reads it used to drop them without a report. A host that retries or logs on `onError` now sees outages behind a pack with related lists. + +The package gains one dependency, `@objectstack/types` (already a dependency of `@objectstack/core`), for the `/data` door's classifier the related-list read asks. 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 4df2af8dc1b..d3011af9334 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -776,22 +776,38 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(answer.text).not.toContain('rc_off'); }); - it('[ADR-0112] a related child whose list read fails (an outage, no coded refusal) fails the call SERVICE_UNAVAILABLE on both doors, naming nothing, never as a refusal', async () => { + it('[ADR-0112] a related child whose list read fails (an outage, no coded refusal) fails the call INTERNAL_ERROR on both doors, naming nothing, never as a refusal', async () => { const OUTAGE = 'disk I/O error reading rc_revision.version'; const real = engine.find.bind(engine); const failing = vi.spyOn(engine, 'find').mockImplementation(async (object: string, ...rest: any[]) => { if (object === 'rc_revision') throw new Error(OUTAGE); return (real as any)(object, ...rest); }); + // The doors' fault log (`logServerFault`, `@objectstack/types`) writes to the console here. + const errorLines = vi.spyOn(console, 'error').mockImplementation(() => {}); + const warnLines = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); // Reached through each door, so the answer is the outage's on both. expect(failing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(2); expect(answer.isError).toBe(true); - expect(answer.payload.error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(answer.payload.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word); + // An outage is a fault, never a declared capability absence: each door logs it at error, + // with the thrown error and the outage on its cause, on every call, the second included. + await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + const faults = errorLines.mock.calls.filter(([line]) => + typeof line === 'string' && line.startsWith('[5xx] 500') && line.includes('get_record_context rc_policy')); + expect(faults).toHaveLength(4); + for (const [, err] of faults) { + expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + expect(String((err as { cause?: { message?: unknown } }).cause?.message)).toContain(OUTAGE); + } + expect(warnLines.mock.calls.filter(([line]) => String(line).includes('capability absence'))).toEqual([]); } finally { failing.mockRestore(); + errorLines.mockRestore(); + warnLines.mockRestore(); } // Control: the same call reads once the list read answers. const control = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); @@ -799,6 +815,36 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(control.payload.data.related[0]).toMatchObject({ object: 'rc_revision' }); }); + it.each<[string, () => unknown, Record]>([ + [ + 'a sandboxed beforeFind hook\'s plain throw stays 400 HOOK_ABORTED, in the hook\'s words', + () => Object.assign(new Error("beforeFind hook 'rc_gate' threw: Revisions are closed for review"), { innerMessage: 'Revisions are closed for review' }), + { code: 'HOOK_ABORTED', status: 400, message: 'Revisions are closed for review' }, + ], + [ + 'a PERMISSION_DENIED with no status stays 403', + () => Object.assign(new Error('Permission denied'), { code: 'PERMISSION_DENIED' }), + { code: 'PERMISSION_DENIED', status: 403 }, + ], + ])('[ADR-0112] at the related list read, a throw the /data door answers as a refusal stays that refusal on both doors: %s', async (_label, thrown, expected) => { + const real = engine.find.bind(engine); + const refusing = vi.spyOn(engine, 'find').mockImplementation(async (object: string, ...rest: any[]) => { + if (object === 'rc_revision') throw thrown(); + return (real as any)(object, ...rest); + }); + try { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(refusing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(2); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject(expected); + } finally { + refusing.mockRestore(); + } + const control = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(control.isError).toBe(false); + expect(control.payload.data.related[0]).toMatchObject({ object: 'rc_revision' }); + }); + 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); diff --git a/packages/services/service-record-context/package.json b/packages/services/service-record-context/package.json index cc88ee493f5..c7425fb3c9f 100644 --- a/packages/services/service-record-context/package.json +++ b/packages/services/service-record-context/package.json @@ -27,7 +27,8 @@ }, "dependencies": { "@objectstack/core": "workspace:*", - "@objectstack/spec": "workspace:*" + "@objectstack/spec": "workspace:*", + "@objectstack/types": "workspace:*" }, "devDependencies": { "@types/node": "^26.6.5", 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 399269ddc0e..7a0885f3b40 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 @@ -435,9 +435,9 @@ describe('get_record_context — a read of a related object that fails is a fail return door; }; - /** The failure's answer: `SERVICE_UNAVAILABLE` 503, naming the pack and the root and nothing the outage said. */ + /** The failure's answer: `INTERNAL_ERROR` 500, naming the pack and the root and nothing the outage said. */ const expectFailureNamingNothing = (failed: Awaited>, original: unknown) => { - expect(failed).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(failed).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); expect(failed.message).toBe(sentencesFor([]).readFailed('policy_document', 'policy')); for (const word of ['policy_revision', 'secret_note', 'acme_private', 'store down']) { expect(failed.message).not.toContain(word); @@ -451,7 +451,7 @@ describe('get_record_context — a read of a related object that fails is a fail ['step 4a: the served-definition read', 'servedObjectDefinitionOf'], ['publishedOf: the published-definition read', 'publishedObjectDefinitionOf'], ['the child list query', 'query'], - ] as const)('%s throwing an uncoded error fails the call SERVICE_UNAVAILABLE, naming nothing', async (_site, member) => { + ] as const)('%s throwing an uncoded error fails the call INTERNAL_ERROR, naming nothing', async (_site, member) => { const thrown = outage(); const door = throwingAt(member, () => thrown); expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, door)), thrown); @@ -476,7 +476,24 @@ describe('get_record_context — a read of a related object that fails is a fail }); it.each<[string, () => unknown]>([ - ['a driver errno on `.code` with no status', () => Object.assign(new Error(OUTAGE), { code: 'SQLITE_BUSY' })], + ['a sandboxed beforeFind hook\'s plain throw (no code; the door answers 400 HOOK_ABORTED)', () => + Object.assign(new Error("beforeFind hook 'step_gate' threw: Steps are closed for review"), { innerMessage: 'Steps are closed for review' })], + ['a PERMISSION_DENIED with no status (the door answers 403)', () => Object.assign(new Error('denied'), { code: 'PERMISSION_DENIED' })], + ])('the child list query: %s stays the door\'s refusal, rethrown as main left it', async (_label, thrown) => { + const refusal = thrown(); + const door = throwingAt('query', () => refusal); + await expect(executeGetRecordContext(CALL, door)).rejects.toBe(refusal); + // Control: at an object-level read, the same throw is no coded refusal, so it fails the call. + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, throwingAt('servedObjectDefinitionOf', () => refusal))), refusal); + }); + + it('the child list query: a sandboxed body that CRASHED (a native error name) is a fault at the door, so it fails the call', async () => { + const crash = Object.assign(new Error("beforeFind hook 'step_gate' threw: TypeError: x is not a function"), { innerMessage: 'TypeError: x is not a function' }); + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, throwingAt('query', () => crash))), crash); + }); + + it.each<[string, () => unknown]>([ + ['a driver errno on `.code` with no status',() => Object.assign(new Error(OUTAGE), { code: 'SQLITE_BUSY' })], ['a coded 5xx', () => Object.assign(new Error(OUTAGE), { code: 'SERVICE_UNAVAILABLE', status: 503 })], ['a status with no code', () => Object.assign(new Error(OUTAGE), { status: 404 })], ['a thrown value that is not an object', () => OUTAGE], diff --git a/packages/services/service-record-context/src/__tests__/verify-citations.test.ts b/packages/services/service-record-context/src/__tests__/verify-citations.test.ts index 9d4022e0301..bb955ec9dde 100644 --- a/packages/services/service-record-context/src/__tests__/verify-citations.test.ts +++ b/packages/services/service-record-context/src/__tests__/verify-citations.test.ts @@ -237,7 +237,7 @@ describe('[ADR-0160 D9] a refusal and a failure', () => { expect(failed.reported).toHaveLength(1); expect(failed.reported[0].call).toEqual({ object: 'policy', id: 'p1' }); // The executor's failure, naming nothing, with the outage on its cause. - expect(failed.reported[0].error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, cause: outage }); + expect(failed.reported[0].error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500, cause: outage }); expect((failed.reported[0].error as Error).message).not.toContain('policy_revision'); const refusal = Object.assign(new Error("Object 'policy_revision' not found"), { code: 'OBJECT_NOT_FOUND', status: 404 }); 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 74d1834cb46..277798ac0d8 100644 --- a/packages/services/service-record-context/src/record-context-tools.ts +++ b/packages/services/service-record-context/src/record-context-tools.ts @@ -1,6 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { recordNotFoundError, wrapRecordMaterial } from '@objectstack/core'; +import { isServerFault, mapDataError } from '@objectstack/types'; import { AI_CONTEXT_BODY_FIELD_TYPES, AI_CONTEXT_MAX_RELATED_ROWS, @@ -76,9 +77,10 @@ import { sentencesFor, type Sentences } from './sentences.js'; * definition lacks is an author defect and states nothing. * * A read of a related object that FAILS rather than refuses (a throw that is - * no coded refusal, {@link isCodedRefusal}: an outage, a bug) is no answer - * about the caller, so it is never answered as a refusal: the call fails - * `SERVICE_UNAVAILABLE` (503), naming the pack and the root only. + * no coded refusal, {@link isCodedRefusal}, or at the child list query one + * the `/data` door answers as a fault: an outage, a bug) is no answer about + * the caller, so it is never answered as a refusal: the call fails + * `INTERNAL_ERROR` (500), naming the pack and the root only. * * ## A related list's `where`, `orderBy` and `limit` (D1, D3: second amendment) * @@ -153,11 +155,13 @@ function refusal(code: string, status: number, message: string): Coded { * alone cannot tell. * * The one line, drawn once for both of its readers: the executor asks it at - * every read of a related object it judges ({@link executeGetRecordContext}, - * step 4a, the published definitions, the child list query), and the - * citation verifier asks it of the executor's own throw - * (`verifyRecordCitations`). So what the executor refuses, the verifier - * drops without a report, and what fails, it reports. + * the object-level reads of a related object ({@link executeGetRecordContext}, + * step 4a and the published definitions), and the citation verifier asks it + * of the executor's own throw (`verifyRecordCitations`). So what the executor + * refuses there, the verifier drops without a report, and what fails, it + * reports. The child list query alone asks the `/data` door's classifier + * instead, since the doors classified that read's throw before the executor + * caught it, and a refusal there is rethrown as the door reads it. */ export function isCodedRefusal(err: unknown): boolean { if (err == null || typeof err !== 'object') return false; @@ -421,19 +425,31 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex // a failure at the reads of a related object this executor judges: step // 4a's exposure check and served definition, a published definition // (`publishedOf`), and the child list query. A coded refusal - // ({@link isCodedRefusal}) answers as `refused` says, as it always has. Any + // ({@link isCodedRefusal}; at the child list query, what the `/data` door + // answers below 500) answers as `refused` says, as it always has. Any // other throw is a failure, which says nothing about what this caller may - // read, so it is not answered as a refusal: the call fails - // `SERVICE_UNAVAILABLE` (503) in the executor's own sentence, which names - // the pack and the root only. No door renders the original error, so - // nothing it says can name an object, a field or a package the caller is - // not shown; it rides on `cause`, which no door puts on the wire, for the - // host (the citation verifier hands it to `onError`). - const refusedOrFailed = async (err: unknown, refused: () => Promise): Promise => { - if (isCodedRefusal(err)) return refused(); + // read, so it is not answered as a refusal: the call fails `INTERNAL_ERROR` + // (500) in the executor's own sentence, which names the pack and the root + // only. No door renders the original error, so nothing it says can name an + // object, a field or a package the caller is not shown; it rides on + // `cause`, which no door puts on the wire. The doors withhold a 5xx's + // sentence too (`Internal server error`), so the sentence is read + // in-process only (the citation verifier's host, through `onError`). + // + // ⛔ Not `SERVICE_UNAVAILABLE`: with a 5xx that code is a declared + // capability absence (`CAPABILITY_ABSENCE_CODES`, `@objectstack/types` + // `server-fault-log.ts`), which the doors' fault log prints once per route + // per process at `warn`, without the error. An outage is a fault: logged at + // `error`, with the thrown error and its `cause`, on every call. + const refusedOrFailed = async ( + err: unknown, + refused: () => Promise, + isRefusal: (err: unknown) => boolean = isCodedRefusal, + ): Promise => { + if (isRefusal(err)) return refused(); throw Object.assign(new Error(say.readFailed(pack.name, root)), { - code: 'SERVICE_UNAVAILABLE', - status: 503, + code: 'INTERNAL_ERROR', + status: 500, cause: err, }); }; @@ -651,12 +667,20 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex limit: probe, }); } catch (err) { - // The child is one this caller is served (step 4a), so the door's own - // coded refusal of the query is answered as the door wrote it, as it - // always was; a query that failed fails the call, naming nothing. - return refusedOrFailed(err, async () => { - throw err; - }); + // The child is one this caller is served (step 4a). Its list read is the + // one read whose throw the doors classified before this line existed, + // so what the `/data` door answers below 500 stays the door's refusal, + // rethrown as the door reads it (a sandboxed `beforeFind` hook's plain + // throw: `400 HOOK_ABORTED`; a `PERMISSION_DENIED` with no status: 403), + // asked of the door's own classifier, never a copy of it. A throw the + // door answers as a fault fails the call, naming nothing. + return refusedOrFailed( + err, + async () => { + throw err; + }, + (thrown) => !isServerFault(mapDataError(thrown, plan.object).status), + ); } const rows = rowsOf(read); const truncated = rows.length > cap; diff --git a/packages/services/service-record-context/src/verify-citations.ts b/packages/services/service-record-context/src/verify-citations.ts index c27c13cccd3..8a78e507e84 100644 --- a/packages/services/service-record-context/src/verify-citations.ts +++ b/packages/services/service-record-context/src/verify-citations.ts @@ -49,10 +49,11 @@ import { executeGetRecordContext, isCodedRefusal } from './record-context-tools. * string alone cannot tell. * * The executor draws the same line with the same reader - * (`isCodedRefusal`) at the reads of a related object it judges, so a - * failure there is no refusal either: it arrives here as - * `SERVICE_UNAVAILABLE` (503), naming nothing, with the original error on - * its `cause`, and is reported. The whole 4xx band is a refusal, so a door that declared a coded 408 or + * (`isCodedRefusal`) at the object-level reads of a related object it + * judges, and at its child list query asks the `/data` door's classifier, + * so a failure there is no refusal either: it arrives here as + * `INTERNAL_ERROR` (500), naming nothing, with the original error on its + * `cause`, and is reported. The whole 4xx band is a refusal, so a door that declared a coded 408 or * 429 would have a transient condition dropped without a report; no door on * the read path declares one today. * - **What a quote is matched against** — the strings of the data member, and diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0f3012c670a..b7659acf658 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3493,6 +3493,9 @@ importers: '@objectstack/spec': specifier: workspace:* version: link:../../spec + '@objectstack/types': + specifier: workspace:* + version: link:../../types devDependencies: '@types/node': specifier: ^26.6.5 From 53e65504edc2d9a31382f22fd8bf7f19f962193d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:43:19 +0000 Subject: [PATCH 3/4] fix(record-context): the outage's cause reaches the fault line; pin the door's refusals at the list read The doors' fault line prints an error's message and stack, never its cause, so the failure's stack ends with the original. The harness pins an error line per call per door with the outage in it, and the two refusals the /data door answers below 500 at the list read. Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- .../mcp-record-context-tools-bridge.test.ts | 14 +++++++------ .../__tests__/record-context-tools.test.ts | 10 +++++---- .../src/record-context-tools.ts | 21 +++++++++++++++++-- 3 files changed, 33 insertions(+), 12 deletions(-) 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 d3011af9334..3048167b369 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -794,14 +794,14 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(answer.payload.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word); // An outage is a fault, never a declared capability absence: each door logs it at error, - // with the thrown error and the outage on its cause, on every call, the second included. + // with the outage as its cause, on every call, the second included. await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); const faults = errorLines.mock.calls.filter(([line]) => typeof line === 'string' && line.startsWith('[5xx] 500') && line.includes('get_record_context rc_policy')); expect(faults).toHaveLength(4); - for (const [, err] of faults) { - expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); - expect(String((err as { cause?: { message?: unknown } }).cause?.message)).toContain(OUTAGE); + for (const [, meta] of faults) { + expect(meta).toMatchObject({ status: 500, code: 'INTERNAL_ERROR' }); + expect(String((meta as { stack?: unknown }).stack)).toContain(`Caused by: Error: ${OUTAGE}`); } expect(warnLines.mock.calls.filter(([line]) => String(line).includes('capability absence'))).toEqual([]); } finally { @@ -822,9 +822,9 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: { code: 'HOOK_ABORTED', status: 400, message: 'Revisions are closed for review' }, ], [ - 'a PERMISSION_DENIED with no status stays 403', + 'a PERMISSION_DENIED with no status stays PERMISSION_DENIED, as the door renders it', () => Object.assign(new Error('Permission denied'), { code: 'PERMISSION_DENIED' }), - { code: 'PERMISSION_DENIED', status: 403 }, + { code: 'PERMISSION_DENIED' }, ], ])('[ADR-0112] at the related list read, a throw the /data door answers as a refusal stays that refusal on both doors: %s', async (_label, thrown, expected) => { const real = engine.find.bind(engine); @@ -837,6 +837,8 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(refusing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(2); expect(answer.isError).toBe(true); expect(answer.payload.error).toMatchObject(expected); + // The door's refusal, as main answered it: never the fault's 500. + expect([undefined, 400, 403]).toContain(answer.payload.error.status); } finally { refusing.mockRestore(); } 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 7a0885f3b40..9f2e29c7915 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 @@ -410,12 +410,12 @@ describe('get_record_context — a read of a related object that fails is a fail const outage = () => new Error(OUTAGE); /** The thrown failure, with what it must not carry. */ - async function failureOf(promise: Promise): Promise<{ code: string; status: number; message: string; cause: unknown }> { + async function failureOf(promise: Promise): Promise<{ code: string; status: number; message: string; cause: unknown; stack?: string }> { try { await promise; } catch (err) { - const e = err as { code: string; status: number; message: string; cause: unknown }; - return { code: e.code, status: e.status, message: e.message, cause: e.cause }; + const e = err as { code: string; status: number; message: string; cause: unknown; stack?: string }; + return { code: e.code, status: e.status, message: e.message, cause: e.cause, stack: e.stack }; } throw new Error('expected a failure'); } @@ -442,8 +442,10 @@ describe('get_record_context — a read of a related object that fails is a fail for (const word of ['policy_revision', 'secret_note', 'acme_private', 'store down']) { expect(failed.message).not.toContain(word); } - // The original is the host's, on `cause` (which no door puts on the wire). + // The original is the host's, on `cause` (which no door puts on the wire), and at the foot of the + // stack, which the doors' fault line prints where it prints no `cause`. expect(failed.cause).toBe(original); + expect(failed.stack).toContain(`Caused by: ${original instanceof Error ? original.stack : String(original)}`); }; it.each([ 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 277798ac0d8..a2fe90f0055 100644 --- a/packages/services/service-record-context/src/record-context-tools.ts +++ b/packages/services/service-record-context/src/record-context-tools.ts @@ -170,6 +170,17 @@ export function isCodedRefusal(err: unknown): boolean { return typeof code === 'string' && code.length > 0 && declared !== undefined && declared >= 400 && declared < 500; } +/** A thrown value as a log reads it: its stack, else its text. */ +function describeThrown(thrown: unknown): string { + if (thrown instanceof Error) return thrown.stack ?? `${thrown.name}: ${thrown.message}`; + if (typeof thrown === 'string') return thrown; + try { + return JSON.stringify(thrown) ?? String(thrown); + } catch { + return String(thrown); + } +} + /** The call's arguments, or a `VALIDATION_ERROR` carrying the spec's own words. */ function parseInput(input: unknown): GetRecordContextInput { const parsed = GetRecordContextInputSchema.safeParse(input); @@ -432,7 +443,8 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex // (500) in the executor's own sentence, which names the pack and the root // only. No door renders the original error, so nothing it says can name an // object, a field or a package the caller is not shown; it rides on - // `cause`, which no door puts on the wire. The doors withhold a 5xx's + // `cause` and at the foot of the stack, neither of which a door puts on the + // wire, and the doors' fault line prints it. The doors withhold a 5xx's // sentence too (`Internal server error`), so the sentence is read // in-process only (the citation verifier's host, through `onError`). // @@ -447,11 +459,16 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex isRefusal: (err: unknown) => boolean = isCodedRefusal, ): Promise => { if (isRefusal(err)) return refused(); - throw Object.assign(new Error(say.readFailed(pack.name, root)), { + const failure = Object.assign(new Error(say.readFailed(pack.name, root)), { code: 'INTERNAL_ERROR', status: 500, cause: err, }); + // The doors' fault line prints an error's message and stack, never its + // `cause` (`logServerFault`, and `ObjectLogger` behind it), so the stack + // carries the original too. A stack is never on the wire. + failure.stack = `${failure.stack ?? `Error: ${failure.message}`}\nCaused by: ${describeThrown(err)}`; + throw failure; }; // Whether something the pack covers was left out for this caller: the one From bd03a37ed869418622699397ed127f0dccdceea6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:46:08 +0000 Subject: [PATCH 4/4] test(runtime): read the outage's fault lines before its answer Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc Co-authored-by: Claude --- .../src/mcp-record-context-tools-bridge.test.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) 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 3048167b369..da3059d9a53 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -788,14 +788,10 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: const warnLines = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); - // Reached through each door, so the answer is the outage's on both. - expect(failing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(2); - expect(answer.isError).toBe(true); - expect(answer.payload.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); - for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word); + await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); // An outage is a fault, never a declared capability absence: each door logs it at error, // with the outage as its cause, on every call, the second included. - await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(warnLines.mock.calls.filter(([line]) => String(line).includes('capability absence'))).toEqual([]); const faults = errorLines.mock.calls.filter(([line]) => typeof line === 'string' && line.startsWith('[5xx] 500') && line.includes('get_record_context rc_policy')); expect(faults).toHaveLength(4); @@ -803,7 +799,11 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(meta).toMatchObject({ status: 500, code: 'INTERNAL_ERROR' }); expect(String((meta as { stack?: unknown }).stack)).toContain(`Caused by: Error: ${OUTAGE}`); } - expect(warnLines.mock.calls.filter(([line]) => String(line).includes('capability absence'))).toEqual([]); + // Reached through each door, so the answer is the outage's on both. + expect(failing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(4); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word); } finally { failing.mockRestore(); errorLines.mockRestore();