Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/38710-service-segmenter.md
Original file line number Diff line number Diff line change
@@ -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). 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.

`@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.
1 change: 1 addition & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
72 changes: 72 additions & 0 deletions packages/core/src/keyword-terms.test.ts
Original file line number Diff line number Diff line change
@@ -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,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u3020\u302a-\u3030\u3036\u3037\u303d-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u);
});
});
97 changes: 97 additions & 0 deletions packages/core/src/keyword-terms.ts
Original file line number Diff line number Diff line change
@@ -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}\u3005-\u3007\u30fc\uff70]+/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,;:!?()[\]{}<>"'`|\\=*~^$%&\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
* 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<string>();
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;
}
Loading
Loading