Skip to content

Commit 59571b2

Browse files
feat(service-record-context): get_record_context lists a long body's outline in pages (outlineFrom / outlineNext) (#37484)
Fixes #37233 Clause-②: yes (widening) Metadata-protocol: added ## 维护者速读 - 用户能看到什么变化:外接 AI 读一条正文很长的记录时,目录超过一页上限的部分可以分页继续列出,每个章节都能读到;此前如果几百个标题都在同一层,第 80 个之后的章节 AI 根本读不到。 - 为什么做:记录级 AI 问答专题(资料包读取工具)的后续收尾,补上目录截断后剩余章节无法到达的缺口,并改正一句会误导 AI 的截断提示。 - 出错会怎样:最坏是 AI 读长文时多翻一页或少列几个标题,读到的内容仍受原有长度上限和权限约束;可以直接撤回本次改动。 - 要你做的:无。 ## What changes ADR-0160 D3 "The body"; L1 ACCEPT 7153812992 on PR #37222, nit N2 (this card), N3, N4. - **The outline comes in pages** (`boundedOutline(headings, from)`, `body-outline.ts`). The pages run through every heading in ONE order — shallowest level first, body order within a level — and a page takes that order from `from` until the next heading would pass either existing bound (80 entries, 8,000 serialized characters); each page lists its headings in body order. Page 1 is today's outline, bar the N3 case below. Every heading is on exactly one page, so following the continuation from page 1 lists every heading with the anchor `headingsOf` gives it. One mechanism serves both cuts: a flat body's pages are runs of it in body order; a nested body's first page is its top levels and later pages carry the deeper headings (which matters too: a top section past the body bound is itself cut, so its sub-headings past the cut were unreachable before as well). - **Input `outlineFrom`, output `body.outlineNext`** (`record-context-tools.zod.ts`). `outlineNext` is present only when a heading remains that a later page lists; pass it as `outlineFrom`. `outlineFrom` 0 is page 1. An `outlineFrom` past the last page, or on a body that is no outline (carried whole, absent from the pack, withheld from the caller), is ONE answer, `RESOURCE_NOT_FOUND` 404, as an unresolved `anchor` is. `anchor` with `outlineFrom` is refused `VALIDATION_ERROR` 400 at step 1, before any read. - **The `outline_truncated` sentence, en and zh-Hans** (`sentences.ts`), now says how many headings this page lists, how many it does not, that pages run shallowest levels first then body order, and the `outlineFrom` that lists the next page (or that no later page lists more). The clause "A listed section's text includes the headings under it" is gone: in a flat cut nothing left out sits under a listed section. The sentence carries numbers only, never an anchor (an anchor is record text, and a note never carries record text) — which is why the cursor is a position and not an anchor. - **N3, revisited because the paging made it cheap.** A heading whose entry alone passes the character bound fits no page. Without a change it would end the pages (the page that must start with it lists nothing), so the pages now pass over it and the note counts it ("1 heading is too long for any page to list, so its anchor is not given" / "K headings are too long ..."). As a side effect one such heading no longer empties page 1. A body whose ONLY headings are such headings is still carried to the bound and marked truncated, as before. Trade-off stated: such a heading (about 3,950 characters or more of heading text) gets no anchor; in a nested body its text is still inside its parent's section. - **N4**: no change needed (the changeset it named has merged). - Tool description: names `outlineNext` / `outlineFrom` beside `anchor`. - **The `body_outline` note, en and zh-Hans, on every page** now says to read a section with the same objectName, recordId and context, plus the anchor and no `outlineFrom`. Before, it said "the same arguments", and on a page reached through `outlineFrom` those arguments plus an anchor are the pair this PR refuses (review S1). - The MCP doors needed no code: both pass the input through whole, and the `/mcp` door's registration validates against the spec's `GetRecordContextInputSchema`, so the key is admitted there by the spec change alone. The real-kernel parity cases below prove both doors carry it. ### Design, and the alternative weighed Continuation (chosen) vs listing every omitted heading's anchor compactly: a compact list is still O(headings) in one answer, so for a large enough body it passes the same bound and needs a cut of its own; the continuation keeps every answer within the existing bounds however big the body, with one mechanism for flat and nested cuts. Cursor: a position in the page order, not an anchor, because the note that tells the model where to continue may not carry record text, and an anchor is derived from heading text. ### Declaration `Metadata-protocol: added`, `@objectstack/spec` graded `minor` (PM ruling, option A, on this PR's open question): the spec's authorable-surface ledger records `GetRecordContextInput:outlineFrom` and `RecordContextBody:outlineNext` as entered keys, and Check Changeset reads that shard as a metadata-protocol addition (precedent: #37140, #37354). `@objectstack/service-record-context` stays `patch`. ### ADR text this will need (governed, not edited here) - D4 "Definition", the input line `{ objectName: string, recordId: string, context?: string, anchor?: string }` gains `outlineFrom?: integer` (the output's body gains `outlineNext`). - D3 "The body", the sentence "A longer body is carried as an outline: its headings in order, each with an `anchor`." needs: an outline past its bounds comes in pages, continued by `outlineFrom`, every heading listed on one page (bar a heading too long to list by itself, stated). Carried by #37490, which should also say that the cursor is a position in the current body, so "exactly one page" holds for one state of the body. ## Tests See Verification for the commands and readings. - `body-outline.test.ts`: a flat body of 300 headings pages as 80/80/80/60 and the pages together are exactly the body's headings in order; a nested body's page 1 holds every top heading and later pages only deeper ones, each page in body order, union = all headings, no duplicates; the character bound before the entry cap; an over-long shallowest heading is on no page, counted, and does not empty page 1. - `record-context-tools.test.ts` (executor): **the acceptance pin** — a body of 300 headings at one level, every page walked by the `outlineNext` the tool gave, all 300 anchors issued once, every section read by its issued anchor and equal to its text, every answer parsing against `GetRecordContextOutputSchema` and within the bounds; the nested cut whose top section is itself cut; the `outline_truncated` sentence for a flat cut AND a nested cut in en AND zh-Hans (counts, `outlineFrom N`, no record text, the old clause absent); the last page; `outlineFrom: 0`; the one 404 answer (past the end / body whole / no body / withheld body); `anchor` + `outlineFrom` refused before any read; negative / fractional / string refused at parse. - `record-context-tools.zod.test.ts` (spec, new): admits and refuses `outlineFrom` and `outlineNext`, asserting zod's issue code and path; the JSON Schema projection carries `outlineFrom` as an integer of at least 0. - `mcp-record-context-tools-bridge.test.ts` (runtime, real kernel): page 2 over both doors, byte-equal, starts at `clause-(N+1)` (a door that dropped the key would answer page 1), and its anchor reads its section; `outlineFrom` on a body carried whole is the same coded 404 on both doors. - `mcp-record-context-tools.test.ts`: the registration's input property list gains `outlineFrom`. ## Acceptance notes - Acceptance bullet 1 (300 same-level headings, every section reached by issued anchors, each answer bounded): pinned in `record-context-tools.test.ts`, "a body of 300 headings at one level". - Acceptance bullet 2 (the note sentence true for nested and flat cuts, both pinned): "the cut note is true for a flat cut and for a nested cut, in en and zh-Hans". - Re-reading `outlineFrom` against a body edited between calls simply answers the page at that position of the current body; anchors on it are the current body's, so nothing stale is served. ## Verification Read first (by risk): `packages/services/service-record-context/src/body-outline.ts` (`boundedOutline`: the skip of an unlistable heading and where `next` is set), `src/record-context-tools.ts` (the body block: the one 404 for an outline page that does not start where asked), `src/sentences.ts` (`outlineTruncated`). Two-minute check: `pnpm --filter @objectstack/service-record-context exec vitest run --maxWorkers=2 src/__tests__/record-context-tools.test.ts -t "300 headings"` — one test passes; it walks four pages and reads 300 sections. All readings at head `5f6f72fd82540c66a716be2a3a874bbd89e58bbd`. <details><summary>Suites of every touched package (under the verify lock: VERDICT command-exit 0)</summary> - Build of the three closures exit 0; `pnpm --filter @objectstack/spec check:generated`: all 14 generated artifacts up to date. - `@objectstack/service-record-context` test: Test Files 4 passed (4), Tests 139 passed (139); typecheck exit 0. - `@objectstack/mcp` test: Test Files 85 passed (85), Tests 1521 passed (1521); typecheck exit 0. - `@objectstack/runtime` test (`--project local`): Test Files 649 passed (649), Tests 12061 passed, 25 skipped (12086); typecheck exit 0. - `@objectstack/spec` test: Test Files 899 passed (899), Tests 28494 passed, 1 todo (28495); typecheck exit 0. </details> <details><summary>Derived gate families (dispatch-gates --commands, 111)</summary> - 109 exit 0 (11 of them re-run after the build, having first refused with no built output to read). - NOT MEASURED, `check:skill-examples` and `check:dual-build-cjs-loads`: PREREQUISITE NOT MET, they read built output of packages this diff does not touch. CI's Lint and Repo Gates measures both. </details> <details><summary>Review S1 pin, and the ablation of the first round</summary> - S1: "a section listed on page 2 is read exactly as that page's body_outline note says" reads page 2's first anchor with the record's arguments, the anchor and no `outlineFrom` (en and zh-Hans), and gets the section. The control, page 2's arguments plus the anchor, is refused `VALIDATION_ERROR` 400. - Ablation (first round, unchanged code path): `for (let at = from; ...` replaced by `for (let at = 0; ...` in `boundedOutline` turned the 300-heading acceptance pin red (24080 anchors issued, not 300), along with three other executor pins; restored blob equals HEAD. </details> --- _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 98cc0e4 commit 59571b2

