Skip to content

Commit f19ee34

Browse files
feat(service-knowledge): under the markdown split, a section that fits is one passage (#38439)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XPVeTnk3WhfrSQRKLNq8upv)_ Fixes #38351 Clause-②: no Metadata-protocol: semantic Skills-docs: follow-up #38442 ## 维护者速读 - 用户能看到什么变化:按标题切分的知识源里,一个放得下一段的小节(一条条文、一节说明、一张表格连同它的注释)现在整节一段,检索命中的是完整的一条,不再是半条;放不下的小节切法与以前完全一样。 - 为什么做:知识切分专题第一阶段,按您对“放得下的小节整节一段做成默认”的裁决(选 A)实现,作者不用再手动调合并阈值。 - 出错会怎样:只影响按标题切分的知识源,这些知识源本来就要因上一个“标题丢失”修复重建一次,这次改动搭同一次重建,不再多建;切分功能仍在预发布期,撤回只需回退本次改动并再重建一次。 - 要你做的:无。 ## What changes - **Splitter** (`packages/services/service-knowledge/src/split/splitter.ts`, `withPrefix`): under `split.strategy: 'markdown'`, after the heading-path prefix is selected exactly as before (full path, else the innermost heading, else none, by the existing half-the-bounds rule), a section whose emitted passage (prefix plus trimmed text) fits the bounds is returned as that one passage, whatever `minChars` is. Only a section that does not fit reaches `splitRecursive`, unchanged, so its passages are byte-identical to before. The path-less branch (text before the first heading) takes the same rule. Body-less headings and the carry logic are untouched. `recursive` and `whole` are untouched. - **Which "fits" (Zone 2 hypothesis 3).** Fitting is judged on the passage as emitted, `fits(lead + body.trim(), b)`, not on `fits(body, left)`. `estimateTokens` rounds up per text and the prefix ends in whitespace, so the two raw sums add and the estimate of the passage is at most the prefix's estimate plus the body's: the emitted check accepts everything the split check accepts, plus the sections that are over the budget left after the prefix only by one rounding token. Characters agree, except for a heading that starts with whitespace other than a space or tab, where the emitted check is again the looser one. The emitted check is the bound the file promises for every passage, so a fitting passage can never exceed it. Pinned by a test. - **Version.** `SPLIT_ALGORITHM_VERSION_BY_STRATEGY.markdown` stays **2**. Read at base `d751790c`: `.changeset/38350-markdown-bodyless-headings.md` is still pending, and the published `@objectstack/service-knowledge@next` is `19.0.0-next.2`, whose changelog does not carry it. So this rides the 1 to 2 move already in this train (topic rule: one bump per train). `SPLIT_ALGORITHM_VERSION` and its export are not touched. - **Prose that restates the ruling** (ruling 7247322956, A): the splitter file head and `splitMarkdown` docblocks; the `KnowledgeSplitSchema` docblock for `markdown`, the `minChars` docblock and `.describe`, and the knowledge source form's `minChars` help text in `packages/spec`; the regenerated `content/docs/references/ai/knowledge-source.mdx`; `content/docs/protocol/knowledge.mdx` section 3.5 and `content/docs/ai/knowledge-rag.mdx`. No key, value, default or export changes (`check:api-surface` and `check:authorable-surface` green). - **Form translations** (patch round 1, contract review record 7249205899 M1/S1): the `en` bundle leaf `source.split.minChars.helpText` in `packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts` regenerated by `node scripts/check-i18n-bundles.mjs --write`; the hand-translated `zh-CN`, `ja-JP` and `es-ES` leaves re-translated to the new rule. The other seven locales serve the new English through their source-hash fallback. - **Changeset** `.changeset/38351-markdown-fitting-section.md`: `@objectstack/service-knowledge` minor, `@objectstack/platform-objects` minor (the bundles above), and `@objectstack/spec` minor, because the spec's shipped prose changes (the `.describe` string ships in the JSON schemas and the reference, the help text ships in the form) and AGENTS.md asks at least `minor` of a `semantic` kind on every package the diff moves. ## Tests `packages/services/service-knowledge/src/__tests__/split.test.ts`, new top-level describe "splitter — markdown: a section that fits is one passage", 11 cases: - three 250-character paragraphs under one heading at the default `minChars`: one passage, prefix first; - the same with `minChars: 0`: still one passage; - a section that does not fit: cut exactly as before (pinned output), and `minChars` still merges its short pieces; - the prefix counts: exactly `maxChars` with the prefix is one passage, one character more is cut; - a path too long for the half-bounds rule falls back to the innermost heading, and that passage fits: one passage under the innermost prefix; - a table and its note inside a fitting section: one passage; - the token budget: under `maxChars` but over the budget is still cut, each piece within it; - "fits" reads the emitted passage (the rounding case above); - text before the first heading that fits: one passage, no path; - a parent's own text before its first child: one passage when it fits; - `recursive` unchanged on the same paragraphs. Before the fix, against the unmodified splitter, 8 of these were red (the 3 that pin unchanged behaviour were green, as they must be). The existing "every heading and line is kept" and "no passage over the budget" properties and the golden files pass unchanged (`headings.markdown.golden.json` is byte-identical). ## Acceptance notes Seeded synthetic corpus (the private corpus is not available; the script stays out of the PR). 400 documents per shape, article length lognormal with median 96 (about 78% under 200), 1 to 6 chapters and 1 to 8 articles each, paragraphs of 120 to 320 characters, 5% of articles carrying a table and its note at a random position, `maxChars` 800. A unit "fits" when its passage under its full heading path is within `maxChars` and the token budget. Real `estimateTokens`, not stubbed. | Shape | Setting | Passages | Mixed passages | Fitting units split | Fitted table + note together | |---|---|---|---|---|---| | Units are headings | default, before | 6,814 | 0% | 261 / 6,018 (4.34%) | 209 / 251 (83.3%) | | Units are headings | default, **after** | 6,537 | **0%** | **0 / 6,018 (0%)** | **251 / 251 (100%)** | | Units are headings | `minChars = maxChars` (before = after) | 6,342 | 0% | 0 | 251 / 251 | | Units are bold paragraphs under chapter headings | default, before | 4,245 | 59.22% | 891 / 6,208 | 60 / 260 | | Units are bold paragraphs under chapter headings | default, **after** | 3,951 (-6.9%) | 59.68% (+0.46 pt) | 813 / 6,208 | 69 / 260 | | Units are bold paragraphs under chapter headings | `minChars = maxChars` (before = after) | 2,486 | 75.22% | 262 / 6,208 | 218 / 260 | - Topic bar met on heading-shaped input: 0% of fitting units split (bar 0.5%), 0 mixed, every fitted table with its note. - Non-heading shape, the reading the ruling asked for: passages -6.9%, mixed share +0.46 points. The `minChars = maxChars` recipe on the same input gives -41% and +16 points. - With a 512-token embedder (budget 409), both shapes read identically before and after: under that budget the fitting sections were already one passage. - Byte-identity of sections that do not fit, measured: 20,000 random Markdown documents (headings, tables, lists, Chinese and English sentence marks) under random `maxChars`, `minChars` and token limits, compared section by section between the base splitter and this one: 162,790 sections identical, 7,735 sections that were cut now one passage, 0 other differences. - Zone 2 hypothesis 5 (the card's 0.2% residual under the recipe): not reproduced. The synthetic corpus gives 0 there, as in the decision analysis; its headings are short, so the prefix fallback is never reached. Not explained here. - Not touched, by the order: `docs/adr/**` (no ADR note owed: no ADR text contradicts the change; ADR-0161 hands the split rules to the splitter's card and only names the `maxChars`/`minChars` keys), `skills/**` (the `Skills-docs:` follow-up), `content/docs/releases/`, and the `markdown` entry's comment in `SPLIT_ALGORITHM_VERSION_BY_STRATEGY`, which names only the body-less heading change. It sits next to the constant sibling #38377 retires, so it is left to avoid a conflict, and the changeset records that version 2 carries both changes. - `content/docs/protocol/knowledge.mdx` section 3.5's `markdown` row said "A heading with no text of its own joins the next passage". That has not been true since the body-less heading fix, so the rewritten row states the landed behaviour. ## Verification Read first, by risk: 1. `packages/services/service-knowledge/src/split/splitter.ts`, `withPrefix`: the two early returns (the `fits(whole, b)` lines) and the comment above the prefix loop. 2. `packages/spec/src/ai/knowledge-source.zod.ts`: the `markdown` bullet and the `minChars` docblock and `.describe` (contract-tier L2 face). 3. `content/docs/protocol/knowledge.mdx` section 3.5. Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/split.test.ts -t "fits is one passage"` shows 11 passing tests. <details><summary>Local runs (heads 4723a4f and c645c31)</summary> Patch round 1, head `c645c319` (two commits on `4723a4fe`, no splitter or test change): `pnpm check:i18n` red at `4723a4fe` (`platform-objects DRIFTED (1)`), exit 0 at `c645c319` (all bundles in sync); `check:i18n-stale-fill` exit 0; `pnpm --filter @objectstack/platform-objects exec vitest run src/apps/translations`: 28 files, 625 tests passed; spec `check:generated`: all 14 up to date; `dispatch-gates --ran`: 118 accounted, 115 run, 3 NOT MEASURED (prerequisite not met in this container; CI runs them); `overlap-check.mjs --branch=HEAD`: clean. Round 0, all on head `4723a4fe`, worktree base `d751790c`. - `pnpm --filter @objectstack/service-knowledge test`: Test Files 21 passed (21), Tests 737 passed (737); lock VERDICT command-exit 0. - `pnpm --filter @objectstack/service-knowledge typecheck`: tsc clean; `check:test-typecheck: OK`, 0 errors. - `pnpm --filter @objectstack/spec exec vitest run src/ai/knowledge-source.metadata-form.test.ts src/ai/knowledge-source.test.ts`: 2 files, 42 tests passed; `pnpm --filter @objectstack/spec typecheck` exit 0. The rest of the spec suite is CI's (prose-only change in spec). - `pnpm --filter @objectstack/spec build && check:generated`: 1 of 14 stale (`check:docs`), regenerated with `--fix` (the reference page above); `check:authorable-surface`, `check:api-surface` green, `authorable-surface.base.json` untouched. - Red before the fix, on the unmodified splitter: `vitest run src/__tests__/split.test.ts -t 'fits is one passage'`, Tests 8 failed / 3 passed (the 3 pin unchanged behaviour), each failure a fitting section returned as 2 to 4 passages. - `node scripts/pm/dispatch-gates.mjs --commands` (derived from the merge base, 8 paths): 114 commands, run locally; `--ran` reconciliation: 114 accounted, 110 exit 0, 4 NOT MEASURED (exit 3, prerequisite not met in this container: `check-plugin-teardown-shape --self-test` needs an unshallow clone; `check:skill-examples`, `check:dual-build-cjs-loads` and `check:i18n` need a full workspace build). CI runs all four. - `node scripts/pm/overlap-check.mjs --branch=HEAD`: `VERDICT clean exit 0`, merges cleanly with `origin/main`, 0 open PR heads overlapping. - Dogfood battery: not owed (no `!` in the title, no `(narrowing)` arm). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5mCvGQKiCEBneFwp1j)_ <!-- signed: repo:objectstack#5 · os-project-manager · session_01FEkQ5mCvGQKiCEBneFwp1j --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e4a02be commit f19ee34

12 files changed

Lines changed: 206 additions & 27 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/service-knowledge': minor
3+
'@objectstack/spec': minor
4+
'@objectstack/platform-objects': minor
5+
---
6+
7+
feat(service-knowledge): under the `markdown` split, a section that fits is one passage
8+
9+
Clause-②: no
10+
Metadata-protocol: semantic
11+
Skills-docs: follow-up owed — skills/objectstack-ai/SKILL.md
12+
13+
On `split.strategy: 'markdown'`, a section was cut as `recursive` cuts, and its pieces were merged only while the merged piece stayed shorter than `minChars` (default 200). A section that fit `maxChars` but held several paragraphs of 200 characters or more was therefore cut into several passages, so a search hit only part of an article.
14+
15+
Now a section whose text, together with the heading path it is given, fits the effective `maxChars` and the embedder's token budget is one passage, whatever `minChars` is (`minChars: 0` included). Only a section that does not fit is cut as before, with `minChars` merging its short pieces; such a section gives exactly the passages it gave before. The text before the first heading, and a heading's text before its first sub-heading, are sections and follow the same rule. `recursive` and `whole` are unchanged. The `@objectstack/spec` docblocks, the `minChars` description and the knowledge source form's help text now say this, and the Setup bundles in `@objectstack/platform-objects` carry the new help text (regenerated for en, re-translated for zh-CN, ja-JP and es-ES); no key, value or default changes.
16+
17+
Which passages change: on `markdown` sources only, the passages of sections that fit but were cut. Each such section becomes one passage, so a table and its note inside a fitting section are always one passage.
18+
19+
The `markdown` split algorithm version stays 2: this change rides the version move to 2 that the body-less heading fix already makes in this release train, so every `markdown` source rebuilds once for both, not twice.
20+
21+
What to do: nothing.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ source: {
255255
```
256256

257257
- `recursive` (the default) cuts at blank lines, then line breaks, then sentence ends, then semicolons, then characters. It reads Chinese and English sentence ends — 「3.2 条」 and 「400.50 元」 stay whole — and never cuts inside a Markdown table or list item that fits.
258-
- `markdown` cuts one section per heading; each passage begins with its heading path, which is embedded with it.
258+
- `markdown` cuts one section per heading; each passage begins with its heading path, which is embedded with it. A section that fits in one passage (its text together with the heading path it is given, within the length below) is one passage; only a section that does not fit is cut as `recursive` cuts, and `minChars` (default 200) merges the short pieces of that cut.
259259
- `whole` keeps each document as one passage.
260260

261261
A passage is at most `split.maxChars` characters — else the **Knowledge → Target chunk size** setting, else 800 — and, when the adapter reports its embedder's input limit, within 80% of that limit by the shared token estimate below. A `whole` document over that budget is **removed from the index and reported** (`failed` and `failures` on the reindex result, an `error` log on the event sync), never truncated; because the estimate runs high, a `whole` document can use about 60% of the model's limit. The full rules are in [the protocol's split section](/docs/protocol/knowledge#35-the-split).

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -564,15 +564,16 @@ them. The object source's `split` key chooses how:
564564
split: {
565565
strategy: 'recursive', // 'whole' | 'recursive' | 'markdown'
566566
maxChars: 600, // optional: longest passage, in characters
567-
minChars: 200, // optional: merge adjacent pieces shorter than this (default 200)
567+
minChars: 200, // optional: merge adjacent pieces shorter than this (default 200);
568+
// under 'markdown', only in a section that does not fit
568569
}
569570
```
570571

571572
| Strategy | How it cuts |
572573
|----------|-------------|
573574
| `whole` | One passage per document. |
574575
| `recursive` (the default) | At blank lines, then line breaks, then sentence ends, then semicolons, then characters — each next level only for a piece still too long. A Markdown table or list item is one unit while it fits; a table that does not fit is cut between rows, each piece repeating the header row. Adjacent pieces are merged while the merged piece is shorter than `minChars`; a short title block leads the text after it. |
575-
| `markdown` | One section per heading (a `#` inside a code fence is no heading), each cut as `recursive` cuts. Every passage begins with its heading path (`Policy > Transport > Air`), which counts toward its length and is embedded with it, and carries it as `headingPath`. A heading with no text of its own joins the next passage. |
576+
| `markdown` | One section per heading (a `#` inside a code fence is no heading); the text before the first heading, and a heading's text before its first sub-heading, are sections too. Every passage begins with its heading path (`Policy > Transport > Air`), which counts toward its length and is embedded with it, and carries it as `headingPath`. A section that fits — its text together with the heading path it is given (the whole path, or the innermost heading when the whole path is too long), within the effective `maxChars` and the token budget — is **one passage, whatever `minChars` is**; only a section that does not fit is cut as `recursive` cuts, its pieces merged up to `minChars`. A heading with no text of its own is named by the path of the section after it when it is that section's ancestor, and is a passage of its own otherwise. |
576577

577578
**Sentence ends, for Chinese and English text.** `。?!` end a sentence
578579
wherever they stand. `. ? !` end one only before whitespace or the end of the
@@ -588,7 +589,9 @@ embedder's `maxInputTokens`, every passage's token estimate (the shared
588589
`estimateTokens` from `@objectstack/spec/shared`) also stays within **80%** of
589590
that limit. A passage keeps both bounds, so the effective length is the
590591
smaller one; with no limit known, only `maxChars` applies. A `minChars` above
591-
the effective `maxChars` reads as `maxChars`. The splitter never overlaps
592+
the effective `maxChars` reads as `maxChars`; under `markdown` it merges only
593+
the pieces of a section that does not fit, so `minChars: 0` still leaves a
594+
fitting section whole. The splitter never overlaps
592595
passages.
593596

594597
**`whole` over the limit.** A `whole` document whose estimate is over the 80%

‎content/docs/references/ai/knowledge-source.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data);
9999
| :--- | :--- | :--- | :--- |
100100
| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown |
101101
| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it |
102-
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars |
102+
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); under markdown, only in a section that does not fit, since a section that fits is one passage; a value above the effective maxChars reads as maxChars |
103103

