From 88f220f0c9cf591132881261f479183ca0a986e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:56:11 +0000 Subject: [PATCH 1/3] feat(record-context): citation verifier reports failures apart from refusals A verifying call refused with an ADR-0112 coded 4xx still drops its citations silently; any other throw drops them too (fail-closed) and is handed to an optional onError, once per call. Doc nits: list cap, adjacent-text join, stripBodyTags is not a sanitizer. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZnFSe9yjMwBFr33Rk --- .../37418-citation-refusal-vs-failure.md | 17 +++ .../src/__tests__/verify-citations.test.ts | 76 ++++++++++++- .../service-record-context/src/index.ts | 1 + .../src/verify-citations.ts | 103 ++++++++++++++++-- packages/spec/src/ai/record-body-anchor.ts | 4 + 5 files changed, 187 insertions(+), 14 deletions(-) create mode 100644 .changeset/37418-citation-refusal-vs-failure.md diff --git a/.changeset/37418-citation-refusal-vs-failure.md b/.changeset/37418-citation-refusal-vs-failure.md new file mode 100644 index 00000000000..976120e462a --- /dev/null +++ b/.changeset/37418-citation-refusal-vs-failure.md @@ -0,0 +1,17 @@ +--- +'@objectstack/service-record-context': patch +'@objectstack/spec': patch +--- + +feat(record-context): the citation verifier tells a refusal from a failure and reports failures to the host + +Clause-②: no +Metadata-protocol: none + +ADR-0160 D9 verifies an answer's citations once, so a citation lost to an outage is lost for good. `verifyRecordCitations` used to drop a citation the same way whether the verifying call was refused or failed. + +- **A refusal** is a throw carrying an ADR-0112 `code` with a declared 4xx `status`, the only shape `get_record_context` refuses with. Its citations are dropped and nothing is reported, as before. +- **Any other throw** (no code, a driver code with no status, a 5xx) is a failure. Its citations are still dropped, so the result stays fail-closed, and the failure goes to the new optional `onError(error, call)` option, once per verifying call, so the host can log or retry. A callback that throws is ignored. +- A refused read and a missing record still give the host the same answer: dropped, not reported. +- New exported types `VerifyRecordCitationsOptions` and `VerifyingCall`. Existing two-argument calls are unchanged. +- Docs: the verifier says which list cap a producer gets (the first 20 read, where `RecordCitationsSchema` refuses 21) and that the tag-removed reading of an HTML body joins adjacent text, so it is not only stricter than matching as stored. `stripBodyTags` says it is not a sanitizer. 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 c8dbb87416b..07bbdfd8dda 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 @@ -12,8 +12,8 @@ import { describe, expect, it } from 'vitest'; import { RECORD_CITATIONS_MAX } from '@objectstack/spec/ai'; -import { executeGetRecordContext, verifyRecordCitations } from '../index.js'; -import { fakeDoor, policyApp, type FakeApp } from './fake-door.js'; +import { executeGetRecordContext, verifyRecordCitations, type VerifyingCall } from '../index.js'; +import { fakeDoor, policyApp, type FakeApp, type FakeDoor } from './fake-door.js'; const ROOT = { object: 'policy', id: 'p1' }; @@ -85,6 +85,11 @@ describe('[ADR-0160 D9] what a quote is matched against', () => { 'Covers fire', ]); } + // Removing a tag joins the text on either side: the tag-removed reading is + // not only stricter than matching as stored. + const joined = htmlApp('html'); + joined.records.policy[0].content = '

Fire

cover