12 files changed

Lines changed: 477 additions & 46 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/service-record-context': patch
3+
'@objectstack/spec': minor
4+
---
5+
6+
feat(service-record-context): get_record_context lists a long body's outline in pages, so every heading's anchor is issued however many the body holds
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: added
10+
11+
ADR-0160 D3 "The body". No pack key and no error code changes. The tool's published input widens by one optional member, `outlineFrom`, and its body answer by one, `outlineNext`.
12+
13+
- **The outline comes in pages.** An outline is still held to 80 entries and to the body bound per answer. Where a body has more headings than one answer lists, the answer's body carries `outlineNext`, and calling `get_record_context` again with the same arguments and `outlineFrom` set to it lists the next page. The pages run through every heading shallowest level first, then in body order, and each page lists its headings in body order: a nested body's first page is its top levels, as before; a body of many headings at one level is listed in runs. Before, a body whose headings all sat at one level issued no anchor for any heading past the first 80, so those sections could not be read.
14+
- **The `outline_truncated` note now says how many headings the page lists, how many it does not, and the `outlineFrom` that lists the next page** (or that no later page lists more). It no longer says that a listed section's text holds the headings left out, which was false when every heading sat at one level.
15+
- **A heading too long to list by itself no longer empties the outline.** No page lists it, the pages pass over it, and the note counts it; the other headings are listed. A body whose only headings are such headings is carried to the bound and marked truncated, as before.
16+
- An `outlineFrom` past the last page, or on a body that is not an outline, is refused `RESOURCE_NOT_FOUND` (404), as an unresolved `anchor` is. A call naming both `anchor` and `outlineFrom` is refused `VALIDATION_ERROR` (400) before anything is read.