104104

105105
---
@@ -135,7 +135,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data);
135135
| :--- | :--- | :--- | :--- |
136136
| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown |
137137
| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it |
138-
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars |
138+
| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); under markdown, only in a section that does not fit, since a section that fits is one passage; a value above the effective maxChars reads as maxChars |
139139

140140

141141
---

‎packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3576,7 +3576,7 @@ export const enMetadataForms: NonNullable<TranslationData['metadataForms']> = {
35763576
},
35773577
"source.split.minChars": {
35783578
label: "Shortest passage",
3579-
helpText: "In characters. Needs a strategy. Adjacent pieces shorter than this are merged, up to this length (default 200). Recursive and Markdown only."
3579+
helpText: "In characters. Needs a strategy. Adjacent pieces shorter than this are merged, up to this length (default 200). Recursive and Markdown only; under Markdown a section that fits is one passage, so this merges only the pieces of a section that does not."
35803580
},
35813581
refresh: {
35823582
label: "Refresh",

‎packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3576,7 +3576,7 @@ export const esESMetadataForms: NonNullable<TranslationData['metadataForms']> =
35763576
},
35773577
"source.split.minChars": {
35783578
label: "Pasaje más corto",
3579-
helpText: "En caracteres. Requiere una estrategia. Las piezas adyacentes más cortas que esto se fusionan, hasta esta longitud (200 de forma predeterminada). Solo Recursiva y Markdown."
3579+
helpText: "En caracteres. Requiere una estrategia. Las piezas adyacentes más cortas que esto se fusionan, hasta esta longitud (200 de forma predeterminada). Solo Recursiva y Markdown; en Markdown una sección que cabe es un solo pasaje, así que solo se fusionan las piezas de una sección que no cabe."
35803580
},
35813581
refresh: {
35823582
label: "Actualización",

‎packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3576,7 +3576,7 @@ export const jaJPMetadataForms: NonNullable<TranslationData['metadataForms']> =
35763576
},
35773577
"source.split.minChars": {
35783578
label: "最短パッセージ",
3579-
helpText: "文字数。戦略が必要です。この長さより短い隣接する断片は、この長さまで結合されます(既定 200)。再帰と Markdown のみ。"
3579+
helpText: "文字数。戦略が必要です。この長さより短い隣接する断片は、この長さまで結合されます(既定 200)。再帰と Markdown のみ。Markdown では収まるセクションは 1 パッセージになるため、結合されるのは収まらないセクションの断片だけです。"
35803580
},
35813581
refresh: {
35823582
label: "更新",

‎packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3576,7 +3576,7 @@ export const zhCNMetadataForms: NonNullable<TranslationData['metadataForms']> =
35763576
},
35773577
"source.split.minChars": {
35783578
label: "最短段落",
3579-
helpText: "以字符计。需要选择策略。短于此长度的相邻片段会被合并,直至达到此长度(默认 200)。仅适用于递归和 Markdown。"
3579+
helpText: "以字符计。需要选择策略。短于此长度的相邻片段会被合并,直至达到此长度(默认 200)。仅适用于递归和 Markdown;在 Markdown 下,放得下的小节整节为一个段落,因此只合并放不下的小节切出的片段。"
35803580
},
35813581
refresh: {
35823582
label: "刷新",

‎packages/services/service-knowledge/src/__tests__/split.test.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,137 @@ describe('splitter — markdown: headings with no body', () => {
190190
});
191191
});
192192

