diff --git a/.changeset/37098-knowledge-splitter.md b/.changeset/37098-knowledge-splitter.md new file mode 100644 index 00000000000..738956a6769 --- /dev/null +++ b/.changeset/37098-knowledge-splitter.md @@ -0,0 +1,58 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-memory': patch +'@objectstack/embedder-openai': patch +'@objectstack/service-settings': patch +--- + +feat(service-knowledge)!: one splitter in the knowledge service (whole / recursive / markdown, aware of Chinese text), the chunk channel to adapters, and the `split` key on an object source; `KnowledgeChunk.metadata` and the Knowledge page's chunk overlap retired + +Clause-②: yes (narrowing) — widens the knowledge contract (the `split` key, `chunks`, `headingPath`, the adapter's `capabilities` and `embedding`, `IEmbedder.maxInputTokens`, the reindex `failed` / `failures`) and narrows two accept sets: `KnowledgeChunk.metadata` is refused, and `knowledge.chunk_overlap` is no longer a key of the `knowledge` settings namespace +Metadata-protocol: narrowed +Skills-docs: none in this change — `skills/objectstack-ai/SKILL.md` lists the object source's keys and does not yet name `split`, and names neither retired key; that file is a governed surface outside this change, so teaching the new key is left to its owner. `content/docs/protocol/knowledge.mdx` (new section 3.5) and `content/docs/ai/knowledge-rag.mdx` document the key, the strategies, the limits and the removals in this change. + + + +**BREAKING** in two places, each with its fix: + +- `KnowledgeChunk.metadata` (`@objectstack/spec/ai`): FROM an optional `Record` accepted and stripped TO a `retiredKey()` tombstone — `KnowledgeChunkSchema.parse()` (and a `KnowledgeDocument` whose `chunks` carry one) refuses it with the prescription, and `tsc` types the key `never`. Nothing ever wrote or read it: the knowledge service cuts the passages and sets no per-passage metadata, and no adapter consulted one. The fix: delete the key; a passage takes its document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on. D3 entry: `knowledge-chunk-metadata-retired`. +- `knowledge.chunk_overlap` (the Knowledge settings page's **Chunk overlap**): FROM a `number` key of the `knowledge` settings namespace (default 80) TO no key — the page no longer shows it, the service no longer resolves it, and a write naming it is refused `400 UNKNOWN_KEY`. Nothing ever read it and the splitter cuts without overlap, so a value set there never had an effect. A stored value is kept, never deleted. The fix: stop writing the key (a script or seed that sets it); there is nothing to replace it with. **Target chunk size** (`knowledge.chunk_target`) is the setting that now shapes passages. + +The knowledge service now cuts documents into passages itself, once, and hands the same passages to every adapter that accepts them, so one source gives the same passages on each adapter. + +New in `@objectstack/spec`, all optional: + +- `ObjectKnowledgeSource.split?`: `{ strategy: 'whole' | 'recursive' | 'markdown', maxChars?, minChars? }`. Omitted, documents are cut `recursive`. New exports `KnowledgeSplitSchema`, `KnowledgeSplitStrategySchema` and the types `KnowledgeSplit`, `KnowledgeSplitStrategy` (`@objectstack/spec/ai`). +- `KnowledgeDocument.chunks?`: the document's passages, set by the service. `KnowledgeChunk` gains `headingPath?` (the headings a passage sits under, outermost first); its `id` is set by the service to `documentId#index`. +- `IKnowledgeAdapter.capabilities?: { chunks?: boolean }`: an adapter that sets `chunks: true` receives every document with `chunks` and indexes those passages as given. An adapter that does not set it receives whole documents, without `chunks`, as before. +- `IKnowledgeAdapter.embedding?: { maxInputTokens? }` and `IEmbedder.maxInputTokens?`: the longest input the adapter's embedder accepts, in tokens. The service reads it each time it splits. New exported types `AdapterCapabilities`, `AdapterEmbeddingDescriptor` (`@objectstack/spec/contracts`). +- `KnowledgeReindexResult.failed?` and `failures?` (`[{ documentId, reason }]`, at most 20 named; `failed` counts all). + +How the service cuts (`@objectstack/service-knowledge`): + +- `recursive` cuts at blank lines, then line breaks, then sentence ends, then semicolons, then characters. `。?!` end a sentence anywhere; `. ? !` only before whitespace or the end of the text, so 「3.2 条」 and 「400.50 元」 stay whole; an end mark followed by a closing quote or bracket ends nothing. A Markdown table or list item is never cut while it fits; a table that does not fit is cut between rows, each piece repeating the header row. Adjacent pieces shorter than `minChars` (default 200) are merged. +- `markdown` cuts one section per heading; every passage begins with its heading path, which counts toward its length and is embedded, and carries it as `headingPath`. +- `whole` keeps one passage per document. +- A passage is at most `split.maxChars` characters, else the settings page's `knowledge.chunk_target`, else 800; and, when the adapter reports `embedding.maxInputTokens`, its `estimateTokens` is at most 80% of that limit. +- A `whole` document over that budget is removed from the index and reported, never truncated: `reindexSource` counts it in `failed` and names it in `failures`, the record event sync logs it at `error` (source, record id, estimate, limit), and `indexDocument` throws. With no limit known nothing is checked. +- `indexDocument` refuses a document that already carries `chunks` (it throws, naming the field), as it refuses `docHash`. +- Known limit: `docHash` does not cover the passages, so a changed `split`, `chunk_target` or embedder limit re-splits a document only when the document itself next changes. The index fingerprint (ADR-0161 K7) will rebuild a source when its split changes. + +`@objectstack/knowledge-memory` no longer splits documents itself: it declares `capabilities.chunks` and indexes the service's passages as given (a document handed to it directly without `chunks` is one passage of its whole text). Its hits are now the service's passages, with the service's `chunkId`s. + +`@objectstack/embedder-openai`: `OpenAIEmbedder.maxInputTokens` is now public (`IEmbedder.maxInputTokens`): the `maxInputTokens` option, else the model's documented limit from the known-model table, else absent. + +`@objectstack/service-settings`: the Knowledge page's **Target chunk size** (`knowledge.chunk_target`) is now read: it is the splitter's `maxChars` beneath a source's own `split.maxChars`, and it is shown for the in-memory adapter too. **Chunk overlap** (`knowledge.chunk_overlap`) is retired: nothing ever read it and the splitter cuts without overlap. The `knowledge` manifest is now `version: 2`. A stored value for it is kept, never deleted; it is no longer shown or resolved, and a write naming it is refused `400 UNKNOWN_KEY`. + +`@objectstack/service-knowledge/testing`: `runKnowledgeAdapterContract`'s `implements` gains a required `chunks: boolean` (whether the adapter sets `capabilities.chunks`), and the suite runs the chunk-channel cases for it. + +What to do: + +- An adapter package that runs `runKnowledgeAdapterContract`: add `chunks: false` to `implements` (or `chunks: true` once the adapter takes the service's passages). +- An adapter that wants the service's passages: set `capabilities: { chunks: true }`, index each `doc.chunks` entry as given, and report its embedder's limit as `embedding.maxInputTokens` (from `IEmbedder.maxInputTokens`), from a getter if the embedder resolves late. +- A caller of `indexDocument` stops setting `chunks`. +- A deployment that set **Chunk overlap**: nothing to do; the value had no effect and keeps having none. A script or seed that writes `knowledge.chunk_overlap` drops the key. +- Code or a test that builds a `KnowledgeChunk` with `metadata`: delete the key; filter on the document's `metadata`. + +The retirement kit: the `retiredKey()` tombstone on `KnowledgeChunkSchema.metadata` in `ai/knowledge-document.zod.ts`, `RETIRED_KEYS_BY_MAJOR[18]` row `ai/KnowledgeChunk:metadata`, D3 `knowledge-chunk-metadata-retired` with its step-18 rationale fragment (no D2 conversion: a chunk is a runtime contract shape, never stored in stack metadata, so `os migrate meta` has no source to rewrite — the `ActionDescriptor.isAsync` disposition), the `[RETIRED]` line in `authorable-surface/ai.json`, the regenerated `knowledge-document.mdx` reference, and the pin `ai/knowledge-document.test.ts`. The settings key follows the Localization format keys' retirement: the specifier removed from `knowledge.manifest.ts` and from the 11 translation packs, the manifest at `version: 2`, stored rows kept, and the manifest pins updated. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 923a9c8324e..e3b2ff169a5 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -79,6 +79,25 @@ installed ([Connect an MCP Client](/docs/ai/connect-mcp)). - **Inline event sync.** When records on indexed objects change, the kernel's `IRealtimeService` events drive `KnowledgeService.handleRecordUpsert/Delete` automatically. No cron, no queue (yet — Phase 2). - **Adapter swap, zero caller changes.** Move from `memory` to `ragflow` to a custom adapter without touching your `search` calls, the `search_knowledge` tool, or any agent prompt. +## Splitting documents into passages + +The knowledge service cuts each document into passages once, and every adapter that takes passages (`knowledge-memory` does) indexes the same ones. An object source chooses how with `split`: + +```ts +source: { + kind: 'object', + object: 'policy', + contentFields: ['title', 'body'], + split: { strategy: 'markdown', maxChars: 600 }, +} +``` + +- `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. +- `markdown` cuts one section per heading; each passage begins with its heading path, which is embedded with it. +- `whole` keeps each document as one passage. + +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). + ## Embedder input limits Every embedding model accepts a text up to some length, counted in tokens. A provider that is sent a longer text truncates it **without an error** — the tail is never embedded, so a search for it finds nothing. `@objectstack/embedder-openai` refuses such an input instead: @@ -86,6 +105,7 @@ Every embedding model accepts a text up to some length, counted in tokens. A pro - When a limit applies, `embed()` measures every input before it sends anything. When one is over the model's limit, the whole call fails with an error naming the input's index, the model, the estimate and the limit. Nothing is sent and nothing is truncated. - The limit comes from the known-model table, which carries each provider's documented per-input limit (OpenAI `text-embedding-3-*` 8192, DashScope `text-embedding-v3` 8192, BigModel `embedding-3` 3072, SiliconFlow `BAAI/bge-m3` 8192, `BAAI/bge-large-*-v1.5` 512, …). Set `maxInputTokens` to override it. - A model that is not in the table, with no `maxInputTokens`, has no limit — its inputs are sent at any length — and the embedder warns once when it is constructed. +- The embedder reports the limit it applies as `maxInputTokens` (`IEmbedder.maxInputTokens`), so a knowledge adapter can pass it on (`embedding.maxInputTokens`) and the service's passages fit it. ```ts new OpenAIEmbedder({ @@ -115,7 +135,7 @@ Known residual: text made mostly of random hex or base64 — UUIDs, sha256 diges ## Why we did not build a vector DB -Mature OSS (RAGFlow, LlamaIndex, Dify) already nail chunking, embedding, hybrid retrieval, rerank, and OCR. ObjectStack's value is **the metadata-native source declaration + the permission-aware filter on top of those engines** — not yet-another-RAG-stack. Customers pick the retrieval engine that matches their data; we make sure it talks to ObjectStack the same way every time. +Mature OSS (RAGFlow, LlamaIndex, Dify) already nail embedding, hybrid retrieval, rerank, and OCR. ObjectStack's value is **the metadata-native source declaration, one structural split for every adapter, and the permission-aware filter on top of those engines** — not yet-another-RAG-stack. Customers pick the retrieval engine that matches their data; we make sure it talks to ObjectStack the same way every time. --- diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 74fd8327535..f667d6fbccf 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -131,6 +131,7 @@ source: { contentFields: ['title', 'body'], // at least one, required metadataFields: ['category', 'author'], // optional, carried onto the document where: { status: 'published' }, // optional ObjectQL filter + split: { strategy: 'markdown', maxChars: 600 }, // optional; see 3.5 } // file — every object under a storage prefix @@ -171,8 +172,19 @@ Canonical shapes shared by every adapter: and `indexDocument` refuses a document that already carries either; the adapter stores them and returns `docHash` as stored, and never computes or alters either. -- `KnowledgeChunk` — adapter-produced chunk of a document. The framework - does **not** chunk; adapters do. +- `KnowledgeDocument.chunks?` — the document's passages, cut by the + service's splitter (see [3.5 The split](#35-the-split)). Set by the service, + and only on a document handed to an adapter that declares + `capabilities.chunks`; `indexDocument` refuses a document that already + carries them. Derived from `content`, so not part of `docHash`. +- `KnowledgeChunk` — one passage: `id` (the service sets it to + `${documentId}#${index}`, so a hit's `chunkId` is the same on every adapter), + `documentId`, `index`, `content` (what the adapter embeds and returns as a + snippet), and `headingPath?` (the headings it sits under, outermost first, + under the `markdown` strategy). The adapter indexes each passage as given and + does not split it again. A passage has no `metadata` of its own: it takes its + document's `metadata`. The chunk's former `metadata` key, which nothing wrote + or read, is retired, and a chunk that carries one is refused with the fix. - `KnowledgeHit` — a search result (`chunkId`, `documentId`, `score`, `snippet`, `sourceRecordId?`, `metadata`). @@ -213,13 +225,16 @@ the all-important `executionContext` (from the permission-aware tool execution work — see `actions-as-tools.mdx`). `KnowledgeReindexOptions` accepts `dryRun` and `limit`; `reindexSource` returns a `KnowledgeReindexResult` (`indexed`, `discovered`, `skipped`, `purged`, -`ok`, …) — see [Reindex: skip and purge](#reindex-skip-and-purge). +`failed`, `failures`, `ok`, …) — see [Reindex: skip and purge](#reindex-skip-and-purge) +and [3.5 The split](#35-the-split). ### 3.4 `IKnowledgeAdapter` (implemented by plugins) ```ts interface IKnowledgeAdapter { readonly id: string; + readonly capabilities?: { chunks?: boolean }; // takes the service's passages + readonly embedding?: { maxInputTokens?: number }; // what its embedder accepts upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise; search(query: string, opts: AdapterSearchOptions): Promise; delete(documentIds: string[], ctx: AdapterContext): Promise; @@ -231,10 +246,18 @@ interface IKnowledgeAdapter { } ``` -The adapter surface is **deliberately minimal**: no embedding -management, no chunk strategy, no rerank toggles. Those are the -adapter's private concerns. Adapters that need extra knobs expose them -in their plugin options. +The adapter contract carries what an adapter **reports**, never how it +is configured: no embedding configuration, no rerank toggles. Those are the +adapter's private concerns; adapters that need extra knobs expose them in +their plugin options. The split is the service's (ADR-0161 K1): an adapter +that declares `capabilities.chunks` receives every document with the +service's passages and indexes them as given; one that does not receives +whole documents, without `chunks`, and splits them itself, as before. +`embedding.maxInputTokens` reports the longest input the adapter's embedder +accepts (an adapter fills it from `IEmbedder.maxInputTokens`); the service +reads it each time it splits, never once at boot, because the embedder may +register later — an adapter that resolves its embedder late serves it from a +getter. Every member past `upsert` / `search` / `delete` is optional (ADR-0161 K8): an adapter that lacks one keeps working, and the service does what it @@ -256,18 +279,76 @@ import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/test runKnowledgeAdapterContract({ name: 'my-adapter', makeAdapter: () => new MyAdapter(/* a fresh, empty store */), - implements: { listDocuments: true, organizationIds: true }, + implements: { listDocuments: true, chunks: true, organizationIds: true }, }); ``` It covers upsert / search / delete, `listDocuments` page boundaries and `docHash` round-trips, the organization filter, and — through a real -`KnowledgeService` — the skip and the purge below, and a search from one -organization under `isolated` and `group`. `implements` declares the optional members, and the suite +`KnowledgeService` — the skip and the purge below, a search from one +organization under `isolated` and `group`, and the chunk channel: an adapter +that takes chunks receives the service's passages and indexes them unchanged, +one that does not keeps receiving whole documents, and a `whole` document over +the embedder's budget is removed and reported. `implements` declares the optional members, and the suite checks the declaration against the adapter. `./testing` is a test-only, ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it. `knowledge-memory` runs it as the reference implementation. +### 3.5 The split + +The knowledge service cuts documents into passages once, in one splitter, +and hands the same passages to every adapter that declares +`capabilities.chunks` — so one source gives the same passages on each of +them. The object source's `split` key chooses how: + +```typescript +split: { + strategy: 'recursive', // 'whole' | 'recursive' | 'markdown' + maxChars: 600, // optional: longest passage, in characters + minChars: 200, // optional: merge adjacent pieces shorter than this (default 200) +} +``` + +| Strategy | How it cuts | +|----------|-------------| +| `whole` | One passage per document. | +| `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. | +| `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. | + +**Sentence ends, for Chinese and English text.** `。?!` end a sentence +wherever they stand. `. ? !` end one only before whitespace or the end of the +text, so 「3.2 条」 and 「400.50 元」 stay whole. An end mark followed by a +closing quote or bracket ends nothing, so the split never falls right after a +closing quote or bracket: 「他说:“好。”然后」 stays one sentence. `;` ends a +clause wherever it stands, `;` only before whitespace. + +**How long a passage may be.** `maxChars` is the source's `split.maxChars`, +else the settings page's **Knowledge → Target chunk size** +(`knowledge.chunk_target`), else 800. And when the adapter reports its +embedder's `maxInputTokens`, every passage's token estimate (the shared +`estimateTokens` from `@objectstack/spec/shared`) also stays within **80%** of +that limit. A passage keeps both bounds, so the effective length is the +smaller one; with no limit known, only `maxChars` applies. A `minChars` above +the effective `maxChars` reads as `maxChars`. The splitter never overlaps +passages. + +**`whole` over the limit.** A `whole` document whose estimate is over the 80% +budget is **removed from the index and reported, never truncated**: +`reindexSource` counts it in `failed` and names it in `failures` +(`[{ documentId, reason }]`, at most 20; `failed` counts them all), the event +sync logs it at `error` with the source, the record id, the estimate and the +limit, and `indexDocument` throws. With no limit known nothing is checked. +The estimate runs high on purpose — on Chinese text about 1.4× a real +tokenizer — so a `whole` document's usable length is about **60%** of the +model's limit; choose `recursive` or `markdown` for longer documents. + +**What a split change does not yet do.** `docHash` covers the assembled +document, not its passages, so changing `split`, `chunk_target` or the +embedder's limit does not by itself make a complete reindex rewrite an +unchanged document: a document is re-split the next time its content, title or +metadata changes. The index fingerprint (ADR-0161 K7), which hashes the +resolved split, is what will rebuild a source when its split changes. + --- ## 4. Plugin model diff --git a/content/docs/references/ai/knowledge-document.mdx b/content/docs/references/ai/knowledge-document.mdx index ec59f18705e..bd6f1ea4367 100644 --- a/content/docs/references/ai/knowledge-document.mdx +++ b/content/docs/references/ai/knowledge-document.mdx @@ -9,10 +9,11 @@ description: "Knowledge Document / Chunk / Hit — canonical shapes shared by ev Knowledge Document / Chunk / Hit — canonical shapes shared by every `IKnowledgeAdapter` implementation. -The framework does **not** prescribe chunk strategy or vector -format. Adapters are free to chunk however they like; the framework -only requires they round-trip these shapes when talking to the -`IKnowledgeService`. +The knowledge service owns the structural split (ADR-0161 K1): it cuts a +document into passages once, by the source's `split` key, and hands the +passages to every adapter that declares `capabilities.chunks` as the +document's `chunks`. An adapter that does not declare it receives whole +documents and splits them itself. The framework never sees a vector. See `content/docs/protocol/knowledge.mdx` for the full design. @@ -42,7 +43,8 @@ const result = KnowledgeChunkSchema.parse(data); | **documentId** | `string` | ✅ | | | **index** | `integer` | ✅ | | | **content** | `string` | ✅ | | -| **metadata** | `Record` | optional | | +| **headingPath** | `string[]` | optional | Headings the chunk sits under, outermost first (markdown strategy) | +| **metadata** | `never` | optional | [REMOVED] `KnowledgeChunk.metadata` was removed in @objectstack/spec 18 (ADR-0049, ADR-0161 K8) — nothing ever wrote or read it: the knowledge service cuts the passages and sets no per-passage metadata, and no adapter consulted one. Delete the key. A passage takes its document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on. | --- @@ -62,6 +64,18 @@ const result = KnowledgeChunkSchema.parse(data); | **permissions** | `string[]` | optional | | | **organizationId** | `string` | optional | Organization of the record the document was assembled from; set by the knowledge service under a walled tenancy posture | | **docHash** | `string` | optional | Service-computed hash of the assembled document (content, title, metadata, and organizationId when set); stored and returned as stored by the adapter | +| **chunks** | `{ id: string; documentId: string; index: integer; content: string; … }[]` | optional | Service-cut passages of the document, handed to an adapter that declares capabilities.chunks | + +### Nested Shape: `KnowledgeDocument.chunks[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **id** | `string` | ✅ | | +| **documentId** | `string` | ✅ | | +| **index** | `integer` | ✅ | | +| **content** | `string` | ✅ | | +| **headingPath** | `string[]` | optional | Headings the chunk sits under, outermost first (markdown strategy) | +| **metadata** | `never` | optional | [REMOVED] `KnowledgeChunk.metadata` was removed in @objectstack/spec 18 (ADR-0049, ADR-0161 K8) — nothing ever wrote or read it: the knowledge service cuts the passages and sets no per-passage metadata, and no adapter consulted one. Delete the key. A passage takes its document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on. | --- diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 2dbd61810f5..d8ea1f587f8 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -24,8 +24,8 @@ See `content/docs/protocol/knowledge.mdx` for the full design. ## TypeScript Usage ```typescript -import { FileKnowledgeSourceSchema, HttpKnowledgeSourceSchema, KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSourceKindSchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; -import type { FileKnowledgeSource, HttpKnowledgeSource, KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSourceKind, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { FileKnowledgeSourceSchema, HttpKnowledgeSourceSchema, KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSourceKindSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; +import type { FileKnowledgeSource, HttpKnowledgeSource, KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSourceKind, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; // Validate data const result = FileKnowledgeSourceSchema.parse(data); @@ -97,6 +97,7 @@ const result = FileKnowledgeSourceSchema.parse(data); | **contentFields** | `string[]` | ✅ | Fields contributing to document content | | **metadataFields** | `string[]` | optional (default: `[]`) | | | **where** | `Record` | optional | | +| **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | ### Nested Shape: `KnowledgeSource.source[kind='file']` @@ -153,6 +154,15 @@ This schema accepts one of the following structures: | **contentFields** | `string[]` | ✅ | Fields contributing to document content | | **metadataFields** | `string[]` | optional (default: `[]`) | | | **where** | `Record` | optional | | +| **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | + +### Nested Shape: `KnowledgeSourceKind[kind='object'].split` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown | +| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it | +| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars | --- @@ -181,6 +191,30 @@ This schema accepts one of the following structures: --- +--- + +## KnowledgeSplit + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown | +| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it | +| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars | + + +--- + +## KnowledgeSplitStrategy + +### Allowed Values + +* `whole` +* `recursive` +* `markdown` + + --- ## ObjectKnowledgeSource @@ -194,6 +228,15 @@ This schema accepts one of the following structures: | **contentFields** | `string[]` | ✅ | Fields contributing to document content | | **metadataFields** | `string[]` | optional (default: `[]`) | | | **where** | `Record` | optional | | +| **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | + +### Nested Shape: `ObjectKnowledgeSource.split` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **strategy** | `Enum<'whole' \| 'recursive' \| 'markdown'>` | ✅ | Split strategy: whole, recursive or markdown | +| **maxChars** | `integer` | optional | Longest passage in characters; wins over the settings default, the embedder limit can lower it | +| **minChars** | `integer` | optional | Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars | --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 09a7607e5c9..4b17f8699a1 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1730 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1732 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -20,7 +20,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 16 | 97 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 16 | 99 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 37 | 524 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -34,13 +34,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 184 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **221** | **1730** | 14 protocol modules | +| **Total** | **221** | **1732** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **16 pages, 97 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **16 pages, 99 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -53,7 +53,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | | [`embedding.zod.ts`](/docs/references/ai/embedding) | `EmbeddingModel`, `VectorStore`, `VectorStoreProvider` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | -| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSourceKind`, `ObjectKnowledgeSource` | +| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `FileKnowledgeSource`, `HttpKnowledgeSource`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSourceKind`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | | [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` | | [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` | | [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 8c3ef04523a..b6c17cf082f 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 112 | +| `ai/` | 113 | diff --git a/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts b/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts index 01d213dd863..a23ea4c9af8 100644 --- a/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts +++ b/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts @@ -294,6 +294,19 @@ describe('OpenAIEmbedder input limit (refused, not truncated)', () => { expect(f).not.toHaveBeenCalled(); }); + it('reports its input limit as IEmbedder.maxInputTokens: the option, else the known-model table, else none', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + expect(new OpenAIEmbedder({ apiKey: 'k' }).maxInputTokens).toBe(8192); + expect(new OpenAIEmbedder({ apiKey: 'k', model: 'text-embedding-v2' }).maxInputTokens).toBe(2048); + expect(new OpenAIEmbedder({ apiKey: 'k', model: 'BAAI/bge-large-zh-v1.5' }).maxInputTokens).toBe(512); + expect(new OpenAIEmbedder({ apiKey: 'k', maxInputTokens: 10 }).maxInputTokens).toBe(10); + expect(new OpenAIEmbedder({ apiKey: 'k', model: 'my-gateway-model', maxBatchSize: 5 }).maxInputTokens).toBeUndefined(); + } finally { + warn.mockRestore(); + } + }); + it('refuses a maxInputTokens that is not a positive integer', () => { for (const bad of [0, -1, 1.5, Number.NaN]) { expect(() => new OpenAIEmbedder({ apiKey: 'k', maxInputTokens: bad })).toThrow( diff --git a/packages/plugins/embedder-openai/src/index.ts b/packages/plugins/embedder-openai/src/index.ts index 6b35892728f..5244f8e12c5 100644 --- a/packages/plugins/embedder-openai/src/index.ts +++ b/packages/plugins/embedder-openai/src/index.ts @@ -229,7 +229,14 @@ export class OpenAIEmbedder implements IEmbedder { private readonly requestedDims?: number; private readonly extraHeaders: Record; private readonly maxBatchSize: number; - private readonly maxInputTokens: number | undefined; + /** + * `IEmbedder.maxInputTokens`: the longest input this embedder sends, in + * tokens by the shared `estimateTokens` — the `maxInputTokens` option, else + * the model's documented limit from the known-model table, else absent (no + * limit known). A knowledge adapter reports it to the knowledge service, + * whose splitter keeps every passage within it (ADR-0161 K8, item 6). + */ + readonly maxInputTokens?: number; constructor(opts: OpenAIEmbedderOptions) { if (!opts.apiKey) throw new Error('OpenAIEmbedder: apiKey required'); diff --git a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts index 85e574c0531..a1ec02fb4e6 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts @@ -10,5 +10,5 @@ import { KnowledgeMemoryAdapter } from '../index'; runKnowledgeAdapterContract({ name: 'knowledge-memory', makeAdapter: () => new KnowledgeMemoryAdapter('under_test'), - implements: { listDocuments: true, organizationIds: true }, + implements: { listDocuments: true, chunks: true, organizationIds: true }, }); diff --git a/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts b/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts index 81c7d949e05..65d67f9e7bf 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/memory-adapter.test.ts @@ -88,13 +88,40 @@ describe('KnowledgeMemoryAdapter', () => { expect(tropical[0]?.documentId).toBe('d2'); }); - it('chunks long documents (snippet bounded)', async () => { + it("indexes the service's passages as given: one hit per passage, the service's chunk id, never re-split", async () => { + const a = new KnowledgeMemoryAdapter(); + expect(a.capabilities.chunks).toBe(true); + const long = 'lorem ipsum dolor sit amet '.repeat(200); + const passages = ['alpha passage about lorem', long, 'gamma passage about lorem']; + await a.upsert( + [{ + id: 'long', + sourceId: 'src1', + content: passages.join('\n\n'), + chunks: passages.map((content, index) => ({ id: `long#${index}`, documentId: 'long', index, content })), + }], + { source }, + ); + const hits = await a.search('lorem', { source, topK: 10 }); + expect(hits.map((h) => h.chunkId).sort()).toEqual(['long#0', 'long#1', 'long#2']); + // The long passage comes back whole: the adapter does not cut what the service cut. + expect(hits.find((h) => h.chunkId === 'long#1')?.snippet).toBe(long); + }); + + it('a document handed over without chunks is one passage of its whole text', async () => { const a = new KnowledgeMemoryAdapter(); const long = 'lorem ipsum dolor sit amet '.repeat(200); await a.upsert([{ id: 'long', sourceId: 'src1', content: long }], { source }); const hits = await a.search('lorem', { source, topK: 10 }); - expect(hits.length).toBeGreaterThan(1); - for (const h of hits) expect(h.snippet.length).toBeLessThanOrEqual(900); + expect(hits).toHaveLength(1); + expect(hits[0]).toMatchObject({ chunkId: 'long#0', snippet: long }); + }); + + it('a document with no passage is still listed with its docHash', async () => { + const a = new KnowledgeMemoryAdapter(); + await a.upsert([{ id: 'empty', sourceId: 'src1', content: '', docHash: 'v1:x', chunks: [] }], { source }); + expect(await a.listDocuments({ source }, { limit: 10 })).toEqual({ documents: [{ documentId: 'empty', docHash: 'v1:x' }] }); + expect(await a.search('anything', { source, topK: 5 })).toEqual([]); }); it('healthCheck returns ok', async () => { diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 70dc64b28dc..2b793119f28 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -15,10 +15,16 @@ import type { import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; /** - * In-memory knowledge adapter. Stores per-source document maps, - * chunks documents naively on paragraph boundaries (with a soft 800-char - * cap), embeds each chunk as a sparse token-frequency vector, and - * answers `search()` via brute-force cosine similarity. + * In-memory knowledge adapter. Stores per-source document maps, embeds each + * passage as a sparse token-frequency vector, and answers `search()` via + * brute-force cosine similarity. + * + * It does not split: it declares `capabilities.chunks` (ADR-0161 K8, item 5), + * so the knowledge service hands it every document already cut into passages + * by the service's one splitter, and it indexes each passage as given — one + * hit per passage, its `chunkId` the service's. A document handed to it + * without `chunks` (a direct call, not through the service) is indexed as one + * passage holding the whole text. * * Deterministic — same input always produces the same hits — so it's * great for tests and reference implementations. **Don't use in prod.** @@ -37,55 +43,39 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; */ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { readonly id: string; - private readonly store = new Map(); + readonly capabilities = { chunks: true } as const; + /** source id → document id → the stored document. */ + private readonly store = new Map>(); constructor(id = 'memory') { this.id = id; } async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { - const sourceId = ctx.source.id; - const existing = this.store.get(sourceId) ?? []; - const byDoc = new Map(); - for (const c of existing) { - const arr = byDoc.get(c.documentId) ?? []; - arr.push(c); - byDoc.set(c.documentId, arr); - } - for (const doc of docs) { - byDoc.set(doc.id, chunkAndEmbed(doc)); - } - this.store.set(sourceId, Array.from(byDoc.values()).flat()); + const byDoc = this.store.get(ctx.source.id) ?? new Map(); + for (const doc of docs) byDoc.set(doc.id, { docHash: doc.docHash, chunks: embedPassages(doc) }); + this.store.set(ctx.source.id, byDoc); } async delete(documentIds: string[], ctx: AdapterContext): Promise { - const sourceId = ctx.source.id; - const chunks = this.store.get(sourceId); - if (!chunks) return; - const dropSet = new Set(documentIds); - this.store.set( - sourceId, - chunks.filter((c) => !dropSet.has(c.documentId)), - ); + const byDoc: Map | undefined = this.store.get(ctx.source.id); + if (!byDoc) return; + for (const id of documentIds) byDoc.delete(id); } async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise { if (!Number.isInteger(opts.limit) || opts.limit < 1) { throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`); } - // One entry per document, from its first chunk (every chunk carries the - // document's hash), in id order so a cursor stays valid across writes. - const byDoc = new Map(); - for (const c of this.store.get(ctx.source.id) ?? []) { - if (!byDoc.has(c.documentId)) byDoc.set(c.documentId, c.docHash); - } + // In id order, so a cursor stays valid across writes. + const byDoc = this.store.get(ctx.source.id) ?? new Map(); const ids = [...byDoc.keys()] .filter((id) => opts.cursor === undefined || id > opts.cursor) .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); const page = ids.slice(0, opts.limit); return { documents: page.map((documentId) => { - const docHash = byDoc.get(documentId); + const docHash = byDoc.get(documentId)?.docHash; return docHash === undefined ? { documentId } : { documentId, docHash }; }), ...(ids.length > page.length ? { nextCursor: page[page.length - 1] } : {}), @@ -93,7 +83,7 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } async search(query: string, opts: AdapterSearchOptions): Promise { - const chunks = this.store.get(opts.source.id) ?? []; + const chunks = [...(this.store.get(opts.source.id)?.values() ?? [])].flatMap((d) => d.chunks); if (chunks.length === 0) return []; const qVec = embedTokens(tokenize(query)); const qNorm = vectorNorm(qVec); @@ -134,12 +124,16 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } } +interface StoredDocument { + /** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */ + docHash?: string; + chunks: ChunkRecord[]; +} + interface ChunkRecord { chunkId: string; documentId: string; sourceRecordId?: string; - /** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */ - docHash?: string; /** The document's `organizationId`, stored as given (ADR-0161 K8, item 9). */ organizationId?: string; content: string; @@ -149,48 +143,28 @@ interface ChunkRecord { vectorNorm: number; } -const CHUNK_TARGET = 800; - -function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] { - const paragraphs = doc.content - .split(/\n{2,}/) - .map((p) => p.trim()) - .filter(Boolean); - const chunks: string[] = []; - let buf = ''; - for (const p of paragraphs.length ? paragraphs : [doc.content]) { - if (buf && buf.length + p.length + 2 > CHUNK_TARGET) { - chunks.push(buf); - buf = ''; - } - if (p.length > CHUNK_TARGET) { - if (buf) { - chunks.push(buf); - buf = ''; - } - for (let i = 0; i < p.length; i += CHUNK_TARGET) { - chunks.push(p.slice(i, i + CHUNK_TARGET)); - } - } else { - buf = buf ? `${buf}\n\n${p}` : p; - } - } - if (buf) chunks.push(buf); - return chunks.map((content, idx) => { - const vec = embedTokens(tokenize(content)); - return { - chunkId: `${doc.id}#${idx}`, - documentId: doc.id, - sourceRecordId: doc.sourceRecordId, - docHash: doc.docHash, - organizationId: doc.organizationId, - content, - title: doc.title, - metadata: doc.metadata ?? {}, - vector: vec, - vectorNorm: vectorNorm(vec), - }; - }); +/** + * One record per passage the service cut (`doc.chunks`), as given; without + * `chunks`, one passage holding the whole text. Never split here. + */ +function embedPassages(doc: KnowledgeDocument): ChunkRecord[] { + const passages = doc.chunks ?? [{ id: `${doc.id}#0`, content: doc.content }]; + return passages + .filter((p) => p.content.trim() !== '') + .map((p) => { + const vec = embedTokens(tokenize(p.content)); + return { + chunkId: p.id, + documentId: doc.id, + sourceRecordId: doc.sourceRecordId, + organizationId: doc.organizationId, + content: p.content, + title: doc.title, + metadata: doc.metadata ?? {}, + vector: vec, + vectorNorm: vectorNorm(vec), + }; + }); } function tokenize(text: string): string[] { diff --git a/packages/services/service-knowledge/src/__tests__/chunk-channel.test.ts b/packages/services/service-knowledge/src/__tests__/chunk-channel.test.ts new file mode 100644 index 00000000000..de707287a57 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/chunk-channel.test.ts @@ -0,0 +1,226 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The service side of the chunk channel (#37098; ADR-0161 K1, K8 items 5, 6 + * and 10) — what the contract suite cannot see from an adapter: + * + * - the event path removes a `whole` document over the embedder's budget and + * reports it at `error`, naming the source, the record, the estimate and the + * limit; `indexDocument` removes it and throws; + * - a reindex names at most `MAX_REINDEX_FAILURES` failures and counts them all; + * - `maxChars` comes from the source's `split.maxChars`, else the settings + * page's `knowledge.chunk_target` (read through the real settings service), + * else 800, and the embedder limit is read from the adapter at use. + */ + +import { describe, expect, it, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import type { AdapterContext, IDataEngine, IKnowledgeAdapter, IKnowledgeService } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource, KnowledgeSplit } from '@objectstack/spec/ai'; +import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; +import { SettingsServicePlugin, type SettingsService } from '@objectstack/service-settings'; +import { KnowledgeService, MAX_REINDEX_FAILURES } from '../knowledge-service.js'; +import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; + +/** A chunk-taking adapter that records what it is handed and deleted. */ +function recordingAdapter(limit?: { maxInputTokens?: number }) { + const upserted: KnowledgeDocument[] = []; + const deleted: string[] = []; + const adapter: IKnowledgeAdapter & { embedding?: { maxInputTokens?: number } } = { + id: 'rec', + capabilities: { chunks: true }, + embedding: limit, + upsert: async (docs: KnowledgeDocument[]) => { + upserted.push(...docs); + }, + search: async () => [], + delete: async (ids: string[], _ctx: AdapterContext) => { + deleted.push(...ids); + }, + }; + return { adapter, upserted, deleted }; +} + +function source(split?: KnowledgeSplit): KnowledgeSource { + return { + id: 'kb', + label: 'kb', + adapter: 'rec', + source: { kind: 'object', object: 'article', contentFields: ['body'], ...(split ? { split } : {}) }, + } as KnowledgeSource; +} + +const LONG = '员工在出差期间应当遵守公司的各项规章制度。'.repeat(40); // 840 chars, ~1400 tokens + +/** + * A data-engine double for the walk and the re-read: equality on a field, + * `$and`, and `id > cursor`; any other `where` shape throws, and the caller's + * `limit` is applied after the filter. + */ +function rowsEngine(rows: Array>): IDataEngine { + const matches = (row: Record, where: Record | undefined): boolean => { + if (!where) return true; + for (const [key, value] of Object.entries(where)) { + if (key === '$and') { + if (!Array.isArray(value)) throw new Error('engine double: $and takes an array'); + if (!value.every((c) => matches(row, c as Record))) return false; + continue; + } + if (key.startsWith('$')) throw new Error(`engine double: operator ${key} is not implemented`); + if (value !== null && typeof value === 'object') { + const ops = Object.keys(value); + if (key !== 'id' || ops.length !== 1 || ops[0] !== '$gt') { + throw new Error(`engine double: condition on '${key}' is not implemented`); + } + if (!(String(row.id) > String((value as { $gt: unknown }).$gt))) return false; + continue; + } + if (row[key] !== value) return false; + } + return true; + }; + return { + find: async (_object: string, query: { where?: Record; limit?: number }) => { + const matched = rows + .filter((r) => matches(r, query?.where)) + .sort((a, b) => (String(a.id) < String(b.id) ? -1 : String(a.id) > String(b.id) ? 1 : 0)); + const page = typeof query?.limit === 'number' ? matched.slice(0, query.limit) : matched; + return page.map((r) => ({ ...r })); + }, + count: async (_object: string, query: { where?: Record }) => + rows.filter((r) => matches(r, query?.where)).length, + } as unknown as IDataEngine; +} + +describe('chunk channel — whole over the budget', () => { + it('the event path removes the document and reports it at error: source, record, estimate, limit', async () => { + const { adapter, upserted, deleted } = recordingAdapter({ maxInputTokens: 512 }); + const logger = { warn: vi.fn(), error: vi.fn(), info: vi.fn() }; + const svc = new KnowledgeService({ logger }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'whole' })); + await svc.handleRecordUpsert('article', { id: 'r1', body: LONG }); + expect(upserted).toEqual([]); + expect(deleted).toEqual(['kb:r1']); + expect(logger.error).toHaveBeenCalledTimes(1); + const line = String(logger.error.mock.calls[0][0]); + expect(line).toContain("record 'r1' of source 'kb'"); + expect(line).toMatch(/estimates \d+ tokens, over the budget of 409/); + expect(line).toContain('512-token input limit'); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('a document that fits is written with its one passage', async () => { + const { adapter, upserted, deleted } = recordingAdapter({ maxInputTokens: 8192 }); + const svc = new KnowledgeService({ logger: { warn: vi.fn() } }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'whole' })); + await svc.handleRecordUpsert('article', { id: 'r1', body: LONG }); + expect(deleted).toEqual([]); + expect(upserted).toHaveLength(1); + expect(upserted[0].chunks).toEqual([{ id: 'kb:r1#0', documentId: 'kb:r1', index: 0, content: LONG }]); + }); + + it('indexDocument removes it and throws, naming the estimate and the budget', async () => { + const { adapter, upserted, deleted } = recordingAdapter({ maxInputTokens: 512 }); + const svc = new KnowledgeService({ logger: { warn: vi.fn() } }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'whole' })); + await expect(svc.indexDocument('kb', { id: 'kb:x', sourceId: 'kb', content: LONG })) + .rejects.toThrow(/did not index document 'kb:x' and removed it from the index: the whole document estimates \d+ tokens, over the embedder's input budget of 409/); + expect(upserted).toEqual([]); + expect(deleted).toEqual(['kb:x']); + }); + + it(`a reindex counts every failure and names the first ${MAX_REINDEX_FAILURES}`, async () => { + const { adapter, upserted } = recordingAdapter({ maxInputTokens: 512 }); + const rows = Array.from({ length: MAX_REINDEX_FAILURES + 5 }, (_, i) => ({ id: `r${String(i).padStart(2, '0')}`, body: LONG })); + rows.push({ id: 'zz', body: 'short' }); + const svc = new KnowledgeService({ dataEngine: rowsEngine(rows), logger: { warn: vi.fn() } }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'whole' })); + const res = await svc.reindexSource('kb'); + expect(res).toMatchObject({ ok: true, discovered: rows.length, indexed: 1, failed: MAX_REINDEX_FAILURES + 5 }); + expect(res.failures).toHaveLength(MAX_REINDEX_FAILURES); + expect(res.failures![0]).toEqual({ documentId: 'kb:r00', reason: expect.stringContaining("split 'whole'") }); + expect(res.message).toContain(`the first ${MAX_REINDEX_FAILURES} named in failures`); + expect(upserted.map((d) => d.id)).toEqual(['kb:zz']); + }); + + it('no limit known: nothing is checked', async () => { + const { adapter, upserted } = recordingAdapter(undefined); + const svc = new KnowledgeService({ logger: { warn: vi.fn() } }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'whole' })); + await svc.handleRecordUpsert('article', { id: 'r1', body: LONG.repeat(20) }); + expect(upserted).toHaveLength(1); + }); +}); + +describe('chunk channel — what the split is resolved from, read at use', () => { + const lengths = (docs: KnowledgeDocument[]) => docs.flatMap((d) => d.chunks ?? []).map((c) => c.content.length); + + it("the source's split.maxChars wins over chunk_target; chunk_target over 800", async () => { + for (const [split, target, max] of [ + // minChars above maxChars reads as maxChars: pieces merge up to the cap. + [{ strategy: 'recursive', maxChars: 100, minChars: 100_000 }, 300, 100], + [{ strategy: 'recursive', minChars: 100_000 }, 300, 300], + [{ strategy: 'recursive', minChars: 100_000 }, undefined, 800], + ] as const) { + const { adapter, upserted } = recordingAdapter(undefined); + const svc = new KnowledgeService({ logger: { warn: vi.fn() }, resolveChunkTarget: async () => target }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source(split)); + await svc.handleRecordUpsert('article', { id: 'r1', body: LONG.repeat(3) }); + const ls = lengths(upserted); + expect(Math.max(...ls)).toBeLessThanOrEqual(max); + expect(Math.max(...ls)).toBeGreaterThan(max * 0.8); + } + }); + + it('a chunk_target that cannot be read is reported at warn and the split goes on by 800', async () => { + const { adapter, upserted } = recordingAdapter(undefined); + const logger = { warn: vi.fn() }; + const svc = new KnowledgeService({ logger, resolveChunkTarget: async () => { throw new Error('store down'); } }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'recursive', minChars: 0 })); + await svc.handleRecordUpsert('article', { id: 'r1', body: LONG.repeat(3) }); + expect(Math.max(...lengths(upserted))).toBeLessThanOrEqual(800); + expect(String(logger.warn.mock.calls[0][0])).toContain('knowledge.chunk_target could not be read (store down)'); + }); + + it("the adapter's embedding descriptor is read at each write, never cached", async () => { + let limit: number | undefined; + const { adapter, upserted, deleted } = recordingAdapter(undefined); + Object.defineProperty(adapter, 'embedding', { get: () => (limit === undefined ? undefined : { maxInputTokens: limit }) }); + const svc = new KnowledgeService({ logger: { warn: vi.fn(), error: vi.fn() } }); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'whole' })); + await svc.handleRecordUpsert('article', { id: 'r1', body: LONG }); + expect(upserted).toHaveLength(1); + limit = 512; // the embedder registered later + await svc.handleRecordUpsert('article', { id: 'r1', body: LONG }); + expect(deleted).toEqual(['kb:r1']); + }); + + it('end to end: the plugin reads knowledge.chunk_target from the settings service at use', async () => { + const kernel = new LiteKernel(); + kernel.use(new KnowledgeServicePlugin({ enableEventSync: false })); + kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false })); + await kernel.bootstrap(); + const settings = kernel.getService('settings'); + const svc = kernel.getService(KNOWLEDGE_SERVICE); + const { adapter, upserted } = recordingAdapter(undefined); + svc.registerAdapter('rec', adapter); + svc.registerSource(source({ strategy: 'recursive', minChars: 100_000 })); + + await svc.indexDocument('kb', { id: 'kb:a', sourceId: 'kb', content: LONG.repeat(3) }); + expect(Math.max(...lengths(upserted))).toBeGreaterThan(640); // 800, nothing stored + upserted.length = 0; + // Saved after boot: the next write is cut by it. + await settings.set('knowledge', 'chunk_target', 200); + await svc.indexDocument('kb', { id: 'kb:a', sourceId: 'kb', content: LONG.repeat(3) }); + expect(Math.max(...lengths(upserted))).toBeLessThanOrEqual(200); + await kernel.shutdown(); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts new file mode 100644 index 00000000000..18a37f87146 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts @@ -0,0 +1,105 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The adapter contract suite (`../testing.ts`) run against two stub adapters + * that implement only the required members, so both halves of the chunk + * channel (ADR-0161 K8, item 5) are pinned outside any shipped adapter: + * + * - `whole-stub` declares no `capabilities` — an adapter written before the + * channel. It keeps receiving whole documents, without `chunks`. + * - `chunk-stub` declares `capabilities.chunks` and stores each passage it is + * handed exactly as given, one hit per passage. + * + * Neither implements `listDocuments`, so the suite also runs its + * "without listDocuments" cases against them. + */ + +import type { AdapterContext, AdapterSearchOptions, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeHit } from '@objectstack/spec/ai'; +import { runKnowledgeAdapterContract } from '../testing.js'; + +interface Passage { + chunkId: string; + documentId: string; + sourceRecordId?: string; + text: string; +} + +const tokens = (text: string): string[] => text.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 1); + +/** + * Score: how many of the passage's tokens are query words, over the geometric + * mean of the two lengths — a cosine over token counts, so a passage that + * repeats the query outranks one that mentions it once, as a real index does. + */ +function rank(passages: Passage[], query: string, opts: AdapterSearchOptions): KnowledgeHit[] { + const q = new Set(tokens(query)); + if (q.size === 0) return []; + return passages + .map((p) => { + const t = tokens(p.text); + const matches = t.filter((w) => q.has(w)).length; + return { p, score: t.length === 0 ? 0 : matches / Math.sqrt(t.length * q.size) }; + }) + .filter((x) => x.score > 0) + .sort((a, b) => b.score - a.score) + .slice(0, opts.topK) + .map(({ p, score }) => ({ + chunkId: p.chunkId, + documentId: p.documentId, + sourceId: opts.source.id, + sourceRecordId: p.sourceRecordId, + score, + snippet: p.text, + })); +} + +class StubAdapter implements IKnowledgeAdapter { + readonly id = 'under_test'; + readonly capabilities?: { chunks: boolean }; + private readonly store = new Map>(); + + constructor(takesChunks: boolean) { + if (takesChunks) this.capabilities = { chunks: true }; + } + + async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { + const byDoc = this.store.get(ctx.source.id) ?? new Map(); + for (const doc of docs) { + if (this.capabilities?.chunks) { + if (doc.chunks === undefined) throw new Error(`chunk-stub: document '${doc.id}' arrived without chunks`); + byDoc.set(doc.id, doc.chunks.map((c) => ({ + chunkId: c.id, + documentId: doc.id, + sourceRecordId: doc.sourceRecordId, + text: c.content, + }))); + } else { + if (doc.chunks !== undefined) throw new Error(`whole-stub: document '${doc.id}' arrived with chunks`); + byDoc.set(doc.id, [{ chunkId: `${doc.id}#0`, documentId: doc.id, sourceRecordId: doc.sourceRecordId, text: doc.content }]); + } + } + this.store.set(ctx.source.id, byDoc); + } + + async search(query: string, opts: AdapterSearchOptions): Promise { + return rank([...(this.store.get(opts.source.id)?.values() ?? [])].flat(), query, opts); + } + + async delete(documentIds: string[], ctx: AdapterContext): Promise { + const byDoc = this.store.get(ctx.source.id); + for (const id of documentIds) byDoc?.delete(id); + } +} + +runKnowledgeAdapterContract({ + name: 'whole-stub (no capabilities)', + makeAdapter: () => new StubAdapter(false), + implements: { listDocuments: false, chunks: false, organizationIds: false }, +}); + +runKnowledgeAdapterContract({ + name: 'chunk-stub (capabilities.chunks)', + makeAdapter: () => new StubAdapter(true), + implements: { listDocuments: false, chunks: true, organizationIds: false }, +}); diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/headings.markdown.golden.json b/packages/services/service-knowledge/src/__tests__/fixtures/split/headings.markdown.golden.json new file mode 100644 index 00000000000..4939ee267dd --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/headings.markdown.golden.json @@ -0,0 +1,63 @@ +[ + { + "id": "doc#0", + "documentId": "doc", + "index": 0, + "content": "Travel policy\n\nThis policy covers every business trip.", + "headingPath": [ + "Travel policy" + ] + }, + { + "id": "doc#1", + "documentId": "doc", + "index": 1, + "content": "Travel policy > Transport > Air\n\nEconomy class only. Business class needs the CEO's written approval in advance.", + "headingPath": [ + "Travel policy", + "Transport", + "Air" + ] + }, + { + "id": "doc#2", + "documentId": "doc", + "index": 2, + "content": "Travel policy > Transport > Rail\n\nSecond class or a soft sleeper berth.", + "headingPath": [ + "Travel policy", + "Transport", + "Rail" + ] + }, + { + "id": "doc#3", + "documentId": "doc", + "index": 3, + "content": "Travel policy > Meals\n\nLodging\n\nMeals are paid as a daily allowance.", + "headingPath": [ + "Travel policy", + "Meals" + ] + }, + { + "id": "doc#4", + "documentId": "doc", + "index": 4, + "content": "Travel policy > Meals\n\n```\n# not a heading inside a code fence\n```", + "headingPath": [ + "Travel policy", + "Meals" + ] + }, + { + "id": "doc#5", + "documentId": "doc", + "index": 5, + "content": "Travel policy > Appendix", + "headingPath": [ + "Travel policy", + "Appendix" + ] + } +] diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/headings.md b/packages/services/service-knowledge/src/__tests__/fixtures/split/headings.md new file mode 100644 index 00000000000..dfd4ecf8d1e --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/headings.md @@ -0,0 +1,25 @@ +# Travel policy + +This policy covers every business trip. + +## Transport + +### Air + +Economy class only. Business class needs the CEO's written approval in advance. + +### Rail + +Second class or a soft sleeper berth. + +## Lodging + +## Meals + +Meals are paid as a daily allowance. + +``` +# not a heading inside a code fence +``` + +## Appendix diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/long-run-zh.bge-512.golden.json b/packages/services/service-knowledge/src/__tests__/fixtures/split/long-run-zh.bge-512.golden.json new file mode 100644 index 00000000000..1bed514c3b2 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/long-run-zh.bge-512.golden.json @@ -0,0 +1,50 @@ +[ + { + "id": "doc#0", + "documentId": "doc", + "index": 0, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象" + }, + { + "id": "doc#1", + "documentId": "doc", + "index": 1, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象" + }, + { + "id": "doc#2", + "documentId": "doc", + "index": 2, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象" + }, + { + "id": "doc#3", + "documentId": "doc", + "index": 3, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象" + }, + { + "id": "doc#4", + "documentId": "doc", + "index": 4, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象" + }, + { + "id": "doc#5", + "documentId": "doc", + "index": 5, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象" + }, + { + "id": "doc#6", + "documentId": "doc", + "index": 6, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象" + }, + { + "id": "doc#7", + "documentId": "doc", + "index": 7, + "content": "员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护" + } +] diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/long-run-zh.txt b/packages/services/service-knowledge/src/__tests__/fixtures/split/long-run-zh.txt new file mode 100644 index 00000000000..697e6911b3a --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/long-run-zh.txt @@ -0,0 +1 @@ +员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护公司形象员工在出差期间应当遵守公司的各项规章制度和当地的法律法规维护 diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/mixed-zh-en.tight.golden.json b/packages/services/service-knowledge/src/__tests__/fixtures/split/mixed-zh-en.tight.golden.json new file mode 100644 index 00000000000..7561b2a87cf --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/mixed-zh-en.tight.golden.json @@ -0,0 +1,38 @@ +[ + { + "id": "doc#0", + "documentId": "doc", + "index": 0, + "content": "本系统支持 OpenAI 的 text-embedding-3-small 模型(版本 v3.2)。" + }, + { + "id": "doc#1", + "documentId": "doc", + "index": 1, + "content": "Its input limit is 8192 tokens, e.g. about 12 pages of English text." + }, + { + "id": "doc#2", + "documentId": "doc", + "index": 2, + "content": "中文文本的估算偏高,大约是实际值的 1.4 倍。\n他说:“这个限制不会截断文档。”然后又补充道,超出上限的整篇文档会被移出索引并报告失败。" + }, + { + "id": "doc#3", + "documentId": "doc", + "index": 3, + "content": "Is that a problem? No! It is the safe direction (see the doc page.) for every adapter." + }, + { + "id": "doc#4", + "documentId": "doc", + "index": 4, + "content": "配置项 split.maxChars 优先于设置页的 chunk_target;两者都未设置时取 800。" + }, + { + "id": "doc#5", + "documentId": "doc", + "index": 5, + "content": "The token budget is 80% of the limit; the character cap still applies." + } +] diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/mixed-zh-en.txt b/packages/services/service-knowledge/src/__tests__/fixtures/split/mixed-zh-en.txt new file mode 100644 index 00000000000..1ea8131ee12 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/mixed-zh-en.txt @@ -0,0 +1,3 @@ +本系统支持 OpenAI 的 text-embedding-3-small 模型(版本 v3.2)。Its input limit is 8192 tokens, e.g. about 12 pages of English text. 中文文本的估算偏高,大约是实际值的 1.4 倍。 +他说:“这个限制不会截断文档。”然后又补充道,超出上限的整篇文档会被移出索引并报告失败。Is that a problem? No! It is the safe direction (see the doc page.) for every adapter. +配置项 split.maxChars 优先于设置页的 chunk_target;两者都未设置时取 800。The token budget is 80% of the limit; the character cap still applies. diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.default.golden.json b/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.default.golden.json new file mode 100644 index 00000000000..3d6cecb8982 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.default.golden.json @@ -0,0 +1,8 @@ +[ + { + "id": "doc#0", + "documentId": "doc", + "index": 0, + "content": "第一章 总则\n\n第一条 为了规范公司差旅费用的报销管理,提高资金使用效率,根据国家有关财务制度和本公司实际情况,制定本办法。\n第二条 本办法适用于公司全体员工因公出差所发生的交通费、住宿费、伙食补助费和公杂费等费用的报销。\n第三条 差旅费报销应当遵循“厉行节约、据实报销、事前审批”的原则。员工出差前应当填写出差审批单,经部门负责人批准后方可出行。\n\n第二章 交通费\n\n第四条 员工出差乘坐交通工具,应当按照本办法第3.2 条规定的标准执行。乘坐飞机的,一律购买经济舱机票;乘坐火车的,可以乘坐二等座或者硬卧。\n第五条 市内交通费按照实际发生额报销,每人每天不超过400.50 元。超过标准的部分,由员工个人承担,但经总经理特别批准的除外。\n第六条 员工因公务需要乘坐出租车的,应当在报销单上注明乘车事由、起止地点和时间。没有注明的,财务部门不予报销!员工对此有异议的,可以向财务部门提出复核申请?财务部门应当在三个工作日内答复。\n\n第三章 住宿费\n\n第七条 住宿费在规定标准内凭发票据实报销。一线城市每人每晚不超过六百元;二线城市每人每晚不超过四百五十元;其他地区每人每晚不超过三百五十元。\n第八条 两名以上同性别员工共同出差的,原则上应当合住一间客房。确因工作需要单独住宿的,应当事先报经部门负责人批准。" + } +] diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.tight.golden.json b/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.tight.golden.json new file mode 100644 index 00000000000..6e903cf024a --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.tight.golden.json @@ -0,0 +1,98 @@ +[ + { + "id": "doc#0", + "documentId": "doc", + "index": 0, + "content": "第一章 总则\n\n第一条 为了规范公司差旅费用的报销管理,提高资金使用效率" + }, + { + "id": "doc#1", + "documentId": "doc", + "index": 1, + "content": ",根据国家有关财务制度和本公司实际情况,制定本办法。" + }, + { + "id": "doc#2", + "documentId": "doc", + "index": 2, + "content": "第二条 本办法适用于公司全体员工因公出差所发生的交通费、住宿费、伙食补助费和公杂费等费用的报销。" + }, + { + "id": "doc#3", + "documentId": "doc", + "index": 3, + "content": "第三条 差旅费报销应当遵循“厉行节约、据实报销、事前审批”的原则。" + }, + { + "id": "doc#4", + "documentId": "doc", + "index": 4, + "content": "员工出差前应当填写出差审批单,经部门负责人批准后方可出行。" + }, + { + "id": "doc#5", + "documentId": "doc", + "index": 5, + "content": "第二章 交通费\n\n第四条 员工出差乘坐交通工具,应当按照本办法第3.2 条规定的标准执行。" + }, + { + "id": "doc#6", + "documentId": "doc", + "index": 6, + "content": "乘坐飞机的,一律购买经济舱机票;乘坐火车的,可以乘坐二等座或者硬卧。" + }, + { + "id": "doc#7", + "documentId": "doc", + "index": 7, + "content": "第五条 市内交通费按照实际发生额报销,每人每天不超过400.50 元。" + }, + { + "id": "doc#8", + "documentId": "doc", + "index": 8, + "content": "超过标准的部分,由员工个人承担,但经总经理特别批准的除外。" + }, + { + "id": "doc#9", + "documentId": "doc", + "index": 9, + "content": "第六条 员工因公务需要乘坐出租车的,应当在报销单上注明乘车事由、起止地点和时间。" + }, + { + "id": "doc#10", + "documentId": "doc", + "index": 10, + "content": "没有注明的,财务部门不予报销!员工对此有异议的,可以向财务部门提出复核申请?" + }, + { + "id": "doc#11", + "documentId": "doc", + "index": 11, + "content": "财务部门应当在三个工作日内答复。" + }, + { + "id": "doc#12", + "documentId": "doc", + "index": 12, + "content": "第三章 住宿费\n\n第七条 住宿费在规定标准内凭发票据实报销。一线城市每人每晚不超过六百元;" + }, + { + "id": "doc#13", + "documentId": "doc", + "index": 13, + "content": "二线城市每人每晚不超过四百五十元;其他地区每人每晚不超过三百五十元。" + }, + { + "id": "doc#14", + "documentId": "doc", + "index": 14, + "content": "第八条 两名以上同性别员工共同出差的,原则上应当合住一间客房。" + }, + { + "id": "doc#15", + "documentId": "doc", + "index": 15, + "content": "确因工作需要单独住宿的,应当事先报经部门负责人批准。" + } +] diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.txt b/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.txt new file mode 100644 index 00000000000..f4af9d3522f --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/regulation-zh.txt @@ -0,0 +1,16 @@ +第一章 总则 + +第一条 为了规范公司差旅费用的报销管理,提高资金使用效率,根据国家有关财务制度和本公司实际情况,制定本办法。 +第二条 本办法适用于公司全体员工因公出差所发生的交通费、住宿费、伙食补助费和公杂费等费用的报销。 +第三条 差旅费报销应当遵循“厉行节约、据实报销、事前审批”的原则。员工出差前应当填写出差审批单,经部门负责人批准后方可出行。 + +第二章 交通费 + +第四条 员工出差乘坐交通工具,应当按照本办法第3.2 条规定的标准执行。乘坐飞机的,一律购买经济舱机票;乘坐火车的,可以乘坐二等座或者硬卧。 +第五条 市内交通费按照实际发生额报销,每人每天不超过400.50 元。超过标准的部分,由员工个人承担,但经总经理特别批准的除外。 +第六条 员工因公务需要乘坐出租车的,应当在报销单上注明乘车事由、起止地点和时间。没有注明的,财务部门不予报销!员工对此有异议的,可以向财务部门提出复核申请?财务部门应当在三个工作日内答复。 + +第三章 住宿费 + +第七条 住宿费在规定标准内凭发票据实报销。一线城市每人每晚不超过六百元;二线城市每人每晚不超过四百五十元;其他地区每人每晚不超过三百五十元。 +第八条 两名以上同性别员工共同出差的,原则上应当合住一间客房。确因工作需要单独住宿的,应当事先报经部门负责人批准。 diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/table.md b/packages/services/service-knowledge/src/__tests__/fixtures/split/table.md new file mode 100644 index 00000000000..698e4652e16 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/table.md @@ -0,0 +1,15 @@ +The allowance table below applies to every trip that starts after the policy date. + +| City tier | Lodging per night | Meals per day | Notes | +| --- | --- | --- | --- | +| Tier 1 | 600 | 100 | Beijing, Shanghai, Guangzhou, Shenzhen | +| Tier 2 | 450 | 80 | Provincial capitals and planned cities | +| Tier 3 | 350 | 60 | Every other prefecture-level city | +| Overseas A | 1800 | 300 | North America, Western Europe, Japan | +| Overseas B | 1200 | 220 | Southeast Asia, Eastern Europe | +| Overseas C | 900 | 180 | Every other country and region | + +- Receipts are required for lodging. A missing receipt is reimbursed at half the tier rate, with a written explanation signed by the traveller. +- Meal allowances are paid per calendar day, without receipts. + +Claims are filed within thirty days of return. diff --git a/packages/services/service-knowledge/src/__tests__/fixtures/split/table.recursive.golden.json b/packages/services/service-knowledge/src/__tests__/fixtures/split/table.recursive.golden.json new file mode 100644 index 00000000000..63ec7def7a6 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/fixtures/split/table.recursive.golden.json @@ -0,0 +1,32 @@ +[ + { + "id": "doc#0", + "documentId": "doc", + "index": 0, + "content": "The allowance table below applies to every trip that starts after the policy date." + }, + { + "id": "doc#1", + "documentId": "doc", + "index": 1, + "content": "| City tier | Lodging per night | Meals per day | Notes |\n| --- | --- | --- | --- |\n| Tier 1 | 600 | 100 | Beijing, Shanghai, Guangzhou, Shenzhen |\n| Tier 2 | 450 | 80 | Provincial capitals and planned cities |\n| Tier 3 | 350 | 60 | Every other prefecture-level city |" + }, + { + "id": "doc#2", + "documentId": "doc", + "index": 2, + "content": "| City tier | Lodging per night | Meals per day | Notes |\n| --- | --- | --- | --- |\n| Overseas A | 1800 | 300 | North America, Western Europe, Japan |\n| Overseas B | 1200 | 220 | Southeast Asia, Eastern Europe |\n| Overseas C | 900 | 180 | Every other country and region |" + }, + { + "id": "doc#3", + "documentId": "doc", + "index": 3, + "content": "- Receipts are required for lodging. A missing receipt is reimbursed at half the tier rate, with a written explanation signed by the traveller." + }, + { + "id": "doc#4", + "documentId": "doc", + "index": 4, + "content": "- Meal allowances are paid per calendar day, without receipts.\n\nClaims are filed within thirty days of return." + } +] diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 485634c77e4..10cfb93c7ba 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -605,7 +605,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('0 rows: one bounded read, no upsert', async () => { const h = reindexHarness([]); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 0, indexed: 0, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 0, indexed: 0, skipped: 0, purged: null, failed: 0, failures: [] }); expect(h.find).toHaveBeenCalledTimes(1); expect(h.adapter.upsertSpy).not.toHaveBeenCalled(); }); @@ -613,7 +613,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('exactly one page: one upsert of the page, then a read that comes back empty', async () => { const h = reindexHarness(taskRows(100)); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 100, indexed: 100, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 100, indexed: 100, skipped: 0, purged: null, failed: 0, failures: [] }); expect(upsertedIds(h.adapter)).toEqual([ids(0, 100)]); expect(h.find).toHaveBeenCalledTimes(2); expect(h.find.mock.calls[1][1].where).toEqual({ id: { $gt: 'r099' } }); @@ -622,7 +622,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('one page + 1: two upserts (100, then 1), each row once, in id order', async () => { const h = reindexHarness(taskRows(101)); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 101, indexed: 101, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 101, indexed: 101, skipped: 0, purged: null, failed: 0, failures: [] }); expect(upsertedIds(h.adapter)).toEqual([ids(0, 100), ids(100, 101)]); // A short page is not the end — only the empty third read is. expect(h.find).toHaveBeenCalledTimes(3); @@ -639,7 +639,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { (src.source as ObjectKnowledgeSource).where = { status: 'open' }; const h = reindexHarness(taskRows(250, (i) => ({ status: i % 5 === 0 ? 'done' : 'open' })), src); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 200, indexed: 200, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 200, indexed: 200, skipped: 0, purged: null, failed: 0, failures: [] }); const all = upsertedIds(h.adapter).flat(); expect(all).toHaveLength(200); expect(new Set(all).size).toBe(200); @@ -656,7 +656,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { ])('limit %i caps the total: reads %j', async (limit, reads, total) => { const h = reindexHarness(taskRows(250)); const res = await h.svc.reindexSource('s1', { limit }); - expect(res).toEqual({ ok: true, object: 'task', discovered: total, indexed: total, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: total, indexed: total, skipped: 0, purged: null, failed: 0, failures: [] }); expect(h.find.mock.calls.map((c) => c[1].limit)).toEqual(reads); expect(upsertedIds(h.adapter).flat()).toEqual(ids(0, total)); }); @@ -664,7 +664,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('a limit above the row count reads to the end', async () => { const h = reindexHarness(taskRows(120)); const res = await h.svc.reindexSource('s1', { limit: 500 }); - expect(res).toEqual({ ok: true, object: 'task', discovered: 120, indexed: 120, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 120, indexed: 120, skipped: 0, purged: null, failed: 0, failures: [] }); }); it('a short page is not the end: a page that lost a row to a hook does not stop the walk', async () => { @@ -676,7 +676,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { return h.find.mock.calls.length === 1 ? page.filter((r) => r.id !== 'r049') : page; }); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 249, indexed: 249, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 249, indexed: 249, skipped: 0, purged: null, failed: 0, failures: [] }); expect(upsertedIds(h.adapter).map((p) => p.length)).toEqual([99, 100, 50]); expect(upsertedIds(h.adapter).flat()).toEqual(ids(0, 250).filter((id) => id !== 's1:r049')); expect(h.find).toHaveBeenCalledTimes(4); @@ -686,7 +686,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { const rows = taskRows(150).map((r) => ({ ...r, id: Number(String(r.id).slice(1)) + 1 })); const h = reindexHarness(rows); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null, failed: 0, failures: [] }); const want = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, k) => `s1:${from + k}`); expect(upsertedIds(h.adapter)).toEqual([want(1, 100), want(101, 150)]); expect(h.find.mock.calls.map((c) => c[1].where)).toEqual([undefined, { id: { $gt: 100 } }, { id: { $gt: 150 } }]); @@ -695,7 +695,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('a fractional limit is floored', async () => { const h = reindexHarness(taskRows(250)); const res = await h.svc.reindexSource('s1', { limit: 150.7 }); - expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null, failed: 0, failures: [] }); expect(h.find.mock.calls.map((c) => c[1].limit)).toEqual([100, 50]); }); @@ -776,7 +776,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { expect(h.find).toHaveBeenCalledTimes(2); // The failed walk released the source's lock. const again = await h.svc.reindexSource('s1'); - expect(again).toEqual({ ok: true, object: 'task', discovered: 250, indexed: 250, skipped: 0, purged: null }); + expect(again).toEqual({ ok: true, object: 'task', discovered: 250, indexed: 250, skipped: 0, purged: null, failed: 0, failures: [] }); }); it('an engine that ignores the cursor ends the walk instead of looping', async () => { @@ -821,7 +821,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { expect(h.find).toHaveBeenCalledTimes(1); release(); const [a, b] = await Promise.all([first, second]); - expect(a).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null }); + expect(a).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null, failed: 0, failures: [] }); expect(b).toEqual(a); expect(order).toEqual(['s1:r000+100', 's1:r100+50', 's1:r000+100', 's1:r100+50']); }); @@ -832,9 +832,9 @@ describe('KnowledgeService — the reindex walk pages by id', () => { const release = h.holdNextFind(); const first = h.svc.reindexSource('s1'); const other = await h.svc.reindexSource('s2'); - expect(other).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10, skipped: 0, purged: null }); + expect(other).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10, skipped: 0, purged: null, failed: 0, failures: [] }); release(); - expect(await first).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10, skipped: 0, purged: null }); + expect(await first).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10, skipped: 0, purged: null, failed: 0, failures: [] }); }); }); @@ -906,9 +906,9 @@ describe('KnowledgeService — a complete reindex skips unchanged documents and it('first reindex over an empty listing writes everything; the next writes nothing unchanged', async () => { const la = listingAdapter(); const h = reindexHarness(taskRows(150), objectSource('s1', 'task'), la.adapter); - expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: 0 }); + expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: 0, failed: 0, failures: [] }); la.upsertSpy.mockClear(); - expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 0, skipped: 150, purged: 0 }); + expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 0, skipped: 150, purged: 0, failed: 0, failures: [] }); expect(la.upsertSpy).not.toHaveBeenCalled(); expect(la.deleteSpy).not.toHaveBeenCalled(); }); @@ -957,7 +957,7 @@ describe('KnowledgeService — a complete reindex skips unchanged documents and h.rows.find((r) => r.id === 'r003')!.status = 'done'; h.find.mockClear(); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 3, indexed: 0, skipped: 3, purged: 2 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 3, indexed: 0, skipped: 3, purged: 2, failed: 0, failures: [] }); expect(deletedOf(la.deleteSpy).sort()).toEqual(['s1:r001', 's1:r003']); for (const call of la.deleteSpy.mock.calls) expect(call[1]).toMatchObject({ reason: 'reindex' }); // The confirming re-reads are the event sync's: `where` AND id, one row, system context. @@ -1030,7 +1030,7 @@ describe('KnowledgeService — a complete reindex skips unchanged documents and const h = reindexHarness(taskRows(4), src, la.adapter); await h.svc.reindexSource('s1'); h.rows.splice(0, 1); - expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 3, indexed: 0, skipped: 3, purged: null }); + expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 3, indexed: 0, skipped: 3, purged: null, failed: 0, failures: [] }); expect(la.deleteSpy).not.toHaveBeenCalled(); }); diff --git a/packages/services/service-knowledge/src/__tests__/split.test.ts b/packages/services/service-knowledge/src/__tests__/split.test.ts new file mode 100644 index 00000000000..3c4236e826b --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/split.test.ts @@ -0,0 +1,276 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The splitter (#37098): golden files for the shapes the card names — a + * Chinese regulation cut by chapter and article, a Markdown table, a long run + * with no punctuation, mixed Chinese and English, 「3.2 条」 and 「400.50 元」, and + * a Markdown heading tree — plus a seeded property test that no passage's + * token estimate is over the budget. + * + * A golden file is the splitter's output for one fixture and one resolved + * split. When the splitter is changed ON PURPOSE, regenerate them with + * `OS_TEST_UPDATE_SPLIT_GOLDEN=1` and read the diff: every changed passage is + * a changed passage in every index built after the change. + */ + +import { readFileSync, writeFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { estimateTokens } from '@objectstack/spec/shared'; +import type { KnowledgeSplit } from '@objectstack/spec/ai'; +import { + DEFAULT_SPLIT_MAX_CHARS, + DEFAULT_SPLIT_MIN_CHARS, + resolveSplit, + splitDocument, + type ResolvedSplit, +} from '../split/index.js'; + +const fixture = (name: string): string => + readFileSync(new URL(`./fixtures/split/${name}`, import.meta.url), 'utf8'); + +function chunksOf(content: string, split: ResolvedSplit) { + const out = splitDocument({ id: 'doc', content }, split); + if (!out.ok) throw new Error(`unexpected split failure: ${out.reason}`); + return out.chunks; +} + +const GOLDEN: Array<{ name: string; input: string; split: KnowledgeSplit; maxInputTokens?: number }> = [ + { name: 'regulation-zh.default', input: 'regulation-zh.txt', split: { strategy: 'recursive' } }, + { name: 'regulation-zh.tight', input: 'regulation-zh.txt', split: { strategy: 'recursive', maxChars: 120, minChars: 40 }, maxInputTokens: 100 }, + { name: 'table.recursive', input: 'table.md', split: { strategy: 'recursive', maxChars: 300, minChars: 100 } }, + { name: 'long-run-zh.bge-512', input: 'long-run-zh.txt', split: { strategy: 'recursive' }, maxInputTokens: 512 }, + { name: 'mixed-zh-en.tight', input: 'mixed-zh-en.txt', split: { strategy: 'recursive', maxChars: 120, minChars: 40 } }, + { name: 'headings.markdown', input: 'headings.md', split: { strategy: 'markdown', maxChars: 120, minChars: 40 } }, +]; + +describe('splitter — golden files', () => { + it.each(GOLDEN)('$name', ({ name, input, split, maxInputTokens }) => { + const chunks = chunksOf(fixture(input), resolveSplit({ split, maxInputTokens })); + const goldenUrl = new URL(`./fixtures/split/${name}.golden.json`, import.meta.url); + if (process.env.OS_TEST_UPDATE_SPLIT_GOLDEN === '1') { + writeFileSync(goldenUrl, `${JSON.stringify(chunks, null, 2)}\n`); + } + expect(chunks).toEqual(JSON.parse(readFileSync(goldenUrl, 'utf8'))); + }); +}); + +describe('splitter — the rules the golden files pin, asserted directly', () => { + const tight = resolveSplit({ split: { strategy: 'recursive', maxChars: 120, minChars: 40 }, maxInputTokens: 100 }); + + it('keeps 「3.2 条」 and 「400.50 元」 whole: an English period ends a sentence only before whitespace', () => { + const chunks = chunksOf(fixture('regulation-zh.txt'), tight); + expect(chunks.some((c) => c.content.includes('第3.2 条'))).toBe(true); + expect(chunks.some((c) => c.content.includes('400.50 元'))).toBe(true); + for (const c of chunks) { + expect(c.content.endsWith('3.')).toBe(false); + expect(c.content.endsWith('400.')).toBe(false); + } + }); + + it('cuts a regulation by article, and a chapter title leads its own chapter', () => { + const chunks = chunksOf(fixture('regulation-zh.txt'), tight); + for (const title of ['第一章 总则', '第二章 交通费', '第三章 住宿费']) { + const holder = chunks.find((c) => c.content.includes(title)); + expect(holder?.content.startsWith(title)).toBe(true); + } + for (const article of ['第二条', '第三条', '第五条', '第六条', '第八条']) { + expect(chunks.some((c) => c.content.startsWith(article))).toBe(true); + } + }); + + it('never splits right after a closing quote or bracket, nor after an end mark before one', () => { + const chunks = chunksOf(fixture('mixed-zh-en.txt'), resolveSplit({ split: { strategy: 'recursive', maxChars: 120, minChars: 40 } })); + expect(chunks.some((c) => c.content.includes('他说:“这个限制不会截断文档。”然后'))).toBe(true); + expect(chunks.some((c) => c.content.includes('(see the doc page.) for every adapter.'))).toBe(true); + expect(chunks.some((c) => c.content.includes('(版本 v3.2)'))).toBe(true); + }); + + it('a table that fits is one unit; one that does not is cut between rows, each piece under the header', () => { + const md = fixture('table.md'); + const roomy = chunksOf(md, resolveSplit({ split: { strategy: 'recursive', maxChars: 800, minChars: 0 } })); + expect(roomy.filter((c) => c.content.includes('| City tier |'))).toHaveLength(1); + const tightTable = chunksOf(md, resolveSplit({ split: { strategy: 'recursive', maxChars: 300, minChars: 100 } })); + const pieces = tightTable.filter((c) => c.content.includes('| Tier') || c.content.includes('| Overseas')); + expect(pieces.length).toBeGreaterThan(1); + for (const p of pieces) expect(p.content.startsWith('| City tier | Lodging per night | Meals per day | Notes |\n| --- |')).toBe(true); + // No row is cut: every body row appears whole in exactly one piece. + for (const row of md.split('\n').filter((l) => /^\| (Tier|Overseas)/.test(l))) { + expect(pieces.filter((p) => p.content.includes(row))).toHaveLength(1); + } + }); + + it('a list item is never cut at a line break; an item that fits stays whole', () => { + const text = '- first item line one\n continues here.\n- second item\n\nAfter the list.'; + const chunks = chunksOf(text, resolveSplit({ split: { strategy: 'recursive', maxChars: 40, minChars: 0 } })); + expect(chunks.map((c) => c.content)).toEqual([ + '- first item line one\n continues here.', + '- second item', + 'After the list.', + ]); + }); + + it('a long run with no punctuation is cut by characters into even pieces within the budget', () => { + const run = fixture('long-run-zh.txt').trim(); + const split = resolveSplit({ split: { strategy: 'recursive' }, maxInputTokens: 512 }); + const chunks = chunksOf(run, split); + expect(chunks.length).toBeGreaterThan(1); + expect(chunks.map((c) => c.content).join('')).toBe(run); + const lengths = chunks.map((c) => c.content.length); + expect(Math.max(...lengths) - Math.min(...lengths)).toBeLessThanOrEqual(chunks.length); + for (const c of chunks) expect(estimateTokens(c.content)).toBeLessThanOrEqual(split.maxTokens!); + }); + + it('markdown: each passage carries its heading path, embedded at its start; a fenced # is no heading', () => { + const chunks = chunksOf(fixture('headings.md'), resolveSplit({ split: { strategy: 'markdown', maxChars: 120, minChars: 40 } })); + const air = chunks.find((c) => c.content.includes('Economy class')); + expect(air?.headingPath).toEqual(['Travel policy', 'Transport', 'Air']); + expect(air?.content.startsWith('Travel policy > Transport > Air\n\n')).toBe(true); + expect(chunks.some((c) => c.headingPath?.includes('# not a heading inside a code fence'))).toBe(false); + }); + + it('markdown: a heading with no body joins the next passage', () => { + const chunks = chunksOf(fixture('headings.md'), resolveSplit({ split: { strategy: 'markdown', maxChars: 120, minChars: 40 } })); + // "## Lodging" has no text; it is carried into the "## Meals" passage. + const meals = chunks.find((c) => c.content.includes('daily allowance')); + expect(meals?.content).toContain('Lodging'); + expect(chunks.some((c) => c.headingPath?.[c.headingPath.length - 1] === 'Lodging')).toBe(false); + // "## Transport" has no text of its own, and is its children's ancestor. + expect(chunks.filter((c) => c.headingPath?.join('/') === 'Travel policy/Transport')).toEqual([]); + }); + + it('ids are documentId#index, in order', () => { + const chunks = chunksOf(fixture('table.md'), resolveSplit({ split: { strategy: 'recursive', maxChars: 300, minChars: 100 } })); + chunks.forEach((c, i) => { + expect(c).toMatchObject({ id: `doc#${i}`, documentId: 'doc', index: i }); + }); + }); +}); + +describe('splitter — whole', () => { + it('one passage per document', () => { + const text = fixture('regulation-zh.txt'); + const chunks = chunksOf(text, resolveSplit({ split: { strategy: 'whole' }, maxInputTokens: 8192 })); + expect(chunks).toEqual([{ id: 'doc#0', documentId: 'doc', index: 0, content: text.trim() }]); + }); + + it('over the budget: a failure naming the estimate and the budget, never a truncated passage', () => { + const text = fixture('regulation-zh.txt'); + const out = splitDocument({ id: 'doc', content: text }, resolveSplit({ split: { strategy: 'whole' }, maxInputTokens: 512 })); + expect(out.ok).toBe(false); + if (out.ok) return; + expect(out.budget).toBe(409); + expect(out.estimate).toBe(estimateTokens(text.trim())); + expect(out.estimate).toBeGreaterThan(409); + }); + + it('with no limit known, nothing is checked', () => { + const text = fixture('long-run-zh.txt'); + expect(splitDocument({ id: 'doc', content: text }, resolveSplit({ split: { strategy: 'whole' } }))).toMatchObject({ ok: true }); + }); + + it('an empty document has no passage, under every strategy', () => { + for (const strategy of ['whole', 'recursive', 'markdown'] as const) { + expect(chunksOf(' \n\n ', resolveSplit({ split: { strategy } }))).toEqual([]); + } + }); +}); + +describe('resolveSplit', () => { + it('800 / 200 / recursive when nothing is configured and no limit is known', () => { + expect(resolveSplit({})).toEqual({ strategy: 'recursive', maxChars: DEFAULT_SPLIT_MAX_CHARS, minChars: DEFAULT_SPLIT_MIN_CHARS }); + expect(DEFAULT_SPLIT_MAX_CHARS).toBe(800); + expect(DEFAULT_SPLIT_MIN_CHARS).toBe(200); + }); + + it("the source's maxChars wins over the settings page's chunk_target, which wins over 800", () => { + expect(resolveSplit({ split: { strategy: 'recursive', maxChars: 300 }, chunkTarget: 500 }).maxChars).toBe(300); + expect(resolveSplit({ split: { strategy: 'markdown' }, chunkTarget: 500 }).maxChars).toBe(500); + expect(resolveSplit({ chunkTarget: 500 }).maxChars).toBe(500); + }); + + it('the token budget is 80% of the embedder limit, floored', () => { + expect(resolveSplit({ maxInputTokens: 8192 }).maxTokens).toBe(6553); + expect(resolveSplit({ maxInputTokens: 512 }).maxTokens).toBe(409); + expect(resolveSplit({ maxInputTokens: 0 }).maxTokens).toBeUndefined(); + }); + + it('a minChars above the effective maxChars reads as maxChars', () => { + expect(resolveSplit({ split: { strategy: 'recursive', maxChars: 100, minChars: 500 } }).minChars).toBe(100); + expect(resolveSplit({ split: { strategy: 'recursive', minChars: 900 } }).minChars).toBe(800); + }); +}); + +// ── Property: no passage is over the budget ─────────────────────────── + +/** mulberry32: a small seeded PRNG, so a failing case reproduces from its seed. */ +function rng(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const ATOMS = [ + '第七条', '纳税人', '应当', '按照规定', '。', ',', ';', '?', '!', '“', '”', '「3.2 条」', '400.50 元', '(', ')', + 'the', 'embedding', 'limit', 'is', '8192', 'v3.2', 'e.g.', '.', ' ', ' ', ' ', '?', '!', ';', '(', ')', 'a1b2c3d4e5f6', + '\n', '\n\n', '- ', '| a | b |\n', '| --- | --- |\n', '| 1 | 2 |\n', '## Heading ', '# Top\n', '```\n', 'https://example.com/a?b=c', + '员工在出差期间应当遵守公司的各项规章制度', +]; + +function randomDoc(next: () => number): string { + const n = Math.floor(next() * 400); + let s = ''; + for (let i = 0; i < n; i++) s += ATOMS[Math.floor(next() * ATOMS.length)]; + // Now and then a long run with no break at all. + if (next() < 0.2) s += '规章制度'.repeat(Math.floor(next() * 300)); + return s; +} + +describe('splitter — property: no passage is over the budget', () => { + it('500 seeded documents × random bounds, every strategy', () => { + const next = rng(37098); + for (let i = 0; i < 500; i++) { + const content = randomDoc(next); + const maxInputTokens = 16 + Math.floor(next() * 2000); + const maxChars = 20 + Math.floor(next() * 900); + const minChars = Math.floor(next() * maxChars); + const strategy = (['recursive', 'markdown'] as const)[i % 2]; + const split = resolveSplit({ split: { strategy, maxChars, minChars }, maxInputTokens }); + const out = splitDocument({ id: `d${i}`, content }, split); + expect(out.ok, `case ${i}`).toBe(true); + if (!out.ok) continue; + for (const c of out.chunks) { + const where = `case ${i} (${strategy}, maxChars ${maxChars}, limit ${maxInputTokens}) chunk ${c.index}`; + expect(c.content.trim(), where).not.toBe(''); + expect(estimateTokens(c.content), where).toBeLessThanOrEqual(split.maxTokens!); + expect(estimateTokens(c.content), where).toBeLessThanOrEqual(maxInputTokens); + expect(c.content.length, where).toBeLessThanOrEqual(maxChars); + } + if (strategy === 'recursive' && !content.includes('|')) { + // Nothing is lost or invented: the passages, read in order, give back the text. + const squash = (t: string) => t.replace(/\s+/g, ''); + expect(squash(out.chunks.map((c) => c.content).join('')), `case ${i}`).toBe(squash(content)); + } + } + }); + + it('whole: a document is either one passage within the budget or a failure, never a cut', () => { + const next = rng(4242); + for (let i = 0; i < 200; i++) { + const content = randomDoc(next); + const maxInputTokens = 16 + Math.floor(next() * 2000); + const split = resolveSplit({ split: { strategy: 'whole' }, maxInputTokens }); + const out = splitDocument({ id: `w${i}`, content }, split); + if (out.ok) { + expect(out.chunks.length).toBeLessThanOrEqual(1); + for (const c of out.chunks) expect(estimateTokens(c.content)).toBeLessThanOrEqual(split.maxTokens!); + } else { + expect(out.estimate).toBeGreaterThan(split.maxTokens!); + } + } + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 14098547beb..9595743a49b 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -14,6 +14,7 @@ import type { KnowledgeLogger } from './knowledge-service.js'; import type { KnowledgeFieldSecurity } from './knowledge-source-admission.js'; import { createKnowledgeReapGuard, guardedObjectsFor } from './knowledge-reap-guard.js'; import { contributeKnowledgeSettings } from './knowledge-settings-contribution.js'; +import { UnknownKeyError, UnknownNamespaceError } from '@objectstack/service-settings'; /** * Whether `err` is the kernel's refusal for a service NOTHING registered under @@ -167,6 +168,34 @@ export class KnowledgeServicePlugin implements Plugin { throw err; } }, + // The settings page's `knowledge.chunk_target`, the splitter's + // `maxChars` under a source's own `split.maxChars` (#37098). Read each + // time the service splits, never here: the settings service may hold a + // value saved after boot. No settings service, or none serving the + // `knowledge` namespace (it is contributed below only where one + // exists), reads as unset. + resolveChunkTarget: async () => { + let settings: { get?(ns: string, key: string): Promise<{ value?: unknown } | undefined> } | undefined; + try { + settings = ctx.getService('settings'); + } catch (err) { + if (isServiceNotRegisteredError(err, 'settings')) return undefined; + throw err; + } + if (typeof settings?.get !== 'function') return undefined; + let resolved: { value?: unknown } | undefined; + try { + resolved = await settings.get('knowledge', 'chunk_target'); + } catch (err) { + // A host's own settings service without this namespace or key: + // nothing is configured there. Any other failure is the service's + // to report (it warns and splits by the source's own value). + if (err instanceof UnknownNamespaceError || err instanceof UnknownKeyError) return undefined; + throw err; + } + const value = resolved?.value; + return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined; + }, // [ADR-0161 K8, item 9] The EFFECTIVE tenancy posture, read per assembly // and per search from the kernel's `tenancy` service, classified the way // every admission seam classifies it: never registered → `undefined` (no diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 6f1bfe1e476..2ed34e81033 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -23,6 +23,7 @@ import { } from '@objectstack/core'; import type { TenancyPosture } from '@objectstack/spec/security'; import { createKnowledgeTools, type KnowledgeTools } from './knowledge-tools.js'; +import { resolveSplit, splitDocument } from './split/index.js'; import { documentOrganizationId, searchOrganizationIds, @@ -71,6 +72,16 @@ export interface KnowledgeServiceOptions { * service. */ resolveSecurity?: () => KnowledgeFieldSecurity | undefined; + /** + * The settings page's `knowledge.chunk_target`, read each time the service + * splits a batch of documents — never once at boot, so a value saved later + * applies to the next write. Answers `undefined` when nothing is stored or + * no settings service serves the namespace; the splitter then uses a + * source's own `split.maxChars`, else 800. A rejection is reported at `warn` + * and read as `undefined`. `KnowledgeServicePlugin` wires it to the + * `settings` service. + */ + resolveChunkTarget?: () => Promise; /** * The deployment's effective tenancy posture (ADR-0105 D1), read at each * assembly and each search (ADR-0161 K8, item 9): under `group` and @@ -175,6 +186,13 @@ export class KnowledgeService implements IKnowledgeService { // ── Document mutations ──────────────────────────────────────────── + /** + * Write one caller-built document. An adapter that declares + * `capabilities.chunks` receives it with the service's passages, split the + * way every other path splits ({@link prepareDocuments}). A `whole` + * document over the embedder's input budget is removed from the index and + * the call throws, naming the estimate and the budget. + */ async indexDocument(sourceId: string, doc: KnowledgeDocument): Promise { const source = this.requireSource(sourceId); const adapter = this.getAdapter(source.adapter); @@ -197,7 +215,74 @@ export class KnowledgeService implements IKnowledgeService { "from the record a document is assembled from; omit it.", ); } - await adapter.upsert([{ ...doc, docHash: computeDocHash(doc) }], { source, reason: 'manual' }); + // The passages are the service's too (ADR-0161 K1): one splitter cuts + // every document, so a caller's own `chunks` are refused the same way. + if (doc.chunks !== undefined) { + throw new Error( + `[knowledge] indexDocument refused document '${doc.id}': chunks are cut by the knowledge service's ` + + "splitter from the content, by the source's split; omit them.", + ); + } + const prepared = await this.prepareDocuments(source, adapter, [{ ...doc, docHash: computeDocHash(doc) }]); + if (prepared.failed.length > 0) { + const failure = prepared.failed[0]; + await adapter.delete([doc.id], { source, reason: 'manual' }); + throw new Error( + `[knowledge] indexDocument did not index document '${doc.id}' and removed it from the index: ${failure.reason}`, + ); + } + await adapter.upsert(prepared.ready, { source, reason: 'manual' }); + } + + /** + * The ONE place documents are split before an adapter sees them (ADR-0161 + * K1). An adapter that does not declare `capabilities.chunks` gets the + * documents as they are, without `chunks` — it splits them itself, as + * before. One that does gets each document with the passages of + * {@link splitDocument}, under the source's `split` (an object source's + * key; any other source splits `recursive`), the settings page's + * `knowledge.chunk_target`, and the adapter's reported + * `embedding.maxInputTokens` — both read now, for this batch, never cached. + * A document the split cannot index (a `whole` document over the budget) + * is answered in `failed`, never truncated; the caller removes it. + */ + private async prepareDocuments( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + docs: KnowledgeDocument[], + ): Promise<{ + ready: KnowledgeDocument[]; + failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }>; + }> { + if (adapter.capabilities?.chunks !== true || docs.length === 0) return { ready: docs, failed: [] }; + const split = resolveSplit({ + split: source.source.kind === 'object' ? (source.source as ObjectKnowledgeSource).split : undefined, + chunkTarget: await this.readChunkTarget(), + maxInputTokens: adapter.embedding?.maxInputTokens, + }); + const ready: KnowledgeDocument[] = []; + const failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }> = []; + for (const doc of docs) { + const out = splitDocument(doc, split); + if (out.ok) ready.push({ ...doc, chunks: out.chunks }); + else failed.push({ documentId: doc.id, reason: out.reason, estimate: out.estimate, budget: out.budget }); + } + return { ready, failed }; + } + + /** The settings page's `knowledge.chunk_target`, read now; `undefined` when unset or unreadable. */ + private async readChunkTarget(): Promise { + const resolve = this.options.resolveChunkTarget; + if (!resolve) return undefined; + try { + return await resolve(); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the settings page's knowledge.chunk_target could not be read (${errorText(err)}); ` + + "splitting by the source's own split.maxChars, else 800.", + ); + return undefined; + } } async deleteDocument(sourceId: string, documentId: string): Promise { @@ -287,6 +372,8 @@ export class KnowledgeService implements IKnowledgeService { indexed: 0, skipped: 0, purged: null, + failed: 0, + failures: [], message: `Reindex for kind=${source.source.kind} is not handled by KnowledgeService. ` + `Trigger ingestion through the adapter (${source.adapter}) directly.`, @@ -301,6 +388,8 @@ export class KnowledgeService implements IKnowledgeService { indexed: 0, skipped: 0, purged: null, + failed: 0, + failures: [], message: 'KnowledgeService has no IDataEngine bound; cannot walk object source.', }; } @@ -330,6 +419,8 @@ export class KnowledgeService implements IKnowledgeService { indexed: 0, skipped: 0, purged: null, + failed: 0, + failures: [], message: `reindex of source '${source.id}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, }; } @@ -346,6 +437,8 @@ export class KnowledgeService implements IKnowledgeService { indexed: 0, skipped: 0, purged: null, + failed: 0, + failures: [], message: 'dryRun=true; no documents pushed.', }; } @@ -383,6 +476,11 @@ export class KnowledgeService implements IKnowledgeService { let discovered = 0; let indexed = 0; let skipped = 0; + // Documents the split could not index (a `whole` document over the + // embedder's budget): removed from the index, counted, and the first + // MAX_REINDEX_FAILURES named. + let failed = 0; + const failures: Array<{ documentId: string; reason: string }> = []; let cursor: string | number | undefined; for (let page = 1; ; page++) { const want = cap === undefined ? REINDEX_PAGE_SIZE : Math.min(REINDEX_PAGE_SIZE, cap - discovered); @@ -395,6 +493,8 @@ export class KnowledgeService implements IKnowledgeService { indexed, skipped, purged: null, + failed, + failures: [...failures], message: `reindex of source '${source.id}' stopped at page ${page}${after}: ${what}`, }); @@ -441,16 +541,32 @@ export class KnowledgeService implements IKnowledgeService { const stored = listed.get(doc.id); return stored === undefined || stored !== doc.docHash; }); - if (changed.length > 0) { + // One split per changed document, for an adapter that takes chunks. + const prepared = await this.prepareDocuments(source, adapter, changed); + if (prepared.ready.length > 0) { try { - await adapter.upsert(changed, { source, reason: 'reindex' }); + await adapter.upsert(prepared.ready, { source, reason: 'reindex' }); } catch (err) { return stopped(`the adapter upsert failed: ${errorText(err)}`); } } + // A document the split cannot index is removed — an older passage of it + // must not keep answering for text the index no longer holds — and + // reported, never truncated. + if (prepared.failed.length > 0) { + try { + await adapter.delete(prepared.failed.map((f) => f.documentId), { source, reason: 'reindex' }); + } catch (err) { + return stopped(`removing the page's documents that cannot be indexed failed: ${errorText(err)}`); + } + for (const f of prepared.failed) { + failed += 1; + if (failures.length < MAX_REINDEX_FAILURES) failures.push({ documentId: f.documentId, reason: f.reason }); + } + } for (const doc of docs) seen.add(doc.id); discovered += rows.length; - indexed += changed.length; + indexed += prepared.ready.length; skipped += docs.length - changed.length; // The next page continues after this page's last id. A last row with no @@ -469,8 +585,22 @@ export class KnowledgeService implements IKnowledgeService { // The purge runs only after a COMPLETE walk: a `limit` walk saw part of // the source, so "not seen" there means nothing (a failed page returned // above; `dryRun` returned before the walk). - const done: KnowledgeReindexResult = { ok: true, object, discovered, indexed, skipped, purged: null }; - if (listingNote) return { ...done, message: listingNote }; + const failedNote = failed === 0 + ? undefined + : `${failed} document(s) cannot be indexed under the source's split and were removed from the index ` + + `(${failures.length === failed ? 'each' : `the first ${failures.length}`} named in failures).`; + const done: KnowledgeReindexResult = { + ok: true, + object, + discovered, + indexed, + skipped, + purged: null, + failed, + failures, + ...(failedNote === undefined ? {} : { message: failedNote }), + }; + if (listingNote) return { ...done, message: failedNote === undefined ? listingNote : `${listingNote} ${failedNote}` }; if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) return done; const candidates = [...listed.keys()].filter((id) => !seen.has(id)); @@ -489,7 +619,7 @@ export class KnowledgeService implements IKnowledgeService { purged: purge.purged, message: `reindex of source '${source.id}' walked every page, but its purge stopped after ${purge.purged} ` + - `deletion(s): ${purge.failure}`, + `deletion(s): ${purge.failure}${failedNote === undefined ? '' : ` ${failedNote}`}`, }; } if (purge.foreign > 0) { @@ -498,7 +628,8 @@ export class KnowledgeService implements IKnowledgeService { purged: purge.purged, message: `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + - `('${source.id}:' and the record id); they were kept, because no row can confirm them.`, + `('${source.id}:' and the record id); they were kept, because no row can confirm them.` + + (failedNote === undefined ? '' : ` ${failedNote}`), }; } return { ...done, purged: purge.purged }; @@ -653,7 +784,7 @@ export class KnowledgeService implements IKnowledgeService { return; } const doc = recordToDocument(source, objSource, payload, this.schemaFor(object), await this.readTenancyPosture()); - await adapter.upsert([doc], { source, reason: 'event-sync' }); + await this.writeSynced(source, adapter, doc, recordId); return; } if (!isRecordId(recordId)) { @@ -666,7 +797,7 @@ export class KnowledgeService implements IKnowledgeService { const row = await rereadRow(engine, objSource, recordId); if (row) { const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); - await adapter.upsert([doc], { source, reason: 'event-sync' }); + await this.writeSynced(source, adapter, doc, recordId); } else { await adapter.delete([documentIdFor(source.id, String(recordId))], { source, reason: 'event-sync' }); } @@ -677,6 +808,37 @@ export class KnowledgeService implements IKnowledgeService { } } + /** + * The event sync's write of one document: split as every path splits + * ({@link prepareDocuments}) and upserted. A document the split cannot + * index (a `whole` document over the embedder's budget) is removed from the + * index and reported at `error`: the write that triggered the sync + * succeeded and search keeps answering, so nothing else shows that this + * record is no longer findable. + */ + private async writeSynced( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + doc: KnowledgeDocument, + recordId: unknown, + ): Promise { + const prepared = await this.prepareDocuments(source, adapter, [doc]); + if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, { source, reason: 'event-sync' }); + for (const f of prepared.failed) { + await adapter.delete([f.documentId], { source, reason: 'event-sync' }); + const limit = adapter.embedding?.maxInputTokens; + const message = + `[knowledge] record '${String(recordId)}' of source '${source.id}' is no longer in the index and search ` + + `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + + `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + + `Fix: give source '${source.id}' split strategy 'recursive' or 'markdown', or shorten the record.`; + // `warn` is the guaranteed channel when a host injects no `error`. + const logger = this.options.logger; + if (logger?.error) logger.error(message); + else logger?.warn?.(message); + } + } + /** The no-engine path cannot judge `where`: say so once per source, never once per event. */ private reportWhereUnenforceable(source: KnowledgeSource): void { if (this.whereUnenforceableReported.has(source.id)) return; @@ -995,6 +1157,13 @@ export class KnowledgeService implements IKnowledgeService { */ export const REINDEX_PAGE_SIZE = 100; +/** + * The most documents one reindex result names in `failures`; `failed` counts + * them all. A source whose every document fails its split (a `whole` source + * over a small model's limit) answers a bounded result, not one entry per row. + */ +export const MAX_REINDEX_FAILURES = 20; + /** * Run `task` after every earlier task chained on the same `key` has settled — * an in-process promise chain per key, dropped from `tails` once idle. diff --git a/packages/services/service-knowledge/src/split/index.ts b/packages/services/service-knowledge/src/split/index.ts new file mode 100644 index 00000000000..15af641547a --- /dev/null +++ b/packages/services/service-knowledge/src/split/index.ts @@ -0,0 +1,12 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +export { + DEFAULT_SPLIT_MAX_CHARS, + DEFAULT_SPLIT_MIN_CHARS, + SPLIT_TOKEN_BUDGET_SHARE, + resolveSplit, + splitDocument, + type ResolvedSplit, + type ResolveSplitInput, + type SplitOutcome, +} from './splitter.js'; diff --git a/packages/services/service-knowledge/src/split/splitter.ts b/packages/services/service-knowledge/src/split/splitter.ts new file mode 100644 index 00000000000..97431e59e71 --- /dev/null +++ b/packages/services/service-knowledge/src/split/splitter.ts @@ -0,0 +1,555 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The knowledge service's ONE splitter (ADR-0161 K1, "Structural split"; the + * strategies are #37098's). The service cuts a document into passages here, + * once, and hands the same passages to every adapter that declares + * `capabilities.chunks` — so one source gives the same passages on each of + * them. + * + * Three strategies, chosen by the object source's `split.strategy`: + * + * - `whole` — one passage per document. A document whose token estimate is + * over the budget is NOT cut or truncated: {@link splitDocument} answers a + * failure and the service removes the document from the index and reports it. + * - `recursive` — blank line → line break → sentence end → semicolon → + * character, the next level only for a piece the level above left too long. + * A Markdown table or list item is one unit while it fits. Adjacent pieces + * are merged while the merged piece is shorter than `minChars`. + * - `markdown` — one section per ATX heading (outside code fences); each + * section is cut as `recursive` cuts, and every passage begins with its + * heading path, which counts toward its length and is embedded with it. + * + * ## The sentence end (the Chinese-aware part) + * + * `。?!` end a sentence wherever they stand. `. ? !` end one only before + * whitespace or the end of the text, so 「3.2 条」 and 「400.50 元」 stay whole. + * A run of end marks ends one sentence (`?!`, `...`). An end mark followed by + * a closing quote or bracket ends nothing — the split never falls right after + * a closing quote or bracket, so quoted speech stays inside its sentence. + * `;` ends a clause wherever it stands, `;` only before whitespace or the end. + * + * ## Bounds + * + * Every passage is at most `maxChars` characters (UTF-16 code units, trimmed), + * and, when the embedder's limit is known, its `estimateTokens` is at most + * `maxTokens` (80% of the limit — {@link resolveSplit}). A unit that fits no + * other way is cut by characters, on code-point boundaries, so the bound + * holds for every passage the splitter returns. A table that does not fit is + * cut between rows, each piece repeating the header row (and its separator + * row); a list item that does not fit is cut as a paragraph. + * + * Pure: reads nothing but its arguments. + */ + +import { estimateTokens } from '@objectstack/spec/shared'; +import type { KnowledgeChunk, KnowledgeSplit, KnowledgeSplitStrategy } from '@objectstack/spec/ai'; + +/** `maxChars` when neither the source nor the settings page sets one. */ +export const DEFAULT_SPLIT_MAX_CHARS = 800; + +/** `minChars` when the source sets none. */ +export const DEFAULT_SPLIT_MIN_CHARS = 200; + +/** The share of the embedder's input limit a passage may fill, by `estimateTokens`. */ +export const SPLIT_TOKEN_BUDGET_SHARE = 0.8; + +/** The split a source resolves to: what {@link splitDocument} cuts by. */ +export interface ResolvedSplit { + strategy: KnowledgeSplitStrategy; + /** Longest passage, in characters. Not read by `whole`. */ + maxChars: number; + /** Adjacent pieces shorter than this are merged. Never above `maxChars`. */ + minChars: number; + /** Largest `estimateTokens` of a passage; absent when no limit is known. */ + maxTokens?: number; +} + +/** Inputs of {@link resolveSplit}, highest precedence first for `maxChars`. */ +export interface ResolveSplitInput { + /** The object source's own `split` key. */ + split?: KnowledgeSplit; + /** The settings page's `knowledge.chunk_target`. */ + chunkTarget?: number; + /** The adapter's `embedding.maxInputTokens`. */ + maxInputTokens?: number; +} + +const isPositiveInt = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n > 0; + +/** + * Resolve the split: `maxChars` is the source's `split.maxChars`, else the + * settings page's `chunk_target`, else {@link DEFAULT_SPLIT_MAX_CHARS}; the + * token budget is {@link SPLIT_TOKEN_BUDGET_SHARE} of the embedder's limit, by + * the shared estimate, and absent when no limit is known. A passage keeps both + * bounds, so the effective length is the smaller of the two. An omitted + * strategy is `recursive`. + */ +export function resolveSplit(input: ResolveSplitInput): ResolvedSplit { + const maxChars = isPositiveInt(input.split?.maxChars) + ? input.split.maxChars + : isPositiveInt(input.chunkTarget) ? input.chunkTarget : DEFAULT_SPLIT_MAX_CHARS; + const requestedMin = typeof input.split?.minChars === 'number' && input.split.minChars >= 0 + ? Math.floor(input.split.minChars) + : DEFAULT_SPLIT_MIN_CHARS; + const resolved: ResolvedSplit = { + strategy: input.split?.strategy ?? 'recursive', + maxChars, + minChars: Math.min(requestedMin, maxChars), + }; + if (isPositiveInt(input.maxInputTokens)) { + resolved.maxTokens = Math.max(1, Math.floor(input.maxInputTokens * SPLIT_TOKEN_BUDGET_SHARE)); + } + return resolved; +} + +/** What {@link splitDocument} answers. */ +export type SplitOutcome = + | { ok: true; chunks: KnowledgeChunk[] } + | { + ok: false; + /** Why the document cannot be indexed under its split, for the reindex result and the log. */ + reason: string; + /** The document's token estimate. */ + estimate: number; + /** The budget it is over ({@link ResolvedSplit.maxTokens}). */ + budget: number; + }; + +/** + * Cut one document into passages. Each passage's `id` is + * `${documentId}#${index}`. A document with no text but whitespace has no + * passage. Only `whole` can fail: over the token budget. + */ +export function splitDocument(doc: { id: string; content: string }, split: ResolvedSplit): SplitOutcome { + const bounds: Bounds = { maxChars: split.maxChars, maxTokens: split.maxTokens }; + let pieces: Array<{ content: string; headingPath?: string[] }>; + if (split.strategy === 'whole') { + const content = doc.content.trim(); + if (content === '') return { ok: true, chunks: [] }; + if (split.maxTokens !== undefined) { + const estimate = estimateTokens(content); + if (estimate > split.maxTokens) { + return { + ok: false, + estimate, + budget: split.maxTokens, + reason: + `the whole document estimates ${estimate} tokens, over the embedder's input budget of ${split.maxTokens} ` + + `(${Math.round(SPLIT_TOKEN_BUDGET_SHARE * 100)}% of its limit); split 'whole' does not truncate. ` + + "Choose split strategy 'recursive' or 'markdown' for this source, or shorten the document.", + }; + } + } + pieces = [{ content }]; + } else if (split.strategy === 'markdown') { + pieces = splitMarkdown(doc.content, bounds, split.minChars); + } else { + pieces = splitRecursive(doc.content, bounds, split.minChars).map((content) => ({ content })); + } + return { + ok: true, + chunks: pieces.map((p, index) => ({ + id: `${doc.id}#${index}`, + documentId: doc.id, + index, + content: p.content, + ...(p.headingPath && p.headingPath.length > 0 ? { headingPath: p.headingPath } : {}), + })), + }; +} + +// ── Bounds ─────────────────────────────────────────────────────────── + +interface Bounds { + maxChars: number; + maxTokens?: number; +} + +function fits(text: string, b: Bounds): boolean { + const t = text.trim(); + if (t.length > b.maxChars) return false; + return b.maxTokens === undefined || estimateTokens(t) <= b.maxTokens; +} + +// ── recursive ──────────────────────────────────────────────────────── + +/** + * The `recursive` strategy over `text`: trimmed passages, none empty, each + * within `b`. Pieces are slices of `text` (a cut table's pieces repeat its + * header), so the passages read in order give back the text. + */ +export function splitRecursive(text: string, b: Bounds, minChars: number): string[] { + const pieces: Piece[] = []; + toBlocks(text).forEach((block, n) => { + const parts = fits(block.text, b) + ? [block.text] + : block.kind === 'table' ? splitTable(block.text, b) : splitDown(block.text, b, 0); + for (const part of parts) pieces.push({ text: part, block: n, whole: parts.length === 1 }); + }); + return mergeShort(pieces, b, minChars); +} + +/** A piece and the block it came from; `whole` when the block was not cut. */ +interface Piece { + text: string; + block: number; + whole: boolean; +} + +type Level = (text: string) => string[]; + +/** Below the block level: line → sentence → semicolon → character. */ +const LEVELS: Level[] = [splitLines, splitSentences, splitClauses]; + +function splitDown(text: string, b: Bounds, level: number): string[] { + if (fits(text, b)) return [text]; + if (level >= LEVELS.length) return cutByCharacters(text, b); + const parts = LEVELS[level](text); + if (parts.length <= 1) return splitDown(text, b, level + 1); + const out: string[] = []; + for (const part of parts) out.push(...(fits(part, b) ? [part] : splitDown(part, b, level + 1))); + return out; +} + +/** + * Adjacent pieces merged while the merged piece is shorter than `minChars` + * and still fits; a short last piece joins the one before when it fits. + * Pieces of one block always may merge. Across blocks, a piece joins only a + * run made of whole blocks: a short title block leads the text after it, + * and the tail of a cut block never takes the next block (a chapter title + * stays with its own chapter). Every passage is trimmed; none is empty. + */ +function mergeShort(pieces: Piece[], b: Bounds, minChars: number): string[] { + interface Run { text: string; lastBlock: number; allWhole: boolean } + const out: Run[] = []; + let run: Run | undefined; + const joinable = (into: Run, p: Piece): boolean => + (p.block === into.lastBlock || into.allWhole) + && into.text.trim().length < minChars + && fits(into.text + p.text, b); + for (const p of pieces) { + if (run === undefined || run.text.trim() === '') { + run = run === undefined + ? { text: p.text, lastBlock: p.block, allWhole: p.whole } + : { text: run.text + p.text, lastBlock: p.block, allWhole: p.whole }; + continue; + } + if (p.text.trim() === '') { + run.text += p.text; + continue; + } + if (joinable(run, p)) { + run = { text: run.text + p.text, lastBlock: p.block, allWhole: run.allWhole && p.whole }; + } else { + out.push(run); + run = { text: p.text, lastBlock: p.block, allWhole: p.whole }; + } + } + if (run !== undefined && run.text.trim() !== '') { + const prev = out[out.length - 1]; + const tailJoins = prev !== undefined + && run.text.trim().length < minChars + && (prev.lastBlock === run.lastBlock || (prev.allWhole && run.allWhole)) + && fits(prev.text + run.text, b); + if (tailJoins) prev.text += run.text; + else out.push(run); + } + return out.map((r) => r.text.trim()).filter((t) => t !== ''); +} + +// ── Blocks: paragraphs, tables, list items ─────────────────────────── + +interface Block { + kind: 'paragraph' | 'table' | 'list-item'; + text: string; +} + +const TABLE_LINE = /^[ \t]*\|/; +const LIST_ITEM_START = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+\S/; +const BLANK = /^[ \t]*$/; + +/** + * Cut `text` into blocks at blank lines, and around Markdown tables (a run of + * lines starting `|`) and list items (a marker line and the indented lines + * under it), which are never cut at a blank line or a line break. A blank line + * stays with the block before it, so the blocks concatenate to `text`. + */ +function toBlocks(text: string): Block[] { + const lines = splitKeepingNewlines(text); + const blocks: Block[] = []; + let i = 0; + const appendToLast = (line: string): void => { + if (blocks.length === 0) blocks.push({ kind: 'paragraph', text: line }); + else blocks[blocks.length - 1].text += line; + }; + while (i < lines.length) { + const line = lines[i]; + if (BLANK.test(stripNewline(line))) { + appendToLast(line); + i++; + } else if (TABLE_LINE.test(line)) { + let t = ''; + while (i < lines.length && TABLE_LINE.test(lines[i])) t += lines[i++]; + blocks.push({ kind: 'table', text: t }); + } else if (LIST_ITEM_START.test(line)) { + let t = lines[i++]; + while ( + i < lines.length + && !BLANK.test(stripNewline(lines[i])) + && /^[ \t]+\S/.test(lines[i]) + && !LIST_ITEM_START.test(lines[i]) + ) t += lines[i++]; + blocks.push({ kind: 'list-item', text: t }); + } else { + let t = ''; + while ( + i < lines.length + && !BLANK.test(stripNewline(lines[i])) + && !TABLE_LINE.test(lines[i]) + && !LIST_ITEM_START.test(lines[i]) + ) t += lines[i++]; + blocks.push({ kind: 'paragraph', text: t }); + } + } + return blocks; +} + +function splitKeepingNewlines(text: string): string[] { + const out: string[] = []; + let start = 0; + for (let i = 0; i < text.length; i++) { + if (text[i] === '\n') { + out.push(text.slice(start, i + 1)); + start = i + 1; + } + } + if (start < text.length) out.push(text.slice(start)); + return out; +} + +function stripNewline(line: string): string { + return line.endsWith('\n') ? line.slice(0, -1).replace(/\r$/, '') : line; +} + +/** + * A table that does not fit, cut between rows: the header row (and its + * `| --- |` separator row, when the second line is one) leads every piece; + * the body rows are packed into each piece while it fits. A row that does + * not fit even under the header alone is cut by characters. + */ +function splitTable(text: string, b: Bounds): string[] { + const rows = splitKeepingNewlines(text); + let headerRows = 1; + if (rows.length > 1 && /^[ \t]*\|?[ \t]*:?-{3,}/.test(rows[1])) headerRows = 2; + const header = rows.slice(0, headerRows).join(''); + const body = rows.slice(headerRows); + if (body.length === 0 || !fits(header, b)) return splitDown(text, b, 0); + const out: string[] = []; + let buf = ''; + const flush = (): void => { + if (buf !== '') out.push(ensureNewline(header) + buf); + buf = ''; + }; + for (const row of body) { + if (fits(ensureNewline(header) + buf + row, b)) { + buf += row; + continue; + } + flush(); + if (fits(ensureNewline(header) + row, b)) buf = row; + else out.push(...cutByCharacters(row, b)); + } + flush(); + return out; +} + +function ensureNewline(s: string): string { + return s.endsWith('\n') ? s : `${s}\n`; +} + +// ── Lines, sentences, clauses, characters ──────────────────────────── + +function splitLines(text: string): string[] { + return splitKeepingNewlines(text); +} + +/** Always end a sentence. */ +const CJK_SENTENCE_END = new Set(['。', '?', '!']); +/** End a sentence only before whitespace or the end of the text. */ +const ASCII_SENTENCE_END = new Set(['.', '?', '!']); +/** Closing quotes and brackets: an end mark right before one ends nothing. */ +const CLOSERS = new Set(['”', '’', '」', '』', ')', ')', ']', '】', '》', '〉', '"', '\'', '}']); + +function splitSentences(text: string): string[] { + return splitAt(text, (t, i) => { + const c = t[i]; + if (!CJK_SENTENCE_END.has(c) && !ASCII_SENTENCE_END.has(c)) return -1; + let j = i + 1; + while (j < t.length && (CJK_SENTENCE_END.has(t[j]) || ASCII_SENTENCE_END.has(t[j]) || t[j] === '…')) j++; + if (j < t.length && CLOSERS.has(t[j])) return -1; + const asciiOnly = [...t.slice(i, j)].every((ch) => ASCII_SENTENCE_END.has(ch)); + if (asciiOnly && j < t.length && !/\s/.test(t[j])) return -1; + return j; + }); +} + +function splitClauses(text: string): string[] { + return splitAt(text, (t, i) => { + const c = t[i]; + if (c !== ';' && c !== ';') return -1; + const j = i + 1; + if (j < t.length && CLOSERS.has(t[j])) return -1; + if (c === ';' && j < t.length && !/\s/.test(t[j])) return -1; + return j; + }); +} + +/** + * Cut `text` after every position `endAt` accepts (it answers the index the + * piece ends at, or -1). The whitespace after a cut stays with the piece + * before it, so the pieces concatenate to `text`. + */ +function splitAt(text: string, endAt: (t: string, i: number) => number): string[] { + const out: string[] = []; + let start = 0; + for (let i = 0; i < text.length; i++) { + let end = endAt(text, i); + if (end < 0) continue; + while (end < text.length && /\s/.test(text[end])) end++; + out.push(text.slice(start, end)); + start = end; + i = end - 1; + } + if (start < text.length) out.push(text.slice(start)); + return out; +} + +/** + * The last level: cut by characters, on code-point boundaries. First the + * longest prefixes that fit, found by halving (both bounds grow with the + * prefix) — that gives the fewest pieces; then, when that many pieces of + * EVEN length all fit, those instead, so no piece is a sliver. At least one + * code point per piece, so the cut always ends. + */ +function cutByCharacters(text: string, b: Bounds): string[] { + const cps = Array.from(text); + const greedy: string[] = []; + let start = 0; + while (start < cps.length) { + let lo = start + 1; + let hi = Math.min(cps.length, start + b.maxChars + countLeadingSpace(cps, start)); + if (fits(cps.slice(start, lo).join(''), b)) { + while (lo < hi) { + const mid = Math.ceil((lo + hi) / 2); + if (fits(cps.slice(start, mid).join(''), b)) lo = mid; + else hi = mid - 1; + } + } + greedy.push(cps.slice(start, lo).join('')); + start = lo; + } + if (greedy.length < 2) return greedy; + const even: string[] = []; + const size = Math.ceil(cps.length / greedy.length); + for (let at = 0; at < cps.length; at += size) even.push(cps.slice(at, at + size).join('')); + return even.length === greedy.length && even.every((piece) => fits(piece, b)) ? even : greedy; +} + +function countLeadingSpace(cps: string[], from: number): number { + let n = 0; + while (from + n < cps.length && /\s/.test(cps[from + n])) n++; + return n; +} + +// ── markdown ───────────────────────────────────────────────────────── + +const HEADING = /^(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/; +const FENCE = /^[ \t]*(```|~~~)/; + +/** + * The `markdown` strategy: one section per ATX heading outside a code fence; + * text before the first heading is a section with no path. A heading whose + * section has no text joins the next section: as part of its path when it is + * an ancestor, as a leading line otherwise (a trailing one is a passage of + * its own). Each section is cut by {@link splitRecursive} within the bounds + * left after its heading path, and every passage begins with that path. + */ +export function splitMarkdown( + text: string, + b: Bounds, + minChars: number, +): Array<{ content: string; headingPath: string[] }> { + const sections: Array<{ path: string[]; body: string }> = []; + const stack: Array<{ level: number; text: string }> = []; + let body = ''; + let inFence = false; + const flush = (): void => { + sections.push({ path: stack.map((h) => h.text), body }); + body = ''; + }; + for (const line of splitKeepingNewlines(text)) { + const bare = stripNewline(line); + if (FENCE.test(bare)) inFence = !inFence; + const m = inFence ? null : HEADING.exec(bare); + if (!m) { + body += line; + continue; + } + flush(); + const level = m[1].length; + while (stack.length > 0 && stack[stack.length - 1].level >= level) stack.pop(); + stack.push({ level, text: m[2] }); + } + flush(); + + const out: Array<{ content: string; headingPath: string[] }> = []; + let carried: string[] = []; + for (let s = 0; s < sections.length; s++) { + const { path } = sections[s]; + let sectionBody = sections[s].body; + if (sectionBody.trim() === '') { + // An empty section's heading joins the next section — unless it is the + // next one's ancestor, whose path already names it. + const next = sections[s + 1]; + const own = path[path.length - 1]; + if (own === undefined) continue; + const isAncestor = next !== undefined && next.path.length > path.length + && path.every((h, k) => next.path[k] === h); + if (next !== undefined && !isAncestor) carried.push(own); + if (next === undefined) out.push(...withPrefix(path, '', b, minChars)); + continue; + } + if (carried.length > 0) { + sectionBody = `${carried.join('\n')}\n\n${sectionBody.replace(/^\s+/, '')}`; + carried = []; + } + out.push(...withPrefix(path, sectionBody, b, minChars)); + } + return out; +} + +function withPrefix( + path: string[], + body: string, + b: Bounds, + minChars: number, +): Array<{ content: string; headingPath: string[] }> { + if (path.length === 0) return splitRecursive(body, b, minChars).map((content) => ({ content, headingPath: [] })); + // The heading path counts toward the passage's length; a path too long to + // leave half the bounds for text shortens to its innermost heading, then to + // none (the passage still records the whole path). + for (const prefix of [path.join(' > '), path[path.length - 1], '']) { + const lead = prefix === '' ? '' : `${prefix}\n\n`; + const left: Bounds = { + maxChars: b.maxChars - lead.length, + maxTokens: b.maxTokens === undefined ? undefined : b.maxTokens - estimateTokens(lead), + }; + const roomy = left.maxChars >= b.maxChars / 2 && (left.maxTokens === undefined || left.maxTokens >= (b.maxTokens ?? 0) / 2); + if (!roomy && prefix !== '') continue; + if (body.trim() === '') return prefix === '' ? [] : [{ content: prefix, headingPath: path }]; + return splitRecursive(body, left, Math.min(minChars, left.maxChars)) + .map((piece) => ({ content: `${lead}${piece}`.trim(), headingPath: path })); + } + return []; +} diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 3d5368037b4..2580d99a3b0 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -10,7 +10,7 @@ * runKnowledgeAdapterContract({ * name: 'knowledge-memory', * makeAdapter: () => new KnowledgeMemoryAdapter(), - * implements: { listDocuments: true, organizationIds: true }, + * implements: { listDocuments: true, chunks: true, organizationIds: true }, * }); * ``` * @@ -21,7 +21,11 @@ * optional `listDocuments` (page boundaries at 0, one page and one page + 1; * `docHash` returned as stored); and, through a real `KnowledgeService` over a * small data-engine double, the skip of unchanged documents and the purge of - * documents the source no longer has; and the organization filter + * documents the source no longer has; the chunk channel (ADR-0161 K8, + * item 5) — an adapter that declares `capabilities.chunks` receives the + * service's passages and indexes them as given, one that does not keeps + * receiving whole documents, and a `whole` document over the embedder's + * budget is removed and reported, never truncated; and the organization filter * (ADR-0161 K8, item 9) — on the adapter alone, and through a real * `KnowledgeService` under the `isolated`, `group` and `single` postures. * @@ -39,6 +43,7 @@ import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from ' import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; import { KnowledgeService } from './knowledge-service.js'; +import { resolveSplit, splitDocument } from './split/index.js'; /** Input of {@link runKnowledgeAdapterContract}. */ export interface KnowledgeAdapterContractOptions { @@ -53,6 +58,8 @@ export interface KnowledgeAdapterContractOptions { /** The optional members this adapter implements; checked against the adapter. */ implements: { listDocuments: boolean; + /** `capabilities.chunks === true`: the adapter takes the service's passages. */ + chunks: boolean; /** * The adapter's search honours `AdapterSearchOptions.organizationIds` * (ADR-0161 K8, item 9): it ranks only the documents of the organizations @@ -78,22 +85,30 @@ function ctxOf(source: KnowledgeSource): AdapterContext { return { source, reason: 'manual' }; } -function doc( - source: KnowledgeSource, - n: string, - content: string, - docHash?: string, - organizationId?: string, -): KnowledgeDocument { - return { - id: `${source.id}:${n}`, - sourceId: source.id, - sourceRecordId: n, - content, - title: `Title ${n}`, - metadata: { status: 'published' }, - ...(docHash === undefined ? {} : { docHash }), - ...(organizationId === undefined ? {} : { organizationId }), +/** + * A document as the service hands it to this adapter: with one passage (the + * whole text, as split `whole` gives it) when the adapter takes chunks. + */ +function docFor(withChunks: boolean) { + return ( + source: KnowledgeSource, + n: string, + content: string, + docHash?: string, + organizationId?: string, + ): KnowledgeDocument => { + const id = `${source.id}:${n}`; + return { + id, + sourceId: source.id, + sourceRecordId: n, + content, + title: `Title ${n}`, + metadata: { status: 'published' }, + ...(docHash === undefined ? {} : { docHash }), + ...(organizationId === undefined ? {} : { organizationId }), + ...(withChunks ? { chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] } : {}), + }; }; } @@ -182,11 +197,17 @@ interface ServiceSetup { posture?: () => TenancyPosture | undefined; /** The permission re-read's wall ({@link rowsEngine}). */ wall?: (row: Row, context: ExecutionContext) => boolean; + /** + * Stands in for the limit the adapter's embedder would report + * (`embedding.maxInputTokens`); omitted, the adapter's own report is used. + */ + maxInputTokens?: number; } /** * A `KnowledgeService` over `adapter` and `rows`, with the adapter's `upsert` - * counted and the options of every `search` it is handed recorded. + * counted and its documents kept, and the options of every `search` it is + * handed recorded. */ async function serviceOver( make: () => IKnowledgeAdapter | Promise, @@ -196,13 +217,22 @@ async function serviceOver( ) { const adapter: IKnowledgeAdapter = await make(); const upserted: string[][] = []; + const received: KnowledgeDocument[] = []; const searched: AdapterSearchOptions[] = []; // Delegation, not a prototype proxy: an adapter with `#private` fields only - // answers when its methods are called on the adapter itself. + // answers when its methods are called on the adapter itself. The + // descriptors are read through on every access, as the service reads them. const counting: IKnowledgeAdapter = { id: adapter.id, + get capabilities() { + return adapter.capabilities; + }, + get embedding() { + return setup.maxInputTokens === undefined ? adapter.embedding : { maxInputTokens: setup.maxInputTokens }; + }, upsert: async (docs, ctx) => { upserted.push(docs.map((d) => d.id)); + received.push(...docs); return adapter.upsert(docs, ctx); }, search: (query, searchOpts) => { @@ -221,7 +251,7 @@ async function serviceOver( }); svc.registerAdapter('under_test', counting); svc.registerSource(source); - return { adapter, svc, upserted, searched }; + return { adapter, svc, upserted, received, searched }; } /** The last element of `list`, or `undefined` when it is empty. */ @@ -266,12 +296,14 @@ const rowsOf = (n: number): Row[] => */ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOptions): void { const make = opts.makeAdapter; + const doc = docFor(opts.implements.chunks); describe(`IKnowledgeAdapter contract — ${opts.name}`, () => { it('declares exactly the optional members it implements', async () => { const adapter: IKnowledgeAdapter = await make(); expect(typeof adapter.id).toBe('string'); expect(typeof adapter.listDocuments === 'function').toBe(opts.implements.listDocuments); + expect(adapter.capabilities?.chunks === true).toBe(opts.implements.chunks); }); describe('upsert / search / delete', () => { @@ -514,5 +546,81 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); }); } + + describe('the chunk channel (ADR-0161 K8, item 5)', () => { + const longBody = + 'Glaciers carve valleys over centuries. Their ice holds ancient air bubbles. ' + + 'Harbour cranes unload containers at night. The night shift starts at ten. ' + + 'Copper wire conducts heat and electricity well. It is drawn through dies.'; + const splitSource = (id: string) => + objectSource(id, { split: { strategy: 'recursive', maxChars: 80, minChars: 0 } } as Partial); + + if (opts.implements.chunks) { + it("receives the service's passages, cut once, and indexes them as given", async () => { + const source = splitSource('chunks'); + const rows: Row[] = [{ id: 'r1', body: longBody, status: 'published' }]; + const h = await serviceOver(make, rows, source); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 1, failed: 0, failures: [] }); + const [sent] = h.received; + const expected = splitDocument( + sent, + resolveSplit({ + split: (source.source as ObjectKnowledgeSource).split, + maxInputTokens: h.adapter.embedding?.maxInputTokens, + }), + ); + if (!expected.ok) throw new Error(expected.reason); + expect(expected.chunks.length).toBeGreaterThan(1); + expect(sent.chunks).toEqual(expected.chunks); + // Indexed as given: a hit is one of those passages, by id and text. + const third = expected.chunks.find((c) => c.content.includes('Copper'))!; + const hits = await h.adapter.search('copper wire electricity', { source, topK: 3 }); + expect(hits[0]).toMatchObject({ chunkId: third.id, documentId: sent.id, snippet: third.content }); + }); + + it("a whole document over the embedder's budget is removed and reported, never truncated", async () => { + const source = objectSource('whole', { split: { strategy: 'whole' } } as Partial); + const rows: Row[] = [ + { id: 'r1', body: 'short tundra note', status: 'published' }, + { id: 'r2', body: longBody, status: 'published' }, + ]; + // 60 tokens: a 48-token budget, which the short row fits and the long one does not. + const h = await serviceOver(make, rows, source, { maxInputTokens: 60 }); + const first = await h.svc.reindexSource(source.id); + expect(first).toMatchObject({ ok: true, discovered: 2, indexed: 1, failed: 1 }); + expect(first.failures).toEqual([{ documentId: `${source.id}:r2`, reason: expect.stringContaining("split 'whole'") }]); + expect(await h.adapter.search('glaciers copper', { source, topK: 5 })).toEqual([]); + // A document that fit and then grew past the budget leaves the index too. + rows[0].body = `tundra ${longBody}`; + const second = await h.svc.reindexSource(source.id); + expect(second).toMatchObject({ ok: true, failed: 2 }); + expect((await h.adapter.search('tundra', { source, topK: 5 })).map((x) => x.documentId)).toEqual([]); + }); + + it('indexDocument refuses caller-supplied chunks', async () => { + const source = splitSource('push'); + const h = await serviceOver(make, [], source); + await expect( + h.svc.indexDocument(source.id, { + id: `${source.id}:x`, + sourceId: source.id, + content: 'pushed', + chunks: [{ id: `${source.id}:x#0`, documentId: `${source.id}:x`, index: 0, content: 'pushed' }], + }), + ).rejects.toThrow(/chunks are cut by the knowledge service/); + expect(h.upserted).toEqual([]); + }); + } else { + it('receives whole documents, never chunks, whatever the source splits by or the budget', async () => { + const source = splitSource('nochunks'); + const rows: Row[] = [{ id: 'r1', body: longBody, status: 'published' }]; + const h = await serviceOver(make, rows, source, { maxInputTokens: 20 }); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 1, failed: 0 }); + expect(h.received).toHaveLength(1); + expect(h.received[0].content).toBe(longBody); + expect('chunks' in h.received[0]).toBe(false); + }); + } + }); }); } diff --git a/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts b/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts index f1369839cf4..7c4833e92f6 100644 --- a/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts +++ b/packages/services/service-settings/src/manifests/knowledge.manifest.test.ts @@ -12,11 +12,14 @@ describe('knowledgeSettingsManifest', () => { expect(() => SettingsManifestSchema.parse(knowledgeSettingsManifest)).not.toThrow(); }); - it('declares namespace=knowledge, scope=global, version=1', () => { + it('declares namespace=knowledge, scope=global, version=2 (chunk_overlap retired)', () => { const parsed = SettingsManifestSchema.parse(knowledgeSettingsManifest); expect(parsed.namespace).toBe('knowledge'); expect(parsed.scope).toBe('global'); - expect(parsed.version).toBe(1); + expect(parsed.version).toBe(2); + const keys = parsed.specifiers.map((sp: any) => sp.key).filter(Boolean); + expect(keys).toContain('chunk_target'); + expect(keys).not.toContain('chunk_overlap'); }); it('exposes adapter select with memory + turso + ragflow', () => { diff --git a/packages/services/service-settings/src/manifests/knowledge.manifest.ts b/packages/services/service-settings/src/manifests/knowledge.manifest.ts index 5d2a533605e..7c1e91f8b77 100644 --- a/packages/services/service-settings/src/manifests/knowledge.manifest.ts +++ b/packages/services/service-settings/src/manifests/knowledge.manifest.ts @@ -34,10 +34,22 @@ import type { SettingsActionHandler } from '../settings-service.types.js'; * knowledge plugins; this manifest is the canonical settings surface * for "what knowledge backend is wired" and saves operators from * grepping defineStack() during onboarding / incident response. + * + * `chunk_target` is read by the knowledge service's splitter (#37098): the + * longest passage, in characters, beneath a knowledge source's own + * `split.maxChars`, and lowered further by the embedder's input limit. It + * applies to every adapter that takes the service's passages, the in-memory + * one included. `chunk_overlap` was offered here until #37098 and nothing + * ever read it; the splitter cuts without overlap, so it was retired rather + * than implemented. Removing it is why `version` is 2 (the spec's + * `SettingsManifest.version` contract: "increment when keys are + * renamed/removed"). A `sys_setting` row stored for it is kept, never + * deleted; the service no longer resolves it, and a write naming the key is + * refused `400 UNKNOWN_KEY`, the answer every undeclared key gets. */ const manifest = { namespace: 'knowledge', - version: 1, + version: 2, label: 'Knowledge', icon: 'BookOpen', description: @@ -100,16 +112,10 @@ const manifest = { // ── Indexing defaults ───────────────────────────────────────── { type: 'group', id: 'indexing', label: 'Indexing defaults', required: false, - description: 'A value set on a knowledge source itself wins over these defaults.', - visible: "${data.adapter !== 'memory'}" }, + description: 'A value set on a knowledge source itself wins over these defaults.' }, { type: 'number', key: 'chunk_target', label: 'Target chunk size (chars)', required: false, default: 800, min: 64, max: 8192, - description: 'Soft cap on chunk size in characters before token-aware splitting kicks in.', - visible: "${data.adapter !== 'memory'}" }, - { type: 'number', key: 'chunk_overlap', label: 'Chunk overlap (chars)', - required: false, default: 80, min: 0, max: 2048, - description: 'Characters retained from the previous chunk so context survives the boundary.', - visible: "${data.adapter !== 'memory'}" }, + description: "Longest passage, in characters, when the knowledge service splits a document. A size set on a knowledge source itself wins; the embedding model's input limit can lower it." }, { type: 'number', key: 'over_fetch', label: 'Over-fetch multiplier', required: false, default: 4, min: 1, max: 20, description: 'Search fetches this many times the requested number of results, so enough are left to return after they are filtered by document details.', diff --git a/packages/services/service-settings/src/settings-visibility-declaration.pin.test.ts b/packages/services/service-settings/src/settings-visibility-declaration.pin.test.ts index 9aaf25fed0f..7e9cb87eeb5 100644 --- a/packages/services/service-settings/src/settings-visibility-declaration.pin.test.ts +++ b/packages/services/service-settings/src/settings-visibility-declaration.pin.test.ts @@ -74,7 +74,7 @@ describe('settings `visible` — declaration ⇄ evaluator', () => { expect(refusals).toEqual([]); }); - it('the corpus is still the size the ruling measured — 10 manifests, 96 predicates', () => { + it('the corpus is still the size the ruling measured — 10 manifests, 87 predicates', () => { // If a bundled manifest gains or loses a `visible`, this number moves and // the reader is sent back to the measurement rather than trusting a stale // one. It is a tripwire on the premise, not a rule about how many @@ -100,7 +100,11 @@ describe('settings `visible` — declaration ⇄ evaluator', () => { // `${data.provider !== 'memory'}` predicates on the generation-default and // title fields went with it (they now always show), and `title_max_length` // keeps only its `title_generation_enabled` term. - expect(predicates).toHaveLength(90); + // 90 -> 87 at #37098: `knowledge.chunk_overlap` was retired with its + // predicate, and the `indexing` group and `chunk_target` lost their + // `${data.adapter !== 'memory'}` terms — the in-memory adapter takes the + // service's passages too, so the target size applies to it. + expect(predicates).toHaveLength(87); }); it('every bundled predicate is accepted by BOTH sides', () => { diff --git a/packages/services/service-settings/src/translations/ar.ts b/packages/services/service-settings/src/translations/ar.ts index 1a4f5b7b1bd..6471596e01c 100644 --- a/packages/services/service-settings/src/translations/ar.ts +++ b/packages/services/service-settings/src/translations/ar.ts @@ -681,11 +681,7 @@ export const ar: PlatformTranslationData = { }, chunk_target: { label: 'الحجم المستهدف للمقطع (أحرف)', - help: 'حد مرن لحجم المقطع قبل أن يبدأ التقسيم المراعي للرموز.', - }, - chunk_overlap: { - label: 'تداخل المقاطع (أحرف)', - help: 'الأحرف المحتفَظ بها من المقطع السابق كي يبقى السياق عبر الحدّ الفاصل.', + help: 'أقصى طول للمقطع بالأحرف عند تقسيم خدمة المعرفة لمستند. تكون الأولوية للحجم المحدد في مصدر المعرفة نفسه، وقد يخفضه حد الإدخال الخاص بنموذج التضمين.', }, over_fetch: { label: 'مضاعف الجلب الزائد', diff --git a/packages/services/service-settings/src/translations/de.ts b/packages/services/service-settings/src/translations/de.ts index 0e6304e5c00..80db8f8f4c4 100644 --- a/packages/services/service-settings/src/translations/de.ts +++ b/packages/services/service-settings/src/translations/de.ts @@ -723,11 +723,7 @@ export const de: PlatformTranslationData = { }, chunk_target: { label: 'Ziel-Chunkgröße (Zeichen)', - help: 'Weiche Obergrenze der Chunkgröße, bevor die tokenbasierte Aufteilung greift.', - }, - chunk_overlap: { - label: 'Chunk-Überlappung (Zeichen)', - help: 'Aus dem vorigen Chunk übernommene Zeichen, damit der Kontext über die Grenze erhalten bleibt.', + help: 'Längste Passage in Zeichen, wenn der Wissensdienst ein Dokument aufteilt. Eine an der Wissensquelle selbst gesetzte Größe hat Vorrang; das Eingabelimit des Embedding-Modells kann den Wert senken.', }, over_fetch: { label: 'Over-Fetch-Faktor', diff --git a/packages/services/service-settings/src/translations/en.ts b/packages/services/service-settings/src/translations/en.ts index 089e4ba0949..989f4848b1c 100644 --- a/packages/services/service-settings/src/translations/en.ts +++ b/packages/services/service-settings/src/translations/en.ts @@ -412,9 +412,7 @@ export const en: PlatformTranslationData = { ragflow_default_dataset: { label: 'Default dataset id', help: 'Used when a knowledge source does not name its own RAGFlow dataset.' }, chunk_target: { label: 'Target chunk size (chars)', - help: 'Soft cap on chunk size before token-aware splitting kicks in.' }, - chunk_overlap: { label: 'Chunk overlap (chars)', - help: 'Characters retained from the previous chunk so context survives the boundary.' }, + help: 'Longest passage, in characters, when the knowledge service splits a document. A size set on a knowledge source itself wins; the embedding model\'s input limit can lower it.' }, over_fetch: { label: 'Over-fetch multiplier', help: 'Search fetches this many times the requested number of results, so enough are left to return after they are filtered by document details.' }, enforce_rls: { label: 'Enforce RLS on search', diff --git a/packages/services/service-settings/src/translations/es-ES.ts b/packages/services/service-settings/src/translations/es-ES.ts index 80577c81c4e..6a2659a0ea0 100644 --- a/packages/services/service-settings/src/translations/es-ES.ts +++ b/packages/services/service-settings/src/translations/es-ES.ts @@ -578,9 +578,7 @@ export const esES: PlatformTranslationData = { ragflow_default_dataset: { label: 'ID de dataset predeterminado', help: 'Se usa cuando una fuente de conocimiento no indica su propio dataset de RAGFlow.' }, chunk_target: { label: 'Tamaño objetivo de fragmento (caracteres)', - help: 'Límite flexible del tamaño de fragmento antes de que actúe la división consciente de tokens.' }, - chunk_overlap: { label: 'Solapamiento de fragmentos (caracteres)', - help: 'Caracteres conservados del fragmento anterior para que el contexto sobreviva al límite.' }, + help: 'Longitud máxima de un pasaje, en caracteres, cuando el servicio de conocimiento divide un documento. Un tamaño fijado en la propia fuente tiene prioridad; el límite de entrada del modelo de embeddings puede reducirlo.' }, over_fetch: { label: 'Multiplicador de sobre-obtención', help: 'La búsqueda obtiene este múltiplo del número de resultados pedido, para que queden suficientes tras filtrarlos por los datos del documento.' }, enforce_rls: { label: 'Aplicar RLS en la búsqueda', diff --git a/packages/services/service-settings/src/translations/fr.ts b/packages/services/service-settings/src/translations/fr.ts index d39d320b4ec..420d54bc4c2 100644 --- a/packages/services/service-settings/src/translations/fr.ts +++ b/packages/services/service-settings/src/translations/fr.ts @@ -732,11 +732,7 @@ export const fr: PlatformTranslationData = { }, chunk_target: { label: 'Taille cible des morceaux (caractères)', - help: 'Plafond souple de taille des morceaux avant que le découpage par jetons n’intervienne.', - }, - chunk_overlap: { - label: 'Chevauchement des morceaux (caractères)', - help: 'Caractères repris du morceau précédent pour que le contexte franchisse la frontière.', + help: 'Longueur maximale d’un passage, en caractères, lorsque le service de connaissances découpe un document. Une taille fixée sur la source elle-même l’emporte ; la limite d’entrée du modèle d’embedding peut l’abaisser.', }, over_fetch: { label: 'Multiplicateur de sur-récupération', diff --git a/packages/services/service-settings/src/translations/ja-JP.ts b/packages/services/service-settings/src/translations/ja-JP.ts index d61f2e61127..bd218eb3c8e 100644 --- a/packages/services/service-settings/src/translations/ja-JP.ts +++ b/packages/services/service-settings/src/translations/ja-JP.ts @@ -577,9 +577,7 @@ export const jaJP: PlatformTranslationData = { ragflow_default_dataset: { label: 'デフォルトデータセット ID', help: 'ナレッジソースが独自の RAGFlow データセットを指定しない場合に使用されます。' }, chunk_target: { label: '目標チャンクサイズ(文字数)', - help: 'トークン単位の分割が行われる前のチャンクサイズのソフト上限。' }, - chunk_overlap: { label: 'チャンクの重なり(文字数)', - help: '境界を越えてコンテキストを維持するため、前のチャンクから保持する文字数。' }, + help: 'ナレッジサービスがドキュメントを分割するときの、パッセージ 1 件あたりの最大文字数。ナレッジソース自身に設定したサイズが優先され、埋め込みモデルの入力上限によって小さくなることがあります。' }, over_fetch: { label: 'オーバーフェッチ倍率', help: '検索では要求された件数のこの倍数の結果を取得し、ドキュメント情報で絞り込んだ後も十分な件数が残るようにします。' }, enforce_rls: { label: '検索時に RLS を強制', diff --git a/packages/services/service-settings/src/translations/ko.ts b/packages/services/service-settings/src/translations/ko.ts index 3f7c94ed01a..36c69b46541 100644 --- a/packages/services/service-settings/src/translations/ko.ts +++ b/packages/services/service-settings/src/translations/ko.ts @@ -545,8 +545,7 @@ export const ko: PlatformTranslationData = { ragflow_base_url: { label: 'Base URL', help: '예: http://localhost:9380' }, ragflow_api_key: { label: 'API 키' }, ragflow_default_dataset: { label: '기본 데이터 세트 ID', help: '지식 소스가 자체 RAGFlow 데이터 세트를 지정하지 않을 때 사용합니다.' }, - chunk_target: { label: '목표 청크 크기(자)', help: '토큰 기준 분할이 시작되기 전의 청크 크기 소프트 상한입니다.' }, - chunk_overlap: { label: '청크 겹침(자)', help: '경계를 넘어 문맥이 이어지도록 이전 청크에서 유지하는 문자 수입니다.' }, + chunk_target: { label: '목표 청크 크기(자)', help: '지식 서비스가 문서를 나눌 때 구절 하나의 최대 문자 수입니다. 지식 소스 자체에 설정한 크기가 우선하며, 임베딩 모델의 입력 한도에 따라 더 작아질 수 있습니다.' }, over_fetch: { label: '초과 조회 배수', help: '요청한 결과 수의 이 배수만큼 검색해, 문서 정보로 필터링한 뒤에도 돌려줄 결과가 충분히 남게 합니다.' }, enforce_rls: { label: '검색 시 RLS 적용', help: '호출자의 레코드 수준 권한으로 모든 결과를 다시 확인합니다.' }, }, diff --git a/packages/services/service-settings/src/translations/pt-BR.ts b/packages/services/service-settings/src/translations/pt-BR.ts index 64c57f378c2..7160b59d434 100644 --- a/packages/services/service-settings/src/translations/pt-BR.ts +++ b/packages/services/service-settings/src/translations/pt-BR.ts @@ -716,11 +716,7 @@ export const ptBR: PlatformTranslationData = { }, chunk_target: { label: 'Tamanho-alvo da parte (caracteres)', - help: 'Limite flexível do tamanho da parte antes de entrar a divisão por tokens.', - }, - chunk_overlap: { - label: 'Sobreposição das partes (caracteres)', - help: 'Caracteres mantidos da parte anterior para que o contexto atravesse o limite.', + help: 'Tamanho máximo de um trecho, em caracteres, quando o serviço de conhecimento divide um documento. Um tamanho definido na própria fonte tem prioridade; o limite de entrada do modelo de embeddings pode reduzi-lo.', }, over_fetch: { label: 'Multiplicador de busca extra', diff --git a/packages/services/service-settings/src/translations/ru.ts b/packages/services/service-settings/src/translations/ru.ts index 1579aff467d..5bb67b4f918 100644 --- a/packages/services/service-settings/src/translations/ru.ts +++ b/packages/services/service-settings/src/translations/ru.ts @@ -726,11 +726,7 @@ export const ru: PlatformTranslationData = { }, chunk_target: { label: 'Целевой размер фрагмента (символы)', - help: 'Мягкий предел размера фрагмента до начала разбиения с учётом токенов.', - }, - chunk_overlap: { - label: 'Перекрытие фрагментов (символы)', - help: 'Символы, сохраняемые из предыдущего фрагмента, чтобы контекст не терялся на границе.', + help: 'Наибольшая длина фрагмента в символах, когда служба знаний разбивает документ. Размер, заданный в самом источнике знаний, имеет приоритет; лимит ввода модели эмбеддингов может его уменьшить.', }, over_fetch: { label: 'Множитель избыточной выборки', diff --git a/packages/services/service-settings/src/translations/zh-CN.ts b/packages/services/service-settings/src/translations/zh-CN.ts index d7872bc0f17..9d8d26f5a08 100644 --- a/packages/services/service-settings/src/translations/zh-CN.ts +++ b/packages/services/service-settings/src/translations/zh-CN.ts @@ -600,8 +600,7 @@ export const zhCN: PlatformTranslationData = { ragflow_base_url: { label: 'Base URL', help: '示例:http://localhost:9380' }, ragflow_api_key: { label: 'API Key' }, ragflow_default_dataset: { label: '默认 Dataset ID', help: '知识源未指定自己的 RAGFlow 数据集时使用。' }, - chunk_target: { label: '目标 chunk 大小(字符)', help: '在按 token 切分之前的软上限。' }, - chunk_overlap: { label: 'Chunk 重叠(字符)', help: '保留上一个 chunk 末尾的字符,以保证跨界上下文。' }, + chunk_target: { label: '目标 chunk 大小(字符)', help: '知识服务切分文档时每个片段的最大字符数。知识源自身设置的大小优先;嵌入模型的输入上限可能将其调低。' }, over_fetch: { label: '过取倍数', help: '检索时按请求结果数的这一倍数取回候选,以便按文档信息过滤后仍有足够结果可返回。' }, enforce_rls: { label: '搜索时强制 RLS', help: '对每条命中再次校验调用方的行级权限。' }, }, diff --git a/packages/services/service-settings/src/translations/zh-Hant.ts b/packages/services/service-settings/src/translations/zh-Hant.ts index bd6e4998aef..e1f304bcb5f 100644 --- a/packages/services/service-settings/src/translations/zh-Hant.ts +++ b/packages/services/service-settings/src/translations/zh-Hant.ts @@ -484,8 +484,7 @@ export const zhHant: PlatformTranslationData = { ragflow_base_url: { label: 'Base URL', help: '範例:http://localhost:9380' }, ragflow_api_key: { label: 'API 金鑰' }, ragflow_default_dataset: { label: '預設資料集 ID', help: '知識來源未指定自己的 RAGFlow 資料集時使用。' }, - chunk_target: { label: '目標區塊大小(字元)', help: '在依 token 切分啟動前,區塊大小的軟性上限。' }, - chunk_overlap: { label: '區塊重疊(字元)', help: '從前一個區塊保留的字元數,讓上下文能跨越邊界。' }, + chunk_target: { label: '目標區塊大小(字元)', help: '知識服務切分文件時每個片段的最大字元數。知識來源自身設定的大小優先;嵌入模型的輸入上限可能將其調低。' }, over_fetch: { label: '超量擷取倍數', help: '搜尋時取回所要求結果數的這個倍數,以便依文件資訊篩選後仍有足夠結果可傳回。' }, enforce_rls: { label: '搜尋時強制套用 RLS', help: '依呼叫者的記錄層級權限重新檢查每一筆命中結果。' }, }, diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index c354fd6bd65..b1e8f597b32 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -120,6 +120,12 @@ "KnowledgeSourceKindSchema (const)", "KnowledgeSourceParsed (type)", "KnowledgeSourceSchema (const)", + "KnowledgeSplit (type)", + "KnowledgeSplitParsed (type)", + "KnowledgeSplitSchema (const)", + "KnowledgeSplitStrategy (type)", + "KnowledgeSplitStrategyParsed (type)", + "KnowledgeSplitStrategySchema (const)", "LIST_DATASETS_MAX_CANDIDATES_PER_TERM (const)", "LIST_DATASETS_TOOL_NAME (const)", "ListDatasetsInput (type)", diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index ab81d11b5f4..dbd0f4d45ea 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -34,7 +34,9 @@ "ActionConfirmationPending (interface)", "ActionConfirmationRefusalReason (type)", "ActionConfirmationRequiredDetails (interface)", + "AdapterCapabilities (interface)", "AdapterContext (interface)", + "AdapterEmbeddingDescriptor (interface)", "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index c21ad15359c..9a95264d4f6 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -242,9 +242,11 @@ "ai/ImageContent:type", "ai/KnowledgeChunk:content", "ai/KnowledgeChunk:documentId", + "ai/KnowledgeChunk:headingPath", "ai/KnowledgeChunk:id", "ai/KnowledgeChunk:index", - "ai/KnowledgeChunk:metadata", + "ai/KnowledgeChunk:metadata [RETIRED]", + "ai/KnowledgeDocument:chunks", "ai/KnowledgeDocument:content", "ai/KnowledgeDocument:docHash", "ai/KnowledgeDocument:id", @@ -274,6 +276,9 @@ "ai/KnowledgeSource:refresh", "ai/KnowledgeSource:source", "ai/KnowledgeSource:vectorStore", + "ai/KnowledgeSplit:maxChars", + "ai/KnowledgeSplit:minChars", + "ai/KnowledgeSplit:strategy", "ai/ListDatasetsInput:terms", "ai/ListDatasetsOutput:candidates", "ai/ListDatasetsOutput:datasets", @@ -349,6 +354,7 @@ "ai/ObjectKnowledgeSource:kind", "ai/ObjectKnowledgeSource:metadataFields", "ai/ObjectKnowledgeSource:object", + "ai/ObjectKnowledgeSource:split", "ai/ObjectKnowledgeSource:where", "ai/ObjectQuerySource:aggregations", "ai/ObjectQuerySource:filter", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 37d323406eb..daf9026fe92 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -91,6 +91,10 @@ "KnowledgeSourceKind": "ai/KnowledgeSourceKind", "KnowledgeSourceKindSchema": "ai/KnowledgeSourceKind", "KnowledgeSourceSchema": "ai/KnowledgeSource", + "KnowledgeSplit": "ai/KnowledgeSplit", + "KnowledgeSplitSchema": "ai/KnowledgeSplit", + "KnowledgeSplitStrategy": "ai/KnowledgeSplitStrategy", + "KnowledgeSplitStrategySchema": "ai/KnowledgeSplitStrategy", "ListDatasetsInput": "ai/ListDatasetsInput", "ListDatasetsInputSchema": "ai/ListDatasetsInput", "ListDatasetsOutput": "ai/ListDatasetsOutput", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 89026a3c44b..6b68edc2b70 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -118,6 +118,12 @@ "KnowledgeSourceKindSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceKindSchema (const)", "KnowledgeSourceParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSourceParsed (type)", "KnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema (const)", + "KnowledgeSplit": "src/ai/knowledge-source.zod.ts#KnowledgeSplit (type)", + "KnowledgeSplitParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSplitParsed (type)", + "KnowledgeSplitSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSplitSchema (const)", + "KnowledgeSplitStrategy": "src/ai/knowledge-source.zod.ts#KnowledgeSplitStrategy (type)", + "KnowledgeSplitStrategyParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSplitStrategyParsed (type)", + "KnowledgeSplitStrategySchema": "src/ai/knowledge-source.zod.ts#KnowledgeSplitStrategySchema (const)", "LIST_DATASETS_MAX_CANDIDATES_PER_TERM": "src/ai/dataset-tools.zod.ts#LIST_DATASETS_MAX_CANDIDATES_PER_TERM (const)", "LIST_DATASETS_TOOL_NAME": "src/ai/dataset-tools.zod.ts#LIST_DATASETS_TOOL_NAME (const)", "ListDatasetsInput": "src/ai/dataset-tools.zod.ts#ListDatasetsInput (type)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 8e01e4ac6bb..a95aa66d464 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -34,7 +34,9 @@ "ActionConfirmationPending": "src/contracts/ai-service.ts#ActionConfirmationPending (interface)", "ActionConfirmationRefusalReason": "src/contracts/ai-service.ts#ActionConfirmationRefusalReason (type)", "ActionConfirmationRequiredDetails": "src/contracts/ai-service.ts#ActionConfirmationRequiredDetails (interface)", + "AdapterCapabilities": "src/contracts/knowledge-adapter.ts#AdapterCapabilities (interface)", "AdapterContext": "src/contracts/knowledge-adapter.ts#AdapterContext (interface)", + "AdapterEmbeddingDescriptor": "src/contracts/knowledge-adapter.ts#AdapterEmbeddingDescriptor (interface)", "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 07ac8aac993..3cca2214894 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -49,6 +49,8 @@ "ai/KnowledgeRefreshPolicy", "ai/KnowledgeSource", "ai/KnowledgeSourceKind", + "ai/KnowledgeSplit", + "ai/KnowledgeSplitStrategy", "ai/ListDatasetsInput", "ai/ListDatasetsOutput", "ai/MCPApprovalPolicy", diff --git a/packages/spec/src/ai/knowledge-document.test.ts b/packages/spec/src/ai/knowledge-document.test.ts new file mode 100644 index 00000000000..7f576dea089 --- /dev/null +++ b/packages/spec/src/ai/knowledge-document.test.ts @@ -0,0 +1,28 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { KnowledgeChunkSchema, KnowledgeDocumentSchema, type KnowledgeChunk } from './knowledge-document.zod'; + +const chunk = { id: 'kb:r1#0', documentId: 'kb:r1', index: 0, content: 'passage text' }; + +describe('KnowledgeChunk.metadata — retired (ADR-0049; ADR-0161 K8 item 5)', () => { + it('authoring it is refused at parse with the prescription', () => { + expect(() => KnowledgeChunkSchema.parse({ ...chunk, metadata: { status: 'published' } })) + .toThrow(/`KnowledgeChunk\.metadata` was removed.*Delete the key.*KnowledgeDocument\.metadata/s); + expect(() => KnowledgeDocumentSchema.parse({ + id: 'kb:r1', sourceId: 'kb', content: 'passage text', chunks: [{ ...chunk, metadata: {} }], + })).toThrow(/`KnowledgeChunk\.metadata` was removed/); + }); + + it('a chunk without it parses, and carries no metadata', () => { + const parsed = KnowledgeChunkSchema.parse({ ...chunk, headingPath: ['Policy', 'Travel'] }); + expect(parsed).not.toHaveProperty('metadata'); + expect(parsed).toEqual({ ...chunk, headingPath: ['Policy', 'Travel'] }); + }); + + it('authoring it is a type error', () => { + // @ts-expect-error — the retired key's input type is `never`. + const literal: KnowledgeChunk = { ...chunk, metadata: { status: 'published' } }; + expect(literal.id).toBe('kb:r1#0'); + }); +}); diff --git a/packages/spec/src/ai/knowledge-document.zod.ts b/packages/spec/src/ai/knowledge-document.zod.ts index c83d3aac22e..4fca15827da 100644 --- a/packages/spec/src/ai/knowledge-document.zod.ts +++ b/packages/spec/src/ai/knowledge-document.zod.ts @@ -2,19 +2,69 @@ import { z } from 'zod'; import { lazySchema } from '../shared/lazy-schema'; +import { retiredKey } from '../shared/retired-key'; /** * Knowledge Document / Chunk / Hit — canonical shapes shared by every * `IKnowledgeAdapter` implementation. * - * The framework does **not** prescribe chunk strategy or vector - * format. Adapters are free to chunk however they like; the framework - * only requires they round-trip these shapes when talking to the - * `IKnowledgeService`. + * The knowledge service owns the structural split (ADR-0161 K1): it cuts a + * document into passages once, by the source's `split` key, and hands the + * passages to every adapter that declares `capabilities.chunks` as the + * document's `chunks`. An adapter that does not declare it receives whole + * documents and splits them itself. The framework never sees a vector. * * See `content/docs/protocol/knowledge.mdx` for the full design. */ +/** + * One passage of a document, cut by the knowledge service's splitter + * (ADR-0161 K8, item 5) and handed to an adapter that declares + * `capabilities.chunks`, as `KnowledgeDocument.chunks`. The adapter embeds and + * stores each chunk's `content` as given; it does not split a chunk again. + */ +export const KnowledgeChunkSchema = lazySchema(() => z.object({ + /** + * Chunk id, set by the service to `${documentId}#${index}`, so a hit's + * `chunkId` is the same on every adapter. + */ + id: z.string(), + /** Owning document. */ + documentId: z.string(), + /** Index within the document (0-based). */ + index: z.number().int().nonnegative(), + /** + * Chunk text: the text the adapter embeds and returns as a snippet. Under + * the `markdown` strategy it begins with the chunk's heading path. + */ + content: z.string(), + /** + * The headings the chunk sits under, outermost first (the `markdown` + * strategy). Absent when the strategy reads no headings. + */ + headingPath: z.array(z.string()).optional() + .describe('Headings the chunk sits under, outermost first (markdown strategy)'), + /** + * Tombstoned, not deleted: `KnowledgeChunkSchema` is not `.strict()`, so a + * plain deletion would let a caller keep writing `metadata`, parse clean and + * lose the value in silence. `retiredKey()` turns that into a rejection + * carrying the fix, in both channels an author meets: `tsc` (the input type + * is `never`) and the parse. + * + * Retired under ADR-0049 enforce-or-remove, as ADR-0161 K8 item 5 asks of + * #37098: the key had no producer and no reader. The service's splitter + * never sets per-passage metadata, and no adapter read one — a passage's + * metadata is its document's `metadata`, which every adapter already stores + * beside each passage. + */ + metadata: retiredKey( + '`KnowledgeChunk.metadata` was removed in @objectstack/spec 18 (ADR-0049, ADR-0161 K8) — ' + + 'nothing ever wrote or read it: the knowledge service cuts the passages and sets no ' + + 'per-passage metadata, and no adapter consulted one. Delete the key. A passage takes its ' + + "document's `metadata` (`KnowledgeDocument.metadata`), which is what adapters filter on.", + ), +})); + /** * One logical document submitted to an adapter for indexing. * @@ -76,24 +126,15 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ */ docHash: z.string().optional() .describe('Service-computed hash of the assembled document (content, title, metadata, and organizationId when set); stored and returned as stored by the adapter'), -})); - -/** - * Adapter-produced chunk of a document. The framework never sees the - * vector — only the chunk text + metadata. Used for upserts that - * pre-chunk on the caller side (rare; most adapters chunk internally). - */ -export const KnowledgeChunkSchema = lazySchema(() => z.object({ - /** Chunk id (typically `${documentId}#${index}`). */ - id: z.string(), - /** Owning document. */ - documentId: z.string(), - /** Index within the document (0-based). */ - index: z.number().int().nonnegative(), - /** Chunk text. */ - content: z.string(), - /** Optional metadata override (falls back to the document's). */ - metadata: z.record(z.string(), z.unknown()).optional(), + /** + * The document's passages, cut by the knowledge service's splitter + * (ADR-0161 K8, item 5). Set by the service, and only on a document handed + * to an adapter that declares `capabilities.chunks`; a caller-supplied value + * is refused by `indexDocument`. Derived from `content`, so it is not part + * of `docHash`. An adapter that receives it indexes these passages as given. + */ + chunks: z.array(KnowledgeChunkSchema).optional() + .describe('Service-cut passages of the document, handed to an adapter that declares capabilities.chunks'), })); /** diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index afaebc08242..f299a92bbf0 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -55,6 +55,49 @@ export const KnowledgeRefreshPolicySchema = lazySchema(() => z.object({ ), })); +/** The split strategies of the knowledge service's splitter (ADR-0161 K8, item 10). */ +export const KnowledgeSplitStrategySchema = lazySchema(() => z.enum(['whole', 'recursive', 'markdown'])); + +/** + * How the knowledge service cuts this source's documents into passages + * (ADR-0161 K8, item 10). Read by the service's splitter, which hands the + * passages to an adapter that declares `capabilities.chunks`; an adapter + * that does not declare it receives whole documents and this key does not + * apply to it. + * + * - `whole` — one passage per document. A document whose token estimate is + * over the embedder's input budget is removed from the index and reported, + * never truncated. + * - `recursive` — cut at blank lines, then line breaks, then sentence ends + * (`。?!`, and `. ? !` only before whitespace or the end of the text), then + * semicolons, then characters, never inside a Markdown table or list item + * while it fits; adjacent short pieces are merged up to `minChars`. + * - `markdown` — one section per heading; each passage carries its heading + * path, which counts toward its length and is embedded with it. + * + * The effective `maxChars` is the smaller of this value (or the settings + * page's `knowledge.chunk_target`, or 800) and what fits in 80% of the + * embedder's input limit by the shared token estimate. + */ +export const KnowledgeSplitSchema = lazySchema(() => z.object({ + /** Which splitter strategy cuts the documents. */ + strategy: KnowledgeSplitStrategySchema.describe('Split strategy: whole, recursive or markdown'), + /** + * Longest passage, in characters. Wins over the settings page's + * `knowledge.chunk_target`; the embedder's input limit can lower it. + * Not read by `whole`. + */ + maxChars: z.number().int().positive().optional() + .describe('Longest passage in characters; wins over the settings default, the embedder limit can lower it'), + /** + * Adjacent pieces shorter than this are merged, up to this length + * (`recursive` and `markdown`). A value above the effective `maxChars` + * reads as `maxChars`. @default 200 + */ + minChars: z.number().int().nonnegative().optional() + .describe('Adjacent pieces shorter than this are merged up to it (default 200); a value above the effective maxChars reads as maxChars'), +})); + /** Source backed by an ObjectQL object — each record becomes a document. */ export const ObjectKnowledgeSourceSchema = lazySchema(() => z.object({ kind: z.literal('object'), @@ -75,6 +118,13 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => z.object({ * Uses ObjectQL `where` syntax. */ where: z.record(z.string(), z.unknown()).optional(), + /** + * How the knowledge service cuts this object's documents into passages + * ({@link KnowledgeSplitSchema}). Omitted ⇒ `recursive` with the settings + * page's `knowledge.chunk_target` (or 800) as `maxChars`. + */ + split: KnowledgeSplitSchema.optional() + .describe('How the service cuts this object\'s documents into passages; omitted means recursive'), })); /** Source backed by a folder in `IStorageService`. */ @@ -163,6 +213,12 @@ export const KnowledgeSourceSchema = lazySchema(() => z.object({ export type KnowledgeRefreshPolicy = z.input; /** Post-parse shape of {@link KnowledgeRefreshPolicy} — defaults applied, transforms run (ADR-0122): `cron` is the `{ dialect: 'cron', source }` envelope. */ export type KnowledgeRefreshPolicyParsed = z.infer; +export type KnowledgeSplitStrategy = z.input; +/** Post-parse shape of {@link KnowledgeSplitStrategy} (ADR-0122). */ +export type KnowledgeSplitStrategyParsed = z.infer; +export type KnowledgeSplit = z.input; +/** Post-parse shape of {@link KnowledgeSplit} (ADR-0122). */ +export type KnowledgeSplitParsed = z.infer; export type ObjectKnowledgeSource = z.input; export type FileKnowledgeSource = z.input; export type HttpKnowledgeSource = z.input; diff --git a/packages/spec/src/contracts/embedder.ts b/packages/spec/src/contracts/embedder.ts index a5d4e00ea93..0d3e9c7d308 100644 --- a/packages/spec/src/contracts/embedder.ts +++ b/packages/spec/src/contracts/embedder.ts @@ -31,6 +31,14 @@ export interface IEmbedder { * their fixed-width vector columns / index parameters. */ readonly dimensions: number; + /** + * Longest single input the model accepts, in tokens, as measured by the + * shared `estimateTokens` (`@objectstack/spec/shared`). Absent when the + * embedder knows no limit. A knowledge adapter reports it to the knowledge + * service (`IKnowledgeAdapter.embedding.maxInputTokens`), whose splitter + * keeps every passage within it (ADR-0161 K8, item 6). + */ + readonly maxInputTokens?: number; /** * Embed a batch of strings. Output order matches input order. * Implementations SHOULD handle empty input by returning `[]`. diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index a50365d5e8f..58fdd6683f9 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -15,9 +15,11 @@ import type { KnowledgeSource } from '../ai/knowledge-source.zod'; * registered with the host's `IKnowledgeService` via * `registerAdapter(id, this)` during the plugin's `start()` hook. * - * The surface is **deliberately minimal**: no chunk strategy, no - * embedding configuration, no rerank toggles. Adapters that need - * extra knobs expose them via their plugin options object. + * The contract carries what an adapter REPORTS, never how it is configured + * (ADR-0161 K8, rule 4): no embedding configuration, no rerank toggles. + * Adapters that need extra knobs expose them via their plugin options + * object. The split belongs to the service (ADR-0161 K1): an adapter that + * declares `capabilities.chunks` receives the service's passages. * * See `content/docs/protocol/knowledge.mdx`. */ @@ -106,6 +108,40 @@ export interface AdapterListDocumentsPage { nextCursor?: string; } +/** + * What an adapter declares it accepts beyond whole documents (ADR-0161 K8, + * item 5). A method that is absent is the capability signal for everything + * else; this covers what a method cannot say. + */ +export interface AdapterCapabilities { + /** + * `true`: the adapter accepts the service's passages. Every document the + * service hands it carries `chunks`, cut once by the service's splitter, + * and the adapter indexes those passages as given — it does not split + * them again. Absent or `false`: it receives whole documents, without + * `chunks`, and splits them itself. + */ + chunks?: boolean; +} + +/** + * What an adapter reports about the embedder it calls (ADR-0161 K8, item 6). + * A report, not configuration. The service reads it each time it needs it + * and never keeps an answer taken during `init`, because the embedder may + * register later — so an adapter that resolves its embedder late serves it + * from a getter. + */ +export interface AdapterEmbeddingDescriptor { + /** + * Longest single input the adapter's embedder accepts, in tokens + * (`IEmbedder.maxInputTokens`). The service's splitter keeps every passage + * within 80% of it by the shared `estimateTokens`, and removes and reports + * a `whole` document over that budget. Absent: no limit is known, and none + * is checked. + */ + maxInputTokens?: number; +} + /** * Plugin-implemented adapter. **One per backend**. Stateless across * source ids — the source is supplied per-call. @@ -120,6 +156,18 @@ export interface IKnowledgeAdapter { /** Stable adapter id used in `KnowledgeSource.adapter`. */ readonly id: string; + /** + * What the adapter accepts beyond whole documents (ADR-0161 K8, item 5). + * Absent: whole documents only. + */ + readonly capabilities?: AdapterCapabilities; + + /** + * What the adapter reports about the embedder it calls (ADR-0161 K8, + * item 6). Read by the service at use, never cached from `init`. + */ + readonly embedding?: AdapterEmbeddingDescriptor; + /** Insert or replace documents in the adapter's backend. */ upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise; diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index 8cf3a874c72..92d21e084d8 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -82,6 +82,19 @@ export interface KnowledgeReindexResult { * implementation that predates the field. */ purged?: number | null; + /** + * Documents removed from the index instead of written, because they cannot + * be indexed as the source's split asks — today a `whole` document whose + * token estimate is over the embedder's input budget, which is never + * truncated. `0` when none was. Absent from a result of an implementation + * that predates the field. + */ + failed?: number; + /** + * Which documents those were and why, in walk order, bounded by the + * service (`failed` counts them all). Absent when `failed` is absent. + */ + failures?: Array<{ documentId: string; reason: string }>; } /** diff --git a/packages/spec/src/migrations/entries/retired-keys/18.ai__KnowledgeChunk__metadata.ts b/packages/spec/src/migrations/entries/retired-keys/18.ai__KnowledgeChunk__metadata.ts new file mode 100644 index 00000000000..48fa1d5c9f7 --- /dev/null +++ b/packages/spec/src/migrations/entries/retired-keys/18.ai__KnowledgeChunk__metadata.ts @@ -0,0 +1,10 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// #37098 — ADR-0049 enforce-or-remove, as ADR-0161 K8 item 5 asks of the +// splitter card: `KnowledgeChunk.metadata` had no producer and no reader. A +// chunk is a runtime contract shape the knowledge service hands an adapter, +// never stored in stack metadata, so the D2 side is a D3 `SemanticMigration` +// (`knowledge-chunk-metadata-retired`) rather than a MetadataConversion — +// there is no stored source for `os migrate meta` to rewrite. The +// `ActionDescriptor.isAsync` precedent. +export const entry = 'ai/KnowledgeChunk:metadata'; diff --git a/packages/spec/src/migrations/entries/semantic/18.knowledge-chunk-metadata-retired.ts b/packages/spec/src/migrations/entries/semantic/18.knowledge-chunk-metadata-retired.ts new file mode 100644 index 00000000000..37d523ac9fb --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.knowledge-chunk-metadata-retired.ts @@ -0,0 +1,27 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +export const entry: SemanticMigration = { + id: 'knowledge-chunk-metadata-retired', + surface: 'KnowledgeChunk.metadata (a passage the knowledge service hands an adapter in `KnowledgeDocument.chunks`)', + replacement: + 'nothing to re-declare — delete the key. A passage takes its document\'s `metadata` ' + + '(`KnowledgeDocument.metadata`), which every adapter stores beside each passage and filters on', + reason: + 'ADR-0049 enforce-or-remove, as ADR-0161 K8 item 5 asks of the splitter: the key had no ' + + 'producer and no reader. The knowledge service cuts every passage and sets no per-passage ' + + 'metadata, and no adapter in the platform read one, so a value written there was stripped in ' + + 'silence and never reached a filter. Why D3 semantic and not a D2 conversion: a chunk is a ' + + 'runtime contract shape — built by the service and by tests, never stored in stack metadata — ' + + 'so there is no source for the chain to rewrite and `os migrate meta` cannot reach it. The ' + + 'schema tombstones it via `retiredKey()`; the rejection (a `tsc` error at the literal and a ' + + 'parse error) is the channel an adapter or test author actually meets. The ' + + '`ActionDescriptor.isAsync` disposition.', + acceptanceCriteria: + 'No `KnowledgeChunk` literal — in an adapter, a test or a fixture — writes `metadata`. An adapter ' + + 'that filtered on per-passage metadata now filters on the document\'s `metadata` and returns the ' + + 'same hits, since no producer ever set a different value per passage. Authoring the key fails ' + + '`tsc` at the literal and fails `KnowledgeChunkSchema.parse()` with the prescription, instead of ' + + 'parsing clean and being stripped.', +}; diff --git a/packages/spec/src/migrations/registry.ts.template b/packages/spec/src/migrations/registry.ts.template index 2a82c15190e..0391d95ac2b 100644 --- a/packages/spec/src/migrations/registry.ts.template +++ b/packages/spec/src/migrations/registry.ts.template @@ -2255,6 +2255,17 @@ const STEP18_RATIONALE: readonly RationaleFragment[] = [ + '`PackageUpgradeResponse`. The `UpgradePlan.estimatedDuration` tombstone leaves with its ' + 'def\'s source and its RETIRED_KEYS_BY_MAJOR[18] entry stays as history.', }, + { + id: 'knowledge-chunk-metadata-retired', + order: 125, + text: + 'It removes `metadata` from the knowledge chunk (ADR-0049 enforce-or-remove), as ADR-0161 ' + + 'K8 item 5 asks of the splitter that gives the chunk its first producer: the service cuts ' + + 'every passage and sets no per-passage metadata, no adapter read one, and a passage takes its ' + + 'document\'s `metadata`. A chunk is a runtime contract shape, never stored in stack metadata, ' + + 'so there is no D2 conversion; the schema tombstones the key, and its D3 record is the ' + + 'semantic entry `knowledge-chunk-metadata-retired`.', + }, { id: 'list-view-filterable-fields-retired', order: 105,