‎content/docs/references/ai/record-context-tools.mdx‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const result = GetRecordContextInputSchema.parse(data);
3232
| **recordId** | `string` | ✅ | The record's `id`, as create_record and query_records answer it |
3333
| **context** | `string` | optional | The context pack to read the record through, by name. Omit it when the object has one pack |
3434
| **anchor** | `string` | optional | One section of the record's body, by the `anchor` an earlier answer's body outline issued |
35+
| **outlineFrom** | `integer` | optional | Where the body outline's page starts: the `outlineNext` an earlier answer's body gave. Omit it for the first page. Not with `anchor` |
3536

3637

3738
---
@@ -78,7 +79,8 @@ const result = GetRecordContextInputSchema.parse(data);
7879
| **label** | `string` | ✅ | Its label at the caller's locale |
7980
| **text** | `string` | optional | The body text, or the one section `anchor` asked for |
8081
| **anchor** | `string` | optional | The section `text` holds, when the call named one |
81-
| **outline** | `{ anchor: string; heading: string; level: integer }[]` | optional | The body's headings in order, when the body is past the bound and is not carried whole. Held to the service's outline bounds: a cut leaves out the deepest headings first and is stated by an `outline_truncated` note |
82+
| **outline** | `{ anchor: string; heading: string; level: integer }[]` | optional | The body's headings in body order, when the body is past the bound and is not carried whole. One page, held to the service's outline bounds: the pages run through every heading short enough to list, shallowest level first, so a cut leaves the deepest headings to later pages, and is stated by an `outline_truncated` note, which also counts any heading too long for any page to list |
83+
| **outlineNext** | `integer` | optional | Present when a heading a later page lists remains past this outline page: pass it as `outlineFrom` to list the next page. Absent on the last page, even when headings too long to list remain |
8284
| **truncated** | `true` | optional | Present when `text` was cut at the bound: a long body with no headings, or a section past the bound |
8385