193+
describe('splitter — markdown: a section that fits is one passage', () => {
194+
// A paragraph of exactly `n` characters, ending in a sentence mark, with a
195+
// tag so the paragraphs of one text are told apart.
196+
const para = (tag: string, n: number): string => {
197+
const head = `${tag} `;
198+
return `${head}${'word '.repeat(Math.ceil(n / 5)).slice(0, n - head.length - 1)}.`;
199+
};
200+
const three = [para('P1', 250), para('P2', 250), para('P3', 250)];
201+
const sectionOf = (paras: string[]) => `## Article 1\n\n${paras.join('\n\n')}\n`;
202+
const shape = (content: string, split: ResolvedSplit) =>
203+
chunksOf(content, split).map((c) => ({ headingPath: c.headingPath, content: c.content }));
204+
205+
it('three paragraphs of 250 characters under one heading, at the default minChars: one passage, prefix first', () => {
206+
const split = resolveSplit({ split: { strategy: 'markdown' } });
207+
expect(split.minChars).toBe(DEFAULT_SPLIT_MIN_CHARS);
208+
expect(shape(sectionOf(three), split)).toEqual([
209+
{ headingPath: ['Article 1'], content: `Article 1\n\n${three.join('\n\n')}` },
210+
]);
211+
});
212+
213+
it('minChars: 0 is not an opt-out: the fitting section is still one passage', () => {
214+
const split = resolveSplit({ split: { strategy: 'markdown', minChars: 0 } });
215+
expect(shape(sectionOf(three), split)).toEqual([
216+
{ headingPath: ['Article 1'], content: `Article 1\n\n${three.join('\n\n')}` },
217+
]);
218+
});
219+
220+
it('a section that does not fit is cut exactly as before, minChars merging its pieces', () => {
221+
const four = [...three, para('P4', 250)];
222+
const split = resolveSplit({ split: { strategy: 'markdown' } });
223+
expect(shape(sectionOf(four), split)).toEqual(
224+
four.map((p) => ({ headingPath: ['Article 1'], content: `Article 1\n\n${p}` })),
225+
);
226+
// Pieces under minChars still merge in a section that does not fit.
227+
const short = [para('S1', 60), para('S2', 60), para('L1', 700)];
228+
expect(shape(sectionOf(short), split)).toEqual([
229+
{ headingPath: ['Article 1'], content: `Article 1\n\n${short[0]}\n\n${short[1]}` },
230+
{ headingPath: ['Article 1'], content: `Article 1\n\n${short[2]}` },
231+
]);
232+
});
233+
234+
it('"fits" counts the heading-path prefix: exactly maxChars is one passage, one character more is cut', () => {
235+
const split = resolveSplit({ split: { strategy: 'markdown' } });
236+
const lead = 'Article 1\n\n';
237+
const tail = (n: number) => para('P3', n);
238+
const exact = [three[0], three[1], tail(DEFAULT_SPLIT_MAX_CHARS - lead.length - 2 * 250 - 4)];
239+
expect(`${lead}${exact.join('\n\n')}`).toHaveLength(DEFAULT_SPLIT_MAX_CHARS);
240+
expect(chunksOf(sectionOf(exact), split)).toHaveLength(1);
241+
const over = [three[0], three[1], tail(DEFAULT_SPLIT_MAX_CHARS - lead.length - 2 * 250 - 3)];
242+
expect(chunksOf(sectionOf(over), split).map((c) => c.content)).toEqual(over.map((p) => `${lead}${p}`));
243+
});
244+
245+
it('the prefix is the one withPrefix selects: a path too long falls back to the innermost heading, and that passage fits', () => {
246+
const long = 'Chapter with a long title '.repeat(18).trim();
247+
const split = resolveSplit({ split: { strategy: 'markdown' } });
248+
const text = `# ${long}\n\n## Article 9\n\n${three.join('\n\n')}\n`;
249+
expect(shape(text, split)).toEqual([
250+
{ headingPath: [long, 'Article 9'], content: `Article 9\n\n${three.join('\n\n')}` },
251+
]);
252+
});
253+
254+
it('a table and its note inside a fitting section are one passage', () => {
255+
const table = [
256+
'| City tier | Lodging per night | Meals per day |',
257+
'| --- | --- | --- |',
258+
'| Tier 1 | 600 | 120 |',
259+
'| Tier 2 | 450 | 100 |',
260+
'| Tier 3 | 350 | 80 |',
261+
'| Tier 4 | 300 | 70 |',
262+
'| Tier 5 | 250 | 60 |',
263+
'| Overseas | 900 | 200 |',
264+
].join('\n');
265+
// Both over minChars, so before a fitting section was one passage they
266+
// were two.
267+
expect(table.length).toBeGreaterThan(DEFAULT_SPLIT_MIN_CHARS);
268+
const note = para('Note: amounts are per person, tax included, and', 260);
269+
const split = resolveSplit({ split: { strategy: 'markdown' } });
270+
expect(shape(`## Lodging\n\n${table}\n\n${note}\n`, split)).toEqual([
271+
{ headingPath: ['Lodging'], content: `Lodging\n\n${table}\n\n${note}` },
272+
]);
273+
});
274+
275+
it('the token budget counts: a section under maxChars but over the budget is still cut, each piece within it', () => {
276+
const split = resolveSplit({ split: { strategy: 'markdown' }, maxInputTokens: 200 });
277+
const whole = `Article 1\n\n${three.join('\n\n')}`;
278+
expect(whole.length).toBeLessThanOrEqual(split.maxChars);
279+
expect(estimateTokens(whole)).toBeGreaterThan(split.maxTokens!);
280+
const chunks = chunksOf(sectionOf(three), split);
281+
expect(chunks.length).toBeGreaterThan(1);
282+
for (const c of chunks) {
283+
expect(c.content.startsWith('Article 1\n\n')).toBe(true);
284+
expect(estimateTokens(c.content)).toBeLessThanOrEqual(split.maxTokens!);
285+
}
286+
});
287+
288+
it('"fits" reads the passage as emitted: a body over the budget left after the prefix only by rounding is one passage', () => {
289+
// estimateTokens rounds up per text, so the prefix and the body estimate
290+
// one token more apart than together: body 10 + prefix 2 > budget 11,
291+
// while the passage they make estimates 11.
292+
const body = 'abcd abcd abcd abcd\n\nabcd abcd abcd abcd abcd';
293+
const split = resolveSplit({ split: { strategy: 'markdown' }, maxInputTokens: 14 });
294+
expect(split.maxTokens).toBe(11);
295+
expect(estimateTokens('A\n\n') + estimateTokens(body)).toBeGreaterThan(split.maxTokens!);
296+
expect(estimateTokens(`A\n\n${body}`)).toBe(split.maxTokens);
297+
expect(shape(`# A\n\n${body}\n`, split)).toEqual([{ headingPath: ['A'], content: `A\n\n${body}` }]);
298+
});
299+
300+
it('text before the first heading that fits is one passage with no path', () => {
301+
const split = resolveSplit({ split: { strategy: 'markdown' } });
302+
const chunks = chunksOf(`${three.join('\n\n')}\n\n## Article 1\n\nOne line.\n`, split);
303+
expect(chunks.map((c) => ({ headingPath: c.headingPath, content: c.content }))).toEqual([
304+
{ headingPath: undefined, content: three.join('\n\n') },
305+
{ headingPath: ['Article 1'], content: 'Article 1\n\nOne line.' },
306+
]);
307+
});
308+
309+
it("a parent's own text before its first child is a section of its own, one passage when it fits", () => {
310+
const split = resolveSplit({ split: { strategy: 'markdown' } });
311+
const text = `# Chapter 1\n\n${three.join('\n\n')}\n\n## Article 1\n\nOne line.\n`;
312+
expect(shape(text, split)).toEqual([
313+
{ headingPath: ['Chapter 1'], content: `Chapter 1\n\n${three.join('\n\n')}` },
314+
{ headingPath: ['Chapter 1', 'Article 1'], content: 'Chapter 1 > Article 1\n\nOne line.' },
315+
]);
316+
});
317+
318+
it('recursive is unchanged: the same paragraphs, at the default minChars, are three passages', () => {
319+
const split = resolveSplit({ split: { strategy: 'recursive' } });
320+
expect(chunksOf(three.join('\n\n'), split).map((c) => c.content)).toEqual(three);
321+
});
322+
});
323+
193324
describe('splitter — whole', () => {
194325
it('one passage per document', () => {
195326
const text = fixture('regulation-zh.txt');

0 commit comments

Comments
 (0)