You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit f19ee34
Browse filesBrowse the repository at this point in the historyBrowse 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>
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.
Copy file name to clipboardExpand all lines: content/docs/ai/knowledge-rag.mdx
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -255,7 +255,7 @@ source: {
255
255
```
256
256
257
257
-`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.
259
259
-`whole` keeps each document as one passage.
260
260
261
261
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).
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
568
569
}
569
570
```
570
571
571
572
| Strategy | How it cuts |
572
573
|----------|-------------|
573
574
|`whole`| One passage per document. |
574
575
|`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. |
576
577
577
578
**Sentence ends, for Chinese and English text.**`。?!` end a sentence
578
579
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
588
589
`estimateTokens` from `@objectstack/spec/shared`) also stays within **80%** of
589
590
that limit. A passage keeps both bounds, so the effective length is the
590
591
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
592
595
passages.
593
596
594
597
**`whole` over the limit.** A `whole` document whose estimate is over the 80%
|**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 |
103
103
104
104
105
105
---
@@ -135,7 +135,7 @@ const result = KnowledgeRefreshPolicySchema.parse(data);
|**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 |
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."
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."
0 commit comments