Skip to content

docs(knowledge): one passage per unit recipe, and the settings page names chunk_target the longest passage - #38468

Merged
objectstack-fleet[bot] merged 1 commit into
mainfrom
claude/project-thread-7d7mts
Nov 29, 2026
Merged

objectstack-fleet[bot] merged 1 commit into
mainfrom
claude/project-thread-7d7mts

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread

Fixes #38290
Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:写知识源的应用作者在知识检索指南里能读到“一条一段”的做法(每条写成一个标题、在同一条记录上派生一个专供检索的文本字段、可选的顶层标题写明文档和所属部门);管理员在知识设置页看到的“目标片段大小”改名为“片段最大长度”,各语言一致。
  • 为什么做:知识切分专题第一阶段的文档项,回答外部作者提出的“怎样让每一条恰好一段”的问题;放得下的小节整节一段已按您的裁决合入,这里只把做法写清楚。
  • 出错会怎样:只改文档和设置页的文字,键名、默认值、切分行为都不变;写错只会误导读者,直接撤回即可。
  • 要你做的:无。

What changes

  • Knowledge guide (content/docs/ai/knowledge-rag.mdx): a new ### One passage per unit section under "Splitting documents into passages". It teaches, as the landed markdown splitter behaves at f19ee34:
    • one heading per unit (a heading at the start of its line; bold text is not a heading; a unit's sub-items as list items, since a sub-heading is a section and a passage of its own);
    • a unit whose text with its heading path fits is one passage whatever minChars is, and a table with the note after it inside that unit stay together;
    • no passage holds two units (each section is split on its own), and every passage begins with its unit's heading path;
    • a unit that does not fit is cut as recursive cuts, its pieces merged up to minChars; the note after a cut table can land in another piece;
    • minChars is the merge threshold of a unit that does not fit, not a switch, and minChars: 0 turns nothing off;
    • a derived field on the same record carries the index text, listed alone in content (why the same record and not a second object: the hit names the record people open, the search re-checks that record as the asker, where and metadataFields read its own fields);
    • an optional top heading names the document (and the department that owns it), so every passage's heading path begins with it; keep it short, because a path that leaves less than half of the passage length shortens to the unit's own heading; a title already in that heading needs no second content entry;
    • moving a source to this shape changes content and split, so it rebuilds once and re-sends the source to the embedder.
  • Protocol page (content/docs/protocol/knowledge.mdx §3.5): one paragraph that states the result and points to the guide; the setting's name updated.
  • Settings page (packages/services/service-settings): knowledge.chunk_target was labelled Target chunk size (chars) while its help text and the splitter treat it as a maximum. The label is now Longest passage (characters) and the help adds that passages can be shorter, in the manifest and in all 11 locales (en, zh-CN, zh-Hant, ja-JP, ko, de, es-ES, fr, pt-BR, ru, ar). Key, default, bounds and reader unchanged.
  • Changeset: a patch on @objectstack/service-settings, which also says that earlier notes naming Target chunk size mean the same setting (the pending changesets that name it are not edited).

Answer to #38290

The card asked for either a split strategy that cuts at a unit pattern, or a documented way to get one passage per unit. #38351's ruling A (record 7247322956, 「#38351 同意」, merged in PR #38439) made a fitting markdown section one passage by default, so the documented way needs no setting: write each unit as a heading. minChars: 0 is not that switch and is not an opt-out (ruling item 2): minChars only merges the pieces of a section that does not fit. A table and its trailing note inside one fitting unit are one passage. The app's workaround (a second object with one row per article) can become a derived field on the policy record itself. The 84% → 94% figure is not cited here: the topic's adoption comment notes it changed several variables at once.

Acceptance notes

  • skills/objectstack-ai/SKILL.md still names "the Target chunk size setting". Skills are skills: the AI skill teaches that a markdown section that fits maxChars is one passage (after #38351) #38442's surface; its dev was told to write "the Longest passage setting" and to land after this PR.
  • The card's claim names this PR's head in claim 7250337030 (the area's re-post of 7250017151 with the platform branch).
  • The pending changesets that name Target chunk size (.changeset/pre/37098-knowledge-splitter.md, .changeset/pre/37292-skill-knowledge-split.md) are not edited; this PR's changeset carries the superseding sentence.

Verification

All at head 340bb349, tree objectstack-ai/objectstack, base origin/main f459c86.

  • pnpm --filter @objectstack/service-settings test: Test Files 79 passed (79), Tests 1545 passed (1545); exit 0.
  • pnpm --filter @objectstack/service-settings typecheck: exit 0 (dependency closure built first, exit 0).
  • node scripts/pm/overlap-check.mjs --branch=HEAD: VERDICT clean exit 0 (merges cleanly with origin/main; no open PR head on these files).
  • Derived gate families (dispatch-gates --commands): 89 derived, 86 run with exit 0, 3 NOT MEASURED (exit 3, prerequisite not met, nothing measured; CI runs them):
    • node scripts/check-plugin-teardown-shape.mjs --self-test: its positive control is pinned to a commit the shallow clone cannot reach.
    • pnpm --filter @objectstack/spec run check:skill-examples: needs a @objectstack/client-react build this diff does not touch.
    • pnpm check:dual-build-cjs-loads: needs every package's dist/, which this container did not build.
    • dispatch-gates --ran: 89 derived families accounted for, 86 run, 3 NOT MEASURED (derived from the recorded exit 3).
  • Every other family CI runs on this PR is read from its check runs, not re-run here.

Two-minute check: open content/docs/ai/knowledge-rag.mdx at "One passage per unit" and compare each bullet with withPrefix and splitMarkdown in packages/services/service-knowledge/src/split/splitter.ts.

Read first: the new section of content/docs/ai/knowledge-rag.mdx (the claims a reader acts on), then the zh-CN.ts / ja-JP.ts label wording.

Human Minimum

  • 1. Schemas start as Zod; packages/spec holds no runtime logic. (not touched)
  • 2. Every name I added uses the casing for its kind. (no names added)
  • 3. No formatter ran; pnpm lint passes. (CI)
  • 4. One issue, one branch off an up-to-date main, one pull request.
  • 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset.
  • 6. packages/spec touched: its generated artifacts are regenerated and committed. (not touched)
  • 7. No hand edits to content/docs/references/, packages/*/CHANGELOG.md or content/docs/releases/.
  • 8. Title, body and comments are in English.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FEkQ5mDidoPNcFwxVX65bA

…ongest passage

Teach the markdown split's one-passage-per-unit shape in the knowledge
guide (one heading per unit, a derived field on the same record that
carries the index text, an optional top heading naming the document,
minChars as the merge threshold of a unit that does not fit), with a
pointer from the protocol's split section. Rename the Knowledge page's
chunk_target label to "Longest passage (characters)" and say passages can
be shorter, in every locale.

Claude-Session: https://claude.ai/code/session_01FEkQ5mDidoPNcFwxVX65bA
Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/service-settings, touching 1 documentable anchor(s).

2 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/ai/knowledge-rag.mdx (via chunk_target (literal, a string literal in specifiers))
  • content/docs/protocol/knowledge.mdx (via chunk_target (literal, a string literal in specifiers))
What this run could not see

Coarse fallback — 10 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 2052c8995a3d0df192087df6d9809f2aa7e9cb4e → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 29052134c2a00e649b55ef1bd2b2f8f4b9df59e7 — the merge of head 340bb34988ddd7fa35944f1ca573233f11ced52b into base 2052c8995a3d0df192087df6d9809f2aa7e9cb4e, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 29052134c2a00e649b55ef1bd2b2f8f4b9df59e7 && git checkout 29052134c2a00e649b55ef1bd2b2f8f4b9df59e7
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 2052c8995a3d0df192087df6d9809f2aa7e9cb4e 340bb34988ddd7fa35944f1ca573233f11ced52b && git checkout -B drift-repro 2052c8995a3d0df192087df6d9809f2aa7e9cb4e && git merge --no-ff 340bb34988ddd7fa35944f1ca573233f11ced52b

node scripts/docs-audit/affected-docs.mjs --json 2052c8995a3d0df192087df6d9809f2aa7e9cb4e

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 2052c8995a3d0df192087df6d9809f2aa7e9cb4e → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5mDidoPNcFwxVX65bA

PR-body guards is red on check:closing-target-claim only: the card's claim (7250017151) names the claimed worktree branch, and its amendment (7250043703) is not in the claim spelling, so no Claim: on #38290 names this PR's head claude/project-thread-7d7mts. Not a code failure. The claiming area re-posts the claim with this branch; the guard reads the card live, and a body edit re-runs it. No change to the diff is needed.


Generated by Claude Code

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5mDidoPNcFwxVX65bA

Final green head: 340bb34988ddd7fa35944f1ca573233f11ced52b. All 61 check runs at that head are success or skipped by their own if:; the one failure listed is the superseded first run of PR-body guards, whose re-run after the card's claim re-post (7250337030) is success. mergeable_state: clean. No further push is planned; L1 review is requested at this head.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb

席位核对

L1 (thread L1-a, area o5-ai37000) · read 2026-11-29T04:23Z · Head-sha: 340bb34988ddd7fa35944f1ca573233f11ced52b · verdict ACCEPT

This is the first L1 record on this PR, a full review.

Checklist (l1-face --pr 38468 at 340bb34: 1 flag, read below)

  • Shape: open, draft, base main. Fixes #38290 is right. The card asked for a unit-pattern strategy or a documented way to get one passage per unit. Ruling A on service-knowledge: a markdown section that fits maxChars is still cut into several passages #38351, merged as f19ee34, makes the documented way need no setting, and this PR documents it.
  • Scope: 15 files, +88/−23. They are the knowledge guide, the protocol §3.5 pointer, the chunk_target label and help in the manifest and 11 locales, and one @objectstack/service-settings patch changeset. Clause-②: no · Metadata-protocol: none. The key, default, bounds and reader are unchanged, so patch holds. Not governed by path.
  • Gates: 43 success, 17 expected skip, 0 pending.
    • The flagged failure is superseded. PR-body guards check run 141219453124 failed at 03:52Z. Check run 141220322768 on the same head, started 03:56Z, is success.

My readings: the new section against splitter.ts at main

  • "One heading per unit"; bold is no heading. matchHeading (:548) needs one to six # at line start, then a space or tab. Fenced lines are skipped (:594).
  • A sub-heading is a passage of its own. A heading's text before its first child is its own section (:24–25).
  • A unit that fits is one passage whatever minChars is; a table with its note stays. withPrefix returns the one passage when fits(whole, b) holds (:669).
  • No passage holds two units. withPrefix runs per section (:621), with no merge across sections.
  • A unit that does not fit. splitRecursive(body, left, min(minChars, left.maxChars)), with each piece prefixed by lead (:670–671). The table cut between rows with the header repeated is :389–402.
  • minChars: 0 turns nothing off. It is the merge threshold for the non-fitting cut only.
  • The top heading and the half rule. "Written whole only while it leaves at least half of the passage length … otherwise shortens to the unit's own heading; headingPath still lists all of it." This is the roomy test (:666), tried over [path, own, ''], and headingPath: path either way.
  • The derived field. Content parts are joined \n\n in content order (knowledge-service.ts:4745). So a field listed before the index text is pre-heading text, a section and passage of its own, as the guide says. Credential-class and internal fields are withheld (:4700–4701).
  • "Rebuilt once". The fingerprint holds the resolved split and the ordered content list (knowledge-index-fingerprint.ts:17–19). The #when-the-model-or-the-split-changes-rebuild anchor resolves (knowledge-rag.mdx:344).
  • Protocol §3.5. The new paragraph states the same result and links the guide anchor. The setting name is updated.
  • Labels. All 12 locale entries carry the "longest / maximum" label, and the help adds that passages can be shorter. The zh-CN 「片段最大长度」 matches the 速读.
  • The changeset, read sentence by sentence. Each claim holds. The two pending pre/ changesets that name Target chunk size are left unedited, and this one carries the superseding sentence.

Nit (no action owed): the half rule has a third step. When even the unit's own heading leaves less than half, the passage carries no heading text ('' in the prefix list). "Shortens to the unit's own heading" stops one step early, and so does "every piece still begins with the unit's heading path". A heading that long is not a realistic unit.

Owed: nothing from L1. The area lands it. #38466 (#38442) lands after this one, because its "Longest passage" wording depends on this label.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5mDidoPNcFwxVX65bA

Landing #38468 at head 340bb34988ddd7fa35944f1ca573233f11ced52b, on L1 ACCEPT 7250626358 (same head).

Reading Result
check-governed-merges.mjs --pr 38468, from a fresh origin/main checkout NOT governed: 0 of 15 paths hit the register; 111 changed lines, the card's only PR, under the 3,000-line line
Check runs at the head 43 success, the rest skipped by their own if:; the first PR-body guards run is superseded by a success re-run on the same head; mergeable_state: clean; no generated artifact in the diff

State: ready for review and auto-merge armed; the merge queue lands it, and the merge closes #38290.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 29, 2026 04:24
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 29, 2026
Merged via the queue into main with commit c5281d0 Nov 29, 2026
61 of 62 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/project-thread-7d7mts branch November 29, 2026 04:51
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…s maxChars is one passage (objectstack-ai#38466)

<!-- claude-projects-attribution: {"github_login":"os-project-manager"}
-->
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_
Fixes objectstack-ai#38442
Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:用 AI
助手搭知识库的作者,会从技能说明里读到“按标题切分时,放得下的小节整节一段”,不再被引导去把合并阈值手动调到和长度上限一样;平台行为本身不变。
- 为什么做:知识切分专题的收尾,把对外发布的技能说明对齐已经上线的切分行为,也就是您对“放得下的小节整节一段做成默认”的那次裁决。
- 出错会怎样:只改说明文字;写错的话 AI 作者会按错误理解配置知识源,撤回本次改动即可恢复原文。
- 要你做的:等“知识设置项标签改名为最长段落”的那个姊妹合并请求合入之后,再合入本改动。

## What changes

`skills/objectstack-ai/SKILL.md`, the **Splitting (`split`)** block
only. The words follow the splitter as merged in f19ee34 (the `split`
docblock in `packages/spec/src/ai/knowledge-source.zod.ts` and
`content/docs/protocol/knowledge.mdx` §3.5), ruling A on objectstack-ai#38351 (record
7247322956).

- **`markdown` bullet.** Adds: "A section that fits `maxChars` with that
path is one passage; one that does not is cut as `recursive` cuts."
- **`minChars` sentence.** Was "Adjacent pieces shorter than `minChars`
(default 200) are merged." Now: "… are merged in `recursive` text and in
a `markdown` section that does not fit; a section that fits stays whole
whatever `minChars` is." No step that sets `minChars` equal to
`maxChars` is taught (item 6 of the ruling). No new example.
- **Split-change sentence (should-fix S1 of contract review
7250515767).** Was "Changing `split` re-splits a document only when it
next changes.", which is false: the resolved split is part of the index
fingerprint (`content/docs/protocol/knowledge.mdx` §3.5, "A split change
is a new index"). Now: "Changing `split` rebuilds the source's whole
index, and its searches are refused until the rebuild finishes."
- **Settings label (added by the area during the round).** "the **Target
chunk size** setting" is now "the **Longest passage** setting", the
label the sibling card objectstack-ai#38290 gives `knowledge.chunk_target`. ⚠ That
line is true only once PR objectstack-ai#38468 (the PR of objectstack-ai#38290; it renames the label
to "Longest passage (characters)") is on `main`: **this PR lands after
PR objectstack-ai#38468.** On `main` today the label still reads "Target chunk size".
- **Restatements cut in the same block, no fact dropped:** "For
documents with headings" (the bullet's "one section per heading" says
it); "once `split` is written" (the signature and the omitted-`split`
clause say it); "never truncated" (the `whole` bullet's "removed from
the index and reported" says it); the "and refused" of "Retired and
refused" (the `400 UNKNOWN_KEY` and the parse error beside it say it).
- **Ratchet row.** `scripts/check-skills-token-ratchet.mjs`, the
`skills/objectstack-ai/SKILL.md` row only: 7200 to 7248, pinned at the
measurement, with the arithmetic in the row's comment (commits 924f830
and 3fbae96).
- **Changeset:** `.changeset/38442-skill-markdown-fitting-section.md`,
`@objectstack/skills` patch. `skills/**` ships as `@objectstack/skills`
(its build copies the tree into `dist/`), so the diff publishes and
takes no `skip-changeset`.

### Size readings (lines, bytes, ratchet tokens)

| | before (f459c86) | after (3fbae96) | delta |
|---|---|---|---|
| `skills/objectstack-ai/SKILL.md` | 505 lines, 28827 bytes, 7200 tokens
| 507 lines, 29017 bytes, 7248 tokens | +2 lines, +190 bytes, +48 tokens
|
| all `skills/*/SKILL.md` | 4386 lines, 228099 bytes | 4388 lines,
228289 bytes | +2 lines, +190 bytes |
| ratcheted (authored) bundle | 200891 tokens | 200939 tokens | +48
tokens |

Tokens are the ratchet's own count, `ceil((bytes - 27 stamp-line bytes)
/ 4)`.

### The token ratchet: restatement cut first, the row raised by the
measured remainder

Headroom on `main` was 0 (7200 of 7200). The four cuts above pay 79
bytes; the new teaching costs 269; the remainder is +190 bytes, +48
tokens. The row moves 7200 to 7248 under the standing ruling
「A:先削重复,余额按实测提高」 (ruling record 6513306068, letter B), by the measured
remainder only. Arithmetic in priced bytes (the 27-byte stamp line
excluded): 28800 on `main`, 28990 here, `ceil(28990 / 4) = 7248`.

File surface: the claim named the skill file only. The row and the
changeset were added by the seat's widening record 7250198232 on the
card.

## Tests

Prose and one ratchet row: no behaviour changes, so no test and no
ablation. Local gates on head 3fbae96, the 67 commands
`dispatch-gates.mjs --commands` derives, each exit code read before any
pipe:

- 62 exit 0, among them `check-skills-token-ratchet.mjs`
("skills/objectstack-ai/SKILL.md 7248 / 7248 (+0)", "ratcheted
(authored) 200939 / 200939 (+0)") and its `--self-test` ("111 cases
pass"), `check:ratchet-remedy-authority`, `check:pm-dispatch-gates`,
`check-self-test-wired.mjs`, `@objectstack/spec check:skill-docs`,
`check:skill-links`, `check:skill-identifier-liveness`,
`check:skill-compatibility`, `check:skill-frame-sync`,
`check:pm-skill-id-lint`, `check:doc-authoring`, `check:nul-bytes`,
`check:published-files`, `check-empty-changeset.mjs`,
`check-changeset-no-major.mjs`, `check-adr-0087-registration.mjs`.
- 5 exit 3, NOT MEASURED (each needs a whole-workspace build this diff
does not owe locally; CI measures them): `@objectstack/lint
check:doc-formula-expressions`, `check:dts-closure`,
`check:dual-build-cjs-loads`, `check:lean-entry-closure`,
`check:sourcemap-no-sources-content`.
- `dispatch-gates.mjs --ran`: 67 derived, 67 run, 0 unrun.
- The ratchet script's own suite is its `--self-test` (above). The one
test file that names the script,
`packages/spec/scripts/platform-catalog.test.ts`, names it in a comment
and does not exercise it; not run.

## Acceptance notes

- Card item 1 (the `markdown` bullet): done. Item 2 (the `minChars`
sentence): done. Item 3 (no new example; duplicates cut first): done:
the cuts come first and the measured remainder raises the row (section
above).
- "fits `maxChars`" is the card's wording. The block's next paragraph
already says the embedder's input limit can lower `maxChars`, which is
the token budget of the spec text; nothing the spec and the protocol
page do not say is taught.
- History note: commit 924f830 was first held on a no-PR backup branch
and its message still says so; it was fast-forwarded onto this branch
after record 7250198232. The backup branch
`claude/issue-38442-skill-markdown-fitting-section-wip` could not be
deleted from the dev container (403) and waits for a hand with delete
rights.
- The block's last sentence was outside the card's three items; it is
corrected here on the contract review's S1 (record 7250515767), being in
the claimed block. Its nit N1 (the heading-path prefix may be the
innermost heading only) is accepted as written, no change.

## Verification

- Read first: `skills/objectstack-ai/SKILL.md` lines 325-346 (the whole
diff of the skill), beside `content/docs/protocol/knowledge.mdx` §3.5,
the `markdown` row. Riskiest hunks: the `minChars` sentence and the
split-change sentence after it (beside §3.5, "A split change is a new
index").
- Two-minute check: `node scripts/check-skills-token-ratchet.mjs` exits
0 and prints "skills/objectstack-ai/SKILL.md 7248 / 7248 (+0)".

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- signed: repo:objectstack#5 · os-project-manager ·
session_01FEkQ5oQLfL8thb6wtUHnTb -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…Korean questions by 2- and 3-character pieces (objectstack-ai#38469)

<!-- claude-projects-attribution: {"github_login":"os-project-manager"}
-->
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XJFhX5XfWT8anspjCw9gfjz)_
Part of objectstack-ai#38411. This PR covers Ask 1, Ask 2 and the first two Acceptance
items, plus the model-free half of the eval, and on pgvector the cheaper
matcher for a caseless piece (`LIKE` instead of `ILIKE`). Still open:
the BrightRule model-graded before/after (needs a running BrightRule
environment and model credentials), and Ask 3 (not measured, see below).

Clause-②: yes (widening)
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:在本地 libSQL 和 PostgreSQL
两种存储上,用中文、日文或韩文不加空格整句提问时,知识检索的关键词一路终于能匹配到段落;英文提问不受影响。
- 为什么做:属于知识平台专题,解决混合检索在中文问题上实际只剩向量一路的问题。
- 出错会怎样:代价是检索变慢(数字见下),最坏情况是关键词一路排序变差,向量一路照常作答;不改索引、不需重建,可直接撤回。
- 要你做什么:无。

取舍数字(合成制度题集,约 6.7 万段落,218 道中文题):

- 中文题关键词一路前 5 名命中率:0.028 → 0.495。
- 本地 libSQL 关键词一路 p95:约 0.12 秒 → 约 0.5 秒。
- 本地 libSQL 混合检索 p95:0.41 秒 → 0.84 秒。
- PostgreSQL 关键词一路 p95:约 0.6 秒 → 约 1.9 秒(本 PR 已把中文片段改成更便宜的匹配方式,排序不变;改之前约
3 秒)。
- 检索词上限 16 是实测拐点:再往上每多约 40% 耗时只多约 1 个点命中率。
- 想再降延迟的两个杠杆:把上限降到 12(命中率 0.459,libSQL 关键词 p95 约 0.31 秒);PostgreSQL
上给段落正文加三元组索引,已立后续卡 objectstack-ai#38473,不在本 PR。
- 未测:BrightRule 模型评分的前后对比,需要运行环境和模型凭据。

## What changes

- `keywordTerms` in `knowledge-turso/src/sql.ts` and
`knowledge-pgvector/src/sql.ts` (one body, kept identical) cuts a run of
Han, Hiragana, Katakana (including the prolonged sound mark) or Hangul
inside a term into overlapping pieces of three characters and of two. A
run of two characters is one piece. A run of one is dropped, because it
would match nearly every passage. Figures and codes next to a run
(`2000`, `X-200`) stay whole terms. Latin-script and spaced queries get
exactly the terms they had before.
- **Selection rule (Ask 2).** `MAX_KEYWORD_TERMS` stays at 16,
re-decided by measurement (below). The cap is filled in this order:
figures, codes and words; then pieces of three characters and runs of
two; then pieces of two characters. A long question therefore keeps the
pieces the libSQL trigram index serves; a short one fills the cap with
pieces of two. Matching is unchanged. No index change, no fingerprint
change, no reindex.
- **pgvector matcher (round 2).** A keyword term the `tsvector` does not
serve is matched as a substring by `LIKE` when it holds no cased letter
(`containsOperator` in `knowledge-pgvector/src/sql.ts`:
`term.toLowerCase() === term.toUpperCase()`; a Han, kana or Hangul
piece, a figure), and by `ILIKE` otherwise. Case folding can find
nothing more for such a term, so the rankings are identical. Nothing
else in the Search section changes. libSQL is unchanged.
- **Docs.** `content/docs/protocol/knowledge.mdx` (the contract's
optional `keywordLeg` case; both Search bullets: the CJK pieces, and on
pgvector `LIKE` / `ILIKE`) and both plugin READMEs. The turso README
said "a Chinese question is one term", which this change made false.
- **Contract (H2 placement, Clause-② yes).**
`@objectstack/service-knowledge/testing`:
`KnowledgeAdapterContractOptions.implements` gains an **optional**
`keywordLeg` member (absent means `false`). When an adapter declares it,
the shared suite asks the unspaced question
「出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗」 over one passage holding 「2000元以下除外」
and five passages holding the question's characters one by one but none
of its words. The passage must be ranked at `topK` 3. knowledge-turso
and knowledge-pgvector declare it. knowledge-memory and the service
stubs have no keyword leg and are untouched. No placement with zero new
exported members exists: the memory adapter and the stubs run the same
suite and have no keyword leg, and the spec contract has no capability
flag to read. The member is optional, so existing callers compile
unchanged; that makes it widening.

## Tests

<details><summary>Unit pins, contract case, ablation (head
b511770)</summary>

- knowledge-turso `acceptance.test.ts`: the Latin and spaced pin is kept
exactly (`What is the X-200 pump? …` gives today's 10 terms; `出差 住宿`
gives `['出差','住宿']`; cap 16). New pin: an unspaced question gives its
figure and then its pieces; `X-200型号的保修期` keeps `X-200`; runs of two and
one; kana and Hangul.
- knowledge-pgvector `keyword-terms.test.ts` (new, no database): the
same pins, plus which matcher each term goes to (`isWordTerm`).
- Contract case: knowledge-turso on `:memory:` and on a `file:` URL, and
knowledge-pgvector on a live PostgreSQL 16 with pgvector 0.6.0 started
in this container.
- Results, local: knowledge-turso `Test Files 4 passed, Tests 284
passed`; knowledge-pgvector live (`OS_TEST_POSTGRES_URL` set,
`OS_EXPECT_LIVE_DIALECT_MATRIX=1`) `Test Files 11 passed, Tests 108
passed`; service-knowledge `21 files, 726 tests passed`;
knowledge-memory `3 files, 66 tests passed`. Type check is green for
knowledge-turso, knowledge-pgvector, service-knowledge and
knowledge-memory.
- Ablation (base `sql.ts` swapped in, checked by blob hash, then
restored and checked by hash again): turso goes red with 4 failures (the
piece pin and the contract case, on both store kinds; the Latin pin
stays green); pgvector, live, goes red with 3 failures (the contract
case and two pins).
- Reverse type check: the turso type check first read a
`dist/testing.d.ts` built before this change and refused `keywordLeg`
(TS2353). After the rebuild it passes.
</details>

<details><summary>Round 2: the pgvector matcher (head cde0bbe; code
identical to 81be16f)</summary>

- `keyword-terms.test.ts` gains two pins. `containsOperator` gives
`LIKE` for `元以下`, `出差`, `コー`, `휴가`, `42` and `ILIKE` for `ab`, `X-200`,
`É`. A statement pin runs `adapter.search('出差 ab', …)` against a
recording pool and reads, from the ranking statement itself, the
operator in front of the placeholder each pattern is bound to: `%出差%`
gets `content LIKE`, `%ab%` gets `content ILIKE`.
- knowledge-pgvector live (PostgreSQL 16 + pgvector 0.6.0,
`OS_EXPECT_LIVE_DIALECT_MATRIX=1`), contract case included: `Test Files
11 passed (11)`, `Tests 110 passed (110)`, verify lock `VERDICT
command-exit 0`.
- `pnpm --filter @objectstack/knowledge-pgvector typecheck`: `VERDICT
command-exit 0`.
- Ablation: with the adapter reverted to b511770 (blob hash checked,
then restored and checked again), the statement pin fails: `Tests 1
failed | 4 passed (5)`.
- CI on b511770 (job 141221631158) and on 923c009 (jobs 141222136228
and 141222139195): every failing step is an aggregator reading a
`cancelled` lane (for example "type-check lane `typecheck-workspace`
concluded `cancelled` -- expected `success`"). Each later push to this
branch cancelled the run in flight. 923c009 also held one real error,
TS2353 in the new statement pin (`recipeHash` is not a member of the
search options' `index`), fixed in 81be16f and green locally as above.
</details>

## Measurement

Every harness is a scratch script outside the repository. Corpus: the
BrightRule synthetic set (`scripts/eval/build.ts --distractors 1500`,
brightrule @ 07e21ac). Passages are cut one per article or section, with
attachments kept on their own and each passage prefixed
`【unit|title|attachment】 path`, as the app's clause hook does. Each
document is indexed through `TursoKnowledgeAdapter.upsert` (the real
write path). Two tables:

- 11k: 1,577 documents, 11,025 passages.
- 67k: the same plus 8,000 distractors from seeds 11 to 14, giving 9,577
documents and **67,421 passages**. The card's table had 67,379.

Questions: the **218 zh questions whose expected policies are Chinese**
(230 counting the zh-to-English ones). A hit means a passage of an
expected policy (P) or of the expected article (C) in the keyword leg's
top 5 or top 10. The keyword leg is isolated with an all-zero query
vector, which turns the vector leg off. Intervals are 95% bootstrap
intervals over questions (2,000 resamples). Retrieval is deterministic:
**each side was run 3 times and the rankings were identical on every
run**, on both stores and both tables. So the interval comes from the
question sample, not from run noise.

<details><summary>Keyword leg, libSQL store, before and after</summary>

| table | side | P@5 | P@10 | C@5 | C@10 | questions with any hit | p50
| p95 |
|---|---|---|---|---|---|---|---|---|
| 11k | before | 0.032 [0.009, 0.055] | 0.037 [0.014, 0.064] | 0.028
[0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 0.7 ms | 20 ms |
| 11k | after | **0.500** [0.431, 0.569] | 0.514 [0.450, 0.583] | 0.486
[0.421, 0.556] | 0.500 [0.435, 0.569] | 206 | 52 to 56 ms | 80 to 93 ms
|
| 67k | before | 0.028 [0.009, 0.050] | 0.032 [0.009, 0.060] | 0.028
[0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 1.4 ms | 113 to 132 ms |
| 67k | after | **0.495** [0.427, 0.564] | 0.500 [0.431, 0.569] | 0.486
[0.421, 0.556] | 0.491 [0.421, 0.560] | 206 | 305 to 328 ms | **491 to
516 ms** |

All 230 zh questions, 67k: P@5 goes from 0.026 [0.009, 0.048] to 0.470
[0.404, 0.530].
</details>

<details><summary>Choosing the cap and the order (67k, keyword leg
alone)</summary>

| order / cap | P@5 | p50 | p95 |
|---|---|---|---|
| pieces of three and runs of two only (no pieces of two) | 0.404 | 7 ms
| 155 ms |
| three-first, cap 12 | 0.459 | 136 ms | 314 ms |
| **three-first, cap 16 (shipped)** | **0.495** | 321 ms | 507 ms |
| three-first, cap 20 | 0.505 | 440 ms | 690 ms |
| three-first, cap 24 | 0.509 | 552 ms | 910 ms |
| by position, cap 16 | 0.495 | 445 ms | 746 ms |
| by position, cap 32 (every piece of every question but a few) | 0.518
| 670 ms | 1,277 ms |

The questions are 16 characters at the median and 24 at p90, which gives
23 uncapped terms at the median and 34 at p90; 202 of 230 exceed 16. On
the 67k table, a piece of two characters costs one scan of the rows in
scope, about 23 ms (`LIKE` and `instr` cost the same). A piece of three
is served by the trigram index and is nearly free, except for a trigram
most passages hold: about 30 ms to materialise one held by 48,000 rows.
Past 16, recall gains about one point for each further 40% of latency,
and every interval overlaps. Cap 16 with the three-first order is the
knee. Keeping a one-character run measured no recall change.
</details>

<details><summary>Hybrid search latency, libSQL 67k with a 1024-wide
vector column (exact scan)</summary>

| side | p50 | p95 |
|---|---|---|
| before | 258 ms | 410 ms |
| pieces of three only | 266 ms | 429 ms |
| after (three-first, cap 16) | 563 ms | 837 ms |
| three-first, cap 24 | 818 ms | 1,244 ms |

The vector leg here is a bag-of-characters fake embedder, used for its
cost only. Its fused ranking is not reported: a lexical stand-in for an
embedder measures the fusion of two lexical legs, not hybrid retrieval.
</details>

<details><summary>pgvector, live PostgreSQL 16 + pgvector 0.6.0, the
same 67k passages, keyword leg alone</summary>

| side | P@5 | p50 | p95 |
|---|---|---|---|
| before (3 runs) | 0.028 | 132 to 150 ms | 617 to 691 ms |
| pieces, every substring term by `ILIKE` (b511770, 3 runs) | 0.495 |
538 to 563 ms | 2,883 to 3,085 ms |
| **pieces, a caseless term by `LIKE` (this head, 3 runs)** | 0.495 |
187 to 195 ms | **1,832 to 1,925 ms** |

The rankings are identical on every run, identical between the `ILIKE`
and the `LIKE` heads, and the same hit set as libSQL. The tail is
questions holding 公司: its pieces are held by 67,125 of 67,421 passages,
because every clause prefix names its company, so nearly every row
becomes a candidate. On this server `ILIKE '%公司%'` costs 90 ms per scan
against 18 ms for `LIKE` or `strpos`, with identical counts; that is the
matcher change in this PR. What remains of the tail is one substring
scan per piece over nearly every row, and the candidate `tsvector`
computed for each of them.
</details>

Commands, all run from a scratch directory outside the repository:

```
pnpm run eval:build -- --distractors 1500 --out EVALSET                    (in a scratch copy of brightrule, pnpm install --ignore-scripts)
pnpm run eval:build -- --distractors 2000 --seed 11..14 --out EVALSET-sN   (distractors only, keys suffixed)
python3 -I prep.py CORPUS docs.json                                        (clause passages)
tsx eval.ts index docs.json DB 8 zero        and        tsx eval.ts search docs.json DB questions.json VARIANT out.json
tsx eval.mts index / search                  (pgvector, the same shape)
python3 -I score.py zh RUN.json …            (recall, bootstrap intervals, p50/p95)
```

All timings are seconds on a shared 4-core container, with sibling
agents running.

- NOT MEASURED: BrightRule model-graded eval, reason: it needs a running
BrightRule environment and model credentials, and this container has
neither. The keyword-leg retrieval above is the model-free stand-in.
- NOT MEASURED: fused hybrid recall, reason: no real embedder in this
container. A lexical stand-in would measure the fusion of two lexical
legs.
- NOT MEASURED: Ask 3 (a larger per-leg pool before fusion), reason: it
is judged on fused ranking, which needs a real embedder. Ask 3 also
reaches `knowledge-tools.ts`, which is outside this claim.

## Acceptance notes

- **pgvector keyword-leg cost (carrier: objectstack-ai#38473, filed by the seat).**
With the `LIKE` matcher in, pgvector's keyword-leg p95 on the 67k table
goes from about 0.6 s to about 1.9 s. Two levers remain, both outside
this claim. First, compute the candidate `tsvector` only when a word
term needs it (a Search-section change). Second, a pg_trgm GIN index on
the passage content, which serves `LIKE` / `ILIKE` substrings. That is
an index change: a second DDL beside `keywordIndexDdl`
(`knowledge-pgvector/src/sql.ts`), created through `ensureKeywordIndex`
(`pgvector-adapter.ts`), plus a `pg_trgm` extension dependency next to
the `vector` one. It is not a fingerprint change: the index fingerprint
hashes only the embedding model, variant, dimensions and split, and an
older table gets the keyword index at its first search without a
rebuild.
- A lower cap is the cheapest lever on both stores: cap 12 measured P@5
0.459 and libSQL keyword p95 314 ms (cap 16: 0.495 and 507 ms).
- libSQL: a piece of two characters costs one scan of the rows in scope.
Scoring pieces of two only among the candidates that the index-served
terms recruit would remove that scan. It is a Search-section change and
moves each piece's document frequency, so it needs its own measurement.
- **Separator class takes 々, 〆 and 〇 (carrier: objectstack-ai#38411, a remaining item
there, filed by the seat).** The class `\u3000-\u303f` holds 々 (U+3005),
〆 (U+3006) and 〇 (U+3007, the ideographic zero), in both stores. With
this PR's rule that drops a one-character run, 「人々」 yields no keyword
term (on main it kept 「人」) and 「二〇二四年」 loses 「二」. The fix (take
U+3005–U+3007 out of the separator class and into the run, pins in both
stores) lands as a follow-up PR on objectstack-ai#38411 after this one merges, so this
approved head does not move (L1 7250902792).
- To run the pgvector live suites, this container installed
`postgresql-16-pgvector` (0.6.0, Ubuntu noble) and ran a private cluster
on a random port, removed afterwards.

## Verification

- Read first: `packages/plugins/knowledge-turso/src/sql.ts`
(`keywordTerms`: the run split and the final order and cap),
`packages/services/service-knowledge/src/testing.ts` (the optional
`keywordLeg` member and its case),
`packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts` (the
keyword branch of the ranking statement, where `containsOperator` picks
`LIKE` or `ILIKE`).
- Two-minute check: `pnpm --filter @objectstack/knowledge-turso exec
vitest run --maxWorkers=2 src/__tests__/contract.test.ts` should show
the case `the keyword leg › an unspaced question ranks the passage …`
passing on both `:memory:` and `file:`.

<details><summary>Local gate subset at cde0bbe (CI runs the full
farm)</summary>

- Tests and type checks: listed under Tests above.
- `node scripts/pm/dispatch-gates.mjs --commands` derived 101 families
for the 12 changed files (70 at b511770, plus 31 the docs edit brings
in). Each ran with its exit code captured before any pipe. The 31 docs
families and 8 families that read the round-2 files were run at
cde0bbe; the others read files unchanged since b511770 and carry that
reading. `--ran` reconciliation at cde0bbe: `101 derived, 101 run, 0
NOT-MEASURED, 0 UNRUN`. Exit codes: **96 exit 0**, and five not
measured:
- NOT MEASURED: `check:skill-examples`, reason: exit 3, PREREQUISITE NOT
MET, it needs the client SDK's `dist/`. No skill file is touched.
- NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test`, reason:
PREREQUISITE NOT MET, its pinned positive-control commit is beyond this
shallow clone.
- NOT MEASURED: `check:dual-build-cjs-loads`, reason: PREREQUISITE NOT
MET, it needs every package's `dist/`.
- NOT MEASURED: `check:query-options-erasure` and
`check:type-check-debt`, reason: repo-wide ESLint and `tsc` scans that
passed the 240 s per-gate limit. CI's Lint & Repo Gates and TypeScript
Type Check carry them.
- `overlap-check` before the push: `VERDICT clean` against origin/main
and the two open PRs that share `knowledge.mdx` (objectstack-ai#38468, objectstack-ai#38470), and
clean against `origin/claude/project-thread-mu3i0t`.
- Self-scan of the changed files for control bytes: no hits.
</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm

<!-- signed: repo:objectstack#5 · os-project-manager ·
session_01FEkQ5pfJqySEaVD3CKvevm -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

service-knowledge: no split that keeps one passage per article; short articles are merged and tables lose the note after them

2 participants