8486
### Nested Shape: `RecordContextBody.outline[number]`
@@ -148,7 +150,8 @@ const result = GetRecordContextInputSchema.parse(data);
148150
| **label** | `string` | ✅ | Its label at the caller's locale |
149151
| **text** | `string` | optional | The body text, or the one section `anchor` asked for |
150152
| **anchor** | `string` | optional | The section `text` holds, when the call named one |
151-
| **outline** | `{ anchor: string; heading: string; level: integer }[]` | optional | The body's headings in order, when the body is past the bound and is not carried whole. Held to the service's outline bounds: a cut leaves out the deepest headings first and is stated by an `outline_truncated` note |
153+
| **outline** | `{ anchor: string; heading: string; level: integer }[]` | optional | The body's headings in body order, when the body is past the bound and is not carried whole. One page, held to the service's outline bounds: the pages run through every heading short enough to list, shallowest level first, so a cut leaves the deepest headings to later pages, and is stated by an `outline_truncated` note, which also counts any heading too long for any page to list |
154+
| **outlineNext** | `integer` | optional | Present when a heading a later page lists remains past this outline page: pass it as `outlineFrom` to list the next page. Absent on the last page, even when headings too long to list remain |
152155
| **truncated** | `true` | optional | Present when `text` was cut at the bound: a long body with no headings, or a section past the bound |
153156

154157

‎packages/mcp/src/mcp-record-context-tools.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ describe('[ADR-0160 D4] get_record_context — registration', () => {
186186
expect(stdio).toEqual(http);
187187
expect(http.description).toBe(createRecordContextTools().definitions[0].description);
188188
expect(http.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false });
189-
expect(Object.keys(http.inputSchema.properties).sort()).toEqual(['anchor', 'context', 'objectName', 'recordId']);
189+
expect(Object.keys(http.inputSchema.properties).sort()).toEqual(['anchor', 'context', 'objectName', 'outlineFrom', 'recordId']);
190190
});
191191

