Skip to content

Commit db46566

Browse files
feat(spec,service-record-context): the record citation shape, and the verifier that checks a quote as the asking user (ADR-0160 D9) (#37396)
Fixes #37364 Clause-②: yes Metadata-protocol: added Skills-docs: follow-up #37177 ## 维护者速读 - 用户能看到什么变化:用户无感。本次只交付"引用"的格式定义和核对器;AI 回答里的引用还没有产生方,也没有界面展示。 - 为什么做:记录范围 AI 问询专题的第 10 行前半(引用格式与核对器),按维护者已定的三条裁决实现;界面展示和云端产生引用两张后续卡依赖它。 - 出错会怎样:最坏是核对器把一条真实的引用判为"未核对通过"而丢掉,回答少一条引用;它以提问人本人的权限读记录,不会让提问人看到无权看的内容;撤回此 PR 即可,没有数据需要迁移。 - 要你做什么:无。 ## What changes Governing text: ADR-0160 D9 as amended by #37370 (third amendment), ruling 7177410380 on #37144 (Q1 A, Q2 A, Q3 A), ADR point 23. **Spec (`@objectstack/spec/ai`)** - `record-citation.zod.ts` (new): `RecordCitationSchema` = `{ object, id, context?, anchor?, quote }`, closed with `strictObject` (unknown key refused, near-miss aliases such as `objectName`/`recordId`/`pack`/`section`/`text`), every string `min(1)`. `RecordCitationsSchema` = an array of at most `RECORD_CITATIONS_MAX` (20). `RECORD_CITATIONS_PART_TYPE = 'data-record-citations'`: the UI-message data part that carries the verified list (the precedent is `BUILD_PROGRESS_FRAME_TYPE`). - `record-body-anchor.ts` (new): `headingsOf` and `slugOf` moved here unchanged from `service-record-context/src/body-outline.ts`, together with the private readers they need. This way the server and the console derive the same anchor. `slugOf` stays module-private, as before. The tag reader `headingsOf` already used is exported as `stripBodyTags`, because the verifier matches an html body with the same notion of a tag. - Generated: `authorable-surface/ai.json` (5 `RecordCitation` rows), `json-schema.manifest`, `api-surface`, `export-origins`, `declaration-map`, `content/docs/references/ai/*`, and the strictness-ledger count (`ai/` 113 to 114), all written by `check:generated --fix`. **Service (`@objectstack/service-record-context`)** - `body-outline.ts` re-imports `headingsOf` and `BodyHeading` from spec and re-exports them. `body-outline.test.ts` passes untouched. - `verify-citations.ts` (new), `verifyRecordCitations(citations, door)`, exported from `src/index.ts`. It never persists or renders. **The matching rule, which ADR-0160 D9 leaves to row 10 and which the card's What 3 settles.** A citation survives only when its trimmed `quote` is a substring of one of these data-member strings of `get_record_context`'s answer for its `(object, id, context, anchor)`, read through the door bound to the asking user: - a field entry's `value` when it is a string, and its `display`, at the root and in every related-list cell (Q3: a related-row quote is cited on the root record); - `body.text` (the whole body, or the section `anchor` named). An `html`/`richtext` body (judged by the type the caller is served) is also matched with its tags removed. Whitespace runs collapse to one space on both sides. Case and every other character must agree. These are never matched: notes, the framing sentence, any label, the pack/record header (`pack.*`, `record.*`, a row's `displayName`), outline headings, and a value that is not a string (a number, boolean, list or object; its `display` is matched where present). A quote that is empty once trimmed verifies nothing. **What the verifier does with the list.** It makes one `executeGetRecordContext` call per distinct tuple. Any refused call drops its citations (point 23): a `context` no pack has, several packs and no `context` (Q2), an anchor that does not resolve, a record the caller cannot read or that does not exist, an object not served, guarded or unexposed. No retry without the offending argument. An entry that does not parse is dropped, and only the first 20 entries are read. The result is the verified subset in input order, with no reason attached, so a hidden record and a missing one look alike. <details><summary>Read first (by risk)</summary> 1. `packages/services/service-record-context/src/verify-citations.ts`: `haystackOf` holds the matching rule above. The risky part is which strings it collects. 2. `packages/spec/src/ai/record-citation.zod.ts`: the public shape, the aliases and the cap of 20. 3. `packages/services/service-record-context/src/body-outline.ts`: the move. Byte-identical logic now lives in `packages/spec/src/ai/record-body-anchor.ts` (only `stripTags` was renamed to the exported `stripBodyTags`). </details> ## Tests - `packages/spec/src/ai/record-citation.test.ts` (6): the shape refuses an unknown key (`unrecognized_keys`), an empty `quote` (`too_small`), a missing `quote` and `null` (`invalid_type`), an empty `context`/`anchor`. It admits `context` and `anchor`. The list is capped at 20 (`too_big`). The part type is pinned. - `packages/services/service-record-context/src/__tests__/verify-citations.test.ts` (16), one per acceptance bullet plus the rule. Each "dropped" case has a control leg: - section by anchor verified, stale anchor refused, anchor scopes the match; - related-list cell verified on the root, while another policy's row is not; - note, framing and labels refused (the control shows the answer carries each); - withheld and hidden field refused (the control verifies the same quote unhidden); - outline body without anchor refused, the same quote with its anchor verified; - two packs without `context` refused, one pack verified, named packs verified, unknown pack refused; - no read access (unreadable row, missing id, unserved, guarded, unexposed object) all answer `[]`; - one call per distinct tuple (`listCalls` = 2 for 5 citations), unparsable entries dropped, cap of 20, html/richtext tag-stripped and markdown not, whitespace collapse, non-string value not matched. <details><summary>Readings (head 36ec0cf)</summary> - `pnpm --filter @objectstack/service-record-context test`: Test Files 3 passed (3), Tests 115 passed (115). `typecheck`: exit 0. - `pnpm --filter @objectstack/spec test`: first run on c46e26d had 1 failure, `alias-integrity.test.ts` (aliases `recordId` and `record_id` collapse onto one probe). Fixed in 36ec0cf by dropping `record_id`. Re-run of that file plus `record-citation.test.ts`: 26/26. The final full-suite reading is in the report. - `pnpm --filter @objectstack/spec typecheck`: exit 0. - Ablation, one behaviour (the data-member restriction): `scripts/ablation-replace.mjs` made `haystackOf` also collect `answer.framing`, the note texts and `pack.label`. Result: anchor 1 to 0, blob c35fc72 to dcec1804, and `refuses a quote that appears only in a note, the framing, or a label` went red (1 failed / 15 passed). Restored: blob equals HEAD, `git diff HEAD` empty. A first attempt was a no-op that the tool refused before running: its replacement contained the anchor. The test runs `src` directly, so no dist rebuild was needed for the mutated file. </details> ## Acceptance notes - **The cap of 20** is the card's "an array with a cap" turned into a number. It bounds both how many calls a model's list can trigger and the persisted list. Easy to change before 10b/10c read it. - **Tag-stripping removes a tag with nothing in its place**, as `headingsOf` reads heading text. So a quote that spans two paragraph elements, written with a space where the two paragraphs meet, is not verified. HTML entities in the body are not decoded either: an ampersand entity has to be quoted as the entity. Both follow the card's rule as written. They only make verification stricter, never looser. - **Overlap**: #37366 also writes the generated `packages/spec/export-origins/ai.json`. Whichever PR lands second regenerates it. - Out of scope, as the card says: an MCP verify tool, rendering (10b), producing and persisting citations (cloud 10c). ## Verification Two minutes: `pnpm --filter @objectstack/service-record-context exec vitest run --maxWorkers=2 src/__tests__/verify-citations.test.ts`. Expect 16 passed. The `context (Q2)` block shows a two-pack object dropping a citation that has no `context`. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CbeF2saT6wUBV4E9uc --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 51b67f1 commit db46566

20 files changed

Lines changed: 853 additions & 177 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/service-record-context': minor
4+
---
5+
6+
feat(ai): the record citation shape enters spec, with the verifier that checks a citation's quote as the asking user (ADR-0160 D9)
7+
8+
Clause-②: yes
9+
Metadata-protocol: added
10+
Skills-docs: follow-up #37177
11+
12+
An AI answer about a record may carry citations: the passage of the record it rests on.
13+
14+
- **`@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.
15+
- **`@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.
16+
17+
Nothing produces or draws citations yet: the producer persists the verified list with the message, and surfaces draw it without re-verifying.

‎content/docs/references/ai/index.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: AI Protocol — complete schema reference
33
navTitle: AI Protocol
4-
description: "The ObjectStack AI Protocol in 16 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example."
4+
description: "The ObjectStack AI Protocol in 17 reference pages: every schema in @objectstack/spec with its properties, types, defaults and a TypeScript example."
55
---
66

77
{/* ⚠️ 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.
2020
<Card href="/docs/references/ai/mcp" title="Mcp" description="Source: packages/spec/src/ai/mcp.zod.ts" />
2121
<Card href="/docs/references/ai/model-registry" title="Model Registry" description="Source: packages/spec/src/ai/model-registry.zod.ts" />
2222
<Card href="/docs/references/ai/object-query-source" title="Object Query Source" description="Source: packages/spec/src/ai/object-query-source.zod.ts" />
23+
<Card href="/docs/references/ai/record-citation" title="Record Citation" description="Source: packages/spec/src/ai/record-citation.zod.ts" />
2324
<Card href="/docs/references/ai/record-context-tools" title="Record Context Tools" description="Source: packages/spec/src/ai/record-context-tools.zod.ts" />
2425
<Card href="/docs/references/ai/skill" title="Skill" description="Source: packages/spec/src/ai/skill.zod.ts" />
2526
<Card href="/docs/references/ai/solution-blueprint" title="Solution Blueprint" description="Source: packages/spec/src/ai/solution-blueprint.zod.ts" />

‎content/docs/references/ai/meta.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"build-progress",
2121
"dataset-tools",
2222
"object-query-source",
23+
"record-citation",
2324
"record-context-tools"
2425
]
2526
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
---
2+
title: Record Citation schema — AI Protocol reference
3+
navTitle: Record Citation
4+
description: "A record citation — the passage of a record an answer rests on. One citation is { object, id, context?, anchor?, quote }."
5+
---
6+
7+
{/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */}
8+
9+
A record citation — the passage of a record an answer rests on
10+
(ADR-0160 D9, as amended a third time).
11+
12+
One citation is `{ object, id, context?, anchor?, quote }`. It is the record
13+
sibling of a dataset answer's `sourceLine` (`dataset-tools.zod.ts`), with one
14+
difference: a dataset answer's provenance is composed by the tool, while a
15+
citation is written by the model, so it is a claim. The shape lets the
16+
platform check the claim without a model: `quote` must be found verbatim in
17+
the data member of what `get_record_context` answers for `object`, `id`,
18+
`context` and `anchor` to the asking user (`record-context-tools.zod.ts`,
19+
`RecordContextDataSchema`).
20+
21+
- `object`, `id` name the root record of the pack the statement was read
22+
through. A quote taken from a related row still names the root.
23+
- `context` names that pack, spelt as `get_record_context`'s `context`
24+
argument takes it. It may be omitted when the object has one pack; on an
25+
object with several, a citation without it is not verified.
26+
- `anchor` is a heading of the root record's body, as the body outline
27+
issued it (`record-body-anchor.ts`, `headingsOf`). Omitted when the
28+
citation is to the record as a whole or to a field.
29+
- `quote` is the passage relied on, verbatim from text the tool returned.
30+
31+
A citation is verified once, when the answer is produced, by the platform
32+
as the asking user; one whose quote is not found, or whose verifying call is
33+
refused, is dropped before the answer is shown. The verified list is
34+
persisted with the message, and no surface re-verifies it on display. The
35+
verifier is `@objectstack/service-record-context`'s `verifyRecordCitations`;
36+
only the shapes are spec.
37+
38+
The verified list rides an answer as a UI-message data part named
39+
`RECORD_CITATIONS_PART_TYPE`, whose `data` is a
40+
`RecordCitationsSchema` list.
41+
42+
<Callout type="info">
43+
**Source:** `packages/spec/src/ai/record-citation.zod.ts`
44+
</Callout>
45+
46+
## TypeScript Usage
47+
48+
```typescript
49+
import { RecordCitationSchema, RecordCitationsSchema } from '@objectstack/spec/ai';
50+
import type { RecordCitation, RecordCitations } from '@objectstack/spec/ai';
51+
52+
// Validate data
53+
const result = RecordCitationSchema.parse(data);
54+
```
55+
56+
---
57+
58+
## RecordCitation
59+
60+
### Properties
61+
62+
| Property | Type | Required | Description |
63+
| :--- | :--- | :--- | :--- |
64+
| **object** | `string` | ✅ | The root record's object, as `get_record_context` was called with it |
65+
| **id** | `string` | ✅ | The root record's id |
66+
| **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 |
67+
| **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 |
68+
| **quote** | `string` | ✅ | The passage relied on, verbatim from text the tool returned |
69+
70+
71+
---
72+
73+
## RecordCitations
74+
75+
**Type:** `{ object: string; id: string; context?: string; anchor?: string; … }[]`
76+
77+
78+
---
79+

‎content/docs/references/index.mdx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Protocol reference — every schema by module
33
navTitle: Protocol Reference
4-
description: Every schema published by @objectstack/spec — 1733 schemas across 14 protocol modules
4+
description: Every schema published by @objectstack/spec — 1735 schemas across 14 protocol modules
55
---
66

77
{/* ⚠️ 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
2020

2121
| Module | Pages | Schemas | Description |
2222
| :--- | ---: | ---: | :--- |
23-
| [AI Protocol](/docs/references/ai) | 16 | 100 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. |
23+
| [AI Protocol](/docs/references/ai) | 17 | 102 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. |
2424
| [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. |
2525
| [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. |
2626
| [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
3434
| [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. |
3535
| [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. |
3636
| [UI Protocol](/docs/references/ui) | 16 | 184 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. |
37-
| **Total** | **221** | **1733** | 14 protocol modules |
37+
| **Total** | **222** | **1735** | 14 protocol modules |
3838

3939
---
4040

4141
## AI Protocol
4242

43-
**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **16 pages, 100 schemas**
43+
**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 102 schemas**
4444

4545
Agents, tools, skills, RAG and knowledge sources, model registry, conversations.
4646

@@ -57,6 +57,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations.
5757
| [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` |
5858
| [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` |
5959
| [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` |
60+
| [`record-citation.zod.ts`](/docs/references/ai/record-citation) | `RecordCitation`, `RecordCitations` |
6061
| [`record-context-tools.zod.ts`](/docs/references/ai/record-context-tools) | `GetRecordContextInput`, `GetRecordContextOutput`, `RecordContextBody`, `RecordContextData`, `RecordContextFieldEntry`, `RecordContextNote`, `RecordContextNoteKind`, `RecordContextOutlineEntry`, `RecordContextRelatedList`, `RecordContextRelatedRow` |
6162
| [`skill.zod.ts`](/docs/references/ai/skill) | `Skill`, `SkillTriggerCondition` |
6263
| [`solution-blueprint.zod.ts`](/docs/references/ai/solution-blueprint) | `BlueprintApp`, `BlueprintCondition`, `BlueprintDashboard`, `BlueprintField`, `BlueprintNavItem`, `BlueprintObject`, `BlueprintSeed`, `BlueprintSummaryOperations`, `BlueprintView`, `BlueprintWidgetCondition`, `SolutionBlueprint`, `SolutionBlueprintStrict` |

‎docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate.
1919

2020
| Dir | Sites |
2121
|---|---|
22-
| `ai/` | 113 |
22+
| `ai/` | 114 |

0 commit comments

Comments
 (0)