'; + expect(await surviving(joined, [cite('Firecover')])).toEqual(['Firecover']); expect(await surviving(htmlApp('markdown'), [cite('Covers fire damage.'), cite('Covers fire')])).toEqual([ 'Covers fire', ]); @@ -150,6 +155,73 @@ describe('[ADR-0160 D9] a caller with no read access', () => { }); }); +describe('[ADR-0160 D9] a refusal and a failure', () => { + /** A door whose root read guard throws `err` instead of answering. */ + const throwingDoor = (err: unknown): FakeDoor => { + const door = fakeDoor(policyApp()); + door.readGuard = async () => { + throw err; + }; + return door; + }; + const coded = (code: string, status: number) => Object.assign(new Error(code), { code, status }); + + /** The surviving quotes and every failure the host was handed. */ + async function run(door: FakeDoor, citations: unknown[]) { + const reported: Array<{ error: unknown; call: VerifyingCall }> = []; + const verified = await verifyRecordCitations(citations, door, { onError: (error, call) => reported.push({ error, call }) }); + return { quotes: verified.map((c) => c.quote), reported }; + } + + it('drops the citations of a call that fails without a code and reports the failure, once per call', async () => { + // Control: the same citations verify through a door that answers. + expect((await run(fakeDoor(policyApp()), [cite('Fire cover'), cite('Acme')])).quotes).toEqual(['Fire cover', 'Acme']); + + const outage = new Error('connection reset'); + const { quotes, reported } = await run(throwingDoor(outage), [cite('Fire cover'), cite('Acme'), cite('Arson.', { anchor: 'exclusions' })]); + expect(quotes).toEqual([]); + expect(reported).toEqual([ + { error: outage, call: { object: 'policy', id: 'p1' } }, + { error: outage, call: { object: 'policy', id: 'p1', anchor: 'exclusions' } }, + ]); + }); + + it('reports a driver code with no status, and a coded 5xx, as failures', async () => { + for (const err of [Object.assign(new Error('reset'), { code: 'ECONNRESET' }), coded('INTERNAL_ERROR', 500)]) { + const { quotes, reported } = await run(throwingDoor(err), [cite('Fire cover')]); + expect(quotes).toEqual([]); + expect(reported.map((r) => r.error)).toEqual([err]); + } + }); + + it('drops the citations of a coded 4xx refusal and reports nothing', async () => { + for (const err of [coded('PERMISSION_DENIED', 403), coded('RECORD_NOT_FOUND', 404), coded('VALIDATION_ERROR', 400)]) { + expect(await run(throwingDoor(err), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] }); + } + }); + + it('gives the host the same answer for a refused read and a missing record', async () => { + const refused = await run(fakeDoor(policyApp({ unreadableRows: ['p1'] })), [cite('Fire cover')]); + const missing = await run(fakeDoor(policyApp()), [{ object: 'policy', id: 'p404', quote: 'Fire cover' }]); + expect(refused).toEqual({ quotes: [], reported: [] }); + expect(missing).toEqual(refused); + // Control: the readable record verifies the quote. + expect((await run(fakeDoor(policyApp()), [cite('Fire cover')])).quotes).toEqual(['Fire cover']); + }); + + it('never throws when the callback throws, and drops the failed call without one', async () => { + const door = throwingDoor(new Error('down')); + await expect( + verifyRecordCitations([cite('Fire cover')], door, { + onError: () => { + throw new Error('logger down'); + }, + }), + ).resolves.toEqual([]); + await expect(verifyRecordCitations([cite('Fire cover')], throwingDoor(new Error('down')))).resolves.toEqual([]); + }); +}); + describe('[ADR-0160 D9] the list', () => { it('makes one call per distinct (object, id, context, anchor)', async () => { const door = fakeDoor(policyApp()); diff --git a/packages/services/service-record-context/src/index.ts b/packages/services/service-record-context/src/index.ts index 2dc447157e0..f7ec8879f5b 100644 --- a/packages/services/service-record-context/src/index.ts +++ b/packages/services/service-record-context/src/index.ts @@ -15,6 +15,7 @@ export { export type { RecordContextTools } from './record-context-tools.js'; export type { RecordContextDoor } from './door.js'; export { verifyRecordCitations } from './verify-citations.js'; +export type { VerifyRecordCitationsOptions, VerifyingCall } from './verify-citations.js'; export { RECORD_CONTEXT_BODY_MAX_CHARS, RECORD_CONTEXT_OUTLINE_MAX_ENTRIES } from './body-outline.js'; export { contextPackCandidates, diff --git a/packages/services/service-record-context/src/verify-citations.ts b/packages/services/service-record-context/src/verify-citations.ts index c35fc72964d..75b446adbab 100644 --- a/packages/services/service-record-context/src/verify-citations.ts +++ b/packages/services/service-record-context/src/verify-citations.ts @@ -35,6 +35,15 @@ import { executeGetRecordContext } from './record-context-tools.js'; * served: each is an answer with no data member, so its citations are * dropped (ADR-0160 point 23). No pack is picked for a citation that named * none, and no call is retried without the offending argument. + * - **A failed call verifies nothing either, and is reported.** A refusal is + * a throw carrying an ADR-0112 `code` with a declared 4xx `status` — the + * only shape `get_record_context` refuses with. Any other throw (no `code`, + * no status, a 5xx: an outage, a bug) is a failure, not an answer: its + * citations are dropped all the same, so the result stays fail-closed, and + * the failure goes to `options.onError`, once per call, so the host can log + * or retry it instead of losing the citations silently. 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. * - **What a quote is matched against** — the strings of the data member, and * no other: * - a field entry's `value`, when it is a string, and its `display`, at the @@ -49,6 +58,13 @@ import { executeGetRecordContext } from './record-context-tools.js'; * not a string (a number, a boolean, a list or an object; its `display`, * where the entry carries one, is matched). A withheld or hidden field has * no value in the answer, so nothing is matched in it. + * + * The tag-removed reading is a second string, not a replacement, so it can + * verify a quote the stored text does not hold: removing a tag joins the + * text on either side of it, so `

Fire

cover

` reads as + * `Firecover`. It never verifies a quote that is not in the body's + * characters in order, but it is not "only stricter" than matching as + * stored. * - **Verbatim, with whitespace runs collapsed.** Every run of whitespace in * the quote and in the matched string reads as one space, and the quote is * trimmed. Case and every other character must agree. A quote that is empty @@ -59,14 +75,20 @@ import { executeGetRecordContext } from './record-context-tools.js'; * It never throws for a citation. A citation that does not parse * (`RecordCitationSchema`) is dropped like one that is not found, and only the * first {@link RECORD_CITATIONS_MAX} entries of the list are read, so a list a - * model wrote cannot make the platform read without bound. A dropped citation - * leaves no trace in the result: a caller who cannot read a record learns - * nothing from its citations' fate that tells a hidden record from a missing - * one. + * model wrote cannot make the platform read without bound. That is the cap a + * producer gets: this function reads the first 20 and drops the rest, where + * `RecordCitationsSchema` refuses a list of 21 outright; a producer that + * verifies a model's list with this function persists at most 20. A dropped + * citation leaves no trace in the result: a caller who cannot read a record + * learns nothing from its citations' fate that tells a hidden record from a + * missing one. `onError` is for the host, never the caller: it is called for a + * failure only, never for a refusal, so a refused read and a missing record + * give the host the same answer too. A callback that throws is ignored. */ export async function verifyRecordCitations( citations: unknown, door: RecordContextDoor, + options: VerifyRecordCitationsOptions = {}, ): Promise { if (!Array.isArray(citations)) return []; const parsed: RecordCitationParsed[] = []; @@ -78,7 +100,7 @@ export async function verifyRecordCitations( const haystacks = new Map>(); for (const c of parsed) { const key = callKeyOf(c); - if (!haystacks.has(key)) haystacks.set(key, haystackOf(c, door)); + if (!haystacks.has(key)) haystacks.set(key, haystackOf(c, door, options.onError)); } const verified: RecordCitationParsed[] = []; @@ -91,6 +113,50 @@ export async function verifyRecordCitations( return verified; } +/** Options of {@link verifyRecordCitations}. */ +export interface VerifyRecordCitationsOptions { + /** + * Called once per verifying call that failed rather than refused (see the + * rule), with the thrown value and the call's arguments. Its citations are + * dropped whether or not it is given. + */ + onError?: (error: unknown, call: VerifyingCall) => void; +} + +/** The arguments of one verifying `get_record_context` call. */ +export interface VerifyingCall { + object: string; + id: string; + context?: string; + 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, status } = err as { code?: unknown; status?: unknown }; + return typeof code === 'string' && code.length > 0 && typeof status === 'number' && status >= 400 && status < 500; +} + +/** 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; + const call: VerifyingCall = { + object: c.object, + id: c.id, + ...(c.context !== undefined ? { context: c.context } : {}), + ...(c.anchor !== undefined ? { anchor: c.anchor } : {}), + }; + try { + onError(err, call); + } catch { + // The verifier never throws for a citation. + } +} + /** The verifying call a citation makes, as one key. */ function callKeyOf(c: RecordCitationParsed): string { return JSON.stringify([c.object, c.id, c.context ?? null, c.anchor ?? null]); @@ -105,7 +171,11 @@ function collapse(text: string): string { * The strings of the data member of `get_record_context`'s answer for the * citation's call, whitespace collapsed; `undefined` when the call is refused. */ -async function haystackOf(c: RecordCitationParsed, door: RecordContextDoor): Promise { +async function haystackOf( + c: RecordCitationParsed, + door: RecordContextDoor, + onError: VerifyRecordCitationsOptions['onError'], +): Promise { let answer: GetRecordContextOutput; try { answer = await executeGetRecordContext( @@ -117,8 +187,10 @@ async function haystackOf(c: RecordCitationParsed, door: RecordContextDoor): Pro }, door, ); - } catch { - // Every refusal is one outcome: the citation is not verified. + } catch (err) { + // A refusal and a failure are one outcome for the result: the citation is + // not verified. Only a failure is reported. + report(onError, err, c); return undefined; } @@ -137,19 +209,26 @@ async function haystackOf(c: RecordCitationParsed, door: RecordContextDoor): Pro const text = data.body?.text; if (typeof text === 'string') { strings.push(text); - if (text.includes('<') && (await bodyIsHtml(c.object, data.body?.field, door))) strings.push(stripBodyTags(text)); + if (text.includes('<') && (await bodyIsHtml(c, data.body?.field, door, onError))) strings.push(stripBodyTags(text)); } return strings.map(collapse); } /** Whether the body field writes HTML, by the definition the caller is served. */ -async function bodyIsHtml(object: string, field: string | undefined, door: RecordContextDoor): Promise { +async function bodyIsHtml( + c: RecordCitationParsed, + field: string | undefined, + door: RecordContextDoor, + onError: VerifyRecordCitationsOptions['onError'], +): Promise { if (field === undefined) return false; try { - const def = await door.servedObjectDefinitionOf(object); + const def = await door.servedObjectDefinitionOf(c.object); const fields = (def?.fields ?? {}) as Record; return isHtmlBodyType(fields[field]?.type); - } catch { + } catch (err) { + // Fail-closed: the body is matched as stored only. A failure is reported. + report(onError, err, c); return false; } } diff --git a/packages/spec/src/ai/record-body-anchor.ts b/packages/spec/src/ai/record-body-anchor.ts index 19c1a925d03..cb21217a69c 100644 --- a/packages/spec/src/ai/record-body-anchor.ts +++ b/packages/spec/src/ai/record-body-anchor.ts @@ -68,6 +68,10 @@ function markdownHeadingOf(line: string): { level: number; heading: string } | u * how the citation verifier reads an `html` or `richtext` body * (`@objectstack/service-record-context`'s `verifyRecordCitations`), so the * two never disagree on what a tag is. + * + * It is not a sanitizer: it reads text out of markup for matching and never + * makes markup safe to render. Entities are left encoded, and the text on + * either side of a removed tag is joined with nothing between. */ export function stripBodyTags(text: string): string { let out = ''; From 414d568e8b3239f1135c1b154c7894ff6257e8c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:44:25 +0000 Subject: [PATCH 2/3] =?UTF-8?q?docs(changeset):=2037418=20declares=20Claus?= =?UTF-8?q?e-=E2=91=A1=20yes=20(widening)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZnFSe9yjMwBFr33Rk --- .changeset/37418-citation-refusal-vs-failure.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/37418-citation-refusal-vs-failure.md b/.changeset/37418-citation-refusal-vs-failure.md index 976120e462a..a3ed742988d 100644 --- a/.changeset/37418-citation-refusal-vs-failure.md +++ b/.changeset/37418-citation-refusal-vs-failure.md @@ -5,7 +5,7 @@ feat(record-context): the citation verifier tells a refusal from a failure and reports failures to the host -Clause-②: no +Clause-②: yes (widening) — new optional third argument of the exported verifyRecordCitations and two new exported types; existing calls unchanged Metadata-protocol: none ADR-0160 D9 verifies an answer's citations once, so a citation lost to an outage is lost for good. `verifyRecordCitations` used to drop a citation the same way whether the verifying call was refused or failed. From 3ec523a9bcf1097a7b9649f526657ab509652228 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:26:33 +0000 Subject: [PATCH 3/3] fix(record-context): read the declared status as ADR-0112 does; guard async onError A refusal declared with statusCode only is a refusal. A rejected promise from onError is caught. Doc: the bodyIsHtml report site, the executor's 403 conversion (#37463), the 4xx band. Pins for each. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CZnFSe9yjMwBFr33Rk --- .../37418-citation-refusal-vs-failure.md | 4 +- .../src/__tests__/verify-citations.test.ts | 70 ++++++++++++++++++ .../src/verify-citations.ts | 71 ++++++++++++++----- 3 files changed, 127 insertions(+), 18 deletions(-) diff --git a/.changeset/37418-citation-refusal-vs-failure.md b/.changeset/37418-citation-refusal-vs-failure.md index a3ed742988d..f5ed4be11fd 100644 --- a/.changeset/37418-citation-refusal-vs-failure.md +++ b/.changeset/37418-citation-refusal-vs-failure.md @@ -10,8 +10,8 @@ Metadata-protocol: none ADR-0160 D9 verifies an answer's citations once, so a citation lost to an outage is lost for good. `verifyRecordCitations` used to drop a citation the same way whether the verifying call was refused or failed. -- **A refusal** is a throw carrying an ADR-0112 `code` with a declared 4xx `status`, the only shape `get_record_context` refuses with. Its citations are dropped and nothing is reported, as before. -- **Any other throw** (no code, a driver code with no status, a 5xx) is a failure. Its citations are still dropped, so the result stays fail-closed, and the failure goes to the new optional `onError(error, call)` option, once per verifying call, so the host can log or retry. A callback that throws is ignored. +- **A refusal** is a throw carrying an ADR-0112 `code` with a declared 4xx status (read as ADR-0112's reader reads it: `.status`, then `.statusCode`), the only shape `get_record_context` refuses with. Its citations are dropped and nothing is reported, as before. +- **Any other throw** (no code, a driver code with no status, a 5xx) is a failure. Its citations are still dropped, so the result stays fail-closed, and the failure goes to the new optional `onError(error, call)` option, once per verifying call, so the host can log or retry. A failed read of the served definition behind an HTML body is reported too; there only the tag-removed reading is lost. A callback that throws, or returns a promise that rejects, is ignored. - A refused read and a missing record still give the host the same answer: dropped, not reported. - New exported types `VerifyRecordCitationsOptions` and `VerifyingCall`. Existing two-argument calls are unchanged. - Docs: the verifier says which list cap a producer gets (the first 20 read, where `RecordCitationsSchema` refuses 21) and that the tag-removed reading of an HTML body joins adjacent text, so it is not only stricter than matching as stored. `stripBodyTags` says it is not a sanitizer. 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 07bbdfd8dda..de62cb0e7d9 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 @@ -209,6 +209,76 @@ describe('[ADR-0160 D9] a refusal and a failure', () => { expect((await run(fakeDoor(policyApp()), [cite('Fire cover')])).quotes).toEqual(['Fire cover']); }); + it('reads the declared status as ADR-0112 does: a coded refusal declared with statusCode only is not reported', async () => { + const statusCodeOnly = Object.assign(new Error('denied'), { code: 'PERMISSION_DENIED', statusCode: 403 }); + expect(await run(throwingDoor(statusCodeOnly), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] }); + // Control: the same code with a 5xx statusCode is a failure. + const fault = Object.assign(new Error('down'), { code: 'INTERNAL_ERROR', statusCode: 503 }); + expect((await run(throwingDoor(fault), [cite('Fire cover')])).reported.map((r) => r.error)).toEqual([fault]); + }); + + 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')]); + expect(quotes).toEqual([]); + expect(reported).toEqual([{ error: err, call: { object: 'policy', id: 'p1' } }]); + } + }); + + it('reports a failed read behind an html body once, and still verifies what the answer carries', async () => { + const app = policyApp(); + const policy = app.objects.policy as { fields: Record> }; + policy.fields.content = { ...policy.fields.content, type: 'html' }; + app.records.policy[0].content = '

Covers fire damage.

'; + // Control: through a door that answers, the tag-removed reading verifies. + expect((await run(fakeDoor(app), [cite('Covers fire damage.')])).quotes).toEqual(['Covers fire damage.']); + + // The executor's own definition reads, counted on a door that answers. + const probe = fakeDoor(app); + let executorReads = 0; + const served = probe.servedObjectDefinitionOf.bind(probe); + probe.servedObjectDefinitionOf = async (object) => { + executorReads++; + return served(object); + }; + await executeGetRecordContext({ objectName: 'policy', recordId: 'p1' }, probe); + + // The same door, failing every definition read after the executor's. + const door = fakeDoor(app); + const outage = new Error('metadata store down'); + let reads = 0; + const answer = door.servedObjectDefinitionOf.bind(door); + door.servedObjectDefinitionOf = async (object) => { + if (++reads > executorReads) throw outage; + return answer(object); + }; + const { quotes, reported } = await run(door, [cite('Covers fire damage.'), cite('Fire cover'), cite('Covers fire')]); + expect(quotes).toEqual(['Fire cover', 'Covers fire']); + expect(reported).toEqual([{ error: outage, call: { object: 'policy', id: 'p1' } }]); + }); + + it('ignores an async callback whose promise rejects: no unhandled rejection', async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on('unhandledRejection', onUnhandled); + try { + let called = 0; + await expect( + verifyRecordCitations([cite('Fire cover')], throwingDoor(new Error('down')), { + onError: async () => { + called++; + throw new Error('logger down'); + }, + }), + ).resolves.toEqual([]); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(called).toBe(1); + expect(unhandled).toEqual([]); + } finally { + process.off('unhandledRejection', onUnhandled); + } + }); + it('never throws when the callback throws, and drops the failed call without one', async () => { const door = throwingDoor(new Error('down')); await expect( diff --git a/packages/services/service-record-context/src/verify-citations.ts b/packages/services/service-record-context/src/verify-citations.ts index 75b446adbab..5d81d1ffbac 100644 --- a/packages/services/service-record-context/src/verify-citations.ts +++ b/packages/services/service-record-context/src/verify-citations.ts @@ -36,14 +36,25 @@ import { executeGetRecordContext } from './record-context-tools.js'; * dropped (ADR-0160 point 23). No pack is picked for a citation that named * none, and no call is retried without the offending argument. * - **A failed call verifies nothing either, and is reported.** A refusal is - * a throw carrying an ADR-0112 `code` with a declared 4xx `status` — the - * only shape `get_record_context` refuses with. Any other throw (no `code`, - * no status, a 5xx: an outage, a bug) is a failure, not an answer: its - * citations are dropped all the same, so the result stays fail-closed, and - * the failure goes to `options.onError`, once per call, so the host can log - * or retry it instead of losing the citations silently. 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. + * a throw carrying an ADR-0112 `code` with a declared 4xx status — the only + * shape `get_record_context` refuses with. The declared status is read as + * ADR-0112's reader reads it (`resolveThrownHttpError`'s `declaredStatus` + * in `@objectstack/types`): `.status`, then `.statusCode`. Any other throw + * (no `code`, no status, a 5xx, a thrown value that is not an object: an + * outage, a bug) is a failure, not an answer: its citations are dropped all + * the same, so the result stays fail-closed, and the failure goes to + * `options.onError`, once per call, so the host can log or retry it. + * 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. + * + * 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 + * 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 * no other: * - a field entry's `value`, when it is a string, and its `display`, at the @@ -83,7 +94,8 @@ import { executeGetRecordContext } from './record-context-tools.js'; * learns nothing from its citations' fate that tells a hidden record from a * missing one. `onError` is for the host, never the caller: it is called for a * failure only, never for a refusal, so a refused read and a missing record - * give the host the same answer too. A callback that throws is ignored. + * give the host the same answer too. A callback that throws, or returns a + * promise that rejects, is ignored. */ export async function verifyRecordCitations( citations: unknown, @@ -116,9 +128,19 @@ export async function verifyRecordCitations( /** Options of {@link verifyRecordCitations}. */ export interface VerifyRecordCitationsOptions { /** - * Called once per verifying call that failed rather than refused (see the - * rule), with the thrown value and the call's arguments. Its citations are - * dropped whether or not it is given. + * Called with the thrown value and the call's arguments when a read made to + * verify a citation failed rather than refused (see the rule). Two reads + * report: + * + * - the verifying `get_record_context` call: its citations are dropped + * whether or not this is given, and it reports at most once per call; + * - the read of the served definition behind an `html` or `richtext` body: + * the call answered, and only the tag-removed reading of the body is + * lost, so a citation whose quote is in a field or in the body as stored + * still verifies. + * + * A callback that throws, or returns a promise that rejects, changes + * nothing. */ onError?: (error: unknown, call: VerifyingCall) => void; } @@ -133,12 +155,25 @@ export interface VerifyingCall { /** * Whether a throw is an ADR-0112 refusal: a non-empty string `code` and a - * declared 4xx `status`. Anything else is a failure. + * declared 4xx status. Anything else is a failure. */ function isRefusal(err: unknown): boolean { if (err == null || typeof err !== 'object') return false; - const { code, status } = err as { code?: unknown; status?: unknown }; - return typeof code === 'string' && code.length > 0 && typeof status === 'number' && status >= 400 && status < 500; + 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. */ @@ -151,7 +186,11 @@ function report(onError: VerifyRecordCitationsOptions['onError'], err: unknown, ...(c.anchor !== undefined ? { anchor: c.anchor } : {}), }; try { - onError(err, call); + const returned: unknown = onError(err, call); + // An async callback's rejection would otherwise be an unhandled rejection. + if (returned != null && typeof (returned as { then?: unknown }).then === 'function') { + (returned as PromiseLike).then(undefined, () => {}); + } } catch { // The verifier never throws for a citation. }