192192
it('is not listed on a bridge without the record-context service, nor for a grant without data:read', async () => {

‎packages/runtime/src/mcp-record-context-tools-bridge.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,12 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel:
505505
id: 'p1', title: 'Fire cover', status: 'active', secret_note: 'hush', vault: 'v1',
506506
content: '# Scope\nCovers fire.\n# Exclusions\nFlood.', organization_id: 'org_1',
507507
}, sys);
508+
// A body of 300 headings at one level, past the body bound: its outline comes in pages.
509+
await engine.insert('rc_policy', {
510+
id: 'p2', title: 'Long cover', status: 'active', secret_note: 'hush', vault: 'v1',
511+
content: Array.from({ length: 300 }, (_, i) => `## Clause ${i + 1}\nThe insurer pays clause ${i + 1}.\n`).join(''),
512+
organization_id: 'org_1',
513+
}, sys);
508514
await engine.insert('rc_revision', { id: 'r1', version: 'v1', policy: 'p1', owner_id: 'usr_member', organization_id: 'org_1' }, sys);
509515
await engine.insert('rc_revision', { id: 'r2', version: 'v2', policy: 'p1', owner_id: 'usr_other', organization_id: 'org_1' }, sys);
510516
await engine.insert('rc_hidden', { id: 'h1', version: 'h', policy: 'p1', organization_id: 'org_1' }, sys);
@@ -871,6 +877,26 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel:
871877
expect(answer.payload.error).toMatchObject({ code: 'RESOURCE_NOT_FOUND', status: 404 });
872878
});
873879

