From 84859b35680cb1ceb60ee07019e029157f701db4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:30:05 +0000 Subject: [PATCH 1/4] feat(spec,service-record-context): the record citation shape and its verifier (ADR-0160 D9) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .../src/__tests__/verify-citations.test.ts | 182 +++++++++++++++++ .../src/body-outline.ts | 178 +---------------- .../service-record-context/src/index.ts | 4 +- .../src/verify-citations.ts | 155 ++++++++++++++ packages/spec/src/ai/index.ts | 3 + packages/spec/src/ai/record-body-anchor.ts | 189 ++++++++++++++++++ packages/spec/src/ai/record-citation.test.ts | 72 +++++++ packages/spec/src/ai/record-citation.zod.ts | 100 +++++++++ 8 files changed, 714 insertions(+), 169 deletions(-) create mode 100644 packages/services/service-record-context/src/__tests__/verify-citations.test.ts create mode 100644 packages/services/service-record-context/src/verify-citations.ts create mode 100644 packages/spec/src/ai/record-body-anchor.ts create mode 100644 packages/spec/src/ai/record-citation.test.ts create mode 100644 packages/spec/src/ai/record-citation.zod.ts 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 new file mode 100644 index 00000000000..c8dbb87416b --- /dev/null +++ b/packages/services/service-record-context/src/__tests__/verify-citations.test.ts @@ -0,0 +1,182 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0160 D9, third amendment] The citation verifier: a citation survives + * only when its quote is found in the data member of the answer + * `get_record_context` gives the asking user for the citation's `object`, + * `id`, `context` and `anchor`. Every refused call drops its citation (point + * 23). Each "dropped" case below has a control leg that verifies the same + * quote, or shows the text the answer carries, so a verifier that drops + * everything cannot pass. + */ + +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'; + +const ROOT = { object: 'policy', id: 'p1' }; + +/** The quotes that survive, in order. */ +async function surviving(app: FakeApp, citations: unknown[]): Promise { + return (await verifyRecordCitations(citations, fakeDoor(app))).map((c) => c.quote); +} + +const cite = (quote: string, extra: Record = {}) => ({ ...ROOT, quote, ...extra }); + +describe('[ADR-0160 D9] what a quote is matched against', () => { + it('verifies a field value, a display, and a lookup display', async () => { + expect(await surviving(policyApp(), [cite('Fire cover'), cite('active'), cite('Active'), cite('Acme')])).toEqual([ + 'Fire cover', + 'active', + 'Active', + 'Acme', + ]); + }); + + it('verifies a quote found in a related-list cell, cited on the root record (Q3)', async () => { + expect(await surviving(policyApp(), [cite('second')])).toEqual(['second']); + // A row of another policy is not in this record's answer. + expect(await surviving(policyApp(), [cite('other policy')])).toEqual([]); + }); + + it('refuses a quote that appears only in a note, the framing, or a label', async () => { + const statement = 'Reads on policy revisions are narrowed by the agent ceiling.'; + const app = policyApp({ narrowed: { policy_revision: statement } }); + const answer = await executeGetRecordContext({ objectName: 'policy', recordId: 'p1' }, fakeDoor(app)); + // Control: the answer carries each of these strings outside the data strings. + expect(answer.notes.map((n) => n.text)).toContain(statement); + expect(answer.data.pack.label).toBe('Policy document'); + expect(answer.data.fields.map((f) => f.label)).toContain('Secret terms'); + expect(await surviving(app, [cite(statement), cite(answer.framing), cite('Policy document'), cite('Secret terms')])).toEqual([]); + }); + + it('refuses a quote from a field the caller has withheld or hidden', async () => { + expect(await surviving(policyApp(), [cite('S3CRET-TERMS')])).toEqual(['S3CRET-TERMS']); + expect(await surviving(policyApp({ withheldFields: { policy: ['secret_terms'] } }), [cite('S3CRET-TERMS')])).toEqual([]); + expect(await surviving(policyApp({ hiddenFields: { policy: ['secret_terms'] } }), [cite('S3CRET-TERMS')])).toEqual([]); + }); + + it('does not match a value that is not a string', async () => { + const answer = await executeGetRecordContext({ objectName: 'policy', recordId: 'p1' }, fakeDoor(policyApp())); + expect(answer.data.fields.find((f) => f.name === 'premium')?.value).toBe(1200); + expect(await surviving(policyApp(), [cite('1200')])).toEqual([]); + }); + + it('collapses whitespace runs and trims the quote; case and characters must agree', async () => { + expect(await surviving(policyApp(), [cite(' Covers fire.\n'), cite('Covers fire. ## Exclusions')])).toEqual([ + ' Covers fire.\n', + 'Covers fire. ## Exclusions', + ]); + expect(await surviving(policyApp(), [cite('covers fire.'), cite('Covers fire!'), cite(' \n\t ')])).toEqual([]); + }); + + it('matches an html or richtext body also with its tags removed, and only such a body', async () => { + const htmlApp = (type: string): FakeApp => { + const app = policyApp(); + const policy = app.objects.policy as { fields: Record> }; + policy.fields.content = { ...policy.fields.content, type }; + app.records.policy[0].content = '

Scope

Covers fire damage.

'; + return app; + }; + for (const type of ['html', 'richtext']) { + expect(await surviving(htmlApp(type), [cite('Covers fire damage.'), cite('Covers fire')])).toEqual([ + 'Covers fire damage.', + 'Covers fire', + ]); + } + expect(await surviving(htmlApp('markdown'), [cite('Covers fire damage.'), cite('Covers fire')])).toEqual([ + 'Covers fire', + ]); + }); +}); + +describe('[ADR-0160 D9] anchors', () => { + it('verifies a quote in a section by its anchor, and refuses a stale anchor', async () => { + expect(await surviving(policyApp(), [cite('Arson.', { anchor: 'exclusions' })])).toEqual(['Arson.']); + expect(await surviving(policyApp(), [cite('Arson.', { anchor: 'old-exclusions' })])).toEqual([]); + // The anchor scopes the match to its section. + expect(await surviving(policyApp(), [cite('Call us.', { anchor: 'exclusions' })])).toEqual([]); + }); + + it('for a body that came back as an outline, refuses a quote cited without an anchor', async () => { + const app = policyApp(); + app.records.policy[0].content = [ + '# Scope', + `Covers fire. ${'Filler sentence for length. '.repeat(200)}`, + '# Claims', + `Call us within thirty days. ${'More filler for length. '.repeat(200)}`, + ].join('\n'); + const answer = await executeGetRecordContext({ objectName: 'policy', recordId: 'p1' }, fakeDoor(app)); + expect(answer.data.body?.outline?.map((h) => h.anchor)).toEqual(['scope', 'claims']); + expect(await surviving(app, [cite('Call us within thirty days.')])).toEqual([]); + expect(await surviving(app, [cite('Call us within thirty days.', { anchor: 'claims' })])).toEqual(['Call us within thirty days.']); + }); +}); + +describe('[ADR-0160 D9] context (Q2)', () => { + const twoPacks = (): FakeApp => { + const app = policyApp(); + app.packs = [...app.packs, { name: 'policy_brief', label: 'Policy brief', object: 'policy', fields: ['title'] }]; + return app; + }; + + it('refuses a citation without context on an object with two packs, and verifies it on an object with one', async () => { + expect(await surviving(twoPacks(), [cite('Fire cover')])).toEqual([]); + expect(await surviving(policyApp(), [cite('Fire cover')])).toEqual(['Fire cover']); + }); + + it('verifies a citation that names its pack, and refuses one naming a pack that does not exist', async () => { + expect(await surviving(twoPacks(), [cite('Fire cover', { context: 'policy_brief' }), cite('second', { context: 'policy_document' })])).toEqual([ + 'Fire cover', + 'second', + ]); + // `second` is a related cell of `policy_document`, which `policy_brief` does not carry. + expect(await surviving(twoPacks(), [cite('second', { context: 'policy_brief' }), cite('Fire cover', { context: 'nope' })])).toEqual([]); + }); +}); + +describe('[ADR-0160 D9] a caller with no read access', () => { + it('gets "not verified" and nothing that tells a hidden record from a missing one', async () => { + const quote = 'Fire cover'; + const outcomes = await Promise.all([ + verifyRecordCitations([cite(quote)], fakeDoor(policyApp({ unreadableRows: ['p1'] }))), + verifyRecordCitations([{ object: 'policy', id: 'p404', quote }], fakeDoor(policyApp())), + verifyRecordCitations([cite(quote)], fakeDoor(policyApp({ unservedObjects: ['policy'] }))), + verifyRecordCitations([cite(quote)], fakeDoor(policyApp({ guardedObjects: ['policy'] }))), + verifyRecordCitations([cite(quote)], fakeDoor(policyApp({ unexposedObjects: ['policy'] }))), + ]); + for (const outcome of outcomes) expect(outcome).toEqual([]); + }); +}); + +describe('[ADR-0160 D9] the list', () => { + it('makes one call per distinct (object, id, context, anchor)', async () => { + const door = fakeDoor(policyApp()); + const verified = await verifyRecordCitations( + [cite('Fire cover'), cite('Acme'), cite('second'), cite('Arson.', { anchor: 'exclusions' }), cite('Exclusions', { anchor: 'exclusions' })], + door, + ); + expect(verified).toHaveLength(5); + expect(door.listCalls).toBe(2); + }); + + it('drops an entry that does not parse, keeps order, and never throws', async () => { + const list = [cite('Fire cover', { field: 'title' }), null, 'Acme', cite(''), cite('second'), cite('Fire cover')]; + expect(await surviving(policyApp(), list)).toEqual(['second', 'Fire cover']); + expect(await verifyRecordCitations('not a list', fakeDoor(policyApp()))).toEqual([]); + expect(await verifyRecordCitations(undefined, fakeDoor(policyApp()))).toEqual([]); + }); + + it('reads at most RECORD_CITATIONS_MAX entries of the list', async () => { + const list = Array.from({ length: RECORD_CITATIONS_MAX + 5 }, (_, i) => cite(i < RECORD_CITATIONS_MAX ? 'Fire cover' : 'Acme')); + const verified = await verifyRecordCitations(list, fakeDoor(policyApp())); + expect(verified).toHaveLength(RECORD_CITATIONS_MAX); + expect(verified.every((c) => c.quote === 'Fire cover')).toBe(true); + }); + + it('returns the citations as parsed, context and anchor included', async () => { + const c = cite('Arson.', { context: 'policy_document', anchor: 'exclusions' }); + expect(await verifyRecordCitations([c], fakeDoor(policyApp()))).toEqual([c]); + }); +}); diff --git a/packages/services/service-record-context/src/body-outline.ts b/packages/services/service-record-context/src/body-outline.ts index f1e3b8c8a9a..7d242e46d61 100644 --- a/packages/services/service-record-context/src/body-outline.ts +++ b/packages/services/service-record-context/src/body-outline.ts @@ -15,18 +15,13 @@ * whatever the body holds; a cut is stated. The cap bounds the listing, not which * sections exist: every heading's anchor still reads its section. * - * Headings are read the way the field type writes them: Markdown ATX headings - * (`#` to `######` at the start of a line, outside a fenced code block) for - * `textarea` and `markdown`, and `

` to `

` elements for `html` and - * `richtext`. - * - * An anchor is the heading's text, lowercased, every run of characters that is - * not a letter or a digit made one `-`, with `-2`, `-3`, … added to a repeated - * one. It is derived from the heading alone, so an edit that renames or - * removes a heading leaves the old anchor unresolved — refused, never answered - * with another section. + * Which lines and elements are headings, and the anchor each one is read by, + * are the spec's `headingsOf` (`@objectstack/spec/ai`, `record-body-anchor.ts`): + * a citation's `anchor` names the same heading a surface opens (ADR-0160 D9). */ +import { headingsOf, type BodyHeading } from '@objectstack/spec/ai'; + /** * The most characters of body text one answer carries (whole body, section, or * truncated prefix). An outline's listing, serialized, is held to it too. @@ -44,170 +39,17 @@ export const RECORD_CONTEXT_BODY_MAX_CHARS = 8000; */ export const RECORD_CONTEXT_OUTLINE_MAX_ENTRIES = 80; -/** One heading of a body. */ -export interface BodyHeading { - anchor: string; - heading: string; - level: number; - /** Where the heading starts in the body text. */ - start: number; -} - -// Every reader below is a forward scan: one pass over the text, no pattern -// that can backtrack. A body is author-written, so its shape is not ours to -// trust, and the outline is read before the body's length is judged. - -const isBlank = (c: string): boolean => c === ' ' || c === '\t'; -const isWordChar = (c: string): boolean => /^[A-Za-z0-9_]$/.test(c); -const isSpace = (c: string): boolean => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f' || c === '\v'; - -/** Whether `line` opens or closes a fenced code block (``` or ~~~ after optional blanks). */ -function isFence(line: string): boolean { - let i = 0; - while (i < line.length && isBlank(line[i])) i++; - return line.startsWith('```', i) || line.startsWith('~~~', i); -} - -/** An ATX heading's level and text, or `undefined` for any other line. */ -function markdownHeadingOf(line: string): { level: number; heading: string } | undefined { - let level = 0; - while (level < line.length && line[level] === '#') level++; - if (level < 1 || level > 6 || !isBlank(line[level] ?? '')) return undefined; - let start = level; - while (start < line.length && isBlank(line[start])) start++; - let end = line.length; - while (end > start && isBlank(line[end - 1])) end--; - while (end > start && line[end - 1] === '#') end--; - while (end > start && isBlank(line[end - 1])) end--; - const heading = line.slice(start, end).trim(); - return heading ? { level, heading } : undefined; -} - -/** `text` with every `<…>` tag removed; a `<` with no `>` after it is kept as text. */ -function stripTags(text: string): string { - let out = ''; - let i = 0; - while (i < text.length) { - const open = text.indexOf('<', i); - if (open < 0) break; - const close = text.indexOf('>', open + 1); - if (close < 0) break; - out += text.slice(i, open); - i = close + 1; - } - return out + text.slice(i); -} - -/** - * The `

`…`

` elements of `html`, in order. Each search for a `>` or a - * closing tag remembers where it landed, and every later search starts at or - * after an earlier one, so the scan stays linear however many openers are - * left unclosed. - */ -function htmlHeadingsOf(html: string): Array<{ level: number; inner: string; start: number }> { - const lower = html.toLowerCase(); - const out: Array<{ level: number; inner: string; start: number }> = []; - let gt = -2; - const nextGt = (from: number): number => { - if (gt === -1 || gt >= from) return gt; - gt = lower.indexOf('>', from); - return gt; - }; - const closers = new Map(); - const nextCloser = (level: number, from: number): { at: number; end: number } | undefined => { - let at = closers.get(level) ?? -2; - if (at !== -1 && at < from) { - at = from; - for (;;) { - at = lower.indexOf(`') break; - at = k; - } - closers.set(level, at < 0 ? -1 : at); - } - if (at < 0) return undefined; - let end = at + 4; - while (end < lower.length && isSpace(lower[end])) end++; - return { at, end: end + 1 }; - }; - let pos = 0; - for (;;) { - const open = lower.indexOf('= 1 && level <= 6) || isWordChar(after)) { - pos = open + 1; - continue; - } - const tagEnd = nextGt(open + 3); - if (tagEnd < 0) break; - const closer = nextCloser(level, tagEnd + 1); - if (!closer) { - pos = open + 1; - continue; - } - out.push({ level, inner: html.slice(tagEnd + 1, closer.at), start: open }); - pos = closer.end; - } - return out; -} - -/** `heading text` → `heading-text`; letters and digits of every script kept. */ -function slugOf(text: string): string { - return text - .toLowerCase() - .replace(/[^\p{L}\p{N}]+/gu, '-') - .replace(/^-+|-+$/g, ''); -} - -function decodeEntities(text: string): string { - return text - .replace(/ /g, ' ') - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/"/g, '"') - .replace(/'/g, "'") - .replace(/&/g, '&'); -} +// The headings and their anchors are the spec's (`@objectstack/spec/ai`, +// `record-body-anchor.ts`), so this service and a surface that opens a record +// at a cited anchor derive one anchor from one body (ADR-0160 D9). +export { headingsOf }; +export type { BodyHeading }; /** Whether a field type writes HTML (its headings are elements). */ export function isHtmlBodyType(type: unknown): boolean { return type === 'html' || type === 'richtext'; } -/** The headings of `text`, in order, each with its anchor. */ -export function headingsOf(text: string, html: boolean): BodyHeading[] { - const raw: Array<{ heading: string; level: number; start: number }> = []; - if (html) { - for (const h of htmlHeadingsOf(text)) { - const heading = decodeEntities(stripTags(h.inner)).replace(/\s+/g, ' ').trim(); - if (heading) raw.push({ heading, level: h.level, start: h.start }); - } - } else { - let inFence = false; - let offset = 0; - for (const line of text.split('\n')) { - if (isFence(line)) inFence = !inFence; - else if (!inFence) { - const m = markdownHeadingOf(line.endsWith('\r') ? line.slice(0, -1) : line); - if (m) raw.push({ heading: m.heading, level: m.level, start: offset }); - } - offset += line.length + 1; - } - } - const seen = new Map(); - return raw.map((h, i) => { - const base = slugOf(h.heading) || `section-${i + 1}`; - const n = (seen.get(base) ?? 0) + 1; - seen.set(base, n); - return { ...h, anchor: n === 1 ? base : `${base}-${n}` }; - }); -} - /** One section's text: from its heading to the next heading of the same or a higher level. */ export function sectionOf(text: string, headings: readonly BodyHeading[], anchor: string): string | undefined { const at = headings.findIndex((h) => h.anchor === anchor); diff --git a/packages/services/service-record-context/src/index.ts b/packages/services/service-record-context/src/index.ts index 888cf8f4290..2dc447157e0 100644 --- a/packages/services/service-record-context/src/index.ts +++ b/packages/services/service-record-context/src/index.ts @@ -2,7 +2,8 @@ /** * `@objectstack/service-record-context` — the context-pack render service and - * the `get_record_context` executor (ADR-0160 D3–D5). + * the `get_record_context` executor (ADR-0160 D3–D5), and the citation + * verifier (D9). */ export { @@ -13,6 +14,7 @@ export { } from './record-context-tools.js'; export type { RecordContextTools } from './record-context-tools.js'; export type { RecordContextDoor } from './door.js'; +export { verifyRecordCitations } 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 new file mode 100644 index 00000000000..c35fc72964d --- /dev/null +++ b/packages/services/service-record-context/src/verify-citations.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { + RECORD_CITATIONS_MAX, + RecordCitationSchema, + stripBodyTags, + type GetRecordContextOutput, + type RecordCitationParsed, + type RecordContextFieldEntry, +} from '@objectstack/spec/ai'; +import { isHtmlBodyType } from './body-outline.js'; +import type { RecordContextDoor } from './door.js'; +import { executeGetRecordContext } from './record-context-tools.js'; + +/** + * [ADR-0160 D9, third amendment] The citation verifier: which citations of an + * answer survive, judged once, when the answer is produced, as the asking + * user. + * + * A citation is a claim the model wrote. For each one the platform calls + * `get_record_context` with the citation's `object`, `id`, `context` and + * `anchor`, through the door bound to the asking user — the same executor, the + * same gates, the same answer that user would get — and looks for `quote` in + * the data member of that answer. This function persists nothing and renders + * nothing: it returns the verified subset, and the producer persists it with + * the message. + * + * ## The rule + * + * - **One call per distinct `(object, id, context, anchor)`.** Citations that + * name the same call share its answer. + * - **A refused call verifies nothing.** A `context` no pack has, several + * packs and no `context`, an `anchor` that does not resolve, a record the + * caller cannot read or that does not exist, an object the caller is not + * 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. + * - **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 + * root and in every related-list cell (a quote from a related row is cited + * on the root record); + * - the body's `text` — the whole body, or the one section `anchor` named. + * An `html` or `richtext` body is matched as stored and also with its tags + * removed (`stripBodyTags`, the reader the anchor derivation uses). + * + * Never matched: the notes, the framing sentence, any label, the pack's and + * the record's own header, a body outline's headings, and a value that is + * 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. + * - **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 + * once trimmed verifies nothing. + * + * ## What it never does + * + * 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. + */ +export async function verifyRecordCitations( + citations: unknown, + door: RecordContextDoor, +): Promise { + if (!Array.isArray(citations)) return []; + const parsed: RecordCitationParsed[] = []; + for (const raw of citations.slice(0, RECORD_CITATIONS_MAX)) { + const result = RecordCitationSchema.safeParse(raw); + if (result.success) parsed.push(result.data as RecordCitationParsed); + } + + const haystacks = new Map>(); + for (const c of parsed) { + const key = callKeyOf(c); + if (!haystacks.has(key)) haystacks.set(key, haystackOf(c, door)); + } + + const verified: RecordCitationParsed[] = []; + for (const c of parsed) { + const quote = collapse(c.quote).trim(); + if (!quote) continue; + const strings = await haystacks.get(callKeyOf(c)); + if (strings?.some((s) => s.includes(quote))) verified.push(c); + } + return verified; +} + +/** 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]); +} + +/** Every run of whitespace as one space. */ +function collapse(text: string): string { + return text.replace(/\s+/g, ' '); +} + +/** + * 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 { + let answer: GetRecordContextOutput; + try { + answer = await executeGetRecordContext( + { + objectName: c.object, + recordId: c.id, + ...(c.context !== undefined ? { context: c.context } : {}), + ...(c.anchor !== undefined ? { anchor: c.anchor } : {}), + }, + door, + ); + } catch { + // Every refusal is one outcome: the citation is not verified. + return undefined; + } + + const data = answer.data; + const strings: string[] = []; + const addEntries = (entries: readonly RecordContextFieldEntry[] | undefined) => { + for (const entry of entries ?? []) { + if (typeof entry.value === 'string') strings.push(entry.value); + if (typeof entry.display === 'string') strings.push(entry.display); + } + }; + addEntries(data.fields); + for (const list of data.related ?? []) { + for (const row of list.rows) addEntries(row.fields); + } + 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)); + } + 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 { + if (field === undefined) return false; + try { + const def = await door.servedObjectDefinitionOf(object); + const fields = (def?.fields ?? {}) as Record; + return isHtmlBodyType(fields[field]?.type); + } catch { + return false; + } +} diff --git a/packages/spec/src/ai/index.ts b/packages/spec/src/ai/index.ts index 4c23c418f45..18c4594c3b3 100644 --- a/packages/spec/src/ai/index.ts +++ b/packages/spec/src/ai/index.ts @@ -22,6 +22,7 @@ * - AI face name — the derived flat name an item is listed under (ADR-0150 D6) * - Dataset tools — `list_datasets` / `query_dataset` inputs and outputs (ADR-0149 D2) * - Context pack — the `ai_context` kind and the `get_record_context` tool's input and output (ADR-0160) + * - Record citation — the citation shape an answer carries, and the body anchor it names (ADR-0160 D9) * - Object-query source — the `source` block the Ask data tools answer beside their result * - Build Progress — phase vocabulary for the agent loop's `data-build-progress` frames */ @@ -42,6 +43,8 @@ export * from './face-name'; export * from './dataset-tools.zod'; export * from './ai-context.zod'; export * from './record-context-tools.zod'; +export * from './record-citation.zod'; +export * from './record-body-anchor'; export * from './object-query-source.zod'; export * from './knowledge-source.zod'; export * from './knowledge-document.zod'; diff --git a/packages/spec/src/ai/record-body-anchor.ts b/packages/spec/src/ai/record-body-anchor.ts new file mode 100644 index 00000000000..19c1a925d03 --- /dev/null +++ b/packages/spec/src/ai/record-body-anchor.ts @@ -0,0 +1,189 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A record body's headings and the `anchor` each one is read by (ADR-0160 D3, + * "The body"; D9, `anchor`). + * + * An anchor is issued by the `get_record_context` executor's body outline and + * named again by a citation's `anchor` (`record-citation.zod.ts`). The server + * that answers a section and a surface that opens the root record at a cited + * anchor must derive the same anchor from the same body, so the derivation is + * declared here once and read by both + * (`@objectstack/service-record-context`'s `body-outline.ts` re-imports it). + * + * Headings are read the way the field type writes them: Markdown ATX headings + * (`#` to `######` at the start of a line, outside a fenced code block) for + * `textarea` and `markdown`, and `

` to `

` elements for `html` and + * `richtext`. + * + * An anchor is the heading's text, lowercased, every run of characters that is + * not a letter or a digit made one `-`, with `-2`, `-3`, … added to a repeated + * one. It is derived from the heading alone, so an edit that renames or + * removes a heading leaves the old anchor unresolved — refused, never answered + * with another section. + */ + +/** One heading of a body. */ +export interface BodyHeading { + anchor: string; + heading: string; + level: number; + /** Where the heading starts in the body text. */ + start: number; +} + +// Every reader below is a forward scan: one pass over the text, no pattern +// that can backtrack. A body is author-written, so its shape is not ours to +// trust, and the outline is read before the body's length is judged. + +const isBlank = (c: string): boolean => c === ' ' || c === '\t'; +const isWordChar = (c: string): boolean => /^[A-Za-z0-9_]$/.test(c); +const isSpace = (c: string): boolean => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f' || c === '\v'; + +/** Whether `line` opens or closes a fenced code block (``` or ~~~ after optional blanks). */ +function isFence(line: string): boolean { + let i = 0; + while (i < line.length && isBlank(line[i])) i++; + return line.startsWith('```', i) || line.startsWith('~~~', i); +} + +/** An ATX heading's level and text, or `undefined` for any other line. */ +function markdownHeadingOf(line: string): { level: number; heading: string } | undefined { + let level = 0; + while (level < line.length && line[level] === '#') level++; + if (level < 1 || level > 6 || !isBlank(line[level] ?? '')) return undefined; + let start = level; + while (start < line.length && isBlank(line[start])) start++; + let end = line.length; + while (end > start && isBlank(line[end - 1])) end--; + while (end > start && line[end - 1] === '#') end--; + while (end > start && isBlank(line[end - 1])) end--; + const heading = line.slice(start, end).trim(); + return heading ? { level, heading } : undefined; +} + +/** + * `text` with every tag removed; a less-than sign with no greater-than sign + * after it is kept as text. It is how a heading element's text is read, and + * 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. + */ +export function stripBodyTags(text: string): string { + let out = ''; + let i = 0; + while (i < text.length) { + const open = text.indexOf('<', i); + if (open < 0) break; + const close = text.indexOf('>', open + 1); + if (close < 0) break; + out += text.slice(i, open); + i = close + 1; + } + return out + text.slice(i); +} + +/** + * The `

`…`

` elements of `html`, in order. Each search for a `>` or a + * closing tag remembers where it landed, and every later search starts at or + * after an earlier one, so the scan stays linear however many openers are + * left unclosed. + */ +function htmlHeadingsOf(html: string): Array<{ level: number; inner: string; start: number }> { + const lower = html.toLowerCase(); + const out: Array<{ level: number; inner: string; start: number }> = []; + let gt = -2; + const nextGt = (from: number): number => { + if (gt === -1 || gt >= from) return gt; + gt = lower.indexOf('>', from); + return gt; + }; + const closers = new Map(); + const nextCloser = (level: number, from: number): { at: number; end: number } | undefined => { + let at = closers.get(level) ?? -2; + if (at !== -1 && at < from) { + at = from; + for (;;) { + at = lower.indexOf(`') break; + at = k; + } + closers.set(level, at < 0 ? -1 : at); + } + if (at < 0) return undefined; + let end = at + 4; + while (end < lower.length && isSpace(lower[end])) end++; + return { at, end: end + 1 }; + }; + let pos = 0; + for (;;) { + const open = lower.indexOf('= 1 && level <= 6) || isWordChar(after)) { + pos = open + 1; + continue; + } + const tagEnd = nextGt(open + 3); + if (tagEnd < 0) break; + const closer = nextCloser(level, tagEnd + 1); + if (!closer) { + pos = open + 1; + continue; + } + out.push({ level, inner: html.slice(tagEnd + 1, closer.at), start: open }); + pos = closer.end; + } + return out; +} + +/** `heading text` → `heading-text`; letters and digits of every script kept. */ +function slugOf(text: string): string { + return text + .toLowerCase() + .replace(/[^\p{L}\p{N}]+/gu, '-') + .replace(/^-+|-+$/g, ''); +} + +function decodeEntities(text: string): string { + return text + .replace(/ /g, ' ') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, '&'); +} + +/** The headings of `text`, in order, each with its anchor. `html` is whether the body's field type writes HTML. */ +export function headingsOf(text: string, html: boolean): BodyHeading[] { + const raw: Array<{ heading: string; level: number; start: number }> = []; + if (html) { + for (const h of htmlHeadingsOf(text)) { + const heading = decodeEntities(stripBodyTags(h.inner)).replace(/\s+/g, ' ').trim(); + if (heading) raw.push({ heading, level: h.level, start: h.start }); + } + } else { + let inFence = false; + let offset = 0; + for (const line of text.split('\n')) { + if (isFence(line)) inFence = !inFence; + else if (!inFence) { + const m = markdownHeadingOf(line.endsWith('\r') ? line.slice(0, -1) : line); + if (m) raw.push({ heading: m.heading, level: m.level, start: offset }); + } + offset += line.length + 1; + } + } + const seen = new Map(); + return raw.map((h, i) => { + const base = slugOf(h.heading) || `section-${i + 1}`; + const n = (seen.get(base) ?? 0) + 1; + seen.set(base, n); + return { ...h, anchor: n === 1 ? base : `${base}-${n}` }; + }); +} diff --git a/packages/spec/src/ai/record-citation.test.ts b/packages/spec/src/ai/record-citation.test.ts new file mode 100644 index 00000000000..7ba0207417f --- /dev/null +++ b/packages/spec/src/ai/record-citation.test.ts @@ -0,0 +1,72 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0160 D9] The record citation shape: closed, `quote` required and + * non-empty, `context` admitted (third amendment), and the list capped. + * + * The refusal legs assert the issue zod answers (`unrecognized_keys`, + * `too_small`, `invalid_type`, `too_big`) and its path, not a bare failure: a + * shape that degraded to a loose object would still fail on `null`. + */ + +import { describe, expect, it } from 'vitest'; +import { + RECORD_CITATIONS_MAX, + RECORD_CITATIONS_PART_TYPE, + RecordCitationSchema, + RecordCitationsSchema, +} from './index'; + +const CITATION = { object: 'policy', id: 'p1', quote: 'Covers fire.' }; + +/** The first issue's code and path, or `undefined` when the parse succeeds. */ +function firstIssue(schema: { safeParse(v: unknown): { success: boolean; error?: { issues: Array<{ code: string; path: PropertyKey[]; keys?: string[] }> } } }, value: unknown) { + const result = schema.safeParse(value); + if (result.success) return undefined; + const [issue] = result.error!.issues; + return { code: issue.code, path: issue.path, keys: issue.keys }; +} + +describe('[ADR-0160 D9] RecordCitationSchema', () => { + it('admits object, id and quote, with context and anchor optional', () => { + expect(RecordCitationSchema.safeParse(CITATION).success).toBe(true); + const full = { ...CITATION, context: 'crm-policy_document', anchor: 'exclusions' }; + const parsed = RecordCitationSchema.safeParse(full); + expect(parsed.success).toBe(true); + expect(parsed.data).toEqual(full); + }); + + it('refuses an unknown key, never drops it', () => { + expect(firstIssue(RecordCitationSchema, { ...CITATION, field: 'title' })).toMatchObject({ + code: 'unrecognized_keys', + keys: ['field'], + }); + }); + + it('refuses an empty quote, and a missing one', () => { + expect(firstIssue(RecordCitationSchema, { ...CITATION, quote: '' })).toMatchObject({ code: 'too_small', path: ['quote'] }); + const { quote: _quote, ...noQuote } = CITATION; + expect(firstIssue(RecordCitationSchema, noQuote)).toMatchObject({ code: 'invalid_type', path: ['quote'] }); + }); + + it('refuses null, and an empty context or anchor', () => { + expect(firstIssue(RecordCitationSchema, null)).toMatchObject({ code: 'invalid_type', path: [] }); + expect(firstIssue(RecordCitationSchema, { ...CITATION, context: '' })).toMatchObject({ code: 'too_small', path: ['context'] }); + expect(firstIssue(RecordCitationSchema, { ...CITATION, anchor: '' })).toMatchObject({ code: 'too_small', path: ['anchor'] }); + }); +}); + +describe('[ADR-0160 D9] RecordCitationsSchema and the data part', () => { + it('caps the list at RECORD_CITATIONS_MAX', () => { + expect(RECORD_CITATIONS_MAX).toBe(20); + expect(RecordCitationsSchema.safeParse(Array.from({ length: RECORD_CITATIONS_MAX }, () => CITATION)).success).toBe(true); + expect(firstIssue(RecordCitationsSchema, Array.from({ length: RECORD_CITATIONS_MAX + 1 }, () => CITATION))).toMatchObject({ + code: 'too_big', + path: [], + }); + }); + + it('names the UI-message data part the verified list rides', () => { + expect(RECORD_CITATIONS_PART_TYPE).toBe('data-record-citations'); + }); +}); diff --git a/packages/spec/src/ai/record-citation.zod.ts b/packages/spec/src/ai/record-citation.zod.ts new file mode 100644 index 00000000000..4c61db6c485 --- /dev/null +++ b/packages/spec/src/ai/record-citation.zod.ts @@ -0,0 +1,100 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { lazySchema } from '../shared/lazy-schema'; +import { strictObject } from '../shared/strict-object'; + +/** + * A record citation — the passage of a record an answer rests on + * (ADR-0160 D9, as amended a third time). + * + * One citation is `{ object, id, context?, anchor?, quote }`. It is the record + * sibling of a dataset answer's `sourceLine` (`dataset-tools.zod.ts`), with one + * difference: a dataset answer's provenance is composed by the tool, while a + * citation is written by the model, so it is a claim. The shape lets the + * platform check the claim without a model: `quote` must be found verbatim in + * the data member of what `get_record_context` answers for `object`, `id`, + * `context` and `anchor` to the asking user (`record-context-tools.zod.ts`, + * `RecordContextDataSchema`). + * + * - `object`, `id` name the root record of the pack the statement was read + * through. A quote taken from a related row still names the root. + * - `context` names that pack, spelt as `get_record_context`'s `context` + * argument takes it. It may be omitted when the object has one pack; on an + * object with several, a citation without it is not verified. + * - `anchor` is a heading of the root record's body, as the body outline + * issued it (`record-body-anchor.ts`, `headingsOf`). Omitted when the + * citation is to the record as a whole or to a field. + * - `quote` is the passage relied on, verbatim from text the tool returned. + * + * A citation is verified once, when the answer is produced, by the platform + * as the asking user; one whose quote is not found, or whose verifying call is + * refused, is dropped before the answer is shown. The verified list is + * persisted with the message, and no surface re-verifies it on display. The + * verifier is `@objectstack/service-record-context`'s `verifyRecordCitations`; + * only the shapes are spec. + * + * The verified list rides an answer as a UI-message data part named + * {@link RECORD_CITATIONS_PART_TYPE}, whose `data` is a + * {@link RecordCitationsSchema} list. + */ + +/** + * The stream part name a verified citation list rides, as a UI-message-stream + * custom data-part name (the precedent is `BUILD_PROGRESS_FRAME_TYPE`). The + * producer and every surface that draws the list select the part by exactly + * this string. + */ +export const RECORD_CITATIONS_PART_TYPE = 'data-record-citations'; + +/** + * The most citations one answer carries. The verifier reads at most this many + * from the list a model wrote, so a model's list cannot make the platform read + * without bound; the same number bounds the persisted list. + */ +export const RECORD_CITATIONS_MAX = 20; + +/** One citation: the root record, the pack, the body section, and the passage. */ +export const RecordCitationSchema = lazySchema(() => strictObject( + { + surface: 'a record citation', + history: 'Declared closed from its first day: an unrecognized key is refused, never dropped.', + // `get_record_context`'s own spellings, and the near-misses a model reaches for. + aliases: { + objectName: 'object', + table: 'object', + recordId: 'id', + record_id: 'id', + pack: 'context', + contextName: 'context', + section: 'anchor', + text: 'quote', + excerpt: 'quote', + passage: 'quote', + }, + guidance: { + field: 'A citation names no field: quote the passage in `quote`, and it is found wherever the record\'s answer carries it.', + }, + }, + { + object: z.string().min(1).describe('The root record\'s object, as `get_record_context` was called with it'), + id: z.string().min(1).describe('The root record\'s id'), + context: z.string().min(1).optional().describe( + 'The context pack the record was read through, spelt as `get_record_context`\'s `context` argument takes it. ' + + 'Omit it only when the object has one pack', + ), + anchor: z.string().min(1).optional().describe( + 'A heading of the root record\'s body, by the `anchor` the body outline issued. Omit it when the citation is ' + + 'to the record as a whole or to a field', + ), + quote: z.string().min(1).describe('The passage relied on, verbatim from text the tool returned'), + }, +)); + +/** The citations of one answer, at most {@link RECORD_CITATIONS_MAX}. */ +export const RecordCitationsSchema = lazySchema(() => z.array(RecordCitationSchema).max(RECORD_CITATIONS_MAX)); + +export type RecordCitation = z.input; +export type RecordCitationParsed = z.infer; +export type RecordCitations = z.input; +export type RecordCitationsParsed = z.infer; From c46e26d72f2952bba88b3528b38e551d42609949 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:38:23 +0000 Subject: [PATCH 2/4] chore(spec): regenerate the ai artifacts for the record citation shape, and add the changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .changeset/37364-record-citation-verifier.md | 17 ++++ content/docs/references/ai/index.mdx | 3 +- content/docs/references/ai/meta.json | 1 + .../docs/references/ai/record-citation.mdx | 79 +++++++++++++++++++ content/docs/references/index.mdx | 9 ++- .../ai.md | 2 +- packages/spec/api-surface/ai.json | 11 +++ packages/spec/authorable-surface/ai.json | 5 ++ packages/spec/declaration-map/ai.json | 4 + packages/spec/export-origins/ai.json | 11 +++ packages/spec/json-schema.manifest/ai.json | 2 + 11 files changed, 138 insertions(+), 6 deletions(-) create mode 100644 .changeset/37364-record-citation-verifier.md create mode 100644 content/docs/references/ai/record-citation.mdx diff --git a/.changeset/37364-record-citation-verifier.md b/.changeset/37364-record-citation-verifier.md new file mode 100644 index 00000000000..582fd5ec924 --- /dev/null +++ b/.changeset/37364-record-citation-verifier.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-record-context': minor +--- + +feat(ai): the record citation shape enters spec, with the verifier that checks a citation's quote as the asking user (ADR-0160 D9) + +Clause-②: yes +Metadata-protocol: added +Skills-docs: follow-up #37177 + +An AI answer about a record may carry citations: the passage of the record it rests on. + +- **`@objectstack/spec/ai`**: `RecordCitationSchema` is `{ object, id, context?, anchor?, quote }`, closed (an unknown key is refused), with `quote` required and non-empty. `RecordCitationsSchema` is a list of at most `RECORD_CITATIONS_MAX` (20). `RECORD_CITATIONS_PART_TYPE` (`data-record-citations`) names the UI-message data part a verified list rides. `headingsOf` and `stripBodyTags` (`record-body-anchor.ts`) derive a body's headings and anchors, so the server and a surface that opens a record at a cited anchor derive the same anchor. +- **`@objectstack/service-record-context`**: `verifyRecordCitations(citations, door)` returns the citations that survive. For each distinct `(object, id, context, anchor)` it calls `get_record_context` once, through the door bound to the asking user, and keeps a citation only when its `quote` is found in that answer's data member: a field or related-list cell `value` (when it is a string) or `display`, or the body `text` (an `html`/`richtext` body also with its tags removed). Whitespace runs collapse; case and every other character must agree. Notes, the framing sentence and labels are never matched. A refused call (a pack that does not exist, several packs and no `context`, an anchor that does not resolve, a record the caller cannot read) drops its citations. It never throws for a citation, and it reads at most the first 20 entries. + +Nothing produces or draws citations yet: the producer persists the verified list with the message, and surfaces draw it without re-verifying. diff --git a/content/docs/references/ai/index.mdx b/content/docs/references/ai/index.mdx index 5c4045f64b3..3930f47124e 100644 --- a/content/docs/references/ai/index.mdx +++ b/content/docs/references/ai/index.mdx @@ -1,7 +1,7 @@ --- title: AI Protocol — complete schema reference navTitle: AI Protocol -description: "The ObjectStack AI Protocol in 16 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." +description: "The ObjectStack AI Protocol in 17 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -20,6 +20,7 @@ This section contains all protocol schemas for the ai layer of ObjectStack. + diff --git a/content/docs/references/ai/meta.json b/content/docs/references/ai/meta.json index dcfb319de89..00712c3186f 100644 --- a/content/docs/references/ai/meta.json +++ b/content/docs/references/ai/meta.json @@ -20,6 +20,7 @@ "build-progress", "dataset-tools", "object-query-source", + "record-citation", "record-context-tools" ] } \ No newline at end of file diff --git a/content/docs/references/ai/record-citation.mdx b/content/docs/references/ai/record-citation.mdx new file mode 100644 index 00000000000..9be846f6de1 --- /dev/null +++ b/content/docs/references/ai/record-citation.mdx @@ -0,0 +1,79 @@ +--- +title: Record Citation schema — AI Protocol reference +navTitle: Record Citation +description: "A record citation — the passage of a record an answer rests on. One citation is { object, id, context?, anchor?, quote }." +--- + +{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} + +A record citation — the passage of a record an answer rests on +(ADR-0160 D9, as amended a third time). + +One citation is `{ object, id, context?, anchor?, quote }`. It is the record +sibling of a dataset answer's `sourceLine` (`dataset-tools.zod.ts`), with one +difference: a dataset answer's provenance is composed by the tool, while a +citation is written by the model, so it is a claim. The shape lets the +platform check the claim without a model: `quote` must be found verbatim in +the data member of what `get_record_context` answers for `object`, `id`, +`context` and `anchor` to the asking user (`record-context-tools.zod.ts`, +`RecordContextDataSchema`). + +- `object`, `id` name the root record of the pack the statement was read + through. A quote taken from a related row still names the root. +- `context` names that pack, spelt as `get_record_context`'s `context` + argument takes it. It may be omitted when the object has one pack; on an + object with several, a citation without it is not verified. +- `anchor` is a heading of the root record's body, as the body outline + issued it (`record-body-anchor.ts`, `headingsOf`). Omitted when the + citation is to the record as a whole or to a field. +- `quote` is the passage relied on, verbatim from text the tool returned. + +A citation is verified once, when the answer is produced, by the platform +as the asking user; one whose quote is not found, or whose verifying call is +refused, is dropped before the answer is shown. The verified list is +persisted with the message, and no surface re-verifies it on display. The +verifier is `@objectstack/service-record-context`'s `verifyRecordCitations`; +only the shapes are spec. + +The verified list rides an answer as a UI-message data part named +`RECORD_CITATIONS_PART_TYPE`, whose `data` is a +`RecordCitationsSchema` list. + + +**Source:** `packages/spec/src/ai/record-citation.zod.ts` + + +## TypeScript Usage + +```typescript +import { RecordCitationSchema, RecordCitationsSchema } from '@objectstack/spec/ai'; +import type { RecordCitation, RecordCitations } from '@objectstack/spec/ai'; + +// Validate data +const result = RecordCitationSchema.parse(data); +``` + +--- + +## RecordCitation + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **object** | `string` | ✅ | The root record's object, as `get_record_context` was called with it | +| **id** | `string` | ✅ | The root record's id | +| **context** | `string` | optional | The context pack the record was read through, spelt as `get_record_context`'s `context` argument takes it. Omit it only when the object has one pack | +| **anchor** | `string` | optional | A heading of the root record's body, by the `anchor` the body outline issued. Omit it when the citation is to the record as a whole or to a field | +| **quote** | `string` | ✅ | The passage relied on, verbatim from text the tool returned | + + +--- + +## RecordCitations + +**Type:** `{ object: string; id: string; context?: string; anchor?: string; … }[]` + + +--- + diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 2264223dc58..2d3540baa02 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1733 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1735 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -20,7 +20,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 16 | 100 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 17 | 102 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -34,13 +34,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 184 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **221** | **1733** | 14 protocol modules | +| **Total** | **222** | **1735** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **16 pages, 100 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 102 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -57,6 +57,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` | | [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` | | [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` | +| [`record-citation.zod.ts`](/docs/references/ai/record-citation) | `RecordCitation`, `RecordCitations` | | [`record-context-tools.zod.ts`](/docs/references/ai/record-context-tools) | `GetRecordContextInput`, `GetRecordContextOutput`, `RecordContextBody`, `RecordContextData`, `RecordContextFieldEntry`, `RecordContextNote`, `RecordContextNoteKind`, `RecordContextOutlineEntry`, `RecordContextRelatedList`, `RecordContextRelatedRow` | | [`skill.zod.ts`](/docs/references/ai/skill) | `Skill`, `SkillTriggerCondition` | | [`solution-blueprint.zod.ts`](/docs/references/ai/solution-blueprint) | `BlueprintApp`, `BlueprintCondition`, `BlueprintDashboard`, `BlueprintField`, `BlueprintNavItem`, `BlueprintObject`, `BlueprintSeed`, `BlueprintSummaryOperations`, `BlueprintView`, `BlueprintWidgetCondition`, `SolutionBlueprint`, `SolutionBlueprintStrict` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index b6c17cf082f..37985ae75bb 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 113 | +| `ai/` | 114 | diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 0da0ce0e2f0..74918bec2bf 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -58,6 +58,7 @@ "BlueprintViewSchema (const)", "BlueprintWidgetCondition (type)", "BlueprintWidgetConditionSchema (const)", + "BodyHeading (interface)", "BuildProgressFrame (type)", "BuildProgressFrameSchema (const)", "BuildProgressPhase (type)", @@ -214,6 +215,14 @@ "QueryDatasetInputSchema (const)", "QueryDatasetOutput (type)", "QueryDatasetOutputSchema (const)", + "RECORD_CITATIONS_MAX (const)", + "RECORD_CITATIONS_PART_TYPE (const)", + "RecordCitation (type)", + "RecordCitationParsed (type)", + "RecordCitationSchema (const)", + "RecordCitations (type)", + "RecordCitationsParsed (type)", + "RecordCitationsSchema (const)", "RecordContextBody (type)", "RecordContextBodyParsed (type)", "RecordContextBodySchema (const)", @@ -289,8 +298,10 @@ "deriveAiFaceName (function)", "getDatasetToolJsonSchemas (function)", "getRecordContextToolJsonSchemas (function)", + "headingsOf (function)", "scopesToAgentPermissionSets (function)", "skillForm (const)", + "stripBodyTags (function)", "toolForm (const)" ] } diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 33d080f6ceb..d9c4a863fea 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -416,6 +416,11 @@ "ai/QueryDatasetOutput:totals", "ai/QueryDatasetOutput:truncated", "ai/QueryDatasetOutput:warning", + "ai/RecordCitation:anchor", + "ai/RecordCitation:context", + "ai/RecordCitation:id", + "ai/RecordCitation:object", + "ai/RecordCitation:quote", "ai/RecordContextBody:anchor", "ai/RecordContextBody:field", "ai/RecordContextBody:label", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index b45a72c56a2..387c0d02c39 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -149,6 +149,10 @@ "QueryDatasetInputSchema": "ai/QueryDatasetInput", "QueryDatasetOutput": "ai/QueryDatasetOutput", "QueryDatasetOutputSchema": "ai/QueryDatasetOutput", + "RecordCitation": "ai/RecordCitation", + "RecordCitationSchema": "ai/RecordCitation", + "RecordCitations": "ai/RecordCitations", + "RecordCitationsSchema": "ai/RecordCitations", "RecordContextBody": "ai/RecordContextBody", "RecordContextBodySchema": "ai/RecordContextBody", "RecordContextData": "ai/RecordContextData", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index a9376d6b33e..cc5f99d983e 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -58,6 +58,7 @@ "BlueprintViewSchema": "src/ai/solution-blueprint.zod.ts#BlueprintViewSchema (const)", "BlueprintWidgetCondition": "src/ai/solution-blueprint.zod.ts#BlueprintWidgetCondition (type)", "BlueprintWidgetConditionSchema": "src/ai/solution-blueprint.zod.ts#BlueprintWidgetConditionSchema (const)", + "BodyHeading": "src/ai/record-body-anchor.ts#BodyHeading (interface)", "BuildProgressFrame": "src/ai/build-progress.zod.ts#BuildProgressFrame (type)", "BuildProgressFrameSchema": "src/ai/build-progress.zod.ts#BuildProgressFrameSchema (const)", "BuildProgressPhase": "src/ai/build-progress.zod.ts#BuildProgressPhase (type)", @@ -212,6 +213,14 @@ "QueryDatasetInputSchema": "src/ai/dataset-tools.zod.ts#QueryDatasetInputSchema (const)", "QueryDatasetOutput": "src/ai/dataset-tools.zod.ts#QueryDatasetOutput (type)", "QueryDatasetOutputSchema": "src/ai/dataset-tools.zod.ts#QueryDatasetOutputSchema (const)", + "RECORD_CITATIONS_MAX": "src/ai/record-citation.zod.ts#RECORD_CITATIONS_MAX (const)", + "RECORD_CITATIONS_PART_TYPE": "src/ai/record-citation.zod.ts#RECORD_CITATIONS_PART_TYPE (const)", + "RecordCitation": "src/ai/record-citation.zod.ts#RecordCitation (type)", + "RecordCitationParsed": "src/ai/record-citation.zod.ts#RecordCitationParsed (type)", + "RecordCitationSchema": "src/ai/record-citation.zod.ts#RecordCitationSchema (const)", + "RecordCitations": "src/ai/record-citation.zod.ts#RecordCitations (type)", + "RecordCitationsParsed": "src/ai/record-citation.zod.ts#RecordCitationsParsed (type)", + "RecordCitationsSchema": "src/ai/record-citation.zod.ts#RecordCitationsSchema (const)", "RecordContextBody": "src/ai/record-context-tools.zod.ts#RecordContextBody (type)", "RecordContextBodyParsed": "src/ai/record-context-tools.zod.ts#RecordContextBodyParsed (type)", "RecordContextBodySchema": "src/ai/record-context-tools.zod.ts#RecordContextBodySchema (const)", @@ -286,8 +295,10 @@ "deriveAiFaceName": "src/ai/face-name.ts#deriveAiFaceName (function)", "getDatasetToolJsonSchemas": "src/ai/dataset-tools.zod.ts#getDatasetToolJsonSchemas (function)", "getRecordContextToolJsonSchemas": "src/ai/record-context-tools.zod.ts#getRecordContextToolJsonSchemas (function)", + "headingsOf": "src/ai/record-body-anchor.ts#headingsOf (function)", "scopesToAgentPermissionSets": "src/ai/mcp.zod.ts#scopesToAgentPermissionSets (function)", "skillForm": "src/ai/skill.form.ts#skillForm (const)", + "stripBodyTags": "src/ai/record-body-anchor.ts#stripBodyTags (function)", "toolForm": "src/ai/tool.form.ts#toolForm (const)" } } diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 52674e76eb5..1c268ee6298 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -78,6 +78,8 @@ "ai/PromptVariable", "ai/QueryDatasetInput", "ai/QueryDatasetOutput", + "ai/RecordCitation", + "ai/RecordCitations", "ai/RecordContextBody", "ai/RecordContextData", "ai/RecordContextFieldEntry", From 36ec0cf687a093cd370f38784c4b35a4bfcb5cff Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:43:58 +0000 Subject: [PATCH 3/4] fix(spec): drop the record_id alias that collapses onto recordId's probe Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- packages/spec/src/ai/record-citation.zod.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/spec/src/ai/record-citation.zod.ts b/packages/spec/src/ai/record-citation.zod.ts index 4c61db6c485..76ded7ac9d7 100644 --- a/packages/spec/src/ai/record-citation.zod.ts +++ b/packages/spec/src/ai/record-citation.zod.ts @@ -64,7 +64,6 @@ export const RecordCitationSchema = lazySchema(() => strictObject( objectName: 'object', table: 'object', recordId: 'id', - record_id: 'id', pack: 'context', contextName: 'context', section: 'anchor', From 8471b77d705d386251204a83ee11281712e47074 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:19:37 +0000 Subject: [PATCH 4/4] docs(spec): count the record citation module in llms.txt's schema inventory Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- packages/spec/llms.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 49428e2bcbc..bb4b08b166e 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -77,7 +77,7 @@ const query = { --- -## 3. Schema Inventory by Domain (230 schemas) +## 3. Schema Inventory by Domain (231 schemas) Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number @@ -92,7 +92,7 @@ here is verifiable from the installed package. | ui | 18 | View, App, Action, Dashboard, Page, Chart, Component, Animation | | automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization | | shared | 16 | Enums, HTTP, Identifiers, Mapping, Metadata Types, Connector Auth, Retry Policy, Conditional Formatting, Value Domain, Epoch Instant (EpochMs), Duration (DurationMs / DurationSeconds) | -| ai | 16 | Agent, AI Context (context pack), Build Progress, Conversation, Dataset Tools, Knowledge Source/Document, Model Registry, MCP, Object-Query Source, Record Context Tools (`get_record_context`), Skill, Tool | +| ai | 17 | Agent, AI Context (context pack), Build Progress, Conversation, Dataset Tools, Knowledge Source/Document, Model Registry, MCP, Object-Query Source, Record Citation, Record Context Tools (`get_record_context`), Skill, Tool | | identity | 5 | Identity, Organization, Position, SCIM, Eval User | | marketplace | 5 | Marketplace, Package, Package Version, Template Manifest, Taxonomy | | security | 5 | Permission, RLS, Sharing, Queue, Explain |