From 749d0ea0a8b90a0c077324b2682cabb1afe35b4d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:15:42 +0000 Subject: [PATCH 1/8] feat(core): one sliding-window keywordTerms copy for the knowledge adapters and the segmenter Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- packages/core/src/index.ts | 3 + packages/core/src/keyword-terms.test.ts | 72 +++++++ packages/core/src/keyword-terms.ts | 97 +++++++++ packages/services/service-segmenter/LICENSE | 202 ++++++++++++++++++ .../services/service-segmenter/package.json | 66 ++++++ pnpm-lock.yaml | 165 ++++++++++++++ 6 files changed, 605 insertions(+) create mode 100644 packages/core/src/keyword-terms.test.ts create mode 100644 packages/core/src/keyword-terms.ts create mode 100644 packages/services/service-segmenter/LICENSE create mode 100644 packages/services/service-segmenter/package.json diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e303192e7be..082ceed1379 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -63,6 +63,9 @@ export * from './organization-locale.js'; // the dataset tools (`@objectstack/service-analytics`) and the MCP record // tools (`@objectstack/mcp`), which cannot import each other. export * from './sentence-locale.js'; +// The keyword leg's sliding-window terms: one copy for the two knowledge +// adapters and `@objectstack/service-segmenter`, which cannot import each other. +export * from './keyword-terms.js'; export * from './caller-identity.js'; // [ADR-0160 D3] The one envelope a record-material tool answer is built in // (`get_record_context`, `@objectstack/service-record-context`). diff --git a/packages/core/src/keyword-terms.test.ts b/packages/core/src/keyword-terms.test.ts new file mode 100644 index 00000000000..c9844e99944 --- /dev/null +++ b/packages/core/src/keyword-terms.test.ts @@ -0,0 +1,72 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The keyword leg's sliding-window terms, the one copy: the cases the two +// knowledge adapters pin against their own copies, ported unchanged, so the +// three bodies are held to one answer until step 2 removes the adapters'. + +import { describe, expect, it } from 'vitest'; +import { KEYWORD_SEPARATORS, MAX_KEYWORD_TERMS, keywordTerms } from './keyword-terms.js'; + +describe('keywordTerms (sliding windows)', () => { + it('splits a query into terms at white space and punctuation, keeping a code whole', () => { + // Latin-script and spaced terms: the terms they always had. + expect(keywordTerms('What is the X-200 pump? v1.2, a/b; #tag (part 7731)')).toEqual([ + 'What', 'is', 'the', 'X-200', 'pump', 'v1.2', 'a/b', 'tag', 'part', '7731', + ]); + expect(keywordTerms('出差 住宿')).toEqual(['出差', '住宿']); + expect(keywordTerms('pump PUMP Pump')).toEqual(['pump']); + expect(keywordTerms(Array.from({ length: 40 }, (_, i) => `w${i}`).join(' '))).toHaveLength(MAX_KEYWORD_TERMS); + expect(MAX_KEYWORD_TERMS).toBe(16); + expect(keywordTerms('?! …')).toEqual([]); + }); + + it('cuts a run of Han, kana or Hangul into pieces of three characters and of two, keeping figures and codes whole', () => { + // An unspaced question: its figure, then the pieces of three, then those of two, up to the cap. + expect(keywordTerms('出差住宿费2000元以下需要审批吗')).toEqual([ + '2000', '出差住', '差住宿', '住宿费', '元以下', '以下需', '下需要', '需要审', '要审批', '审批吗', + '出差', '差住', '住宿', '宿费', '元以', '以下', + ]); + expect(keywordTerms('X-200型号的保修期')).toEqual([ + 'X-200', '型号的', '号的保', '的保修', '保修期', '型号', '号的', '的保', '保修', '修期', + ]); + // A run of two is one piece, kept with the pieces of three; a run of one is dropped; a repeat counts once. + expect(keywordTerms('出差的住宿标准,「三十天」。出差')).toEqual([ + '出差的', '差的住', '的住宿', '住宿标', '宿标准', '三十天', '出差', '差的', '的住', '住宿', '宿标', '标准', '三十', '十天', + ]); + expect(keywordTerms('费 2000元')).toEqual(['2000']); + // Katakana with its prolonged sound mark, which belongs to no script, and Hangul. + expect(keywordTerms('コーヒー代')).toEqual(['コーヒ', 'ーヒー', 'ヒー代', 'コー', 'ーヒ', 'ヒー', 'ー代']); + expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']); + }); + + it('keeps 々, 〆 and 〇 inside a run, and still splits at 、 and 。', () => { + // The three marks sit in the CJK symbols block, beside its punctuation. + expect(keywordTerms('人々')).toEqual(['人々']); + expect(keywordTerms('二〇二四年')).toEqual(['二〇二', '〇二四', '二四年', '二〇', '〇二', '二四', '四年']); + expect(keywordTerms('〆切日')).toEqual(['〆切日', '〆切', '切日']); + expect(keywordTerms('出差、住宿。审批')).toEqual(['出差', '住宿', '审批']); + }); + + it('splits at the punctuation of the CJK symbols block and at none of its letters or numbers', () => { + // Derived from the runtime's own Unicode tables, not from a list: a member of + // U+3000–303F separates terms exactly when it is neither a letter nor a number. + const block = Array.from({ length: 0x40 }, (_, i) => String.fromCodePoint(0x3000 + i)); + const letterOrNumber = (c: string): boolean => /[\p{L}\p{N}]/u.test(c); + const separates = (c: string): boolean => `a${c}b`.split(KEYWORD_SEPARATORS).length === 2; + expect(block.filter(separates)).toEqual(block.filter((c) => !letterOrNumber(c))); + const letters = block.filter(letterOrNumber); + expect(letters).toEqual(expect.arrayContaining(['々', '〆', '〇', '〡', '〩', '〱', '〵', '〸', '〺', '〻', '〼'])); + // Each of them, three in a row, is a term or yields pieces: none is dropped as punctuation. + for (const c of letters) expect(keywordTerms(c.repeat(3)).join('')).toContain(c); + // The vertical iteration mark and the Hangzhou numerals are Han: they stay inside a run. + expect(keywordTerms('人〻')).toEqual(['人〻']); + expect(keywordTerms('第〢〣号')).toEqual(['第〢〣', '〢〣号', '第〢', '〢〣', '〣号']); + // 、, 。 and the corner brackets still separate. + expect(keywordTerms('出差、住宿。「审批」')).toEqual(['出差', '住宿', '审批']); + }); + + it('splits with the same class as the libSQL and PostgreSQL stores', () => { + // Both stores' tests pin the same literal against their own classes: keep the three pins, and so the three classes, identical. + expect(KEYWORD_SEPARATORS).toEqual(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%& -〄〈-〠〪-〰〶〷〽-〿!-/:-@[-`{-・‘-‟…]+/u); + }); +}); diff --git a/packages/core/src/keyword-terms.ts b/packages/core/src/keyword-terms.ts new file mode 100644 index 00000000000..4935b7d1890 --- /dev/null +++ b/packages/core/src/keyword-terms.ts @@ -0,0 +1,97 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The keyword leg's terms of a question, by sliding windows — the one copy. + * + * Moved verbatim, with its constants, from `@objectstack/knowledge-turso`'s + * `sql.ts`; `@objectstack/knowledge-pgvector`'s `sql.ts` holds an identical + * body. Here because its readers sit in packages that cannot import each + * other: the two knowledge adapters, and `@objectstack/service-segmenter`, + * which cuts a Han run into dictionary words and answers with this rule for + * every other run, and for a Han run as well when its dictionary segmenter is + * not installed or failed to load. A caller that finds no `segmenter` service + * registered answers with this function too. The two adapter copies are + * removed when the adapters read the segmenter service (objectstack#38710, + * step 2); until then the three bodies are equal, and their tests pin the + * same cases. + */ + +/** + * The most terms of one query the keyword leg matches; the rest are left to the + * vector leg. Kept at 16 for pieces, by measurement on a table of about 67,000 + * passages and over 200 unspaced Chinese questions: each piece of two + * characters is a scan of the rows in scope, so a higher cap bought about one + * point of recall for each further 40% of latency. + */ +export const MAX_KEYWORD_TERMS = 16; + +/** + * A run of characters written without spaces between words: Han, Hiragana, + * Katakana (with the prolonged sound mark, which belongs to no script) and + * Hangul, and the three marks written inside a word in the CJK symbols block, + * 々 (U+3005), 〆 (U+3006) and 〇 (U+3007), named whatever their script (〆 + * belongs to none). + */ +export const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}々-〇ーー]+/gu; + +/** + * Where the keyword leg splits a query into terms: white space, punctuation + * that never sits inside a code (see {@link keywordTerms}), the general + * punctuation quotes and the ellipsis, the punctuation of the fullwidth forms, + * and the members of the CJK symbols block (U+3000–303F) that are neither a + * letter nor a number (`\p{L}`, `\p{N}`): 、, 。, the brackets, the tone marks. + * The block's letters and numbers stay inside a term: 々, 〆, 〇, 〻, the kana + * repeat marks 〱–〵, 〼 and the Hangzhou numerals 〡–〩 and 〸–〺. + * The same class as the libSQL and PostgreSQL stores'. + */ +export const KEYWORD_SEPARATORS = /[\s,;:!?()[\]{}<>"'`|\\=*~^$%& -〄〈-〠〪-〰〶〷〽-〿!-/:-@[-`{-・‘-‟…]+/u; + +/** + * The terms of a query for the keyword leg: split at white space and at + * punctuation that never sits inside a code (a hyphen, a dot, a slash, an + * underscore, `#`, `@` and `+` stay inside one, so `X-200`, `v1.2` and + * `a/b` are each one term), stripped of what is not a letter or a digit at + * either end, compared case-insensitively, at most {@link MAX_KEYWORD_TERMS}. + * + * A run of Han, kana or Hangul inside a term (an unspaced question is one + * such run, or a few) is cut into overlapping pieces of three characters and + * of two; a run of two characters is one piece, a run of one is dropped (it + * would match nearly every passage). What surrounds a run in the term, a + * figure or a code (`2000`, `X-200`), is a term of its own, whole. Under the + * cap, the terms come in this order, each kind in query order: the figures, + * codes and words, then the pieces of three characters and the runs of two, + * then the pieces of two characters, so a long question keeps the pieces an + * index serves and a short one fills the cap with pieces of two. + */ +export function keywordTerms(query: string): string[] { + const words: string[] = []; + const longer: string[] = []; + const pairs: string[] = []; + const word = (text: string): void => { + const stripped = text.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); + if (stripped !== '') words.push(stripped); + }; + for (const term of query.split(KEYWORD_SEPARATORS)) { + let at = 0; + for (const run of term.matchAll(UNSEGMENTED_RUN)) { + word(term.slice(at, run.index)); + at = run.index + run[0].length; + const chars = [...run[0]]; + if (chars.length === 2) longer.push(run[0]); + if (chars.length < 3) continue; + for (let i = 0; i + 2 < chars.length; i++) longer.push(chars[i] + chars[i + 1] + chars[i + 2]); + for (let i = 0; i + 1 < chars.length; i++) pairs.push(chars[i] + chars[i + 1]); + } + word(term.slice(at)); + } + const seen = new Set(); + const terms: string[] = []; + for (const term of [...words, ...longer, ...pairs]) { + const key = term.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + terms.push(term); + if (terms.length === MAX_KEYWORD_TERMS) break; + } + return terms; +} diff --git a/packages/services/service-segmenter/LICENSE b/packages/services/service-segmenter/LICENSE new file mode 100644 index 00000000000..16bc23f4043 --- /dev/null +++ b/packages/services/service-segmenter/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, + in at least one of the following places: within a NOTICE + text file distributed as part of the Derivative Works; within + the Source form or documentation, if provided along with + the Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the + License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 ObjectStack + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/services/service-segmenter/package.json b/packages/services/service-segmenter/package.json new file mode 100644 index 00000000000..082fd11f291 --- /dev/null +++ b/packages/services/service-segmenter/package.json @@ -0,0 +1,66 @@ +{ + "name": "@objectstack/service-segmenter", + "version": "19.0.0-next.2", + "license": "Apache-2.0", + "description": "Segmenter Service for ObjectStack — implements ISegmenterService: the keyword terms of a question, cut into real words by a dictionary segmenter", + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "sideEffects": false, + "exports": { + ".": { + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + } + }, + "scripts": { + "build": "tsup && node ../../../scripts/check-dts-emitted.mjs", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@objectstack/core": "workspace:*", + "@objectstack/spec": "workspace:*" + }, + "optionalDependencies": { + "@node-rs/jieba": "2.0.4" + }, + "devDependencies": { + "@types/node": "^26.6.5", + "typescript": "^6.0.3", + "vitest": "^4.1.11" + }, + "keywords": [ + "objectstack", + "service", + "segmenter", + "jieba", + "chinese", + "search" + ], + "author": "ObjectStack", + "repository": { + "type": "git", + "url": "git+https://github.com/objectstack-ai/objectstack.git", + "directory": "packages/services/service-segmenter" + }, + "homepage": "https://objectstack.ai/docs", + "bugs": "https://github.com/objectstack-ai/objectstack/issues", + "publishConfig": { + "access": "public" + }, + "files": [ + "dist", + "README.md", + "CHANGELOG.md" + ], + "engines": { + "node": ">=22.0.0" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b269576de98..d74ae595c84 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3527,6 +3527,29 @@ importers: specifier: ^4.1.11 version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1)) + packages/services/service-segmenter: + dependencies: + '@objectstack/core': + specifier: workspace:* + version: link:../../core + '@objectstack/spec': + specifier: workspace:* + version: link:../../spec + devDependencies: + '@types/node': + specifier: ^26.6.5 + version: 26.6.5 + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vitest: + specifier: ^4.1.11 + version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1)) + optionalDependencies: + '@node-rs/jieba': + specifier: 2.0.4 + version: 2.0.4 + packages/services/service-settings: dependencies: '@noble/ciphers': @@ -7880,6 +7903,92 @@ packages: '@nodable/entities@3.1.0': resolution: {integrity: sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==} + '@node-rs/jieba-android-arm-eabi@2.0.4': + resolution: {integrity: sha512-cQkLpMGJQ3utAfmdUSHgto+zErR10qQglCd08zF1ZGBQfAcOP3lK+L53vpozxWpGngA2MsgMfb3uaXfBUrjLYw==} + engines: {node: '>= 10'} + cpu: [arm] + os: [android] + + '@node-rs/jieba-android-arm64@2.0.4': + resolution: {integrity: sha512-qC1flCXhOuFMWKaiyyaLBI7FsGDCk8Gix85nG2RkEqj22jiQWSxvzIOJNIK/4FH0HSd7yrMgaw4nOyYNKGs55A==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [android] + + '@node-rs/jieba-darwin-arm64@2.0.4': + resolution: {integrity: sha512-/cGLKHB8dhcgTR7FRMvisXgPtt4Yiq9ygAQjHqskKKEOxrek60dJJzpgFPo5MY8EJyNInqxlRdN8H2a/vIFG7A==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@node-rs/jieba-darwin-x64@2.0.4': + resolution: {integrity: sha512-+sAHLzJF4XNrZUIwZBi1bBiwZDDSUVldW17cA94GBUb6F5UPB0OLq0ldOw8XtdA0MaotNnLlJQkm5ARuI1xheQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@node-rs/jieba-freebsd-x64@2.0.4': + resolution: {integrity: sha512-v6MTAPnVhq2HnKH4ASWGfaFv7FEQZUEWve0/UtJx3ViiwYbG2pgZ3XZPRumXRIst0xdFfIoukrYqnMjj89HTVA==} + engines: {node: '>= 10'} + cpu: [x64] + os: [freebsd] + + '@node-rs/jieba-linux-arm-gnueabihf@2.0.4': + resolution: {integrity: sha512-Y7Wm7nhV9UNfq4ojCN6HSbjO1p1pyqDZyGlwAT1NsruGRvowC0luhXEFTo6VSDMIQ7PTP+IQXZfuc5d7fgTDFA==} + engines: {node: '>= 10'} + cpu: [arm] + os: [linux] + + '@node-rs/jieba-linux-arm64-gnu@2.0.4': + resolution: {integrity: sha512-+x5FP4PDoRAagSvxyXeK3GdWjzZwigTD9GGyTWEKGViGcSUrY3/IsuPmVmOax3jHeQZkcX8aazybRiEwy2vIbQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@node-rs/jieba-linux-arm64-musl@2.0.4': + resolution: {integrity: sha512-PyIXG7eyScZ1jN7ZqMS7XE2qei1PVQd3AnvdYwgTaUawkQxNQGeCOGARuzXYxqpYV+ipg5zju+VJ23j3ucE0RQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@node-rs/jieba-linux-x64-gnu@2.0.4': + resolution: {integrity: sha512-VjetEm7IoerpyhIaASJg2HcADFZ+mTEBc18ciKqCt15Wdu1Tmv44vF0XUHKYBH0Q7U3LhoXXswTgjb/pcH3K+Q==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@node-rs/jieba-linux-x64-musl@2.0.4': + resolution: {integrity: sha512-WK9gU+lMq0wAuaDcFaqbr03Rv4/tNb9hFwfG3mYI96uG5TdVK2DBuRKzoPHP7XVz6iEmOu98lfhmL2/1Y0/DAw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@node-rs/jieba-win32-arm64-msvc@2.0.4': + resolution: {integrity: sha512-tcRW2cMHjYFfDPqG/St59ZoaR34CyLQJ5I4NGhZIfVhbYftJWnjvGPZBFdbudjgRCJ1in6rOZalDNGDex9+DHA==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@node-rs/jieba-win32-ia32-msvc@2.0.4': + resolution: {integrity: sha512-I8+WnUD1FKIIC2NdunUE9EpoQRUM0iAeKvAxpOzpO1xDhw1D2Ya/9qY1K/xibnh8jGEGZnE4Bsc27zt9M/ZQow==} + engines: {node: '>= 10'} + cpu: [ia32] + os: [win32] + + '@node-rs/jieba-win32-x64-msvc@2.0.4': + resolution: {integrity: sha512-aR6tFs1Lk7lZW/gy1q+F1GFdMqJVpLvAT5zpRCE+QbZSj9KRfKNooa5Y7c9v5yrxx4EH3vB31J3SWRR+OmVpog==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + + '@node-rs/jieba@2.0.4': + resolution: {integrity: sha512-/dTk3vV/v8+RIEUP7XOCkqRCVU0tqL3Ia9VTzHt38IDysGQmX7T56tM2IpwCLAWXubH7TyrcY54Stjsvcrbjqw==} + engines: {node: '>= 10'} + '@oclif/core@5.1.12': resolution: {integrity: sha512-t8W/ljOb9DIsFNXbfLU4UpZ8+C/X0QuvJOuQXQVCthiw5zSdwKnKoq7HmyBUJwwo28302eiN0rRj8vN9k1U1Mw==} engines: {node: '>=22.0.0'} @@ -15972,6 +16081,62 @@ snapshots: '@nodable/entities@3.1.0': {} + '@node-rs/jieba-android-arm-eabi@2.0.4': + optional: true + + '@node-rs/jieba-android-arm64@2.0.4': + optional: true + + '@node-rs/jieba-darwin-arm64@2.0.4': + optional: true + + '@node-rs/jieba-darwin-x64@2.0.4': + optional: true + + '@node-rs/jieba-freebsd-x64@2.0.4': + optional: true + + '@node-rs/jieba-linux-arm-gnueabihf@2.0.4': + optional: true + + '@node-rs/jieba-linux-arm64-gnu@2.0.4': + optional: true + + '@node-rs/jieba-linux-arm64-musl@2.0.4': + optional: true + + '@node-rs/jieba-linux-x64-gnu@2.0.4': + optional: true + + '@node-rs/jieba-linux-x64-musl@2.0.4': + optional: true + + '@node-rs/jieba-win32-arm64-msvc@2.0.4': + optional: true + + '@node-rs/jieba-win32-ia32-msvc@2.0.4': + optional: true + + '@node-rs/jieba-win32-x64-msvc@2.0.4': + optional: true + + '@node-rs/jieba@2.0.4': + optionalDependencies: + '@node-rs/jieba-android-arm-eabi': 2.0.4 + '@node-rs/jieba-android-arm64': 2.0.4 + '@node-rs/jieba-darwin-arm64': 2.0.4 + '@node-rs/jieba-darwin-x64': 2.0.4 + '@node-rs/jieba-freebsd-x64': 2.0.4 + '@node-rs/jieba-linux-arm-gnueabihf': 2.0.4 + '@node-rs/jieba-linux-arm64-gnu': 2.0.4 + '@node-rs/jieba-linux-arm64-musl': 2.0.4 + '@node-rs/jieba-linux-x64-gnu': 2.0.4 + '@node-rs/jieba-linux-x64-musl': 2.0.4 + '@node-rs/jieba-win32-arm64-msvc': 2.0.4 + '@node-rs/jieba-win32-ia32-msvc': 2.0.4 + '@node-rs/jieba-win32-x64-msvc': 2.0.4 + optional: true + '@oclif/core@5.1.12': dependencies: ansi-escapes: 4.3.2 From 3aa85541f6ec5f6b476e9e0b605e40b13678f9c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:25:08 +0000 Subject: [PATCH 2/8] feat(service-segmenter): the segmenter contract and service, cutting a Han run into dictionary words Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- .changeset/38710-service-segmenter.md | 16 + .changeset/config.json | 1 + packages/services/service-segmenter/README.md | 68 +++++ .../src/__fixtures__/policy-clauses.ts | 43 +++ .../service-segmenter/src/fixture.test.ts | 92 ++++++ .../services/service-segmenter/src/index.ts | 8 + .../service-segmenter/src/jieba-loader.ts | 85 ++++++ .../service-segmenter/src/platform-words.ts | 47 +++ .../src/segmenter-service-plugin.test.ts | 58 ++++ .../src/segmenter-service-plugin.ts | 60 ++++ .../src/segmenter-service.test.ts | 153 ++++++++++ .../src/segmenter-service.ts | 281 ++++++++++++++++++ .../services/service-segmenter/tsconfig.json | 20 ++ .../services/service-segmenter/tsup.config.ts | 22 ++ .../service-segmenter/vitest.config.ts | 4 + .../contracts/core-service-contracts.test.ts | 7 +- .../src/contracts/core-service-contracts.ts | 10 + packages/spec/src/contracts/index.ts | 1 + .../spec/src/contracts/segmenter-service.ts | 109 +++++++ 19 files changed, 1083 insertions(+), 2 deletions(-) create mode 100644 .changeset/38710-service-segmenter.md create mode 100644 packages/services/service-segmenter/README.md create mode 100644 packages/services/service-segmenter/src/__fixtures__/policy-clauses.ts create mode 100644 packages/services/service-segmenter/src/fixture.test.ts create mode 100644 packages/services/service-segmenter/src/index.ts create mode 100644 packages/services/service-segmenter/src/jieba-loader.ts create mode 100644 packages/services/service-segmenter/src/platform-words.ts create mode 100644 packages/services/service-segmenter/src/segmenter-service-plugin.test.ts create mode 100644 packages/services/service-segmenter/src/segmenter-service-plugin.ts create mode 100644 packages/services/service-segmenter/src/segmenter-service.test.ts create mode 100644 packages/services/service-segmenter/src/segmenter-service.ts create mode 100644 packages/services/service-segmenter/tsconfig.json create mode 100644 packages/services/service-segmenter/tsup.config.ts create mode 100644 packages/services/service-segmenter/vitest.config.ts create mode 100644 packages/spec/src/contracts/segmenter-service.ts diff --git a/.changeset/38710-service-segmenter.md b/.changeset/38710-service-segmenter.md new file mode 100644 index 00000000000..ffdaff917da --- /dev/null +++ b/.changeset/38710-service-segmenter.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': patch +'@objectstack/core': patch +'@objectstack/service-segmenter': patch +--- + +feat(service-segmenter): a segmenter service that cuts a Chinese question into real words for the keyword leg + +Clause-②: yes +Metadata-protocol: none + +New package `@objectstack/service-segmenter`: `SegmenterServicePlugin` registers `ISegmenterService` under the `segmenter` slot. `keywordTerms(query, { purpose, entries })` answers a question's keyword terms in the shape the knowledge adapters' terms have today (distinct, at most 16). A run of Han characters is cut by `@node-rs/jieba` (HMM off, an optional dependency, loaded once per process) after a longest-match pass that keeps the platform's words (年假, 脱密, 应急采购, 超预算, …) and the caller's `word` entries whole; stop words are dropped and adjacent single characters are joined into two-character words. The query is NFKC-normalised first, a Thai, Lao, Khmer or Myanmar run is cut by `Intl.Segmenter`, and everything else (English, figures, codes, kana and Hangul runs) is cut exactly as before. Without jieba (not installed, or failed to load: the boot log names which, and `status()` reports it), the service answers by sliding windows with the layered words still kept whole. The purpose `record_search` is reserved and refused with `NOT_IMPLEMENTED`. + +Nothing calls the service yet: the knowledge adapters keep their own terms until they read the slot. + +`@objectstack/spec/contracts` adds `ISegmenterService`, `SEGMENTER_SERVICE` and their types, and `ServiceSlotContracts` gains the `segmenter` slot (not a `CoreServiceName` member). `@objectstack/core` adds `keywordTerms`, `MAX_KEYWORD_TERMS`, `KEYWORD_SEPARATORS` and `UNSEGMENTED_RUN`: the sliding-window rule the two knowledge adapters each hold a copy of, as one shared copy. diff --git a/.changeset/config.json b/.changeset/config.json index fe4da498aa3..362d5897808 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -66,6 +66,7 @@ "@objectstack/service-cluster-redis", "@objectstack/service-datasource", "@objectstack/service-i18n", + "@objectstack/service-segmenter", "@objectstack/service-job", "@objectstack/service-knowledge", "@objectstack/service-mailbox", diff --git a/packages/services/service-segmenter/README.md b/packages/services/service-segmenter/README.md new file mode 100644 index 00000000000..66977cf2ddb --- /dev/null +++ b/packages/services/service-segmenter/README.md @@ -0,0 +1,68 @@ +# @objectstack/service-segmenter + +The provider for the kernel's **`segmenter`** service slot — `ISegmenterService` from +`@objectstack/spec/contracts`. It answers the keyword terms of a question for knowledge +retrieval, with a Han run cut into real words by a dictionary segmenter +([`@node-rs/jieba`](https://www.npmjs.com/package/@node-rs/jieba), HMM off) instead of the +sliding windows of three and two characters. + +**Nothing calls it yet.** The knowledge adapters still cut their own terms; they read this +slot in a later release. Registering the plugin today changes no search. + +## Installation + +```bash +pnpm add @objectstack/service-segmenter +``` + +`@node-rs/jieba` is an optional dependency with prebuilt binaries (Linux glibc and musl, macOS, +Windows). Without it, or when it fails to load, the service still registers and answers by the +sliding windows of `keywordTerms` from `@objectstack/core`, with the platform words and supplied +words still kept whole. The boot log says which, and tells "not installed" apart from "failed to +load". + +## Usage + +```typescript +import { LiteKernel } from '@objectstack/core'; +import { SEGMENTER_SERVICE, type ISegmenterService } from '@objectstack/spec/contracts'; +import { SegmenterServicePlugin } from '@objectstack/service-segmenter'; + +const kernel = new LiteKernel(); +kernel.use(new SegmenterServicePlugin()); +await kernel.bootstrap(); + +const segmenter = kernel.getService(SEGMENTER_SERVICE); +segmenter.keywordTerms('我在集团干了12年了,一年有几天年假?'); // ['集团', '一年', '年假', '12'] +segmenter.keywordTerms('明规条款怎么查', { entries: [{ term: '明规条款', kind: 'word' }] }); // ['明规条款'] +segmenter.status(); // { engine: 'dictionary', segmenter: 'jieba', purposes: ['knowledge'] } +``` + +## The rule (purpose `knowledge`) + +1. NFKC normalisation: fullwidth letters and digits fold to ASCII. +2. A run of Han characters: the layered words are matched first, by longest match (a word is kept + whole, a stop word of two or more characters is dropped); the rest is cut by jieba, stop words + dropped, and adjacent single characters joined into words of two (年|假 → 年假). +3. A run of Thai, Lao, Khmer or Myanmar: cut by `Intl.Segmenter`. +4. Everything else — English words, figures, document numbers, codes, and runs holding kana or + Hangul — exactly as `keywordTerms` from `@objectstack/core` cuts it. + +Two layers of words, the later one winning for a term: the platform's (`PLATFORM_WORDS`, +`PLATFORM_STOP_WORDS`), then the `entries` the caller passes. An entry with `enabled: false` +withdraws a platform word or stop word. The purpose `record_search` is reserved and refused with +`NOT_IMPLEMENTED`. + +## Exports + +| Export | What it is | +|:---|:---| +| `SegmenterServicePlugin` | The kernel plugin; registers the service under `segmenter`. | +| `SegmenterService`, `createSegmenterService` | The service and its async constructor (one load of jieba). | +| `SERVED_PURPOSES` | The purposes served: `knowledge`. | +| `jiebaLoader`, `isNotInstalled`, `JIEBA_CUT_MODE` | The jieba load, its not-installed test, and the cut it runs (`cut`). | +| `PLATFORM_WORDS`, `PLATFORM_STOP_WORDS` | The platform layer of words. | + +## License + +Apache-2.0 diff --git a/packages/services/service-segmenter/src/__fixtures__/policy-clauses.ts b/packages/services/service-segmenter/src/__fixtures__/policy-clauses.ts new file mode 100644 index 00000000000..bc4a2014435 --- /dev/null +++ b/packages/services/service-segmenter/src/__fixtures__/policy-clauses.ts @@ -0,0 +1,43 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A small synthetic policy corpus and the colloquial questions asked of it: + * twelve clauses, each question naming the one clause that answers it. Written + * for this fixture (no customer text), in the shape of a company's rules: + * leave, travel, procurement, confidentiality, contracts. The questions are + * spoken the way employees ask, so most of their characters are noise for a + * keyword search. + */ +export const CLAUSES: ReadonlyArray<{ id: string; text: string }> = [ + { id: 'annual_leave', text: '第十二条 员工累计工作已满1年不满10年的,年假5天;已满10年不满20年的,年假10天;已满20年的,年假15天。' }, + { id: 'sick_leave', text: '第十三条 员工因病需要停止工作治疗的,凭医院证明申请病假,病假期间按规定发放病假工资。' }, + { id: 'marriage_leave', text: '第十四条 员工本人结婚的,可享受婚假3天;符合晚婚条件的,婚假另行增加。' }, + { id: 'travel_lodging', text: '第二十条 出差人员住宿费按城市分级标准据实报销,一类城市每人每天不超过500元。' }, + { id: 'over_budget', text: '第二十一条 差旅费用超预算的,须事先提交超预算申请,经部门负责人和财务总监批准后方可列支。' }, + { id: 'entertainment', text: '第二十二条 业务招待费实行事前审批,招待标准不得超过公司规定的人均限额。' }, + { id: 'emergency_procurement', text: '第三十条 因突发事件需要应急采购的,由使用部门提出申请,经分管领导批准后先行采购,事后补办手续。' }, + { id: 'centralized_procurement', text: '第三十一条 单项金额在50万元以上的物资,实行集中采购,由采购中心统一组织招标。' }, + { id: 'declassification', text: '第四十条 涉密人员离岗离职的,实行脱密期管理,核心涉密人员脱密期为三年,重要涉密人员为二年。' }, + { id: 'tech_renovation', text: '第五十条 技改项目由生产技术部组织可行性论证,投资额超过1000万元的报集团董事会审议。' }, + { id: 'contract_review', text: '第六十条 合同签订前须经法务部门审核,重大合同须经总经理办公会审议通过。' }, + { id: 'overtime', text: '第七十条 员工加班须经部门负责人事先批准,加班时间可以安排调休,不能调休的支付加班工资。' }, +]; + +export const QUESTIONS: ReadonlyArray<{ q: string; expect: string }> = [ + { q: '我在集团干了12年了,一年有几天年假?', expect: 'annual_leave' }, + { q: '刚来公司半年能休年假吗', expect: 'annual_leave' }, + { q: '生病了请假要什么材料,病假有没有工资', expect: 'sick_leave' }, + { q: '我下个月结婚,婚假能休几天?', expect: 'marriage_leave' }, + { q: '去上海出差住宿一晚最多能报多少钱', expect: 'travel_lodging' }, + { q: '这次出差的费用超预算了怎么办', expect: 'over_budget' }, + { q: '请客户吃饭的招待费要先审批吗', expect: 'entertainment' }, + { q: '设备突然坏了,能不能先买了再走流程,应急采购怎么弄', expect: 'emergency_procurement' }, + { q: '买一批60万的设备要不要招标', expect: 'centralized_procurement' }, + { q: '涉密岗位的同事辞职了,脱密期是多久', expect: 'declassification' }, + { q: '我们车间的技改项目投资1200万,需要谁来批', expect: 'tech_renovation' }, + { q: '跟供应商签合同之前要找法务看吗', expect: 'contract_review' }, + { q: '周末加班了可以换成调休吗', expect: 'overtime' }, + { q: '核心涉密人员离职后多长时间不能出国', expect: 'declassification' }, + { q: '差旅超预算需要谁批准', expect: 'over_budget' }, + { q: '工作满20年以后年假是多少天', expect: 'annual_leave' }, +]; diff --git a/packages/services/service-segmenter/src/fixture.test.ts b/packages/services/service-segmenter/src/fixture.test.ts new file mode 100644 index 00000000000..58e4ca6b065 --- /dev/null +++ b/packages/services/service-segmenter/src/fixture.test.ts @@ -0,0 +1,92 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The fixture the card's acceptance names: colloquial Chinese questions over +// policy clauses, ranked by the keyword leg alone. It measures the sliding +// windows the knowledge adapters cut today against jieba's two cuts, pins that +// the segmenter's hit@3 rises over the windows, and pins which jieba cut the +// service runs (`JIEBA_CUT_MODE`) as the one this measurement picked. +// +// The ranker stands in for a store's keyword leg without a database: a clause +// scores one point for each distinct term it holds as a substring (what +// `content LIKE` matches), ties broken by corpus order. Deterministic: no +// vectors, no clock, no randomness. + +import { describe, expect, it } from 'vitest'; +import { keywordTerms } from '@objectstack/core'; +import { JIEBA_CUT_MODE, jiebaLoader } from './jieba-loader.js'; +import { createSegmenterService } from './segmenter-service.js'; +import { PLATFORM_WORDS } from './platform-words.js'; +import { CLAUSES, QUESTIONS } from './__fixtures__/policy-clauses.js'; + +function rank(terms: readonly string[]): string[] { + return CLAUSES.map((clause, order) => ({ + id: clause.id, + order, + score: terms.filter((t) => clause.text.toLowerCase().includes(t.toLowerCase())).length, + })) + .filter((c) => c.score > 0) + .sort((a, b) => b.score - a.score || a.order - b.order) + .map((c) => c.id); +} + +function hitAt(k: number, cut: (q: string) => string[]): number { + return QUESTIONS.filter(({ q, expect }) => rank(cut(q)).slice(0, k).includes(expect)).length; +} + +const cut = await createSegmenterService({ loader: jiebaLoader('cut') }); +const cutForSearch = await createSegmenterService({ loader: jiebaLoader('cutForSearch') }); +const service = await createSegmenterService(); + +describe('segmenter fixture — keyword-only retrieval over policy clauses', () => { + const measured = { + windows: hitAt(3, keywordTerms), + cut: hitAt(3, (q) => cut.keywordTerms(q)), + cutForSearch: hitAt(3, (q) => cutForSearch.keywordTerms(q)), + }; + const termsPerQuestion = (f: (q: string) => string[]): number => + Math.round((QUESTIONS.reduce((n, { q }) => n + f(q).length, 0) / QUESTIONS.length) * 10) / 10; + const detail = { + hitAt1: { windows: hitAt(1, keywordTerms), cut: hitAt(1, (q) => cut.keywordTerms(q)), cutForSearch: hitAt(1, (q) => cutForSearch.keywordTerms(q)) }, + termsPerQuestion: { + windows: termsPerQuestion(keywordTerms), + cut: termsPerQuestion((q) => cut.keywordTerms(q)), + cutForSearch: termsPerQuestion((q) => cutForSearch.keywordTerms(q)), + }, + }; + + it('records the measurement', () => { + // Printed so a run of this file reads the three numbers off its output. + console.info(`segmenter fixture, ${QUESTIONS.length} questions: hit@3 ${JSON.stringify(measured)} · ${JSON.stringify(detail)}`); + expect(cut.status().engine).toBe('dictionary'); + }); + + it('raises keyword-only hit@3 over the sliding windows', () => { + expect(measured.cut).toBeGreaterThan(measured.windows); + expect(hitAt(3, (q) => service.keywordTerms(q))).toBeGreaterThan(measured.windows); + }); + + it('runs the jieba cut this measurement picked', () => { + // The cut with the higher hit@3 wins; on a tie the plain cut, which sends fewer terms. + const picked = measured.cutForSearch > measured.cut ? 'cutForSearch' : 'cut'; + expect(JIEBA_CUT_MODE).toBe(picked); + }); + + it('keeps 年假, 脱密, 应急采购 and 超预算 whole', () => { + expect(service.keywordTerms('我在集团干了12年了,一年有几天年假?')).toContain('年假'); + expect(service.keywordTerms('同事辞职了,脱密怎么算')).toContain('脱密'); + expect(service.keywordTerms('设备坏了,应急采购怎么弄')).toContain('应急采购'); + expect(service.keywordTerms('这次出差的费用超预算了怎么办')).toContain('超预算'); + }); + + it('yields no three-character sliding fragment for any question', async () => { + const raw = await jiebaLoader('cut')(); + if (!raw.ok) throw new Error(raw.error); + for (const { q } of QUESTIONS) { + // A term of three characters or more is a dictionary word, the segmenter's own or a platform word, never a window. + const words = new Set([...raw.segmenter.cut(q.normalize('NFKC')), ...PLATFORM_WORDS]); + for (const term of service.keywordTerms(q).filter((t) => /^\p{Script=Han}{3,}$/u.test(t))) expect(words, `${q} → ${term}`).toContain(term); + } + expect(service.keywordTerms('我在集团干了12年了,一年有几天年假?')).not.toEqual(expect.arrayContaining(['我在集'])); + for (const window of ['我在集', '在集团', '集团干', '团干了']) expect(keywordTerms('我在集团干了12年了,一年有几天年假?')).toContain(window); + }); +}); diff --git a/packages/services/service-segmenter/src/index.ts b/packages/services/service-segmenter/src/index.ts new file mode 100644 index 00000000000..e0519808b73 --- /dev/null +++ b/packages/services/service-segmenter/src/index.ts @@ -0,0 +1,8 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +export { SegmenterServicePlugin } from './segmenter-service-plugin.js'; +export type { SegmenterServicePluginOptions } from './segmenter-service-plugin.js'; +export { SegmenterService, SERVED_PURPOSES, createSegmenterService } from './segmenter-service.js'; +export { JIEBA_CUT_MODE, isNotInstalled, jiebaLoader } from './jieba-loader.js'; +export type { DictionarySegmenter, JiebaCutMode, SegmenterLoad, SegmenterLoader } from './jieba-loader.js'; +export { PLATFORM_STOP_WORDS, PLATFORM_WORDS } from './platform-words.js'; diff --git a/packages/services/service-segmenter/src/jieba-loader.ts b/packages/services/service-segmenter/src/jieba-loader.ts new file mode 100644 index 00000000000..b7f8f62bad2 --- /dev/null +++ b/packages/services/service-segmenter/src/jieba-loader.ts @@ -0,0 +1,85 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SegmenterFallbackReason } from '@objectstack/spec/contracts'; + +/** The part of a dictionary segmenter the service calls: a cut with the HMM off. */ +export interface DictionarySegmenter { + /** The segmenter's name, for `status()` and the boot log (e.g. `'jieba'`). */ + readonly name: string; + /** Cut `text` into words, in order, every character kept. */ + cut(text: string): string[]; +} + +/** The outcome of one load: a segmenter, or why there is none. */ +export type SegmenterLoad = + | { ok: true; segmenter: DictionarySegmenter } + | { ok: false; reason: SegmenterFallbackReason; error: string }; + +/** How the service loads its dictionary segmenter; tests hand in their own. */ +export type SegmenterLoader = () => Promise; + +/** + * Which jieba cut the service uses for a Han span. `cut` gives each span once, + * as its most likely words; `cutForSearch` adds the shorter words inside a + * long one (住宿费 → 住宿, 宿费, 住宿费). Chosen by measured keyword-only hit@3 + * on the service's fixture (`fixture.test.ts`), which pins the choice. + */ +export type JiebaCutMode = 'cut' | 'cutForSearch'; +export const JIEBA_CUT_MODE: JiebaCutMode = 'cut'; + +interface JiebaInstance { + cut(sentence: string, hmm?: boolean): string[]; + cutForSearch(sentence: string, hmm?: boolean): string[]; +} +interface JiebaModule { + Jieba: { withDict(dict: Uint8Array): JiebaInstance }; +} +interface JiebaDictModule { + dict: Uint8Array; +} + +/** The module ids the loader imports; their absence is `not_installed`. */ +const JIEBA_MODULES = ['@node-rs/jieba', '@node-rs/jieba/dict.js']; + +/** + * Is `e` the module loader saying the package itself is not there, as opposed + * to the package failing while it loads (the native binding of this platform + * missing, a dictionary that does not parse)? Only a not-found error that + * names one of the loader's own module ids is "not installed": the jieba + * package reports a missing platform binary with an error of its own. + */ +export function isNotInstalled(e: unknown): boolean { + const code = (e as { code?: unknown } | null)?.code; + if (code !== 'ERR_MODULE_NOT_FOUND' && code !== 'MODULE_NOT_FOUND') return false; + const message = e instanceof Error ? e.message : String(e); + return JIEBA_MODULES.some((id) => message.includes(`'${id}'`) || message.includes(`"${id}"`)); +} + +/** Read a CommonJS module's export through `import()`, whichever way the host exposes it. */ +function cjsExports(mod: unknown): T { + const m = mod as { default?: unknown }; + return (m.default && typeof m.default === 'object' ? m.default : mod) as T; +} + +/** + * Load `@node-rs/jieba` with its default dictionary, once: one read-only + * instance for the process, with the HMM off (it guesses words a dictionary + * does not hold, and invents some, such as 能付 and 黑后). + */ +export function jiebaLoader(mode: JiebaCutMode = JIEBA_CUT_MODE): SegmenterLoader { + return async () => { + try { + const { Jieba } = cjsExports(await import('@node-rs/jieba')); + const { dict } = cjsExports(await import('@node-rs/jieba/dict.js')); + const jieba = Jieba.withDict(dict); + const cut = mode === 'cut' ? (text: string) => jieba.cut(text, false) : (text: string) => jieba.cutForSearch(text, false); + return { ok: true, segmenter: { name: 'jieba', cut } }; + } catch (e) { + return { + ok: false, + reason: isNotInstalled(e) ? 'not_installed' : 'load_failed', + error: e instanceof Error ? e.message : String(e), + }; + } + }; +} diff --git a/packages/services/service-segmenter/src/platform-words.ts b/packages/services/service-segmenter/src/platform-words.ts new file mode 100644 index 00000000000..e2ca9d3d678 --- /dev/null +++ b/packages/services/service-segmenter/src/platform-words.ts @@ -0,0 +1,47 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The platform layer of words: what every deployment starts from, before any + * entry a caller supplies. Both lists are for knowledge retrieval, compared + * after NFKC normalisation. + */ + +/** + * Words kept whole, never cut: the terms of everyday policy text (leave, + * expenses, procurement, confidentiality) that the segmenter's own dictionary + * splits, or that a question names in a form it does not hold. Each is matched + * by longest match before the segmenter runs, so it is kept whole on the + * sliding-window fallback too. + */ +export const PLATFORM_WORDS: readonly string[] = Object.freeze([ + // Leave and attendance + '年假', '年休假', '病假', '事假', '婚假', '产假', '陪产假', '丧假', '调休', '倒休', + // Expenses and budgets + '超预算', '差旅费', '住宿费', '交通费', '招待费', '报销单', + // Procurement and projects + '应急采购', '集中采购', '单一来源采购', '技改', + // Confidentiality + '脱密', '脱密期', '涉密', '保密期', +]); + +/** + * Words dropped from every answer: the function words and question words of + * a colloquial question, which nearly every passage holds or none answers + * with. A word of one character is dropped before adjacent single characters + * are joined; a longer one is also matched before the segmenter runs, so it + * is dropped on the sliding-window fallback too. + */ +export const PLATFORM_STOP_WORDS: readonly string[] = Object.freeze([ + // One character + '的', '了', '着', '过', '是', '在', '有', '和', '与', '及', '或', '而', '也', '都', '就', '还', '又', + '把', '被', '给', '对', '从', '向', '到', '让', '我', '你', '您', '他', '她', '它', '这', '那', '哪', + '吗', '呢', '吧', '啊', '呀', '嘛', '么', '啥', '谁', '几', '要', '会', '能', '得', '地', '个', + // Pronouns and demonstratives + '我们', '你们', '他们', '她们', '咱们', '自己', '这个', '那个', '这些', '那些', '这里', '那里', '这样', '那样', + // Question words + '什么', '怎么', '怎样', '怎么样', '怎么办', '如何', '为什么', '为何', '哪些', '哪个', '哪里', '多少', '多久', + '几天', '几个', '是否', '能否', '可否', '是不是', '有没有', '请问', '一下', + // Modal and linking words + '可以', '需要', '应该', '应当', '能够', '必须', '如果', '因为', '所以', '但是', '而且', '或者', '还是', + '已经', '一个', '一些', '的话', '时候', +]); diff --git a/packages/services/service-segmenter/src/segmenter-service-plugin.test.ts b/packages/services/service-segmenter/src/segmenter-service-plugin.test.ts new file mode 100644 index 00000000000..050a95dc13d --- /dev/null +++ b/packages/services/service-segmenter/src/segmenter-service-plugin.test.ts @@ -0,0 +1,58 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import { SEGMENTER_SERVICE, type ISegmenterService } from '@objectstack/spec/contracts'; +import { SegmenterServicePlugin } from './segmenter-service-plugin.js'; +import type { SegmenterLoader } from './jieba-loader.js'; + +function context() { + const services = new Map(); + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + return { + ctx: { registerService: vi.fn((name: string, s: unknown) => services.set(name, s)), logger } as any, + services, + logger, + }; +} + +const notInstalled: SegmenterLoader = async () => ({ ok: false, reason: 'not_installed', error: "Cannot find package '@node-rs/jieba'" }); +const loadFailed: SegmenterLoader = async () => ({ ok: false, reason: 'load_failed', error: 'Cannot find native binding' }); + +describe('SegmenterServicePlugin', () => { + it('registers the service under segmenter and says it cuts by jieba', async () => { + const { ctx, services, logger } = context(); + await new SegmenterServicePlugin().init(ctx); + const service = services.get(SEGMENTER_SERVICE) as ISegmenterService; + expect(service.status().engine).toBe('dictionary'); + expect(service.keywordTerms('一年有几天年假')).toContain('年假'); + expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('cut by jieba')); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('still registers on the sliding-window fallback, and tells not installed from failed to load', async () => { + const missing = context(); + await new SegmenterServicePlugin({ loader: notInstalled }).init(missing.ctx); + expect((missing.services.get(SEGMENTER_SERVICE) as ISegmenterService).status()).toMatchObject({ + engine: 'sliding_window', fallbackReason: 'not_installed', + }); + expect(missing.logger.warn).toHaveBeenCalledWith(expect.stringContaining('is not installed')); + + const broken = context(); + await new SegmenterServicePlugin({ loader: loadFailed }).init(broken.ctx); + expect((broken.services.get(SEGMENTER_SERVICE) as ISegmenterService).status()).toMatchObject({ + engine: 'sliding_window', fallbackReason: 'load_failed', error: 'Cannot find native binding', + }); + expect(broken.logger.warn).toHaveBeenCalledWith(expect.stringContaining('failed to load (Cannot find native binding)')); + expect(broken.logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('is not installed')); + }); + + it('boots on a kernel and fills the slot it declares', async () => { + const kernel = new LiteKernel(); + kernel.use(new SegmenterServicePlugin()); + await kernel.bootstrap(); + const service = kernel.getService(SEGMENTER_SERVICE); + expect(service.keywordTerms('应急采购需要走什么流程')).toEqual(['应急采购', '流程']); + await kernel.shutdown(); + }); +}); diff --git a/packages/services/service-segmenter/src/segmenter-service-plugin.ts b/packages/services/service-segmenter/src/segmenter-service-plugin.ts new file mode 100644 index 00000000000..2e6f4f8c1c3 --- /dev/null +++ b/packages/services/service-segmenter/src/segmenter-service-plugin.ts @@ -0,0 +1,60 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { Plugin, PluginContext } from '@objectstack/core'; +import { SEGMENTER_SERVICE } from '@objectstack/spec/contracts'; +import type { SegmenterLoader } from './jieba-loader.js'; +import { createSegmenterService } from './segmenter-service.js'; + +export interface SegmenterServicePluginOptions { + /** How the dictionary segmenter is loaded. Default: `@node-rs/jieba`. For tests. */ + loader?: SegmenterLoader; +} + +/** + * SegmenterServicePlugin — registers {@link ISegmenterService} under + * `segmenter` (`SEGMENTER_SERVICE`) during init, on every path. + * + * It loads its dictionary segmenter once, in init, and never retries: the + * boot log says which segmentation the process runs, and `status()` answers + * the same for its life. Without the segmenter the service still registers + * and answers by sliding windows, with the layered words still kept whole; the + * log tells "not installed" (install the optional `@node-rs/jieba`) apart + * from "failed to load" (its error is named). + * + * Nothing reads the slot yet: the knowledge adapters keep their own terms + * until they are wired to it (objectstack#38710, step 2). + */ +export class SegmenterServicePlugin implements Plugin { + name = 'com.objectstack.service.segmenter'; + /** Services init() registers on every path (ADR-0116). */ + providesServices = [SEGMENTER_SERVICE]; + version = '1.0.0'; + type = 'standard' as const; + + private readonly options: SegmenterServicePluginOptions; + + constructor(options: SegmenterServicePluginOptions = {}) { + this.options = options; + } + + async init(ctx: PluginContext): Promise { + const service = await createSegmenterService({ loader: this.options.loader }); + ctx.registerService(SEGMENTER_SERVICE, service); + const status = service.status(); + if (status.engine === 'dictionary') { + ctx.logger.info(`SegmenterServicePlugin: Han text is cut by ${status.segmenter} (dictionary segmentation)`); + } else if (status.fallbackReason === 'not_installed') { + ctx.logger.warn( + 'SegmenterServicePlugin: @node-rs/jieba is not installed, so Han text is cut by sliding windows ' + + '(supplied and platform words are still kept whole). Install the optional dependency @node-rs/jieba ' + + 'to cut it into dictionary words.', + ); + } else { + ctx.logger.warn( + `SegmenterServicePlugin: @node-rs/jieba is installed but failed to load (${status.error}), so Han text is ` + + 'cut by sliding windows (supplied and platform words are still kept whole). Check that the prebuilt ' + + 'binary for this platform was installed.', + ); + } + } +} diff --git a/packages/services/service-segmenter/src/segmenter-service.test.ts b/packages/services/service-segmenter/src/segmenter-service.test.ts new file mode 100644 index 00000000000..78f44b3523f --- /dev/null +++ b/packages/services/service-segmenter/src/segmenter-service.test.ts @@ -0,0 +1,153 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The segmenter's rule, case by case: dictionary words for a Han run, the +// sliding windows of `@objectstack/core` for everything else, the layered +// words, the fallback and the refused purpose. + +import { describe, expect, it } from 'vitest'; +import { keywordTerms } from '@objectstack/core'; +import type { SegmenterEntry } from '@objectstack/spec/contracts'; +import { SegmenterService, createSegmenterService } from './segmenter-service.js'; +import { isNotInstalled, type SegmenterLoad } from './jieba-loader.js'; + +const jieba = await createSegmenterService(); +const failed: SegmenterLoad = { ok: false, reason: 'load_failed', error: 'Cannot find native binding' }; +const windows = new SegmenterService(failed); + +describe('SegmenterService — the dictionary segmenter loads here', () => { + it('runs jieba in this workspace, so the cases below test the dictionary path', () => { + expect(jieba.status()).toEqual({ engine: 'dictionary', segmenter: 'jieba', purposes: ['knowledge'] }); + }); +}); + +describe('SegmenterService — a Han run', () => { + it('cuts a question into words and drops stop words, figures kept whole', () => { + expect(jieba.keywordTerms('出差住宿费2000元以下需要审批吗')).toEqual(['出差', '住宿费', '以下', '审批', '2000']); + expect(jieba.keywordTerms('X-200型号的保修期')).toEqual(['型号', '保修期', 'X-200']); + }); + + it('keeps the platform words whole that jieba alone splits', () => { + expect(jieba.keywordTerms('我在集团干了12年了,一年有几天年假?')).toEqual(['集团', '一年', '年假', '12']); + expect(jieba.keywordTerms('涉密人员脱密期是多久')).toEqual(['涉密', '人员', '脱密期']); + expect(jieba.keywordTerms('应急采购需要走什么流程')).toEqual(['应急采购', '流程']); + }); + + it('joins adjacent single characters into words of two, after single-character stop words are dropped', () => { + // 年|假 with no platform word for it: joined. 干 stands alone between stop words: dropped. + const plain = new SegmenterService({ ok: true, segmenter: { name: 'split', cut: (t) => [...t] } }); + expect(plain.keywordTerms('休假')).toEqual(['休假']); + // 我 and 了 are stop words of one character: 干 is left alone and dropped, never joined across them. + expect(plain.keywordTerms('我干了活')).toEqual([]); + // Three side by side: two overlapping words of two. + expect(plain.keywordTerms('培训费')).toEqual(['培训', '训费']); + }); + + it('never yields a sliding fragment of three characters', () => { + for (const q of ['我在集团干了12年了,一年有几天年假?', '出差住宿费超预算怎么办', '涉密人员脱密期是多久']) { + const terms = jieba.keywordTerms(q); + const fragments = keywordTerms(q).filter((t) => [...t].length === 3 && !terms.includes(t)); + for (const fragment of fragments) expect(terms).not.toContain(fragment); + expect(terms.some((t) => ['我在集', '在集团', '集团干'].includes(t))).toBe(false); + } + }); + + it('folds fullwidth letters and digits before it cuts (NFKC)', () => { + expect(jieba.keywordTerms('ABC123型号')).toEqual(['型号', 'ABC123']); + }); +}); + +describe('SegmenterService — everything else is cut as the knowledge adapters cut it today', () => { + // The cases the adapters pin on `keywordTerms`, with no Han run in them. + const cases = [ + 'What is the X-200 pump? v1.2, a/b; #tag (part 7731)', + 'pump PUMP Pump', + Array.from({ length: 40 }, (_, i) => `w${i}`).join(' '), + 'コーヒー代', + '휴가는', + 'コーヒー 휴가는 v1.2', + '?! …', + ]; + it('answers exactly what keywordTerms answers for English, codes, figures, kana and Hangul', () => { + for (const q of cases) { + expect(jieba.keywordTerms(q), q).toEqual(keywordTerms(q)); + expect(windows.keywordTerms(q), q).toEqual(keywordTerms(q)); + } + }); + + it('keeps a run holding kana whole for the sliding windows, its Han characters included', () => { + expect(jieba.keywordTerms('休暇の申請')).toEqual(keywordTerms('休暇の申請')); + }); + + it('cuts a Thai run with Intl.Segmenter', () => { + const terms = jieba.keywordTerms('ลาพักร้อนกี่วัน'); + expect(terms.length).toBeGreaterThan(1); + expect(terms.join('')).toBe('ลาพักร้อนกี่วัน'); + }); +}); + +describe('SegmenterService — supplied entries over the platform defaults', () => { + it('keeps a supplied word whole and drops a supplied stop word', () => { + const entries: SegmenterEntry[] = [ + { term: '明规条款', kind: 'word' }, + { term: '集团', kind: 'stop_word' }, + ]; + // 集团 dropped, 明规条款 whole, 怎么 a stop word, 查 alone. + expect(jieba.keywordTerms('集团明规条款怎么查', { entries })).toEqual(['明规条款']); + expect(jieba.keywordTerms('集团明规条款怎么查')).not.toContain('明规条款'); + }); + + it('withdraws a platform stop word or word with a disabled entry', () => { + expect(jieba.keywordTerms('是否报销')).toEqual(['报销']); + expect(jieba.keywordTerms('是否报销', { entries: [{ term: '是否', kind: 'stop_word', enabled: false }] })).toEqual(['是否', '报销']); + expect(jieba.keywordTerms('年假', { entries: [{ term: '年假', kind: 'word', enabled: false }] })).toEqual(['年假']); + }); + + it('lets a later entry for the same term win, and ignores an entry for another purpose', () => { + const entries: SegmenterEntry[] = [ + { term: '报销', kind: 'stop_word' }, + { term: '报销', kind: 'word' }, + { term: '流程', kind: 'stop_word', purpose: 'record_search' }, + { term: '审批', kind: 'stop_word', purpose: 'both' }, + ]; + expect(jieba.keywordTerms('报销审批流程', { entries })).toEqual(['报销', '流程']); + }); + + it('keeps a supplied word whole when the dictionary segmenter failed to load', () => { + const entries: SegmenterEntry[] = [{ term: '明规条款', kind: 'word' }]; + expect(windows.status()).toEqual({ + engine: 'sliding_window', fallbackReason: 'load_failed', error: 'Cannot find native binding', purposes: ['knowledge'], + }); + const terms = windows.keywordTerms('明规条款怎么查', { entries }); + expect(terms[0]).toBe('明规条款'); + // Without the entry the windows cut it, as today. + expect(windows.keywordTerms('明规条款')).toEqual(keywordTerms('明规条款')); + }); + + it('answers exactly the sliding windows on the fallback when no layered word is in the question', () => { + for (const q of ['出差住宿标准', 'X-200型号的保修期', '第〢〣号']) expect(windows.keywordTerms(q), q).toEqual(keywordTerms(q)); + }); +}); + +describe('SegmenterService — purpose', () => { + it('defaults to knowledge and refuses record_search with NOT_IMPLEMENTED', () => { + expect(jieba.keywordTerms('年假', { purpose: 'knowledge' })).toEqual(jieba.keywordTerms('年假')); + let thrown: unknown; + try { + jieba.keywordTerms('年假', { purpose: 'record_search' }); + } catch (e) { + thrown = e; + } + expect(thrown).toMatchObject({ code: 'NOT_IMPLEMENTED', status: 501 }); + }); +}); + +describe('isNotInstalled', () => { + it('tells the package missing apart from the package failing to load', () => { + const missing = Object.assign(new Error("Cannot find package '@node-rs/jieba' imported from /x.js"), { code: 'ERR_MODULE_NOT_FOUND' }); + const nested = Object.assign(new Error("Cannot find module '@node-rs/jieba-linux-x64-gnu'"), { code: 'MODULE_NOT_FOUND' }); + expect(isNotInstalled(missing)).toBe(true); + expect(isNotInstalled(Object.assign(new Error("Cannot find module '@node-rs/jieba'"), { code: 'MODULE_NOT_FOUND' }))).toBe(true); + expect(isNotInstalled(nested)).toBe(false); + expect(isNotInstalled(new Error('Cannot find native binding'))).toBe(false); + }); +}); diff --git a/packages/services/service-segmenter/src/segmenter-service.ts b/packages/services/service-segmenter/src/segmenter-service.ts new file mode 100644 index 00000000000..79ef13cb2ee --- /dev/null +++ b/packages/services/service-segmenter/src/segmenter-service.ts @@ -0,0 +1,281 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { MAX_KEYWORD_TERMS, UNSEGMENTED_RUN, keywordTerms as slidingWindowTerms } from '@objectstack/core'; +import { StandardErrorCode } from '@objectstack/spec/api'; +import { + DEFAULT_SEGMENTER_PURPOSE, + type ISegmenterService, + type SegmenterEntry, + type SegmenterPurpose, + type SegmenterStatus, + type SegmenterTermsOptions, +} from '@objectstack/spec/contracts'; +import type { DictionarySegmenter, SegmenterLoad, SegmenterLoader } from './jieba-loader.js'; +import { jiebaLoader } from './jieba-loader.js'; +import { PLATFORM_STOP_WORDS, PLATFORM_WORDS } from './platform-words.js'; + +/** The purposes this provider serves. Record search is reserved and refused. */ +export const SERVED_PURPOSES: readonly SegmenterPurpose[] = Object.freeze(['knowledge']); + +type Kind = SegmenterEntry['kind']; +/** The layered words of one call: each key (NFKC, lower-cased) and what it is. */ +interface Lexicon { + kinds: ReadonlyMap; + /** The longest key, in code points: how far the longest match looks ahead. */ + longest: number; +} + +/** A term's comparison key: NFKC, then lower case, as the terms are deduplicated. */ +const keyOf = (term: string): string => term.normalize('NFKC').trim().toLowerCase(); + +/** A run of Han characters only, with the marks 々, 〆 and 〇 a Han word holds. */ +const PURE_HAN_RUN = /^[\p{Script=Han}々-〇]+$/u; + +/** + * A run of a script written without spaces that is neither Han, kana nor + * Hangul: Thai, Lao, Khmer and Myanmar. Cut by `Intl.Segmenter`, the fallback + * for an unspaced script with no dictionary segmenter here. + */ +const OTHER_UNSPACED_RUN = /[\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]+/gu; +const OTHER_UNSPACED_LOCALE: ReadonlyArray<[RegExp, string]> = [ + [/\p{Script=Thai}/u, 'th'], [/\p{Script=Lao}/u, 'lo'], [/\p{Script=Khmer}/u, 'km'], [/\p{Script=Myanmar}/u, 'my'], +]; + +function layer(base: Map, entries: readonly SegmenterEntry[], purpose: SegmenterPurpose): void { + for (const entry of entries) { + const applies = (entry.purpose ?? DEFAULT_SEGMENTER_PURPOSE) === purpose || entry.purpose === 'both'; + const key = keyOf(entry.term); + if (!applies || key === '') continue; + if (entry.enabled === false) { + if (base.get(key) === entry.kind) base.delete(key); + continue; + } + base.set(key, entry.kind); + } +} + +function lexiconOf(kinds: Map): Lexicon { + let longest = 0; + for (const key of kinds.keys()) longest = Math.max(longest, [...key].length); + return { kinds, longest }; +} + +function notImplemented(purpose: string): Error { + const err = new Error( + `The segmenter does not serve the purpose "${purpose}": it serves ${SERVED_PURPOSES.map((p) => `"${p}"`).join(', ')}. ` + + 'Record search keeps its own terms until a rule for it is written; call with purpose "knowledge", or with none.', + ) as Error & { code?: string; status?: number }; + err.code = StandardErrorCode.enum.NOT_IMPLEMENTED; + err.status = 501; + return err; +} + +/** One piece of a Han run after the longest match: a kept word, a dropped stop word, or text left to cut. */ +type Piece = { word: string } | { stop: true } | { span: string }; + +/** + * The service. Built once per process around one load of its dictionary + * segmenter, which it never retries: what `status()` answers at boot is what + * it answers for the life of the process. + * + * ## The rule, for purpose `knowledge` + * + * 1. The query is NFKC-normalised: fullwidth letters and digits fold to their + * ASCII forms, halfwidth kana to their usual forms. + * 2. A run of Han characters (an unspaced Chinese question is one, or a few) + * is matched against the layered words by longest match, left to right: a + * word is kept whole, a stop word of two or more characters is dropped. What + * is left is cut by the dictionary segmenter (jieba, HMM off); its words that + * are stop words are dropped, and the single characters that remain, where + * two or more stand side by side, are joined into overlapping words of two + * characters (年|假 → 年假). A single character alone is dropped, as a run of + * one always was. Without the dictionary segmenter, what is left is cut by + * the sliding windows of `keywordTerms` instead. + * 3. A run of Thai, Lao, Khmer or Myanmar is cut by `Intl.Segmenter`. + * 4. Everything else — English words, figures, document numbers, codes, and + * runs that hold kana or Hangul — is cut by `keywordTerms` from + * `@objectstack/core`, exactly as the knowledge adapters cut it today. + * 5. Stop words are dropped from the whole answer; the terms are deduplicated + * case-insensitively and capped at `MAX_KEYWORD_TERMS`, the words of steps + * 2 and 3 first, in query order, then those of step 4 in its own order. + */ +export class SegmenterService implements ISegmenterService { + private readonly segmenter: DictionarySegmenter | undefined; + private readonly load: SegmenterLoad; + private readonly platform: Map; + private readonly platformLexicon: Lexicon; + /** The layered lexicon of a supplied entries array, by identity: a caller that holds its entries gets them built once. */ + private readonly layered = new WeakMap(); + private readonly wordSegmenters = new Map(); + + constructor(load: SegmenterLoad) { + this.load = load; + this.segmenter = load.ok ? load.segmenter : undefined; + this.platform = new Map(); + for (const word of PLATFORM_WORDS) this.platform.set(keyOf(word), 'word'); + for (const word of PLATFORM_STOP_WORDS) this.platform.set(keyOf(word), 'stop_word'); + this.platformLexicon = lexiconOf(this.platform); + } + + status(): SegmenterStatus { + if (this.load.ok) return { engine: 'dictionary', segmenter: this.load.segmenter.name, purposes: SERVED_PURPOSES }; + return { + engine: 'sliding_window', + fallbackReason: this.load.reason, + ...(this.load.reason === 'load_failed' ? { error: this.load.error } : {}), + purposes: SERVED_PURPOSES, + }; + } + + keywordTerms(query: string, options: SegmenterTermsOptions = {}): string[] { + const purpose = options.purpose ?? DEFAULT_SEGMENTER_PURPOSE; + if (!SERVED_PURPOSES.includes(purpose)) throw notImplemented(purpose); + const lexicon = this.lexiconFor(purpose, options.entries); + const text = query.normalize('NFKC'); + + const segmented: string[] = []; + let residual = ''; + let at = 0; + // The two classes share no character, so their runs never overlap. + const runs = [ + ...[...text.matchAll(UNSEGMENTED_RUN)].map((m) => ({ at: m.index, chars: m[0], other: false })), + ...[...text.matchAll(OTHER_UNSPACED_RUN)].map((m) => ({ at: m.index, chars: m[0], other: true })), + ].sort((a, b) => a.at - b.at); + for (const run of runs) { + if (run.other) { + if (!this.otherScript(run.chars, segmented)) continue; // no Intl.Segmenter: one word, as today + residual += `${text.slice(at, run.at)} `; + } else { + if (!PURE_HAN_RUN.test(run.chars)) continue; // it holds kana or Hangul: the sliding windows, as today + residual += text.slice(at, run.at) + this.hanRun(run.chars, lexicon, segmented); + } + at = run.at + run.chars.length; + } + residual += text.slice(at); + + const stop = (term: string): boolean => lexicon.kinds.get(term.toLowerCase()) === 'stop_word'; + const seen = new Set(); + const terms: string[] = []; + for (const term of [...segmented, ...slidingWindowTerms(residual)]) { + const key = term.toLowerCase(); + if (seen.has(key) || stop(term)) continue; + seen.add(key); + terms.push(term); + if (terms.length === MAX_KEYWORD_TERMS) break; + } + return terms; + } + + private lexiconFor(purpose: SegmenterPurpose, entries: readonly SegmenterEntry[] | undefined): Lexicon { + if (!entries || entries.length === 0) return this.platformLexicon; + const cached = this.layered.get(entries); + if (cached && purpose === DEFAULT_SEGMENTER_PURPOSE) return cached; + const kinds = new Map(this.platform); + layer(kinds, entries, purpose); + const lexicon = lexiconOf(kinds); + if (purpose === DEFAULT_SEGMENTER_PURPOSE) this.layered.set(entries, lexicon); + return lexicon; + } + + /** + * Cut one pure Han run into `out`; answer what of it the sliding windows still + * cut (with the dictionary segmenter, nothing: a separator keeps the run's + * neighbours apart). + */ + private hanRun(run: string, lexicon: Lexicon, out: string[]): string { + const pieces = longestMatch(run, lexicon); + if (!this.segmenter) { + // The sliding-window fallback: kept words whole, stop words out, the rest windowed as today. + let rest = ' '; + for (const piece of pieces) { + if ('word' in piece) out.push(piece.word); + rest += 'span' in piece ? piece.span : ' '; + } + return `${rest} `; + } + let singles: string[] = []; + const flush = (): void => { + for (let i = 0; i + 1 < singles.length; i++) out.push(singles[i] + singles[i + 1]); + singles = []; + }; + for (const piece of pieces) { + if ('word' in piece) { + flush(); + out.push(piece.word); + } else if ('stop' in piece) { + flush(); + } else { + for (const token of this.segmenter.cut(piece.span)) { + if (lexicon.kinds.get(token.toLowerCase()) === 'stop_word') flush(); + else if ([...token].length === 1) singles.push(token); + else { + flush(); + out.push(token); + } + } + } + } + flush(); + return ' '; + } + + /** Cut a run of an unspaced script with no dictionary segmenter here; `false` when the host has no `Intl.Segmenter`. */ + private otherScript(run: string, out: string[]): boolean { + const locale = OTHER_UNSPACED_LOCALE.find(([script]) => script.test(run))?.[1] ?? 'th'; + if (!this.wordSegmenters.has(locale)) { + this.wordSegmenters.set( + locale, + typeof Intl.Segmenter === 'function' ? new Intl.Segmenter(locale, { granularity: 'word' }) : undefined, + ); + } + const segmenter = this.wordSegmenters.get(locale); + if (!segmenter) return false; + for (const { segment, isWordLike } of segmenter.segment(run)) { + if (isWordLike && [...segment].length > 1) out.push(segment); + } + return true; + } +} + +/** + * A Han run as the layered words see it, by longest match from the left: a + * word of any length, or a stop word of two characters or more (a stop word of + * one is left to the segmenter's words, where it would otherwise cut into a + * word holding it, as 有 into 有效期). + */ +function longestMatch(run: string, lexicon: Lexicon): Piece[] { + const chars = [...run]; + const pieces: Piece[] = []; + let span = ''; + for (let i = 0; i < chars.length; ) { + let matched = 0; + let kind: Kind | undefined; + for (let len = Math.min(lexicon.longest, chars.length - i); len >= 1; len--) { + const found = lexicon.kinds.get(chars.slice(i, i + len).join('').toLowerCase()); + if (found === 'word' || (found === 'stop_word' && len >= 2)) { + matched = len; + kind = found; + break; + } + } + if (matched === 0) { + span += chars[i]; + i += 1; + continue; + } + if (span !== '') pieces.push({ span }); + span = ''; + pieces.push(kind === 'word' ? { word: chars.slice(i, i + matched).join('') } : { stop: true }); + i += matched; + } + if (span !== '') pieces.push({ span }); + return pieces; +} + +/** + * Build the service around one load of its dictionary segmenter (by default + * `@node-rs/jieba`; a test hands in its own loader). + */ +export async function createSegmenterService(options: { loader?: SegmenterLoader } = {}): Promise { + return new SegmenterService(await (options.loader ?? jiebaLoader())()); +} diff --git a/packages/services/service-segmenter/tsconfig.json b/packages/services/service-segmenter/tsconfig.json new file mode 100644 index 00000000000..47a9084699e --- /dev/null +++ b/packages/services/service-segmenter/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "types": [ + "node" + ], + "lib": [ + "ES2022" + ] + }, + "include": [ + "src" + ], + "exclude": [ + "node_modules", + "dist" + ] +} diff --git a/packages/services/service-segmenter/tsup.config.ts b/packages/services/service-segmenter/tsup.config.ts new file mode 100644 index 00000000000..33d5b69f854 --- /dev/null +++ b/packages/services/service-segmenter/tsup.config.ts @@ -0,0 +1,22 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { defineConfig } from 'tsup'; + +import { dropSourcesContent } from '../../../scripts/tsup-drop-sources-content.mjs'; + +export default defineConfig({ + entry: ['src/index.ts'], + splitting: false, + sourcemap: true, + clean: true, + dts: !process.env.OS_SKIP_DTS, + format: ['esm', 'cjs'], + target: 'es2020', + // `@node-rs/jieba` is a native addon (a prebuilt binary per platform, picked + // at load) and an OPTIONAL dependency: it is loaded once, by a dynamic + // import, and its absence is a reported fallback, not a crash. Named here + // rather than left to tsup's dependency auto-externals, so the bundle never + // tries to resolve or inline it whatever field of package.json it sits in. + external: ['@node-rs/jieba', /^@node-rs\/jieba\//], + esbuildOptions: dropSourcesContent, +}); diff --git a/packages/services/service-segmenter/vitest.config.ts b/packages/services/service-segmenter/vitest.config.ts new file mode 100644 index 00000000000..092f3349553 --- /dev/null +++ b/packages/services/service-segmenter/vitest.config.ts @@ -0,0 +1,4 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// This package needs nothing beyond the shared preset; see its header. +export { default } from '../../../vitest.preset.mts'; diff --git a/packages/spec/src/contracts/core-service-contracts.test.ts b/packages/spec/src/contracts/core-service-contracts.test.ts index 9c458fa2ce1..aece451a527 100644 --- a/packages/spec/src/contracts/core-service-contracts.test.ts +++ b/packages/spec/src/contracts/core-service-contracts.test.ts @@ -23,6 +23,7 @@ import type { IWebhookService } from './webhook-service'; import type { ITriggerApiService } from './trigger-api-service'; import type { ICommentDoorsService } from './comment-doors-service'; import type { IPersonalViewDoorsService } from './personal-view-doors-service'; +import type { ISegmenterService } from './segmenter-service'; /** Compile-time assertion helper: fails to typecheck unless `T` is exactly `true`. */ type Expect = T; @@ -138,6 +139,8 @@ describe('slot → contract ledger beyond the enum', () => { expectTypeOf(getService('personal-views')).toEqualTypeOf(); expectTypeOf(getService('personal-views')?.handlePersonalViewDoor) .toEqualTypeOf(); + // The segmenter's slot, which a knowledge search reads at the moment it cuts a question. + expectTypeOf(getService('segmenter')).toEqualTypeOf(); // CONTROL: the same lookup resolves the slots that were already // mapped exactly as before. @@ -150,7 +153,7 @@ describe('slot → contract ledger beyond the enum', () => { it('holds exactly the non-core slots whose contract is written', () => { const extra = [ 'security', 'shareLinks', 'objectql', 'http.server', 'http-server', 'webhooks', 'trigger-api', 'comments', - 'personal-views', + 'personal-views', 'segmenter', ] as const; // Exact, not merely a subset: a key added to or dropped from the // non-core ledger without this list changing is a type error here. @@ -163,7 +166,7 @@ describe('slot → contract ledger beyond the enum', () => { // into `CoreServiceContracts` and this assertion is what catches it. expect(slots.has(key), `'${key}' is a CoreServiceName — move its entry into CoreServiceContracts`).toBe(false); } - expect(extra).toHaveLength(9); + expect(extra).toHaveLength(10); }); it('still resolves a slot with no written contract to unknown', () => { diff --git a/packages/spec/src/contracts/core-service-contracts.ts b/packages/spec/src/contracts/core-service-contracts.ts index 10c49f76787..45697b3762c 100644 --- a/packages/spec/src/contracts/core-service-contracts.ts +++ b/packages/spec/src/contracts/core-service-contracts.ts @@ -45,6 +45,7 @@ import type { IWebhookService } from './webhook-service'; import type { ITriggerApiService } from './trigger-api-service'; import type { ICommentDoorsService } from './comment-doors-service'; import type { IPersonalViewDoorsService } from './personal-view-doors-service'; +import type { ISegmenterService } from './segmenter-service'; /** * The evidenced slot → contract bindings. @@ -220,6 +221,15 @@ export interface ServiceSlotContracts extends CoreServiceContracts { * (`handlePersonalViewDoor`). */ 'personal-views': IPersonalViewDoorsService; + /** + * {@link ISegmenterService}, registered by `@objectstack/service-segmenter`: + * `SegmenterServicePlugin` registers it under `segmenter` + * (`SEGMENTER_SERVICE`) on every path, the sliding-window fallback + * included. Not a `CoreServiceName` member: an empty slot changes nothing + * at boot, and a reader answers with `keywordTerms` from + * `@objectstack/core` instead. + */ + segmenter: ISegmenterService; } /** diff --git a/packages/spec/src/contracts/index.ts b/packages/spec/src/contracts/index.ts index b21cc6d9438..682f251ae84 100644 --- a/packages/spec/src/contracts/index.ts +++ b/packages/spec/src/contracts/index.ts @@ -79,6 +79,7 @@ export * from './package-service.js'; export * from './knowledge-service.js'; export * from './knowledge-adapter.js'; export * from './embedder.js'; +export * from './segmenter-service.js'; // Provisioning & Deployment // './provisioning-service.js' (IProvisioningService) and './tenant-router.js' diff --git a/packages/spec/src/contracts/segmenter-service.ts b/packages/spec/src/contracts/segmenter-service.ts new file mode 100644 index 00000000000..ec8fe3e924c --- /dev/null +++ b/packages/spec/src/contracts/segmenter-service.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `ISegmenterService` — the keyword terms of a question, cut into real words. + * + * Implemented by `@objectstack/service-segmenter`, which registers it under + * {@link SEGMENTER_SERVICE}. A consumer depends on this contract only, never on + * the package, and resolves the slot where it cuts a question, not at boot: a + * kernel may compose no segmenter, and the slot's absence is not a verdict to + * keep. With the slot empty, the consumer answers with `keywordTerms` from + * `@objectstack/core`, the sliding-window rule the knowledge adapters use today. + * + * The answer has the shape that rule's answer has: an ordered list of distinct + * terms (compared case-insensitively), at most `MAX_KEYWORD_TERMS` of them, so + * a keyword leg built on that list takes this one unchanged. + * + * Words come in two layers, and the later one wins for a term: the + * provider's platform defaults (a supplementary dictionary and a stop-word + * list), then the entries the caller supplies ({@link SegmenterTermsOptions.entries}). + * The contract carries the entries, never where they are stored. + */ + +/** + * What a question is cut for. `knowledge` (knowledge retrieval) keeps only + * the words that identify a passage: stop words are dropped. `record_search` + * is reserved for record search, which needs a more conservative rule; no + * provider implements it yet, and a call for it is refused with + * `NOT_IMPLEMENTED` (read {@link SegmenterStatus.purposes} for what a + * provider serves). + */ +export type SegmenterPurpose = 'knowledge' | 'record_search'; + +/** The purpose a call takes when it names none. */ +export const DEFAULT_SEGMENTER_PURPOSE: SegmenterPurpose = 'knowledge'; + +/** Which calls an entry applies to: one purpose, or `both`. */ +export type SegmenterEntryPurpose = SegmenterPurpose | 'both'; + +/** + * What an entry makes of its term. `word`: the term is kept whole, never cut. + * `stop_word`: the term is dropped from every answer. + */ +export type SegmenterEntryKind = 'word' | 'stop_word'; + +/** One word a caller supplies, layered over the provider's platform defaults. */ +export interface SegmenterEntry { + /** The word itself, compared after NFKC normalisation and case-insensitively. */ + term: string; + kind: SegmenterEntryKind; + /** The calls it applies to. Absent: {@link DEFAULT_SEGMENTER_PURPOSE}. */ + purpose?: SegmenterEntryPurpose; + /** + * `false` withdraws the term from every layer below: a disabled `stop_word` + * entry keeps a platform stop word as a term, a disabled `word` entry stops + * protecting a platform word. Absent: `true`. + */ + enabled?: boolean; +} + +export interface SegmenterTermsOptions { + /** Absent: {@link DEFAULT_SEGMENTER_PURPOSE}. */ + purpose?: SegmenterPurpose; + /** + * The caller's layer, over the platform defaults. Within it a later entry + * for the same term wins over an earlier one. + */ + entries?: readonly SegmenterEntry[]; +} + +/** + * How a provider cuts a Han run. `dictionary`: by its dictionary segmenter. + * `sliding_window`: by the sliding-window rule of `keywordTerms`, because the + * dictionary segmenter is not available; supplied and platform words are still + * kept whole. + */ +export type SegmenterEngine = 'dictionary' | 'sliding_window'; + +/** + * Why a provider answers by sliding windows. `not_installed`: the segmenter's + * package is not installed. `load_failed`: it is installed and could not be + * loaded (a missing native binary for this platform, a broken dictionary). + */ +export type SegmenterFallbackReason = 'not_installed' | 'load_failed'; + +/** What a provider is doing right now, for diagnostics. */ +export interface SegmenterStatus { + engine: SegmenterEngine; + /** Present exactly when `engine` is `sliding_window`. */ + fallbackReason?: SegmenterFallbackReason; + /** The load error's message, when `fallbackReason` is `load_failed`. */ + error?: string; + /** The dictionary segmenter's name, when `engine` is `dictionary` (e.g. `'jieba'`). */ + segmenter?: string; + /** The purposes this provider serves; a call for any other is refused. */ + purposes: readonly SegmenterPurpose[]; +} + +export interface ISegmenterService { + /** + * The keyword terms of `query`. Throws an error with `code` + * `NOT_IMPLEMENTED` and `status` 501 for a purpose the provider does not + * serve. + */ + keywordTerms(query: string, options?: SegmenterTermsOptions): string[]; + status(): SegmenterStatus; +} + +/** DI service token for the kernel-registered {@link ISegmenterService}. */ +export const SEGMENTER_SERVICE = 'segmenter' as const; From ce638053ebb3f3135f78eb8c6d82517fee3e14f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:29:47 +0000 Subject: [PATCH 3/8] chore(spec): regenerate the contracts api-surface and export-origins for the segmenter contract Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- packages/spec/api-surface/contracts.json | 11 +++++++++++ packages/spec/export-origins/contracts.json | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index f012c7992d5..91ab8c10d83 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -115,6 +115,7 @@ "CryptoContextScope (type)", "CryptoHandle (interface)", "CubeMeta (interface)", + "DEFAULT_SEGMENTER_PURPOSE (const)", "DEFAULT_STORAGE_LIST_LIMIT (const)", "DatasetCompareTo (type)", "DatasetSelection (type)", @@ -230,6 +231,7 @@ "ISecurityService (interface)", "ISeedLoaderService (interface)", "ISeedSettlementService (interface)", + "ISegmenterService (interface)", "IServiceRegistry (interface)", "IShareLinkService (interface)", "ISharingRuleService (interface)", @@ -353,6 +355,7 @@ "RouteHandler (type)", "RunListResult (interface)", "SEED_SETTLEMENT_SERVICE (const)", + "SEGMENTER_SERVICE (const)", "SHARE_LINK_SERVICE (const)", "SaveNoticeChannel (interface)", "SchemaValidationReport (interface)", @@ -366,6 +369,14 @@ "SecurityContext (type)", "SeedSettlementSnapshot (interface)", "SeedSuppressionReason (type)", + "SegmenterEngine (type)", + "SegmenterEntry (interface)", + "SegmenterEntryKind (type)", + "SegmenterEntryPurpose (type)", + "SegmenterFallbackReason (type)", + "SegmenterPurpose (type)", + "SegmenterStatus (interface)", + "SegmenterTermsOptions (interface)", "SendEmailInput (interface)", "SendEmailResult (interface)", "SendSmsInput (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 4d03a5d5c49..d8761956281 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -115,6 +115,7 @@ "CryptoContextScope": "src/contracts/crypto-provider.ts#CryptoContextScope (type)", "CryptoHandle": "src/contracts/crypto-provider.ts#CryptoHandle (interface)", "CubeMeta": "src/contracts/analytics-service.ts#CubeMeta (interface)", + "DEFAULT_SEGMENTER_PURPOSE": "src/contracts/segmenter-service.ts#DEFAULT_SEGMENTER_PURPOSE (const)", "DEFAULT_STORAGE_LIST_LIMIT": "src/contracts/storage-service.ts#DEFAULT_STORAGE_LIST_LIMIT (const)", "DatasetCompareTo": "src/api/analytics.zod.ts#DatasetCompareTo (type)", "DatasetSelection": "src/api/analytics.zod.ts#DatasetSelection (type)", @@ -230,6 +231,7 @@ "ISecurityService": "src/contracts/security-service.ts#ISecurityService (interface)", "ISeedLoaderService": "src/contracts/seed-loader-service.ts#ISeedLoaderService (interface)", "ISeedSettlementService": "src/contracts/seed-settlement.ts#ISeedSettlementService (interface)", + "ISegmenterService": "src/contracts/segmenter-service.ts#ISegmenterService (interface)", "IServiceRegistry": "src/contracts/service-registry.ts#IServiceRegistry (interface)", "IShareLinkService": "src/contracts/share-link-service.ts#IShareLinkService (interface)", "ISharingRuleService": "src/contracts/sharing-service.ts#ISharingRuleService (interface)", @@ -353,6 +355,7 @@ "RouteHandler": "src/contracts/http-server.ts#RouteHandler (type)", "RunListResult": "src/contracts/automation-service.ts#RunListResult (interface)", "SEED_SETTLEMENT_SERVICE": "src/contracts/seed-settlement.ts#SEED_SETTLEMENT_SERVICE (const)", + "SEGMENTER_SERVICE": "src/contracts/segmenter-service.ts#SEGMENTER_SERVICE (const)", "SHARE_LINK_SERVICE": "src/contracts/share-link-service.ts#SHARE_LINK_SERVICE (const)", "SaveNoticeChannel": "src/contracts/automation-service.ts#SaveNoticeChannel (interface)", "SchemaValidationReport": "src/contracts/external-datasource-service.ts#SchemaValidationReport (interface)", @@ -366,6 +369,14 @@ "SecurityContext": "src/contracts/security-service.ts#SecurityContext (type)", "SeedSettlementSnapshot": "src/contracts/seed-settlement.ts#SeedSettlementSnapshot (interface)", "SeedSuppressionReason": "src/contracts/seed-settlement.ts#SeedSuppressionReason (type)", + "SegmenterEngine": "src/contracts/segmenter-service.ts#SegmenterEngine (type)", + "SegmenterEntry": "src/contracts/segmenter-service.ts#SegmenterEntry (interface)", + "SegmenterEntryKind": "src/contracts/segmenter-service.ts#SegmenterEntryKind (type)", + "SegmenterEntryPurpose": "src/contracts/segmenter-service.ts#SegmenterEntryPurpose (type)", + "SegmenterFallbackReason": "src/contracts/segmenter-service.ts#SegmenterFallbackReason (type)", + "SegmenterPurpose": "src/contracts/segmenter-service.ts#SegmenterPurpose (type)", + "SegmenterStatus": "src/contracts/segmenter-service.ts#SegmenterStatus (interface)", + "SegmenterTermsOptions": "src/contracts/segmenter-service.ts#SegmenterTermsOptions (interface)", "SendEmailInput": "src/contracts/email-service.ts#SendEmailInput (interface)", "SendEmailResult": "src/contracts/email-service.ts#SendEmailResult (interface)", "SendSmsInput": "src/contracts/sms-service.ts#SendSmsInput (interface)", From e5854c4dcab32c1ff595a72163a43d2d8290b17e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:50:33 +0000 Subject: [PATCH 4/8] docs(spec): llms.txt counts the new published package Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- packages/spec/llms.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 421abf76260..5583b1a11a9 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -178,9 +178,9 @@ function registerObject(rawConfig: unknown) { --- -## 7. Package Ecosystem (77 packages) +## 7. Package Ecosystem (78 packages) -The workspace publishes 77 packages under the `@objectstack` scope. The table +The workspace publishes 78 packages under the `@objectstack` scope. The table below is a curated entry-point list, not the full set — drivers, connectors, triggers, plugins and kernel-managed services each form their own family. From fe083e7eca3dab397e3e7701a357931b9bffb8f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:10:13 +0000 Subject: [PATCH 5/8] test(service-segmenter): run the tests against source, not dist Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- .../service-segmenter/vitest.config.ts | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/services/service-segmenter/vitest.config.ts b/packages/services/service-segmenter/vitest.config.ts index 092f3349553..6902da9d832 100644 --- a/packages/services/service-segmenter/vitest.config.ts +++ b/packages/services/service-segmenter/vitest.config.ts @@ -1,4 +1,26 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// This package needs nothing beyond the shared preset; see its header. -export { default } from '../../../vitest.preset.mts'; +// The shared preset's one setting, plus source aliases for the workspace +// packages these tests import: unaliased, the workspace links resolve to +// `dist/`, and a verdict about the segmenter (the sliding windows it is +// compared with, the contract it implements) would follow build state, not the +// checkout. `pnpm check:test-source-alias` is the gate. ANCHORED regexes in the +// array form: a bare string `find` matches by prefix, so `@objectstack/spec` +// would swallow `/contracts` into `…/src/index.ts/contracts`. +import { defineConfig } from 'vitest/config'; +import path from 'node:path'; + +export default defineConfig({ + test: { + // The shared preset's setting (`vitest.preset.mts`): a late console.* must + // not redden a green suite. Enforced by scripts/check-console-intercept-disarm.mjs. + disableConsoleIntercept: true, + }, + resolve: { + alias: [ + { find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') }, + { find: /^@objectstack\/spec\/api$/, replacement: path.resolve(__dirname, '../../spec/src/api/index.ts') }, + { find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(__dirname, '../../spec/src/contracts/index.ts') }, + ], + }, +}); From 75fcae78fcc4c1b7890b4ad73770bf4fbe8574fb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 13:37:19 +0000 Subject: [PATCH 6/8] fix(service-segmenter): one jieba per process, stop words compared whole, supplied words in any script Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- .changeset/38710-service-segmenter.md | 2 +- packages/core/src/keyword-terms.test.ts | 2 +- packages/core/src/keyword-terms.ts | 4 +- packages/services/service-segmenter/README.md | 24 +- .../service-segmenter/src/jieba-loader.ts | 70 ++++- .../service-segmenter/src/platform-words.ts | 16 +- .../src/segmenter-service-plugin.ts | 6 +- .../src/segmenter-service.test.ts | 76 ++++- .../src/segmenter-service.ts | 278 +++++++++--------- .../service-segmenter/vitest.config.ts | 6 +- .../spec/src/contracts/segmenter-service.ts | 29 +- 11 files changed, 323 insertions(+), 190 deletions(-) diff --git a/.changeset/38710-service-segmenter.md b/.changeset/38710-service-segmenter.md index ffdaff917da..c85d29e9120 100644 --- a/.changeset/38710-service-segmenter.md +++ b/.changeset/38710-service-segmenter.md @@ -9,7 +9,7 @@ feat(service-segmenter): a segmenter service that cuts a Chinese question into r Clause-②: yes Metadata-protocol: none -New package `@objectstack/service-segmenter`: `SegmenterServicePlugin` registers `ISegmenterService` under the `segmenter` slot. `keywordTerms(query, { purpose, entries })` answers a question's keyword terms in the shape the knowledge adapters' terms have today (distinct, at most 16). A run of Han characters is cut by `@node-rs/jieba` (HMM off, an optional dependency, loaded once per process) after a longest-match pass that keeps the platform's words (年假, 脱密, 应急采购, 超预算, …) and the caller's `word` entries whole; stop words are dropped and adjacent single characters are joined into two-character words. The query is NFKC-normalised first, a Thai, Lao, Khmer or Myanmar run is cut by `Intl.Segmenter`, and everything else (English, figures, codes, kana and Hangul runs) is cut exactly as before. Without jieba (not installed, or failed to load: the boot log names which, and `status()` reports it), the service answers by sliding windows with the layered words still kept whole. The purpose `record_search` is reserved and refused with `NOT_IMPLEMENTED`. +New package `@objectstack/service-segmenter`: `SegmenterServicePlugin` registers `ISegmenterService` under the `segmenter` slot. `keywordTerms(query, { purpose, entries })` answers a question's keyword terms in the shape the knowledge adapters' terms have today (distinct, at most 16). The caller's `word` entries are kept whole wherever the question spells them, in any script. A run of Han characters is cut by `@node-rs/jieba` (HMM off, an optional dependency, one instance per process) with the platform's words (年假, 脱密, 应急采购, 超预算, …) in its dictionary; a word equal to a stop word is dropped, and adjacent single characters are joined into two-character words. The query is NFKC-normalised first, a Thai, Lao, Khmer or Myanmar run is cut by `Intl.Segmenter`, and everything else (English, figures, codes, kana and Hangul runs) is cut exactly as before. Without jieba (not installed, or failed to load: the boot log names which, and `status()` reports it), the service answers by sliding windows with the supplied words still kept whole. The purpose `record_search` is reserved and refused with `NOT_IMPLEMENTED`. Nothing calls the service yet: the knowledge adapters keep their own terms until they read the slot. diff --git a/packages/core/src/keyword-terms.test.ts b/packages/core/src/keyword-terms.test.ts index c9844e99944..47ff2226770 100644 --- a/packages/core/src/keyword-terms.test.ts +++ b/packages/core/src/keyword-terms.test.ts @@ -67,6 +67,6 @@ describe('keywordTerms (sliding windows)', () => { it('splits with the same class as the libSQL and PostgreSQL stores', () => { // Both stores' tests pin the same literal against their own classes: keep the three pins, and so the three classes, identical. - expect(KEYWORD_SEPARATORS).toEqual(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%& -〄〈-〠〪-〰〶〷〽-〿!-/:-@[-`{-・‘-‟…]+/u); + expect(KEYWORD_SEPARATORS).toEqual(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u3020\u302a-\u3030\u3036\u3037\u303d-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u); }); }); diff --git a/packages/core/src/keyword-terms.ts b/packages/core/src/keyword-terms.ts index 4935b7d1890..e9f3c3a1ab4 100644 --- a/packages/core/src/keyword-terms.ts +++ b/packages/core/src/keyword-terms.ts @@ -32,7 +32,7 @@ export const MAX_KEYWORD_TERMS = 16; * 々 (U+3005), 〆 (U+3006) and 〇 (U+3007), named whatever their script (〆 * belongs to none). */ -export const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}々-〇ーー]+/gu; +export const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3005-\u3007\u30fc\uff70]+/gu; /** * Where the keyword leg splits a query into terms: white space, punctuation @@ -44,7 +44,7 @@ export const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Kata * repeat marks 〱–〵, 〼 and the Hangzhou numerals 〡–〩 and 〸–〺. * The same class as the libSQL and PostgreSQL stores'. */ -export const KEYWORD_SEPARATORS = /[\s,;:!?()[\]{}<>"'`|\\=*~^$%& -〄〈-〠〪-〰〶〷〽-〿!-/:-@[-`{-・‘-‟…]+/u; +export const KEYWORD_SEPARATORS = /[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u3020\u302a-\u3030\u3036\u3037\u303d-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u; /** * The terms of a query for the keyword leg: split at white space and at diff --git a/packages/services/service-segmenter/README.md b/packages/services/service-segmenter/README.md index 66977cf2ddb..07a7bf681bd 100644 --- a/packages/services/service-segmenter/README.md +++ b/packages/services/service-segmenter/README.md @@ -17,8 +17,8 @@ pnpm add @objectstack/service-segmenter `@node-rs/jieba` is an optional dependency with prebuilt binaries (Linux glibc and musl, macOS, Windows). Without it, or when it fails to load, the service still registers and answers by the -sliding windows of `keywordTerms` from `@objectstack/core`, with the platform words and supplied -words still kept whole. The boot log says which, and tells "not installed" apart from "failed to +sliding windows of `keywordTerms` from `@objectstack/core`, with the supplied words still kept +whole. The boot log says which, and tells "not installed" apart from "failed to load". ## Usage @@ -40,17 +40,21 @@ segmenter.status(); // { engine: 'dictionary', segmenter: 'jieba', purposes: ['k ## The rule (purpose `knowledge`) -1. NFKC normalisation: fullwidth letters and digits fold to ASCII. -2. A run of Han characters: the layered words are matched first, by longest match (a word is kept - whole, a stop word of two or more characters is dropped); the rest is cut by jieba, stop words - dropped, and adjacent single characters joined into words of two (年|假 → 年假). -3. A run of Thai, Lao, Khmer or Myanmar: cut by `Intl.Segmenter`. -4. Everything else — English words, figures, document numbers, codes, and runs holding kana or +1. NFKC normalisation between separators: fullwidth letters and digits fold to ASCII. +2. The supplied `word` entries are taken out of the whole question by longest match, in any script + (明规条款, `OA审批`, `5G套餐`), and kept whole. +3. A run of Han characters: cut by one process-wide jieba instance, with the platform words in its + dictionary. Words equal to a stop word are dropped (compared whole, so 还是 never eats 归还), and + adjacent single characters are joined into words of two (年|假 → 年假). Without jieba, the stop + words of two characters or more are taken out of the run and the rest is windowed. +4. A run of Thai, Lao, Khmer or Myanmar: cut by `Intl.Segmenter`. +5. Everything else — English words, figures, document numbers, codes, and runs holding kana or Hangul — exactly as `keywordTerms` from `@objectstack/core` cuts it. Two layers of words, the later one winning for a term: the platform's (`PLATFORM_WORDS`, -`PLATFORM_STOP_WORDS`), then the `entries` the caller passes. An entry with `enabled: false` -withdraws a platform word or stop word. The purpose `record_search` is reserved and refused with +`PLATFORM_STOP_WORDS`), then the `entries` the caller passes, read afresh on every call. An entry +with `enabled: false` withdraws a platform stop word or an earlier entry; the platform words live in +jieba's dictionary and are not withdrawn. The purpose `record_search` is reserved and refused with `NOT_IMPLEMENTED`. ## Exports diff --git a/packages/services/service-segmenter/src/jieba-loader.ts b/packages/services/service-segmenter/src/jieba-loader.ts index b7f8f62bad2..8d22e10e32b 100644 --- a/packages/services/service-segmenter/src/jieba-loader.ts +++ b/packages/services/service-segmenter/src/jieba-loader.ts @@ -1,6 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import type { SegmenterFallbackReason } from '@objectstack/spec/contracts'; +import { PLATFORM_WORDS } from './platform-words.js'; /** The part of a dictionary segmenter the service calls: a cut with the HMM off. */ export interface DictionarySegmenter { @@ -28,6 +29,7 @@ export type JiebaCutMode = 'cut' | 'cutForSearch'; export const JIEBA_CUT_MODE: JiebaCutMode = 'cut'; interface JiebaInstance { + loadDict(dict: Uint8Array): void; cut(sentence: string, hmm?: boolean): string[]; cutForSearch(sentence: string, hmm?: boolean): string[]; } @@ -62,24 +64,60 @@ function cjsExports(mod: unknown): T { } /** - * Load `@node-rs/jieba` with its default dictionary, once: one read-only - * instance for the process, with the HMM off (it guesses words a dictionary - * does not hold, and invents some, such as 能付 and 黑后). + * The frequency each platform word is added to jieba's dictionary with: high + * enough that jieba keeps the word whole where the question holds it (一年有几天 + * 年假 → 年假), low enough that a likelier split across it still wins (去年假期 → + * 去年 | 假期, never 去 | 年假 | 期). Measured on both kinds of sentence: 10 + * splits 年假, and every value from 100 to 10000 cuts both as above. + */ +export const PLATFORM_WORD_FREQUENCY = 1000; + +/** + * The one load of jieba in this process, shared by every loader and every + * service built on it: one read-only instance, with its default dictionary and + * the platform words. A load that failed is not retried either. + */ +let processJieba: Promise<{ ok: true; jieba: JiebaInstance } | { ok: false; reason: SegmenterFallbackReason; error: string }> | undefined; + +async function loadProcessJieba(): Promise<{ ok: true; jieba: JiebaInstance } | { ok: false; reason: SegmenterFallbackReason; error: string }> { + try { + const { Jieba } = cjsExports(await import('@node-rs/jieba')); + const { dict } = cjsExports(await import('@node-rs/jieba/dict.js')); + const jieba = Jieba.withDict(dict); + jieba.loadDict(new TextEncoder().encode(PLATFORM_WORDS.map((w) => `${w} ${PLATFORM_WORD_FREQUENCY}`).join('\n'))); + return { ok: true, jieba }; + } catch (e) { + return { + ok: false, + reason: isNotInstalled(e) ? 'not_installed' : 'load_failed', + error: e instanceof Error ? e.message : String(e), + }; + } +} + +/** The segmenter of each cut mode, built once over the process's one jieba. */ +const segmenters = new Map>(); + +/** + * Load `@node-rs/jieba` with its default dictionary and the platform words + * ({@link PLATFORM_WORDS}), once per process: one read-only instance, with the + * HMM off (it guesses words a dictionary does not hold, and invents some, such + * as 能付 and 黑后). Every call of every loader answers the same segmenter for + * a cut mode, and the two cut modes share the one instance. */ export function jiebaLoader(mode: JiebaCutMode = JIEBA_CUT_MODE): SegmenterLoader { - return async () => { - try { - const { Jieba } = cjsExports(await import('@node-rs/jieba')); - const { dict } = cjsExports(await import('@node-rs/jieba/dict.js')); - const jieba = Jieba.withDict(dict); - const cut = mode === 'cut' ? (text: string) => jieba.cut(text, false) : (text: string) => jieba.cutForSearch(text, false); - return { ok: true, segmenter: { name: 'jieba', cut } }; - } catch (e) { - return { - ok: false, - reason: isNotInstalled(e) ? 'not_installed' : 'load_failed', - error: e instanceof Error ? e.message : String(e), - }; + return () => { + let load = segmenters.get(mode); + if (!load) { + processJieba ??= loadProcessJieba(); + load = processJieba.then((loaded): SegmenterLoad => { + if (!loaded.ok) return loaded; + const { jieba } = loaded; + const cut = mode === 'cut' ? (text: string) => jieba.cut(text, false) : (text: string) => jieba.cutForSearch(text, false); + return { ok: true, segmenter: Object.freeze({ name: 'jieba', cut }) }; + }); + segmenters.set(mode, load); } + return load; }; } diff --git a/packages/services/service-segmenter/src/platform-words.ts b/packages/services/service-segmenter/src/platform-words.ts index e2ca9d3d678..4b92dd62f66 100644 --- a/packages/services/service-segmenter/src/platform-words.ts +++ b/packages/services/service-segmenter/src/platform-words.ts @@ -9,9 +9,11 @@ /** * Words kept whole, never cut: the terms of everyday policy text (leave, * expenses, procurement, confidentiality) that the segmenter's own dictionary - * splits, or that a question names in a form it does not hold. Each is matched - * by longest match before the segmenter runs, so it is kept whole on the - * sliding-window fallback too. + * splits, or that a question names in a form it does not hold. They are added + * to jieba's own dictionary (`PLATFORM_WORD_FREQUENCY`), so jieba weighs them + * against the words around them: 一年有几天年假 keeps 年假, while 去年假期 still + * cuts 去年 | 假期. On the sliding-window fallback they are windowed like any + * other text. */ export const PLATFORM_WORDS: readonly string[] = Object.freeze([ // Leave and attendance @@ -27,9 +29,11 @@ export const PLATFORM_WORDS: readonly string[] = Object.freeze([ /** * Words dropped from every answer: the function words and question words of * a colloquial question, which nearly every passage holds or none answers - * with. A word of one character is dropped before adjacent single characters - * are joined; a longer one is also matched before the segmenter runs, so it - * is dropped on the sliding-window fallback too. + * with. A segmenter word equal to one is dropped, compared whole, so a stop + * word never removes part of a word (还是 does not touch 归还 in 归还是否); a + * word of one character is dropped before adjacent single characters are + * joined. On the sliding-window fallback, the stop words of two characters or + * more are also taken out of a Han run before the windows run. */ export const PLATFORM_STOP_WORDS: readonly string[] = Object.freeze([ // One character diff --git a/packages/services/service-segmenter/src/segmenter-service-plugin.ts b/packages/services/service-segmenter/src/segmenter-service-plugin.ts index 2e6f4f8c1c3..63f10ded729 100644 --- a/packages/services/service-segmenter/src/segmenter-service-plugin.ts +++ b/packages/services/service-segmenter/src/segmenter-service-plugin.ts @@ -17,7 +17,7 @@ export interface SegmenterServicePluginOptions { * It loads its dictionary segmenter once, in init, and never retries: the * boot log says which segmentation the process runs, and `status()` answers * the same for its life. Without the segmenter the service still registers - * and answers by sliding windows, with the layered words still kept whole; the + * and answers by sliding windows, with supplied words still kept whole; the * log tells "not installed" (install the optional `@node-rs/jieba`) apart * from "failed to load" (its error is named). * @@ -46,13 +46,13 @@ export class SegmenterServicePlugin implements Plugin { } else if (status.fallbackReason === 'not_installed') { ctx.logger.warn( 'SegmenterServicePlugin: @node-rs/jieba is not installed, so Han text is cut by sliding windows ' + - '(supplied and platform words are still kept whole). Install the optional dependency @node-rs/jieba ' + + '(supplied words are still kept whole). Install the optional dependency @node-rs/jieba ' + 'to cut it into dictionary words.', ); } else { ctx.logger.warn( `SegmenterServicePlugin: @node-rs/jieba is installed but failed to load (${status.error}), so Han text is ` + - 'cut by sliding windows (supplied and platform words are still kept whole). Check that the prebuilt ' + + 'cut by sliding windows (supplied words are still kept whole). Check that the prebuilt ' + 'binary for this platform was installed.', ); } diff --git a/packages/services/service-segmenter/src/segmenter-service.test.ts b/packages/services/service-segmenter/src/segmenter-service.test.ts index 78f44b3523f..de87aa1475f 100644 --- a/packages/services/service-segmenter/src/segmenter-service.test.ts +++ b/packages/services/service-segmenter/src/segmenter-service.test.ts @@ -8,7 +8,7 @@ import { describe, expect, it } from 'vitest'; import { keywordTerms } from '@objectstack/core'; import type { SegmenterEntry } from '@objectstack/spec/contracts'; import { SegmenterService, createSegmenterService } from './segmenter-service.js'; -import { isNotInstalled, type SegmenterLoad } from './jieba-loader.js'; +import { isNotInstalled, jiebaLoader, type SegmenterLoad } from './jieba-loader.js'; const jieba = await createSegmenterService(); const failed: SegmenterLoad = { ok: false, reason: 'load_failed', error: 'Cannot find native binding' }; @@ -43,16 +43,42 @@ describe('SegmenterService — a Han run', () => { }); it('never yields a sliding fragment of three characters', () => { - for (const q of ['我在集团干了12年了,一年有几天年假?', '出差住宿费超预算怎么办', '涉密人员脱密期是多久']) { - const terms = jieba.keywordTerms(q); - const fragments = keywordTerms(q).filter((t) => [...t].length === 3 && !terms.includes(t)); - for (const fragment of fragments) expect(terms).not.toContain(fragment); - expect(terms.some((t) => ['我在集', '在集团', '集团干'].includes(t))).toBe(false); - } + // Of the windows' three-character pieces, only those that are dictionary words come back. + const shared = (q: string): string[] => { + const pieces = keywordTerms(q).filter((t) => [...t].length === 3); + expect(pieces.length, q).toBeGreaterThan(2); + return jieba.keywordTerms(q).filter((t) => pieces.includes(t)); + }; + expect(shared('我在集团干了12年了,一年有几天年假?')).toEqual([]); + expect(shared('涉密人员脱密期是多久')).toEqual(['脱密期']); + expect(shared('出差住宿费超预算怎么办')).toEqual(['住宿费', '超预算']); + }); + + it('drops a stop word only as a whole word, never out of a word that holds it', () => { + // 年假 is a platform word, but jieba weighs it: 去年 | 假期 is the likelier cut. + expect(jieba.keywordTerms('去年假期多少天')).toEqual(['去年', '假期']); + // The stop word 还是 sits across 归还 | 是否; it removes neither. + expect(jieba.keywordTerms('设备归还是否需要审批')).toEqual(['设备', '归还', '审批']); + // The stop word 所以 sits across 场所 | 以外. + expect(jieba.keywordTerms('办公场所以外')).toEqual(['办公', '场所', '以外']); + }); + + it('folds fullwidth letters and digits before it cuts (NFKC), and a folded separator still separates', () => { + expect(jieba.keywordTerms('ABC123型号')).toEqual(['型号', 'ABC123']); + // … is a separator; NFKC folds it to ..., which is not. It still splits the two terms. + expect(jieba.keywordTerms('pump…valve')).toEqual(['pump', 'valve']); + expect(jieba.keywordTerms('pump…valve')).toEqual(keywordTerms('pump…valve')); }); +}); - it('folds fullwidth letters and digits before it cuts (NFKC)', () => { - expect(jieba.keywordTerms('ABC123型号')).toEqual(['型号', 'ABC123']); +describe('SegmenterService — one jieba per process', () => { + it('shares one segmenter among every service and every loader call', async () => { + const [a, b] = await Promise.all([createSegmenterService(), createSegmenterService()]); + const segmenterOf = (s: SegmenterService): unknown => (s as unknown as { segmenter: unknown }).segmenter; + expect(segmenterOf(a)).toBeDefined(); + expect(segmenterOf(a)).toBe(segmenterOf(b)); + expect(segmenterOf(a)).toBe(segmenterOf(jieba)); + expect(await jiebaLoader()()).toBe(await jiebaLoader('cut')()); }); }); @@ -96,12 +122,41 @@ describe('SegmenterService — supplied entries over the platform defaults', () expect(jieba.keywordTerms('集团明规条款怎么查')).not.toContain('明规条款'); }); - it('withdraws a platform stop word or word with a disabled entry', () => { + it('withdraws a platform stop word, or an earlier entry, with a disabled entry', () => { expect(jieba.keywordTerms('是否报销')).toEqual(['报销']); expect(jieba.keywordTerms('是否报销', { entries: [{ term: '是否', kind: 'stop_word', enabled: false }] })).toEqual(['是否', '报销']); + const word: SegmenterEntry = { term: '明规条款', kind: 'word' }; + expect(jieba.keywordTerms('明规条款', { entries: [word] })).toEqual(['明规条款']); + expect(jieba.keywordTerms('明规条款', { entries: [word, { ...word, enabled: false }] })).not.toContain('明规条款'); + // A platform word lives in jieba's dictionary, which an entry does not reach (the contract says so). expect(jieba.keywordTerms('年假', { entries: [{ term: '年假', kind: 'word', enabled: false }] })).toEqual(['年假']); }); + it('keeps a supplied word whole in any script, wherever the question spells it', () => { + const entries: SegmenterEntry[] = [ + { term: 'OA审批', kind: 'word' }, + { term: '5g套餐', kind: 'word' }, + { term: 'コーヒー代', kind: 'word' }, + { term: 'sick leave', kind: 'word' }, + ]; + expect(jieba.keywordTerms('OA审批流程怎么走', { entries })).toEqual(['OA审批', '流程']); + // Matched after NFKC and case-insensitively: the fullwidth 5G folds, the case differs. + expect(jieba.keywordTerms('5G套餐多少钱', { entries })).toEqual(['5G套餐']); + expect(jieba.keywordTerms('コーヒー代は経費ですか', { entries })[0]).toBe('コーヒー代'); + expect(jieba.keywordTerms('how many days of sick leave', { entries })).toEqual(['sick leave', 'how', 'many', 'days', 'of']); + // A spaced-script edge touching another letter is not a match: OA is not found in OAuth. + expect(jieba.keywordTerms('OAuth登录', { entries: [{ term: 'OA', kind: 'word' }] })).toEqual(['登录', 'OAuth']); + }); + + it('reads the entries afresh on every call, an array changed in place included; empty is the same as absent', () => { + const entries: SegmenterEntry[] = []; + expect(jieba.keywordTerms('明规条款怎么查', { entries })).toEqual(jieba.keywordTerms('明规条款怎么查')); + entries.push({ term: '明规条款', kind: 'word' }); + expect(jieba.keywordTerms('明规条款怎么查', { entries })).toEqual(['明规条款']); + entries[0] = { term: '明规条款', kind: 'stop_word' }; + expect(jieba.keywordTerms('明规条款怎么查', { entries })).not.toContain('明规条款'); + }); + it('lets a later entry for the same term win, and ignores an entry for another purpose', () => { const entries: SegmenterEntry[] = [ { term: '报销', kind: 'stop_word' }, @@ -143,6 +198,7 @@ describe('SegmenterService — purpose', () => { describe('isNotInstalled', () => { it('tells the package missing apart from the package failing to load', () => { + // Hand-built errors, spelled as Node spells them (measured: an ESM import and a require of a missing package). const missing = Object.assign(new Error("Cannot find package '@node-rs/jieba' imported from /x.js"), { code: 'ERR_MODULE_NOT_FOUND' }); const nested = Object.assign(new Error("Cannot find module '@node-rs/jieba-linux-x64-gnu'"), { code: 'MODULE_NOT_FOUND' }); expect(isNotInstalled(missing)).toBe(true); diff --git a/packages/services/service-segmenter/src/segmenter-service.ts b/packages/services/service-segmenter/src/segmenter-service.ts index 79ef13cb2ee..ee4412d3aa3 100644 --- a/packages/services/service-segmenter/src/segmenter-service.ts +++ b/packages/services/service-segmenter/src/segmenter-service.ts @@ -1,6 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { MAX_KEYWORD_TERMS, UNSEGMENTED_RUN, keywordTerms as slidingWindowTerms } from '@objectstack/core'; +import { KEYWORD_SEPARATORS, MAX_KEYWORD_TERMS, UNSEGMENTED_RUN, keywordTerms as slidingWindowTerms } from '@objectstack/core'; import { StandardErrorCode } from '@objectstack/spec/api'; import { DEFAULT_SEGMENTER_PURPOSE, @@ -12,24 +12,38 @@ import { } from '@objectstack/spec/contracts'; import type { DictionarySegmenter, SegmenterLoad, SegmenterLoader } from './jieba-loader.js'; import { jiebaLoader } from './jieba-loader.js'; -import { PLATFORM_STOP_WORDS, PLATFORM_WORDS } from './platform-words.js'; +import { PLATFORM_STOP_WORDS } from './platform-words.js'; /** The purposes this provider serves. Record search is reserved and refused. */ export const SERVED_PURPOSES: readonly SegmenterPurpose[] = Object.freeze(['knowledge']); type Kind = SegmenterEntry['kind']; -/** The layered words of one call: each key (NFKC, lower-cased) and what it is. */ + +/** A set of terms matched by longest match, and how far the match looks ahead. */ +interface Matcher { + keys: ReadonlySet; + /** The longest key, in code points. */ + longest: number; +} + +/** The layered words of one call. Built afresh for every call that supplies entries; nothing outlives the call. */ interface Lexicon { + /** Each layered term (the platform stop words, then the supplied entries) and its kind, by {@link keyOf}. */ kinds: ReadonlyMap; - /** The longest key, in code points: how far the longest match looks ahead. */ - longest: number; + /** The supplied `word` entries, matched over the whole question before anything is cut. */ + words: Matcher; + /** The stop words of two characters or more, matched inside a Han run on the sliding-window fallback only. */ + stops: Matcher; } -/** A term's comparison key: NFKC, then lower case, as the terms are deduplicated. */ -const keyOf = (term: string): string => term.normalize('NFKC').trim().toLowerCase(); +/** Lower case, character by character, so a key and the text it is matched in keep one code point per character. */ +const lower = (text: string): string => [...text].map((c) => c.toLowerCase()).join(''); + +/** A term's comparison key: NFKC, trimmed, lower case. */ +const keyOf = (term: string): string => lower(term.normalize('NFKC').trim()); /** A run of Han characters only, with the marks 々, 〆 and 〇 a Han word holds. */ -const PURE_HAN_RUN = /^[\p{Script=Han}々-〇]+$/u; +const PURE_HAN_RUN = /^[\p{Script=Han}\u3005-\u3007]+$/u; /** * A run of a script written without spaces that is neither Han, kana nor @@ -41,23 +55,44 @@ const OTHER_UNSPACED_LOCALE: ReadonlyArray<[RegExp, string]> = [ [/\p{Script=Thai}/u, 'th'], [/\p{Script=Lao}/u, 'lo'], [/\p{Script=Khmer}/u, 'km'], [/\p{Script=Myanmar}/u, 'my'], ]; -function layer(base: Map, entries: readonly SegmenterEntry[], purpose: SegmenterPurpose): void { +/** One character of an unspaced script: the sliding windows' class, or one of the scripts `Intl.Segmenter` cuts. */ +const UNSPACED_CHAR = new RegExp(`^(?:${UNSEGMENTED_RUN.source}|${OTHER_UNSPACED_RUN.source})$`, 'u'); + +/** + * Is `c` a letter or digit of a script written with spaces (Latin, Cyrillic, + * Greek, digits …)? A supplied word is not matched where such an edge of it + * touches another such character: `OA` is not found inside `OAuth`, while + * `OA审批` is found in `OA审批流程` and 年假 anywhere in a Han run. + */ +const spacedLetter = (c: string | undefined): boolean => c !== undefined && /[\p{L}\p{N}]/u.test(c) && !UNSPACED_CHAR.test(c); + +function matcherOf(keys: Iterable): Matcher { + const set = new Set(keys); + let longest = 0; + for (const key of set) longest = Math.max(longest, [...key].length); + return { keys: set, longest }; +} + +function lexiconOf(entries: readonly SegmenterEntry[], purpose: SegmenterPurpose): Lexicon { + const kinds = new Map(); + for (const word of PLATFORM_STOP_WORDS) kinds.set(keyOf(word), 'stop_word'); for (const entry of entries) { const applies = (entry.purpose ?? DEFAULT_SEGMENTER_PURPOSE) === purpose || entry.purpose === 'both'; const key = keyOf(entry.term); if (!applies || key === '') continue; if (entry.enabled === false) { - if (base.get(key) === entry.kind) base.delete(key); + if (kinds.get(key) === entry.kind) kinds.delete(key); continue; } - base.set(key, entry.kind); + kinds.set(key, entry.kind); } -} - -function lexiconOf(kinds: Map): Lexicon { - let longest = 0; - for (const key of kinds.keys()) longest = Math.max(longest, [...key].length); - return { kinds, longest }; + const words: string[] = []; + const stops: string[] = []; + for (const [key, kind] of kinds) { + if (kind === 'word') words.push(key); + else if ([...key].length >= 2) stops.push(key); + } + return { kinds, words: matcherOf(words), stops: matcherOf(stops) }; } function notImplemented(purpose: string): Error { @@ -70,51 +105,83 @@ function notImplemented(purpose: string): Error { return err; } -/** One piece of a Han run after the longest match: a kept word, a dropped stop word, or text left to cut. */ -type Piece = { word: string } | { stop: true } | { span: string }; +/** A term and where it starts in the question, for query order. */ +interface Placed { + at: number; + term: string; +} /** - * The service. Built once per process around one load of its dictionary - * segmenter, which it never retries: what `status()` answers at boot is what - * it answers for the life of the process. + * Take the matcher's terms out of `text` by longest match, left to right: each + * found term is placed, and its span becomes one separator, so nothing cut + * later reaches into it. + */ +function takeOut(text: string, matcher: Matcher, found: Placed[], at = 0): string { + if (matcher.longest === 0) return text; + const chars = [...text]; + const lowered = chars.map((c) => c.toLowerCase()); + let rest = ''; + for (let i = 0; i < chars.length; ) { + let hit = 0; + for (let len = Math.min(matcher.longest, chars.length - i); len >= 1; len--) { + if (!matcher.keys.has(lowered.slice(i, i + len).join(''))) continue; + if (spacedLetter(chars[i]) && spacedLetter(chars[i - 1])) continue; + if (spacedLetter(chars[i + len - 1]) && spacedLetter(chars[i + len])) continue; + hit = len; + break; + } + if (hit === 0) { + rest += chars[i]; + i += 1; + continue; + } + found.push({ at: at + rest.length, term: chars.slice(i, i + hit).join('') }); + rest += ' '; + i += hit; + } + return rest; +} + +/** + * The service. Every instance in a process shares the one load of its + * dictionary segmenter (`jiebaLoader`), which is never retried: what + * `status()` answers at boot is what it answers for the life of the process. * * ## The rule, for purpose `knowledge` * - * 1. The query is NFKC-normalised: fullwidth letters and digits fold to their - * ASCII forms, halfwidth kana to their usual forms. - * 2. A run of Han characters (an unspaced Chinese question is one, or a few) - * is matched against the layered words by longest match, left to right: a - * word is kept whole, a stop word of two or more characters is dropped. What - * is left is cut by the dictionary segmenter (jieba, HMM off); its words that - * are stop words are dropped, and the single characters that remain, where - * two or more stand side by side, are joined into overlapping words of two - * characters (年|假 → 年假). A single character alone is dropped, as a run of - * one always was. Without the dictionary segmenter, what is left is cut by - * the sliding windows of `keywordTerms` instead. - * 3. A run of Thai, Lao, Khmer or Myanmar is cut by `Intl.Segmenter`. - * 4. Everything else — English words, figures, document numbers, codes, and + * 1. The query is NFKC-normalised between its separators (a separator NFKC + * would fold into a term character, such as … into ..., still separates): + * fullwidth letters and digits fold to their ASCII forms, halfwidth kana to + * their usual forms. + * 2. The supplied `word` entries are taken out of the whole question first, by + * longest match, in any script, and kept whole. + * 3. A run of Han characters (an unspaced Chinese question is one, or a few) + * is cut by the dictionary segmenter (jieba, HMM off, the platform words in + * its dictionary). Its words that are stop words are dropped, compared whole, + * and the single characters that remain, where two or more stand side by + * side, are joined into overlapping words of two characters (年|假 → 年假). A + * single character alone is dropped, as a run of one always was. Without the + * dictionary segmenter, the stop words of two characters or more are taken + * out of the run by longest match, and the rest is cut by the sliding windows + * of `keywordTerms`. + * 4. A run of Thai, Lao, Khmer or Myanmar is cut by `Intl.Segmenter`. + * 5. Everything else — English words, figures, document numbers, codes, and * runs that hold kana or Hangul — is cut by `keywordTerms` from - * `@objectstack/core`, exactly as the knowledge adapters cut it today. - * 5. Stop words are dropped from the whole answer; the terms are deduplicated + * `@objectstack/core`, as the knowledge adapters cut it today. + * 6. Stop words are dropped from the whole answer; the terms are deduplicated * case-insensitively and capped at `MAX_KEYWORD_TERMS`, the words of steps - * 2 and 3 first, in query order, then those of step 4 in its own order. + * 2–4 first, in query order, then those of step 5 in its own order. */ export class SegmenterService implements ISegmenterService { private readonly segmenter: DictionarySegmenter | undefined; private readonly load: SegmenterLoad; - private readonly platform: Map; private readonly platformLexicon: Lexicon; - /** The layered lexicon of a supplied entries array, by identity: a caller that holds its entries gets them built once. */ - private readonly layered = new WeakMap(); private readonly wordSegmenters = new Map(); constructor(load: SegmenterLoad) { this.load = load; this.segmenter = load.ok ? load.segmenter : undefined; - this.platform = new Map(); - for (const word of PLATFORM_WORDS) this.platform.set(keyOf(word), 'word'); - for (const word of PLATFORM_STOP_WORDS) this.platform.set(keyOf(word), 'stop_word'); - this.platformLexicon = lexiconOf(this.platform); + this.platformLexicon = lexiconOf([], DEFAULT_SEGMENTER_PURPOSE); } status(): SegmenterStatus { @@ -130,10 +197,16 @@ export class SegmenterService implements ISegmenterService { keywordTerms(query: string, options: SegmenterTermsOptions = {}): string[] { const purpose = options.purpose ?? DEFAULT_SEGMENTER_PURPOSE; if (!SERVED_PURPOSES.includes(purpose)) throw notImplemented(purpose); - const lexicon = this.lexiconFor(purpose, options.entries); - const text = query.normalize('NFKC'); + // Read afresh on every call: the contract promises a changed entry takes effect on the next call. + const lexicon = options.entries && options.entries.length > 0 ? lexiconOf(options.entries, purpose) : this.platformLexicon; + + const placed: Placed[] = []; + const text = takeOut( + query.split(KEYWORD_SEPARATORS).map((piece) => piece.normalize('NFKC')).join(' '), + lexicon.words, + placed, + ); - const segmented: string[] = []; let residual = ''; let at = 0; // The two classes share no character, so their runs never overlap. @@ -143,20 +216,21 @@ export class SegmenterService implements ISegmenterService { ].sort((a, b) => a.at - b.at); for (const run of runs) { if (run.other) { - if (!this.otherScript(run.chars, segmented)) continue; // no Intl.Segmenter: one word, as today + if (!this.otherScript(run.chars, run.at, placed)) continue; // no Intl.Segmenter: one word, as today residual += `${text.slice(at, run.at)} `; } else { if (!PURE_HAN_RUN.test(run.chars)) continue; // it holds kana or Hangul: the sliding windows, as today - residual += text.slice(at, run.at) + this.hanRun(run.chars, lexicon, segmented); + residual += text.slice(at, run.at) + this.hanRun(run.chars, run.at, lexicon, placed); } at = run.at + run.chars.length; } residual += text.slice(at); - const stop = (term: string): boolean => lexicon.kinds.get(term.toLowerCase()) === 'stop_word'; + const stop = (term: string): boolean => lexicon.kinds.get(lower(term)) === 'stop_word'; const seen = new Set(); const terms: string[] = []; - for (const term of [...segmented, ...slidingWindowTerms(residual)]) { + const ordered = placed.sort((a, b) => a.at - b.at).map((p) => p.term); + for (const term of [...ordered, ...slidingWindowTerms(residual)]) { const key = term.toLowerCase(); if (seen.has(key) || stop(term)) continue; seen.add(key); @@ -166,53 +240,30 @@ export class SegmenterService implements ISegmenterService { return terms; } - private lexiconFor(purpose: SegmenterPurpose, entries: readonly SegmenterEntry[] | undefined): Lexicon { - if (!entries || entries.length === 0) return this.platformLexicon; - const cached = this.layered.get(entries); - if (cached && purpose === DEFAULT_SEGMENTER_PURPOSE) return cached; - const kinds = new Map(this.platform); - layer(kinds, entries, purpose); - const lexicon = lexiconOf(kinds); - if (purpose === DEFAULT_SEGMENTER_PURPOSE) this.layered.set(entries, lexicon); - return lexicon; - } - /** - * Cut one pure Han run into `out`; answer what of it the sliding windows still - * cut (with the dictionary segmenter, nothing: a separator keeps the run's - * neighbours apart). + * Cut one pure Han run, starting at `at` in the question, into `out`; answer + * what of it the sliding windows still cut (with the dictionary segmenter, + * nothing: a separator keeps the run's neighbours apart). */ - private hanRun(run: string, lexicon: Lexicon, out: string[]): string { - const pieces = longestMatch(run, lexicon); + private hanRun(run: string, at: number, lexicon: Lexicon, out: Placed[]): string { if (!this.segmenter) { - // The sliding-window fallback: kept words whole, stop words out, the rest windowed as today. - let rest = ' '; - for (const piece of pieces) { - if ('word' in piece) out.push(piece.word); - rest += 'span' in piece ? piece.span : ' '; - } - return `${rest} `; + // The sliding-window fallback: stop words of two characters or more out, the rest windowed as today. + return ` ${takeOut(run, lexicon.stops, [], at)} `; } - let singles: string[] = []; + let singles: Placed[] = []; const flush = (): void => { - for (let i = 0; i + 1 < singles.length; i++) out.push(singles[i] + singles[i + 1]); + for (let i = 0; i + 1 < singles.length; i++) out.push({ at: singles[i].at, term: singles[i].term + singles[i + 1].term }); singles = []; }; - for (const piece of pieces) { - if ('word' in piece) { + let offset = at; + for (const token of this.segmenter.cut(run)) { + const here = offset; + offset += token.length; + if (lexicon.kinds.get(lower(token)) === 'stop_word') flush(); + else if ([...token].length === 1) singles.push({ at: here, term: token }); + else { flush(); - out.push(piece.word); - } else if ('stop' in piece) { - flush(); - } else { - for (const token of this.segmenter.cut(piece.span)) { - if (lexicon.kinds.get(token.toLowerCase()) === 'stop_word') flush(); - else if ([...token].length === 1) singles.push(token); - else { - flush(); - out.push(token); - } - } + out.push({ at: here, term: token }); } } flush(); @@ -220,7 +271,7 @@ export class SegmenterService implements ISegmenterService { } /** Cut a run of an unspaced script with no dictionary segmenter here; `false` when the host has no `Intl.Segmenter`. */ - private otherScript(run: string, out: string[]): boolean { + private otherScript(run: string, at: number, out: Placed[]): boolean { const locale = OTHER_UNSPACED_LOCALE.find(([script]) => script.test(run))?.[1] ?? 'th'; if (!this.wordSegmenters.has(locale)) { this.wordSegmenters.set( @@ -230,51 +281,16 @@ export class SegmenterService implements ISegmenterService { } const segmenter = this.wordSegmenters.get(locale); if (!segmenter) return false; - for (const { segment, isWordLike } of segmenter.segment(run)) { - if (isWordLike && [...segment].length > 1) out.push(segment); + for (const { segment, index, isWordLike } of segmenter.segment(run)) { + if (isWordLike && [...segment].length > 1) out.push({ at: at + index, term: segment }); } return true; } } /** - * A Han run as the layered words see it, by longest match from the left: a - * word of any length, or a stop word of two characters or more (a stop word of - * one is left to the segmenter's words, where it would otherwise cut into a - * word holding it, as 有 into 有效期). - */ -function longestMatch(run: string, lexicon: Lexicon): Piece[] { - const chars = [...run]; - const pieces: Piece[] = []; - let span = ''; - for (let i = 0; i < chars.length; ) { - let matched = 0; - let kind: Kind | undefined; - for (let len = Math.min(lexicon.longest, chars.length - i); len >= 1; len--) { - const found = lexicon.kinds.get(chars.slice(i, i + len).join('').toLowerCase()); - if (found === 'word' || (found === 'stop_word' && len >= 2)) { - matched = len; - kind = found; - break; - } - } - if (matched === 0) { - span += chars[i]; - i += 1; - continue; - } - if (span !== '') pieces.push({ span }); - span = ''; - pieces.push(kind === 'word' ? { word: chars.slice(i, i + matched).join('') } : { stop: true }); - i += matched; - } - if (span !== '') pieces.push({ span }); - return pieces; -} - -/** - * Build the service around one load of its dictionary segmenter (by default - * `@node-rs/jieba`; a test hands in its own loader). + * Build the service around the process's one load of its dictionary segmenter + * (by default `@node-rs/jieba`; a test hands in its own loader). */ export async function createSegmenterService(options: { loader?: SegmenterLoader } = {}): Promise { return new SegmenterService(await (options.loader ?? jiebaLoader())()); diff --git a/packages/services/service-segmenter/vitest.config.ts b/packages/services/service-segmenter/vitest.config.ts index 6902da9d832..6a4f24f7b7c 100644 --- a/packages/services/service-segmenter/vitest.config.ts +++ b/packages/services/service-segmenter/vitest.config.ts @@ -18,9 +18,9 @@ export default defineConfig({ }, resolve: { alias: [ - { find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') }, - { find: /^@objectstack\/spec\/api$/, replacement: path.resolve(__dirname, '../../spec/src/api/index.ts') }, - { find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(__dirname, '../../spec/src/contracts/index.ts') }, + { find: /^@objectstack\/core$/, replacement: path.resolve(import.meta.dirname, '../../core/src/index.ts') }, + { find: /^@objectstack\/spec\/api$/, replacement: path.resolve(import.meta.dirname, '../../spec/src/api/index.ts') }, + { find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(import.meta.dirname, '../../spec/src/contracts/index.ts') }, ], }, }); diff --git a/packages/spec/src/contracts/segmenter-service.ts b/packages/spec/src/contracts/segmenter-service.ts index ec8fe3e924c..02068313bff 100644 --- a/packages/spec/src/contracts/segmenter-service.ts +++ b/packages/spec/src/contracts/segmenter-service.ts @@ -37,8 +37,18 @@ export const DEFAULT_SEGMENTER_PURPOSE: SegmenterPurpose = 'knowledge'; export type SegmenterEntryPurpose = SegmenterPurpose | 'both'; /** - * What an entry makes of its term. `word`: the term is kept whole, never cut. - * `stop_word`: the term is dropped from every answer. + * What an entry makes of its term. + * + * - `word`: the term is kept whole wherever the question spells it (after NFKC + * normalisation, case-insensitively), in any script: 明规条款, `OA审批`, + * `5G套餐`, a kana or Hangul word, a phrase with one space. A term that + * begins or ends with a letter or digit of a spaced script (Latin, Cyrillic, + * digits …) is not found where that edge touches another such character, so + * `OA` is not found inside `OAuth`. + * - `stop_word`: a term of the answer equal to it is dropped, compared whole; + * a stop word never removes part of a word. (A provider answering by + * sliding windows may also take a stop word out of an unspaced run before it + * windows the run.) */ export type SegmenterEntryKind = 'word' | 'stop_word'; @@ -50,9 +60,10 @@ export interface SegmenterEntry { /** The calls it applies to. Absent: {@link DEFAULT_SEGMENTER_PURPOSE}. */ purpose?: SegmenterEntryPurpose; /** - * `false` withdraws the term from every layer below: a disabled `stop_word` - * entry keeps a platform stop word as a term, a disabled `word` entry stops - * protecting a platform word. Absent: `true`. + * `false` withdraws the same term of the same kind from below the entry: a + * platform stop word, or an earlier entry of the same layer. A provider's + * platform words may live inside its dictionary segmenter, where an entry + * cannot withdraw them. Absent: `true`. */ enabled?: boolean; } @@ -62,7 +73,11 @@ export interface SegmenterTermsOptions { purpose?: SegmenterPurpose; /** * The caller's layer, over the platform defaults. Within it a later entry - * for the same term wins over an earlier one. + * for the same term wins over an earlier one. Read afresh on every call, and + * never cached across calls: an entry changed, added or removed takes effect + * on the next call, whether the caller passes a new array or the same one + * changed in place. Absent and empty mean the same: the platform defaults + * alone. */ entries?: readonly SegmenterEntry[]; } @@ -70,7 +85,7 @@ export interface SegmenterTermsOptions { /** * How a provider cuts a Han run. `dictionary`: by its dictionary segmenter. * `sliding_window`: by the sliding-window rule of `keywordTerms`, because the - * dictionary segmenter is not available; supplied and platform words are still + * dictionary segmenter is not available; supplied `word` entries are still * kept whole. */ export type SegmenterEngine = 'dictionary' | 'sliding_window'; From 9556620f39a3db21ec9373242bab795bb6b40ef7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 01:09:24 +0000 Subject: [PATCH 7/8] docs(spec): a supplied word holding a separator other than one space is not found, and a test pins it Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- packages/services/service-segmenter/README.md | 3 ++- .../src/segmenter-service.test.ts | 17 +++++++++++++++++ .../spec/src/contracts/segmenter-service.ts | 4 +++- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/services/service-segmenter/README.md b/packages/services/service-segmenter/README.md index 07a7bf681bd..d993f185793 100644 --- a/packages/services/service-segmenter/README.md +++ b/packages/services/service-segmenter/README.md @@ -42,7 +42,8 @@ segmenter.status(); // { engine: 'dictionary', segmenter: 'jieba', purposes: ['k 1. NFKC normalisation between separators: fullwidth letters and digits fold to ASCII. 2. The supplied `word` entries are taken out of the whole question by longest match, in any script - (明规条款, `OA审批`, `5G套餐`), and kept whole. + (明规条款, `OA审批`, `5G套餐`), and kept whole. A word that holds a separator other than a single + space (`R&D`, 《员工手册》) is not found: the question is split at its separators first. 3. A run of Han characters: cut by one process-wide jieba instance, with the platform words in its dictionary. Words equal to a stop word are dropped (compared whole, so 还是 never eats 归还), and adjacent single characters are joined into words of two (年|假 → 年假). Without jieba, the stop diff --git a/packages/services/service-segmenter/src/segmenter-service.test.ts b/packages/services/service-segmenter/src/segmenter-service.test.ts index de87aa1475f..d1d8607f92d 100644 --- a/packages/services/service-segmenter/src/segmenter-service.test.ts +++ b/packages/services/service-segmenter/src/segmenter-service.test.ts @@ -148,6 +148,23 @@ describe('SegmenterService — supplied entries over the platform defaults', () expect(jieba.keywordTerms('OAuth登录', { entries: [{ term: 'OA', kind: 'word' }] })).toEqual(['登录', 'OAuth']); }); + it('does not find a supplied word that holds a separator other than a single space', () => { + // The question is split at the keyword separators before the words are matched, so a word holding + // one never matches whole (the contract says so); the pieces around the separator are cut as usual. + const entries: SegmenterEntry[] = [ + { term: 'R&D', kind: 'word' }, + { term: '《员工手册》', kind: 'word' }, + ]; + const rd = jieba.keywordTerms('R&D预算怎么申请', { entries }); + expect(rd).not.toContain('R&D'); + expect(rd).toEqual(jieba.keywordTerms('R&D预算怎么申请')); + const handbook = jieba.keywordTerms('《员工手册》在哪里看', { entries }); + expect(handbook).not.toContain('《员工手册》'); + expect(handbook).toEqual(jieba.keywordTerms('《员工手册》在哪里看')); + // Control: the same title without its marks is found whole. + expect(jieba.keywordTerms('员工手册在哪里看', { entries: [{ term: '员工手册', kind: 'word' }] })).toContain('员工手册'); + }); + it('reads the entries afresh on every call, an array changed in place included; empty is the same as absent', () => { const entries: SegmenterEntry[] = []; expect(jieba.keywordTerms('明规条款怎么查', { entries })).toEqual(jieba.keywordTerms('明规条款怎么查')); diff --git a/packages/spec/src/contracts/segmenter-service.ts b/packages/spec/src/contracts/segmenter-service.ts index 02068313bff..2e191f71346 100644 --- a/packages/spec/src/contracts/segmenter-service.ts +++ b/packages/spec/src/contracts/segmenter-service.ts @@ -44,7 +44,9 @@ export type SegmenterEntryPurpose = SegmenterPurpose | 'both'; * `5G套餐`, a kana or Hangul word, a phrase with one space. A term that * begins or ends with a letter or digit of a spaced script (Latin, Cyrillic, * digits …) is not found where that edge touches another such character, so - * `OA` is not found inside `OAuth`. + * `OA` is not found inside `OAuth`. A term that holds a separator other than + * a single space (`R&D`, 《员工手册》, 办法(试行)) is not found: the question is + * split at its separators before the words are matched. * - `stop_word`: a term of the answer equal to it is dropped, compared whole; * a stop word never removes part of a word. (A provider answering by * sliding windows may also take a stop word out of an unspaced run before it From ff965718b660afca4bd19665286ff69d28ffa364 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 03:37:19 +0000 Subject: [PATCH 8/8] chore(spec): regenerate the contracts api-surface and export-origins after merging main Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude --- packages/spec/api-surface/contracts.json | 3 +++ packages/spec/export-origins/contracts.json | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 91ab8c10d83..ef89a9527d6 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", + "AdapterRetrievalCapability (interface)", "AdapterScopeTerm (type)", "AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities (interface)", @@ -222,6 +223,7 @@ "IPubSub (interface)", "IQueueService (interface)", "IRealtimeService (interface)", + "IReranker (interface)", "IRlsMembershipResolver (interface)", "ISchemaDiffService (interface)", "ISchemaDriver (interface)", @@ -333,6 +335,7 @@ "QueueMessage (interface)", "QueueMessageRecord (interface)", "QueuePublishOptions (interface)", + "RERANKER_SERVICE (const)", "RESERVED_RLS_MEMBERSHIP_KEYS (const)", "RESUME_AUTHORITY_SERVICE (const)", "RLS_MEMBERSHIP_RESOLVER_SERVICE (const)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index d8761956281..ebb7b8911ea 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", + "AdapterRetrievalCapability": "src/contracts/knowledge-adapter.ts#AdapterRetrievalCapability (interface)", "AdapterScopeTerm": "src/contracts/knowledge-adapter.ts#AdapterScopeTerm (type)", "AdapterSearchOptions": "src/contracts/knowledge-adapter.ts#AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities": "src/contracts/analytics-service.ts#AnalyticsDriverCapabilities (interface)", @@ -222,6 +223,7 @@ "IPubSub": "src/contracts/cluster-service.ts#IPubSub (interface)", "IQueueService": "src/contracts/queue-service.ts#IQueueService (interface)", "IRealtimeService": "src/contracts/realtime-service.ts#IRealtimeService (interface)", + "IReranker": "src/contracts/reranker.ts#IReranker (interface)", "IRlsMembershipResolver": "src/contracts/rls-membership-resolver.ts#IRlsMembershipResolver (interface)", "ISchemaDiffService": "src/contracts/schema-diff-service.ts#ISchemaDiffService (interface)", "ISchemaDriver": "src/contracts/schema-driver.ts#ISchemaDriver (interface)", @@ -333,6 +335,7 @@ "QueueMessage": "src/contracts/queue-service.ts#QueueMessage (interface)", "QueueMessageRecord": "src/contracts/queue-service.ts#QueueMessageRecord (interface)", "QueuePublishOptions": "src/contracts/queue-service.ts#QueuePublishOptions (interface)", + "RERANKER_SERVICE": "src/contracts/reranker.ts#RERANKER_SERVICE (const)", "RESERVED_RLS_MEMBERSHIP_KEYS": "src/contracts/rls-membership-resolver.ts#RESERVED_RLS_MEMBERSHIP_KEYS (const)", "RESUME_AUTHORITY_SERVICE": "src/contracts/automation-service.ts#RESUME_AUTHORITY_SERVICE (const)", "RLS_MEMBERSHIP_RESOLVER_SERVICE": "src/contracts/rls-membership-resolver.ts#RLS_MEMBERSHIP_RESOLVER_SERVICE (const)",