880+
it('[ADR-0160 D3] a long body\'s outline pages on both doors: outlineFrom reaches the executor through each, and the page it lists issues anchors that read their sections', async () => {
881+
const first = await both({ objectName: 'rc_policy', recordId: 'p2', context: 'rc_main' });
882+
expect(first.isError).toBe(false);
883+
const next = first.payload.data.body.outlineNext;
884+
expect(next).toBe(first.payload.data.body.outline.length);
885+
const page = await both({ objectName: 'rc_policy', recordId: 'p2', context: 'rc_main', outlineFrom: next });
886+
expect(page.isError).toBe(false);
887+
// A door that dropped the key would answer the first page again.
888+
expect(page.payload.data.body.outline[0]).toEqual({ anchor: `clause-${next + 1}`, heading: `Clause ${next + 1}`, level: 2 });
889+
const anchor = page.payload.data.body.outline.at(-1).anchor;
890+
const section = await both({ objectName: 'rc_policy', recordId: 'p2', context: 'rc_main', anchor });
891+
expect(section.payload.data.body.text).toMatch(/^## Clause \d+\nThe insurer pays clause \d+\.\n$/);
892+
});
893+
894+
it('[ADR-0160 D3] an outlineFrom on a body carried whole is one coded answer on both doors', async () => {
895+
const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main', outlineFrom: 80 });
896+
expect(answer.isError).toBe(true);
897+
expect(answer.payload.error).toMatchObject({ code: 'RESOURCE_NOT_FOUND', status: 404 });
898+
});
899+
874900
it('a pack served from the metadata registry (saved at run time, not shipped by the stack) is read', async () => {
875901
await protocol.saveMetaItem({
876902
type: 'ai_context', name: 'rc_registry',

‎packages/services/service-record-context/src/__tests__/body-outline.test.ts‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ describe('[ADR-0160 D3] the outline is bounded whatever the body holds', () => {
151151

152152
it('a heading too long to list within the bound is left out, never carried past it', () => {
153153
const headings = md([`# ${'x'.repeat(RECORD_CONTEXT_BODY_MAX_CHARS)}`]);
154-
expect(boundedOutline(headings)).toEqual({ outline: [], omitted: 1 });
154+
expect(boundedOutline(headings)).toEqual({ outline: [], omitted: 1, unlistable: 1 });
155155
});
156156

157157
it('a listed anchor is the one the reader gave, cut or not', () => {
@@ -160,3 +160,72 @@ describe('[ADR-0160 D3] the outline is bounded whatever the body holds', () => {
160160
expect(outline.map((h) => h.anchor)).toEqual(['notes', ...Array.from({ length: 79 }, (_, i) => `notes-${i + 2}`)]);
161161
});
162162
});
163+
164+
describe('[ADR-0160 D3] the outline comes in pages that list every heading', () => {
165+
const md = (lines: string[]) => headingsOf(lines.join('\nbody text\n'), false);
166+
/** Every page from the first, following `next`, each held to both bounds. */
167+
const pagesOf = (headings: ReturnType<typeof md>) => {
168+
const pages: Array<ReturnType<typeof boundedOutline>['outline']> = [];
169+
let from: number | undefined = 0;
170+
// Bounded, so pages that never advance fail here rather than loop.
171+
while (from !== undefined && pages.length <= headings.length) {
172+
const page = boundedOutline(headings, from);
173+
expect(page.outline.length).toBeGreaterThan(0);
174+
expect(page.outline.length).toBeLessThanOrEqual(RECORD_CONTEXT_OUTLINE_MAX_ENTRIES);
175+
expect(JSON.stringify(page.outline).length).toBeLessThanOrEqual(RECORD_CONTEXT_BODY_MAX_CHARS);
176+
expect(page.omitted).toBe(headings.length - page.outline.length);
177+
pages.push(page.outline);
178+
from = page.next;
179+
}
180+
return pages;
181+
};
182+
183+
it('a flat body\'s pages are runs of it in body order, and together list every heading once', () => {
184+
const headings = md(Array.from({ length: 300 }, (_, i) => `## Clause ${i + 1}`));
185+
const pages = pagesOf(headings);
186+
expect(pages.map((p) => p.length)).toEqual([80, 80, 80, 60]);
187+
expect(pages.flat().map((h) => h.anchor)).toEqual(headings.map((h) => h.anchor));
188+
expect(boundedOutline(headings, 80).next).toBe(160);
189+
expect(boundedOutline(headings, 240)).not.toHaveProperty('next');
190+
});
191+
192+
it('a nested body\'s first page is its top levels, and later pages list the deeper headings left out', () => {
193+
const lines: string[] = [];
194+
for (let a = 1; a <= 10; a++) {
195+
lines.push(`# Part ${a}`);
196+
for (let b = 1; b <= 20; b++) lines.push(`## Part ${a} clause ${b}`);
197+
}
198+
const headings = md(lines);
199+
const pages = pagesOf(headings);
200+
expect(pages[0].filter((h) => h.level === 1)).toHaveLength(10);
201+
expect(pages.slice(1).flat().every((h) => h.level === 2)).toBe(true);
202+
const listed = pages.flat().map((h) => h.anchor);
203+
expect(new Set(listed).size).toBe(headings.length);
204+
expect([...listed].sort()).toEqual(headings.map((h) => h.anchor).sort());
205+
// Each page lists its headings in body order.
206+
for (const page of pages) {
207+
const at = page.map((h) => headings.findIndex((x) => x.anchor === h.anchor));
208+
expect(at).toEqual([...at].sort((x, y) => x - y));
209+
}
210+
});
211+
212+
it('a page is held to the character bound before the entry cap, and the next page starts where it stopped', () => {
213+
const headings = md(Array.from({ length: 40 }, (_, i) => `# ${'Long heading '.repeat(25)}${i}`));
214+
const first = boundedOutline(headings);
215+
expect(first.next).toBe(first.outline.length);
216+
expect(pagesOf(headings).flat().map((h) => h.anchor)).toEqual(headings.map((h) => h.anchor));
217+
});
218+
219+
it('a heading too long to list by itself is on no page, counted, and never empties a page the others fit on', () => {
220+
// The shallowest heading, first in the order the pages run in, is the one too long to list.
221+
const headings = md([`# ${'x'.repeat(RECORD_CONTEXT_BODY_MAX_CHARS)}`, ...Array.from({ length: 100 }, (_, i) => `## Clause ${i + 1}`)]);
222+
const first = boundedOutline(headings);
223+
expect(first.outline).toHaveLength(RECORD_CONTEXT_OUTLINE_MAX_ENTRIES);
224+
expect(first.outline[0]).toEqual({ anchor: 'clause-1', heading: 'Clause 1', level: 2 });
225+
expect(first).toMatchObject({ omitted: 101 - RECORD_CONTEXT_OUTLINE_MAX_ENTRIES, next: 81, unlistable: 1 });
226+
const last = boundedOutline(headings, 81);
227+
expect(last.outline.map((h) => h.anchor)).toEqual(headings.slice(81).map((h) => h.anchor));
228+
expect(last).not.toHaveProperty('next');
229+
expect(last.unlistable).toBe(1);
230+
});
231+
});

0 commit comments

Comments
 (0)