From 5d9b5d9842055da83f26124a9753152a37d5b91d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 00:40:47 +0000 Subject: [PATCH 1/8] test(knowledge): red pins for the segmented keyword terms (step 2 of #38710) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Failing tests first: the knowledge service hands each adapter the keyword terms its segmenter cuts (年假 whole, no three-character window), a sys_search_term record changes the next search with no rebuild on this replica and on a peer, and both stores rank by the handed terms. The segmenter plugin stores one entry per normalised term and source, and offers its Setup entry. Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- .../src/__tests__/keyword-terms.test.ts | 12 + .../src/__tests__/acceptance.test.ts | 26 ++ .../services/service-knowledge/package.json | 1 + .../src/__tests__/search-terms-38710.test.ts | 247 ++++++++++++++++++ .../search-term-object.integration.test.ts | 42 ++- pnpm-lock.yaml | 3 + 6 files changed, 322 insertions(+), 9 deletions(-) create mode 100644 packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts index e00037b8755..a3f2aaddd6c 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts @@ -117,4 +117,16 @@ describe('knowledge-pgvector keyword leg statement', () => { expect(operatorOf('%出差%')).toBe('LIKE'); expect(operatorOf('%ab%')).toBe('ILIKE'); }); + + it('matches the terms the knowledge service hands, not its own cut of the question (ADR-0161, the dated note of 2026-12-05 under K8)', async () => { + const { pool, ranked } = recordingPool(); + const adapter = new PgvectorKnowledgeAdapter({ id: 'kw', pool, embedder: new FakeEmbedder() }); + const question = '我在集团干了 12 年了,一年有几天年假?'; + await adapter.search(question, { source, topK: 5, index: { fingerprint: 'fp' }, keywordTerms: ['集团', '一年', '年假', '12'] }); + expect(ranked).toHaveLength(1); + const { values } = ranked[0]; + expect(values).toEqual(expect.arrayContaining(['%集团%', '%一年%', '%年假%'])); + // None of the sliding windows its own cut would have sent. + for (const window of ['%我在集%', '%在集团%', '%集团干%']) expect(values).not.toContain(window); + }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 14491e09692..1a7832d31e0 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1898,3 +1898,29 @@ describe('knowledge-turso through KnowledgeService: the question is embedded at expect(String((refused as Error).message)).toContain('63-wide query vector'); }); }); + +describe('knowledge-turso: the keyword terms the knowledge service hands (ADR-0161, the dated note of 2026-12-05 under K8)', () => { + const store = storeOf('memory'); + afterAll(() => store.closeAll()); + const QUESTION = '我在集团干了 12 年了,一年有几天年假?'; + // What the segmenter cuts the question into: words, no sliding window. + const CUT = ['集团', '一年', '年假', '12']; + + it('ranks by the handed terms, not by its own cut of the question', async () => { + const adapter = store.adapter(); + const s = source('kw_handed'); + await adapter.upsert( + [doc(s, 'leave', '员工每年享有年假五天'), doc(s, 'travel', '出差住宿标准为每晚三百元'), doc(s, 'stock', '仓库盘点每月一次')], + ctx(s), + ); + const keyword = { source: s, topK: 3, retrieval: { mode: 'keyword' as const } }; + // Its own cut: sixteen windows, none of them 年假, none held by a passage. + expect(keywordTerms(QUESTION)).not.toContain('年假'); + expect(await adapter.search(QUESTION, keyword)).toEqual([]); + // Handed the words: the passage on annual leave, first. + const hits = await adapter.search(QUESTION, { ...keyword, keywordTerms: CUT }); + expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:leave`]); + // Handed none: nothing to match, so a keyword search answers nothing. + expect(await adapter.search(QUESTION, { ...keyword, keywordTerms: [] })).toEqual([]); + }); +}); diff --git a/packages/services/service-knowledge/package.json b/packages/services/service-knowledge/package.json index 41262e2ce98..0c0896aafc7 100644 --- a/packages/services/service-knowledge/package.json +++ b/packages/services/service-knowledge/package.json @@ -43,6 +43,7 @@ "@objectstack/driver-sql": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/service-queue": "workspace:*", + "@objectstack/service-segmenter": "workspace:*", "@types/node": "^26.6.5", "tsx": "^4.23.15", "typescript": "^6.0.3", diff --git a/packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts b/packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts new file mode 100644 index 00000000000..9db63748797 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts @@ -0,0 +1,247 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The keyword terms of a search are cut once, by the knowledge service, and +// handed to every adapter it searches (ADR-0161, the dated note of 2026-12-05 +// under K8). The service cuts with the kernel's segmenter (`ISegmenterService`) +// and the administrator's 检索词条 (`sys_search_term`), read on a real stack: +// `ObjectQL` over a real SQL driver, with the object as `SegmenterServicePlugin` +// registers it. Without a segmenter the service hands no terms, and the adapter +// cuts the question itself (`keywordTerms` of `@objectstack/core`). +// +// What is pinned: +// - a Chinese question reaches the adapter as words (年假 whole), with no +// three-character sliding window; +// - a record added, changed or disabled changes the next search's terms, with +// no rebuild, on this replica at once and on a peer through the cluster +// channel, and on a peer that missed the message once the cache expires; +// - entries apply in the order the contract reads them: the unscoped ones +// first, then the source's own, each by `created_at` then `id`; +// - a record naming a source no deployment holds is refused at write, and an +// entry left naming a source that is gone is said once at `warn`. + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SegmenterServicePlugin } from '@objectstack/service-segmenter'; +import type { AdapterSearchOptions, IKnowledgeAdapter, IPubSub, ISegmenterService } from '@objectstack/spec/contracts'; +import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { + SEARCH_TERM_CHANGE_CLUSTER_CHANNEL, + SEARCH_TERMS_TTL_MS, + bindSearchTermHooks, +} from '../knowledge-search-terms.js'; + +const SYSTEM = { positions: [], permissions: [], isSystem: true }; +const OBJECT = 'sys_search_term'; +const QUESTION = '我在集团干了 12 年了,一年有几天年假?'; +const WINDOWS = ['我在集', '在集团', '集团干', '团干了', '一年有', '年有几', '有几天', '几天年', '天年假']; + +function source(name: string): KnowledgeSource { + return { + name, + label: name, + adapter: 'rec', + source: { kind: 'object', object: 'policy', content: ['body'] } as ObjectKnowledgeSource, + }; +} + +/** An adapter that records what each search is handed. */ +function recordingAdapter() { + const seen: AdapterSearchOptions[] = []; + const adapter: IKnowledgeAdapter = { + id: 'rec', + capabilities: { retrieval: { modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' } }, + upsert: vi.fn(async () => undefined), + delete: vi.fn(async () => undefined), + search: vi.fn(async (_q: string, o: AdapterSearchOptions): Promise => { + seen.push(o); + return []; + }), + }; + return { adapter, seen }; +} + +/** One in-process bus shared by the replicas of a test: a message reaches every subscriber, the sender's own included. */ +function sharedBus(): IPubSub { + const handlers = new Map void>>(); + return { + publish: async (channel, payload) => { + for (const h of handlers.get(channel) ?? []) h({ payload }); + }, + subscribe: (channel, handler) => { + const set = handlers.get(channel) ?? new Set(); + handlers.set(channel, set); + set.add(handler as never); + return () => set.delete(handler as never); + }, + close: async () => undefined, + } as IPubSub; +} + +interface Stack { + engine: ObjectQL; + segmenter: ISegmenterService; +} + +/** One database with `sys_search_term` registered and normalised by the segmenter plugin, as the runtime mounts it. */ +async function stack(): Promise { + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never), + true, + ); + await engine.init(); + const bundles: unknown[] = []; + const services: Record = { objectql: engine, manifest: { register: (m: unknown) => bundles.push(m) } }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + await new SegmenterServicePlugin().init(ctx as never); + for (const bundle of bundles) engine.registerApp(bundle as never); + await engine.syncSchemas(); + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + return { engine, segmenter: services.segmenter as ISegmenterService }; +} + +/** A replica: its own knowledge service over the shared database, with the hooks the plugin binds. */ +function replica(st: Stack, sources: KnowledgeSource[], opts: { segmenter?: boolean } = {}) { + const logger = { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }; + const svc = new KnowledgeService({ + dataEngine: st.engine as never, + logger: logger as never, + resolveSegmenter: () => (opts.segmenter === false ? undefined : st.segmenter), + }); + const rec = recordingAdapter(); + svc.registerAdapter('rec', rec.adapter); + for (const s of sources) svc.registerSource(s); + const terms = async (query = QUESTION, sourceId = sources[0]!.name): Promise => { + rec.seen.length = 0; + await svc.searchWithRefusals(query, { sourceIds: [sourceId], executionContext: SYSTEM }); + expect(rec.seen).not.toHaveLength(0); + return rec.seen[0]!.keywordTerms; + }; + return { svc, rec, logger, terms }; +} + +const write = (st: Stack, row: Record) => st.engine.insert(OBJECT, row, { context: SYSTEM } as never) as Promise<{ id: string }>; + +describe('knowledge search: the keyword terms are cut once by the service and handed to the adapter', () => { + let st: Stack; + beforeEach(async () => { + st = await stack(); + }); + + it('a Chinese question reaches the adapter as words: 年假 whole, no three-character sliding window', async () => { + const one = replica(st, [source('handbook')]); + bindSearchTermHooks(st.engine as never, one.svc); + const terms = await one.terms(); + expect(terms).toContain('年假'); + for (const window of WINDOWS) expect(terms).not.toContain(window); + // A keyword-only source is handed the same terms; a vector-only one is cut for nothing. + expect(await one.terms('pump X-200 warranty')).toEqual(['pump', 'X-200', 'warranty']); + }); + + it('without a segmenter no terms are handed: the adapter cuts the question itself', async () => { + const one = replica(st, [source('handbook')], { segmenter: false }); + expect(await one.terms()).toBeUndefined(); + }); + + it('a record added changes the next search, with no rebuild', async () => { + const one = replica(st, [source('handbook')]); + bindSearchTermHooks(st.engine as never, one.svc); + expect(await one.terms()).toContain('集团'); + await write(st, { term: '集团', kind: 'stop_word' }); + expect(await one.terms()).not.toContain('集团'); + await write(st, { term: '几天年假', kind: 'word' }); + expect(await one.terms()).toContain('几天年假'); + // Nothing was indexed again: terms are cut from the question alone. + expect(one.rec.adapter.upsert).not.toHaveBeenCalled(); + }); + + it('reads the unscoped entries first, then the source\'s own, each by created_at then id', async () => { + const one = replica(st, [source('handbook'), source('contracts')]); + bindSearchTermHooks(st.engine as never, one.svc); + // An unscoped stop word, then the same term disabled for one source: a + // later entry of the same kind withdraws the earlier one there only. + await write(st, { term: '集团', kind: 'stop_word' }); + await write(st, { term: '集团', kind: 'stop_word', knowledge_source: 'handbook', enabled: false }); + expect(await one.terms(QUESTION, 'handbook')).toContain('集团'); + expect(await one.terms(QUESTION, 'contracts')).not.toContain('集团'); + }); + + it('refuses a record naming a source the deployment does not hold, and says once when an entry\'s source is gone', async () => { + const one = replica(st, [source('handbook')]); + bindSearchTermHooks(st.engine as never, one.svc); + const refusal = await write(st, { term: '明规条款', kind: 'word', knowledge_source: 'hand_book' }).then( + () => null, + (e: unknown) => e as Record, + ); + expect(refusal).toMatchObject({ code: 'VALIDATION_FAILED', status: 400 }); + // A source that existed when the entry was written, and is gone since. + one.svc.registerSource(source('retired')); + await write(st, { term: '明规条款', kind: 'word', knowledge_source: 'retired' }); + one.svc.unregisterSource('retired'); + await one.terms(); + await one.terms(); + const said = one.logger.warn.mock.calls.filter(([m]) => String(m).includes("'retired'")); + expect(said).toHaveLength(1); + }); +}); + +describe('knowledge search terms across replicas', () => { + let st: Stack; + beforeEach(async () => { + st = await stack(); + vi.useFakeTimers({ toFake: ['Date'] }); + }); + afterEach(() => vi.useRealTimers()); + + it('a record written on one replica changes the next search on another, through the cluster channel', async () => { + const bus = sharedBus(); + const a = replica(st, [source('handbook')]); + const b = replica(st, [source('handbook')]); + // Only the replica that takes the write hears its hook. + bindSearchTermHooks(st.engine as never, a.svc); + a.svc.attachSearchTermChangePubSub(bus, 'node-a'); + b.svc.attachSearchTermChangePubSub(bus, 'node-b'); + expect(await b.terms()).toContain('集团'); + await write(st, { term: '集团', kind: 'stop_word' }); + expect(await a.terms()).not.toContain('集团'); + expect(await b.terms()).not.toContain('集团'); + }); + + it('a peer that missed the message reads the change once its cache expires', async () => { + const a = replica(st, [source('handbook')]); + const b = replica(st, [source('handbook')]); + bindSearchTermHooks(st.engine as never, a.svc); + expect(await b.terms()).toContain('集团'); + await write(st, { term: '集团', kind: 'stop_word' }); + // No channel: b still serves what it read. + expect(await b.terms()).toContain('集团'); + vi.setSystemTime(Date.now() + SEARCH_TERMS_TTL_MS + 1); + expect(await b.terms()).not.toContain('集团'); + }); + + it('publishes an address only, and ignores its own message', async () => { + const published: unknown[] = []; + const bus = sharedBus(); + const spy = vi.spyOn(bus, 'publish').mockImplementation(async (channel, payload) => { + published.push({ channel, payload }); + }); + const a = replica(st, [source('handbook')]); + bindSearchTermHooks(st.engine as never, a.svc); + a.svc.attachSearchTermChangePubSub(bus, 'node-a'); + await write(st, { term: '集团', kind: 'stop_word' }); + expect(spy).toHaveBeenCalled(); + expect(published[0]).toEqual({ + channel: SEARCH_TERM_CHANGE_CLUSTER_CHANNEL, + payload: { originNode: 'node-a', at: expect.any(String) }, + }); + }); +}); diff --git a/packages/services/service-segmenter/src/search-term-object.integration.test.ts b/packages/services/service-segmenter/src/search-term-object.integration.test.ts index eb0f77a0459..7273cd0481d 100644 --- a/packages/services/service-segmenter/src/search-term-object.integration.test.ts +++ b/packages/services/service-segmenter/src/search-term-object.integration.test.ts @@ -9,8 +9,10 @@ * * What is pinned: * - * - the plugin registers the object, and no Setup entry with it (nothing reads - * a record until step 2 of objectstack#38710, so no screen is offered yet); + * - the plugin registers the object with its Setup entry, which lands with + * the knowledge service's reader, so no screen is offered that does nothing; + * - one entry per term and source: the plugin's hooks store the term's key + * (`keyOf`) and an empty source as `''`, under a unique index; * - reads and writes are the platform administrator's: a caller without * `manage_platform_settings` is refused create, update, delete and read * with the permission envelope (`PERMISSION_DENIED`, 403), even with a full @@ -27,7 +29,7 @@ * - the fields are the contract's entry one to one: records read back and * passed as `entries` change the service's answer as the contract says. * (Who reads the records for a search, and how a source's records are - * picked, is step 2; this pins only that the shapes meet.) + * picked, is the knowledge service's; this pins only that the shapes meet.) */ import { describe, it, expect, beforeAll, vi } from 'vitest'; @@ -38,7 +40,7 @@ import { SysSearchTerm } from '@objectstack/platform-objects/system'; import type { SegmenterEntry } from '@objectstack/spec/contracts'; import { resolveThrownHttpError } from '@objectstack/types'; import { SEARCH_TERM_BUNDLE_ID, SegmenterServicePlugin } from './segmenter-service-plugin.js'; -import { createSegmenterService } from './segmenter-service.js'; +import { createSegmenterService, keyOf } from './segmenter-service.js'; const OBJECT = 'sys_search_term'; @@ -99,18 +101,18 @@ async function boot(): Promise { return services[name]; }, }; - await new SegmenterServicePlugin().init(ctx as never); - const engine = new ObjectQL(); engine.registerDriver( new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never), true, ); await engine.init(); + // The engine first, as the kernel orders it (the plugin's optional dependency): the plugin binds its hooks on it. + services.objectql = engine; + await new SegmenterServicePlugin().init(ctx as never); for (const bundle of bundles) engine.registerApp(bundle as never); await engine.syncSchemas(); - services.objectql = engine; services.metadata = { get: async (type: string, name: string) => (type === 'permission' ? SETS.find((s) => s.name === name) : engine.getSchema(name)) ?? null, @@ -131,16 +133,38 @@ describe('sys_search_term, registered by SegmenterServicePlugin, on a real stack stack = await boot(); }); - it('is registered by the plugin, with no Setup entry', () => { + it('is registered by the plugin, with its Setup entry for the platform administrator', () => { const mine = stack.bundles.filter((b) => b.id === SEARCH_TERM_BUNDLE_ID); expect(mine).toHaveLength(1); const [bundle] = mine; expect(bundle).toMatchObject({ id: SEARCH_TERM_BUNDLE_ID, namespace: 'sys', scope: 'system' }); expect(bundle.objects).toEqual([SysSearchTerm]); - expect(bundle.navigationContributions).toBeUndefined(); + // The knowledge service reads the records (step 2), so the screen lands with the reader. + expect(bundle.navigationContributions).toEqual([ + expect.objectContaining({ + app: 'setup', + items: [expect.objectContaining({ type: 'object', objectName: OBJECT, requiresObject: OBJECT, requiredPermissions: ['manage_platform_settings'] })], + }), + ]); expect(stack.engine.getSchema(OBJECT)).toBeDefined(); }); + it('stores one entry per normalised term and source: NFKC, trimmed, lower case; no source stored as empty', async () => { + const { engine } = await boot(); + const created = (await engine.insert(OBJECT, { term: 'OA审批', kind: 'word' }, { context: admin() } as never)) as Record; + expect(created).toMatchObject({ term: 'OA审批', term_key: keyOf('OA审批'), knowledge_source: '' }); + expect(keyOf('OA审批')).toBe('oa审批'); + // The same term under another spelling, for every source: refused by the unique key. + await expect(engine.insert(OBJECT, { term: 'oa审批', kind: 'stop_word', knowledge_source: null }, { context: admin() } as never)).rejects.toBeDefined(); + // For one source it is another entry. + await expect(engine.insert(OBJECT, { term: 'oa审批', kind: 'stop_word', knowledge_source: 'handbook' }, { context: admin() } as never)) + .resolves.toMatchObject({ term_key: 'oa审批', knowledge_source: 'handbook' }); + // A rename of the term moves its key. + await engine.update(OBJECT, { id: created.id, term: '明规条款' }, { context: admin() } as never); + const [row] = (await engine.find(OBJECT, { where: { id: created.id }, context: SYS_CTX } as never)) as Array>; + expect(row).toMatchObject({ term: '明规条款', term_key: '明规条款', knowledge_source: '' }); + }); + it('refuses create, update, delete and read to a caller without manage_platform_settings, whatever its grant', async () => { const { engine } = stack; const seeded = (await engine.insert(OBJECT, { term: '制度汇编', kind: 'word' }, { context: SYS_CTX } as never)) as { id: string }; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f00d6234a39..7667890495b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3291,6 +3291,9 @@ importers: '@objectstack/service-queue': specifier: workspace:* version: link:../service-queue + '@objectstack/service-segmenter': + specifier: workspace:* + version: link:../service-segmenter '@types/node': specifier: ^26.6.5 version: 26.6.5 From 70a8ff37fd627448f594ea9071ced1a2636f4e66 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 00:41:21 +0000 Subject: [PATCH 2/8] docs(adr-0161): K8 note for AdapterSearchOptions.keywordTerms (step 2 of #38710) An eleventh dated note under K8 registers one optional member: the knowledge service cuts the question once with the kernel's segmenter and the administrator's search words, and hands the terms to every adapter. Read with K1's "Hybrid retrieval" row: how a term is matched and how the legs fuse stay the adapter's. Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- ...ord-return-knowledge-source-is-a-governed-type.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index 7a8d8edd5ab..0016d0bd2d2 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -26,6 +26,7 @@ - **Amended** (2026-12-01, [#38438](https://github.com/objectstack-ai/objectstack/issues/38438)): an eighth dated note, under the list of [Consequences](#consequences), records that the service keeps a sync state for each source, where the bullet "A stored fingerprint and recipe hash are the only index state the service relies on" says "The service keeps none of its own". Built by [#38307](https://github.com/objectstack-ai/objectstack/pull/38307). Whether an index is due for a build is still read from the stored fingerprint and recipe hash. It decides nothing and adds no contract member. The status line above is left as it is. - **Amended** (2026-12-01, [#38676](https://github.com/objectstack-ai/objectstack/issues/38676)): a ninth dated note, under "Rules for every member" in [K8](#k8--the-contract-additions-decided-item-by-item), registers two contract members, both optional: `IKnowledgeAdapter.embedQuery`, by which an adapter embeds the question of a search as its own `search` embeds it, and `AdapterSearchOptions.queryVector`, by which the knowledge service carries that vector back to the adapter instance that made it, for every `search` call of that search, the refill round included. It is read with the "Embedding calls" row of [K1](#k1--the-boundary), with the second sentence of the list under that section and with item 15 of K8, and it amends none of them: the adapter still embeds, with its own embedder and query prefix, at the point where it embeds today, and the service computes no vector. Decided by the maintainer on 2026-12-01, by his choice of the decision card's option 「写进约定,一次提问只转一次」 at 00:22Z (ruling record [`7296268226`](https://github.com/objectstack-ai/objectstack/issues/38676#issuecomment-7296268226) on #38676), which carries one condition: 「附带条件:存储驱动原本会给出的拒绝提示(比如“需要重建索引”)要保持在前面,不能被转向量的报错盖掉。」 The note states that condition as an outcome and names the means it takes, a function the adapter calls where it embeds today, which fixes the second member's type. A cross-reference stands under [K1](#k1--the-boundary). The status line above is left as it is. - **Amended** (2026-12-03, [#39346](https://github.com/objectstack-ai/objectstack/issues/39346)): a tenth dated note under the table of [K8](#k8--the-contract-additions-decided-item-by-item), below the note of 2026-11-28 on item 12, amends one sentence of that note. Under "◆ Ruled: an author's save" it says of the package duplicate door: "What it answers where no knowledge service is registered, and to a caller who may not search what a source indexes, is unchanged". The first half of that sentence is amended: where no knowledge service is registered, the duplicate is not refused for that reason and copies each knowledge source unserved; the caller is asked the capability gate and is not asked whether they may search what a source indexes, because nothing on such a deployment can judge it. Ruling D of #37983 stands: an author's save there is refused as before. Decided by the maintainer on 2026-12-03, by his choice of the decision card's option 「A 放行复制,知识源不生效」 (ruling record [`7380897321`](https://github.com/objectstack-ai/objectstack/issues/38374#issuecomment-7380897321) on #38374). It adds no contract member, no door value and no settings key. The status line above is left as it is. +- **Amended** (2026-12-05, [#38710](https://github.com/objectstack-ai/objectstack/issues/38710)): an eleventh dated note, under "Rules for every member" in [K8](#k8--the-contract-additions-decided-item-by-item), registers one contract member, optional: `AdapterSearchOptions.keywordTerms`, the keyword terms of the question, cut once by the knowledge service with the kernel's segmenter and the administrator's search words, and handed to every adapter the search calls. It is read with the "Hybrid retrieval" row of [K1](#k1--the-boundary) and amends none of its words: the adapter still decides how a term is matched and how the legs are fused. Written on the maintainer's words of 2026-11-30 that open #38710, 「首要解决的应该是 用中文分词词典在应用层切词(Node 有现成的库),只留真正的词。」, and on the rulings of that card (records `7272241375` and `7272436453`). The status line above is left as it is. --- @@ -507,6 +508,17 @@ Rules for every member: > > This note registers exactly two members, `IKnowledgeAdapter.embedQuery` and `AdapterSearchOptions.queryVector`, and no other: the list stays closed beyond them (rules 3 and 5). It declares, and PR #38798 builds it; the PR that lands this note changes no file under `packages/`. A reader that finds one of the two shapes cannot be built as written stops and says so on its card (rule 3). Until #38798 lands, `main` has neither member: at `0fc9eab900` no line under `packages/` or `content/` names `embedQuery` or `queryVector`, and every `search` call of `knowledge-turso` and `knowledge-pgvector` that reaches its vector leg embeds the query itself. The code this note cites was read on `main` at `0fc9eab900`, and PR #38798 at head `4561e81d0e`. The two tables of K1, the table of K8, the rules above and every earlier note are left as written; read the "Embedding calls" row, the second sentence of the list under K1 and item 15 with this note. + +> **Note (2026-12-05, [#38710](https://github.com/objectstack-ai/objectstack/issues/38710)) — one member, `AdapterSearchOptions.keywordTerms`: the knowledge service cuts the question into its keyword terms once, and every adapter the search calls matches those terms.** The maintainer's words that open #38710, verbatim and untranslated, as its filing gate records them (2026-11-30): 「首要解决的应该是 用中文分词词典在应用层切词(Node 有现成的库),只留真正的词。」 and, on tuning, 「但是管理员如果需要调优和维护呢」. In English: the first thing to solve is to cut words with a Chinese dictionary segmenter in the application layer (Node has a ready library), keeping only real words; and what if an administrator needs to tune and maintain it. His rulings on that card chose the segmenter, `@node-rs/jieba`, and the administrator's object now (record [`7272241375`](https://github.com/objectstack-ai/objectstack/issues/38710#issuecomment-7272241375)), and the package, `@objectstack/service-segmenter`, with two layers of words, the platform's and the administrator's 检索词条 (`sys_search_term`), one set per deployment (record [`7272436453`](https://github.com/objectstack-ai/objectstack/issues/38710#issuecomment-7272436453)). The card's body left one design point to its second step, 「词条怎么到适配器」: the service hands the adapter the entries, or the service hands it the terms it has cut. ◆ This note takes the second, for the approver to accept with it or strike. +> +> - **The member.** `AdapterSearchOptions.keywordTerms?: readonly string[]`, on `packages/spec/src/contracts/knowledge-adapter.ts#AdapterSearchOptions`: the terms the keyword leg matches, in the shape the sliding-window rule `keywordTerms` of `@objectstack/core` answers (distinct, compared case-insensitively, at most `MAX_KEYWORD_TERMS`). **Present**: the adapter matches these terms, and does not cut the question itself; empty, the keyword leg has nothing to match. **Absent**: the adapter cuts the question by `keywordTerms` of `@objectstack/core`, as before this member. The service hands it when the kernel holds a segmenter (`ISegmenterService`, resolved where a search cuts, never at boot), and never under `vector`. +> - **◆ Why the terms, and not the entries.** An adapter is a storage plugin: it holds no data engine and resolves no service, so the entries would reach it only as data the service read anyway, and each adapter would then call the segmenter itself. Handing the terms keeps one cut per source of a search, shared by its two rounds, the same terms on every store, and adapters with no knowledge of the segmenter or of the object. An entry scoped to one source changes that source's terms only, so the service cuts once for each source it searches. +> - **The "Hybrid retrieval" row of K1.** The row gives the adapter "How vector and keyword scores are blended, which index or scan is used, and how candidates are found." From this note the words of the question are the platform's to cut, on the maintainer's 「在应用层切词」. Which index or scan matches a term (an FTS phrase, `LIKE`, a `tsvector` word), and how the legs are fused, stay the adapter's; neither store's statement changes shape. The row is left as written. +> - **What the service reads.** The enabled and disabled entries of `sys_search_term`, as the contract's `SegmenterEntry`: the entries with no source first, then the source's own, each by `created_at`, then `id`, never `updated_at`; `enabled` passed as a boolean. The read is cached per service, one per environment's kernel, dropped when a record changes on this replica, on a peer's message on the cluster channel `search-term.changed` (an address, never a value), and after a short time, because that channel delivers at most once. +> - **Not in this note.** A segmenter inside an adapter, a tokenizer on a knowledge source (the note of 2026-11-30 above keeps it out), and record search, which the segmenter contract reserves. +> +> This note registers exactly one member, `AdapterSearchOptions.keywordTerms`, and no other: the list stays closed beyond it (rules 3 and 5). It lands in the PR that builds it, with its first readers, `knowledge-turso` and `knowledge-pgvector`, and the knowledge service that hands it (rule 1). `knowledge-memory` does not read it and is searched as before (rule 2). The rules above and every earlier note are left as written. + ### K9 — One `search_knowledge` definition, and every knowledge tool goes through the tool registry and the MCP seams **What landed** (PR #36823, merged as `8aecf6d770`, read in the tree at `254e396a29`). The tool has one definition, `packages/services/service-knowledge/src/knowledge-tools.ts#getKnowledgeToolDefinitions`, and one executor, bound by `packages/services/service-knowledge/src/knowledge-tools.ts#createKnowledgeTools`. The knowledge service hands both out through `knowledgeTools()`. Both MCP transports register that definition and call that executor as the principal they bind, where the grant admits `data:read` (`packages/mcp/src/mcp-http-tools.ts#registerKnowledgeTools`; the HTTP bridge in `packages/runtime/src/domains/mcp.ts`, the stdio bridge in `packages/mcp/src/stdio-data-bridge.ts`). From 718f56152acd5f609ffd02c5ecb6be27aa10e203 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 00:46:44 +0000 Subject: [PATCH 3/8] feat(knowledge): cut each question once with the segmenter and the search words (step 2 of #38710) - spec: AdapterSearchOptions.keywordTerms (ADR-0161, the dated note of 2026-12-05 under K8). - knowledge-turso, knowledge-pgvector: match the handed terms; absent, cut with keywordTerms of @objectstack/core. Both keywordTerms() copies in src/sql.ts are removed; each store's SQL is unchanged. - service-knowledge: reads sys_search_term (unscoped first, then the source's own, by created_at then id; enabled as a boolean), cuts once per source per search, caches per service, drops the cache on a write here, on a peer's search-term.changed and after 30 s; refuses a word naming no registered source and says once when one is gone. - service-segmenter: keyOf exported; hooks store term_key and an empty source as ''; Setup entry; README rows restored. - platform-objects: term_key and a unique (term_key, knowledge_source). - service-cluster: lane 6, search-term.changed. - core: the knowledge token mounts SegmenterServicePlugin beside its store. Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- packages/cli/package.json | 1 + .../test/serve-capability-identity.test.ts | 7 +- .../core/src/capability-composition.test.ts | 7 +- packages/core/src/capability-composition.ts | 6 +- packages/core/src/capability-providers.ts | 15 + .../src/system/sys-search-term.object.test.ts | 15 +- .../src/system/sys-search-term.object.ts | 32 +- .../src/__tests__/idf-once.test.ts | 2 +- .../src/__tests__/keyword-terms.test.ts | 3 +- .../src/pgvector-adapter.ts | 10 +- .../plugins/knowledge-pgvector/src/sql.ts | 81 ----- .../src/__tests__/acceptance.test.ts | 3 +- packages/plugins/knowledge-turso/src/sql.ts | 80 ----- .../knowledge-turso/src/turso-adapter.ts | 10 +- .../metadata-cluster-bridge-plugin.test.ts | 49 +++ .../src/metadata-cluster-bridge-plugin.ts | 86 ++++- .../services/service-knowledge/src/index.ts | 8 + .../src/knowledge-search-terms.ts | 297 ++++++++++++++++++ .../src/knowledge-service-plugin.ts | 21 +- .../src/knowledge-service-search.ts | 13 +- .../src/knowledge-service-top-level.ts | 16 + .../src/knowledge-service.ts | 36 +++ packages/services/service-segmenter/README.md | 12 +- .../services/service-segmenter/src/index.ts | 4 +- .../src/segmenter-service-plugin.ts | 82 ++++- .../src/segmenter-service.test.ts | 16 +- .../src/segmenter-service.ts | 8 +- .../spec/src/contracts/knowledge-adapter.ts | 17 + packages/verify/package.json | 1 + .../src/harness.required-providers.test.ts | 4 +- pnpm-lock.yaml | 6 + 31 files changed, 727 insertions(+), 221 deletions(-) create mode 100644 packages/services/service-knowledge/src/knowledge-search-terms.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index d3cbd2115d0..52bb6039c67 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -155,6 +155,7 @@ "@objectstack/service-queue": "workspace:*", "@objectstack/service-realtime": "workspace:*", "@objectstack/service-record-context": "workspace:*", + "@objectstack/service-segmenter": "workspace:*", "@objectstack/service-settings": "workspace:*", "@objectstack/service-sms": "workspace:*", "@objectstack/service-storage": "workspace:*", diff --git a/packages/cli/test/serve-capability-identity.test.ts b/packages/cli/test/serve-capability-identity.test.ts index 4995383504b..a3646520034 100644 --- a/packages/cli/test/serve-capability-identity.test.ts +++ b/packages/cli/test/serve-capability-identity.test.ts @@ -32,7 +32,7 @@ import { describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS, providesCapability } from '@objectstack/core'; +import { CAPABILITY_PROVIDERS, KNOWLEDGE_SEGMENTER_PROVIDER, KNOWLEDGE_STORE_PROVIDERS, providesCapability } from '@objectstack/core'; import Serve from '../src/commands/serve.js'; // Pay the first transform of these dist-resolved workspace deps at MODULE LOAD: @@ -228,6 +228,11 @@ describe('#7652: declared identities match what the provider packages register', Object.values(KNOWLEDGE_STORE_PROVIDERS).map((store) => ({ cap: `knowledge:${store.export}`, pkg: store.pkg, export: store.export, identities: store.identities, })), + // And the segmenter it mounts beside them. + [{ + cap: `knowledge:${KNOWLEDGE_SEGMENTER_PROVIDER.export}`, pkg: KNOWLEDGE_SEGMENTER_PROVIDER.pkg, + export: KNOWLEDGE_SEGMENTER_PROVIDER.export, identities: [...KNOWLEDGE_SEGMENTER_PROVIDER.identities], + }], ); /** diff --git a/packages/core/src/capability-composition.test.ts b/packages/core/src/capability-composition.test.ts index 8878e160ffa..2c11082d621 100644 --- a/packages/core/src/capability-composition.test.ts +++ b/packages/core/src/capability-composition.test.ts @@ -294,7 +294,7 @@ describe('resolveKnowledgeStore — which store the knowledge token mounts', () }); describe('resolveCapabilityExtras — what a boot mounts after a main provider', () => { - it('knowledge: exactly one store, with its argument; never the in-memory one', () => { + it('knowledge: exactly one store, with its argument, then the segmenter; never the in-memory store', () => { const extras = resolveCapabilityExtras('knowledge', { stack: {}, packageRoot: '/a', database: { driver: 'postgres', url: 'postgres://h/d' } }); expect(extras).toEqual([ { @@ -303,6 +303,11 @@ describe('resolveCapabilityExtras — what a boot mounts after a main provider', identities: ['com.objectstack.plugin.knowledge-pgvector', 'KnowledgePgvectorPlugin'], argument: { url: 'postgres://h/d' }, }, + { + pkg: '@objectstack/service-segmenter', + export: 'SegmenterServicePlugin', + identities: ['com.objectstack.service.segmenter', 'SegmenterServicePlugin'], + }, ]); expect(Object.values(KNOWLEDGE_STORE_PROVIDERS).map((s) => s.pkg)).not.toContain('@objectstack/knowledge-memory'); }); diff --git a/packages/core/src/capability-composition.ts b/packages/core/src/capability-composition.ts index 16bdec734d8..6f7ad681fbc 100644 --- a/packages/core/src/capability-composition.ts +++ b/packages/core/src/capability-composition.ts @@ -59,7 +59,7 @@ import { PLATFORM_ALWAYS_ON_CAPABILITIES, PLATFORM_CAPABILITY_PROVIDERS } from '@objectstack/spec/kernel'; import { readEnvWithDeprecation } from '@objectstack/types'; -import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js'; +import { CAPABILITY_PROVIDERS, KNOWLEDGE_SEGMENTER_PROVIDER, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js'; import type { CapabilityIdentities, KnowledgeStoreSpec } from './capability-providers.js'; import { resolveStackCollection, stackDeclaredCapabilities } from './stack-collections.js'; @@ -336,7 +336,8 @@ export interface CapabilityExtra { * handle both read in place of a row's `extras`. * * - `knowledge`: the one vector store {@link resolveKnowledgeStore} chooses - * for the platform database. + * for the platform database, then the segmenter its searches cut questions + * with ({@link KNOWLEDGE_SEGMENTER_PROVIDER}). * - any other token: its row's `extras`, each with no argument. * * Each boot skips an extra it already holds (`providesCapability`), as it @@ -347,6 +348,7 @@ export function resolveCapabilityExtras(token: string, input: CapabilityArgument const { store, argument } = resolveKnowledgeStore(input); return [ { pkg: store.pkg, export: store.export, identities: store.identities, argument, ...(store.optional ? { optional: true } : {}) }, + { ...KNOWLEDGE_SEGMENTER_PROVIDER }, ]; } return (CAPABILITY_PROVIDERS[token]?.extras ?? []).map((extra) => ({ ...extra })); diff --git a/packages/core/src/capability-providers.ts b/packages/core/src/capability-providers.ts index c2ce6b48376..d0373ba66f5 100644 --- a/packages/core/src/capability-providers.ts +++ b/packages/core/src/capability-providers.ts @@ -314,6 +314,21 @@ export const KNOWLEDGE_STORE_PROVIDERS: Readonly = { + pkg: '@objectstack/service-segmenter', + export: 'SegmenterServicePlugin', + identities: ['com.objectstack.service.segmenter', 'SegmenterServicePlugin'], +}; + /** * Is one of `identities` ALREADY loaded — i.e. did the app (or the boot) supply * this capability's provider itself, so the resolver must not load a second one? diff --git a/packages/platform-objects/src/system/sys-search-term.object.test.ts b/packages/platform-objects/src/system/sys-search-term.object.test.ts index d0d4c253c7e..c81ce4baee4 100644 --- a/packages/platform-objects/src/system/sys-search-term.object.test.ts +++ b/packages/platform-objects/src/system/sys-search-term.object.test.ts @@ -33,7 +33,7 @@ describe('sys_search_term — declaration', () => { }); it("maps onto the segmenter contract's entry one to one, plus the scope the contract leaves to its caller", () => { - expect(Object.keys(fields).sort()).toEqual(['enabled', 'id', 'kind', 'knowledge_source', 'note', 'purpose', 'term']); + expect(Object.keys(fields).sort()).toEqual(['enabled', 'id', 'kind', 'knowledge_source', 'note', 'purpose', 'term', 'term_key']); // Every option is a value of the contract's type, and every value of the // type is an option: the arrays below are typed by the contract, so a // value the contract drops fails to compile, and the equality fails on a @@ -104,16 +104,9 @@ describe('sys_search_term — declaration', () => { expect(fails({ term: '明规条款', kind: 'word', enabled: false })).toBe(false); }); - it("spells every platform word as its own comparison key, so the rule's raw text compare is the service's", () => { - // The rule above compares the stored term as written; the segmenter - // compares a term by its key (`keyOf` in service-segmenter's - // segmenter-service.ts: NFKC, trimmed, lower case character by - // character). For the two to agree, each platform word must already BE - // its key: a future word in upper case or full-width form would let - // its lower-case spelling be disabled past the rule. - const keyOf = (text: string): string => [...text.normalize('NFKC').trim()].map((c) => c.toLowerCase()).join(''); - for (const term of PLATFORM_SEARCH_WORDS) expect(keyOf(term), term).toBe(term); - }); + // That each platform word is its own comparison key is pinned against the + // segmenter's exported `keyOf` itself, in service-segmenter's + // segmenter-service.test.ts, which can import both (this package cannot). it('spells every platform word as a plain CEL string literal', () => { // The condition quotes each word with single quotes and no escaping. diff --git a/packages/platform-objects/src/system/sys-search-term.object.ts b/packages/platform-objects/src/system/sys-search-term.object.ts index 6da20c3f9da..8aa5a6077c2 100644 --- a/packages/platform-objects/src/system/sys-search-term.object.ts +++ b/packages/platform-objects/src/system/sys-search-term.object.ts @@ -43,10 +43,13 @@ const celString = (term: string): string => `'${term}'`; * own and those with no source) before it passes them. * * Declared here and registered by `SegmenterServicePlugin` - * (`@objectstack/service-segmenter`) with its manifest: the object exists only - * where the segmenter is mounted. ⛔ Nothing reads a record yet: the knowledge - * service passes them to the segmenter in step 2, so until then a record - * changes no search, and the plugin contributes no Setup entry for it. + * (`@objectstack/service-segmenter`) with its manifest and its Setup entry: + * the object exists only where the segmenter is mounted. The knowledge service + * reads every record and passes them as the entries of each search's cut, the + * unscoped ones first, then the source's own, each by `created_at`, then `id` + * (objectstack#38710, step 2); a record written applies to the next search, + * with no rebuild. One entry per term and source: the plugin's hooks store the + * term's key and an empty source as `''`, under the unique index below. * * Deployment-level: one set for the whole deployment, no organization column * (ADR-0131 D7), so a record serves every organization's knowledge sources. @@ -130,13 +133,23 @@ export const SysSearchTerm = ObjectSchema.create({ }, ), + term_key: Field.text({ + label: 'Term Key', + required: false, + readonly: true, + maxLength: 255, + description: + 'The term as it is compared: full-width and half-width forms folded, trimmed, lower case. Written by the platform; one entry per key and knowledge source.', + group: 'System', + }), + knowledge_source: Field.text({ label: 'Knowledge Source', required: false, maxLength: 255, description: "The one knowledge source the term applies to, as callers name it: NAMESPACE-NAME for a package's source, the bare name otherwise. " + - 'Empty: every knowledge source of the deployment.', + 'Empty: every knowledge source of the deployment. A name no registered source answers to is refused.', group: 'Term', }), @@ -159,7 +172,14 @@ export const SysSearchTerm = ObjectSchema.create({ }), }, - indexes: [{ fields: ['term'] }], + indexes: [ + { fields: ['term'] }, + // [#38710] One entry per normalised term and source. `'global'`, said out + // loud (ADR-0120 D1): the object has no organization column. The plugin's + // hooks write `term_key` and store an empty source as `''`, so no NULL + // voids the key. + { fields: ['term_key', 'knowledge_source'], unique: 'global' }, + ], validations: [ { diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts index 061011514bc..454f5c0140b 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts @@ -11,7 +11,7 @@ import { describe, expect, it } from 'vitest'; import type { KnowledgeSource } from '@objectstack/spec/ai'; import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js'; -import { keywordTerms } from '../sql.js'; +import { keywordTerms } from '@objectstack/core'; import { FakeEmbedder } from './live-pg.testkit.js'; const source = { name: 'idf', label: 'idf', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts index a3f2aaddd6c..d72e034ad44 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts @@ -7,7 +7,8 @@ import { describe, expect, it } from 'vitest'; import type { KnowledgeSource } from '@objectstack/spec/ai'; import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js'; -import { KEYWORD_SEPARATORS, containsOperator, isWordTerm, keywordTerms } from '../sql.js'; +import { KEYWORD_SEPARATORS, keywordTerms } from '@objectstack/core'; +import { containsOperator, isWordTerm } from '../sql.js'; import { FakeEmbedder } from './live-pg.testkit.js'; describe('knowledge-pgvector keywordTerms', () => { diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index cad44d84e80..341647312a0 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -24,7 +24,6 @@ import { isWordTerm, keywordIndexDdl, keywordIndexName, - keywordTerms, metadataIndexDdl, metadataIndexName, metadataScopeForms, @@ -34,6 +33,7 @@ import { vectorTable, vectorTableDdl, } from './sql.js'; +import { keywordTerms } from '@objectstack/core'; import { searchRefusalOf } from './errors.js'; /** One answer of a query: its rows. */ @@ -220,7 +220,9 @@ interface Readiness { * dimensions; adding one is an operator's step, documented with the * package). A passage whose cosine similarity is not positive is not ranked * by it. - * - The keyword leg: the query's terms (`keywordTerms`). A word of three + * - The keyword leg: the terms the knowledge service hands + * (`AdapterSearchOptions.keywordTerms`, cut once by the kernel's segmenter), + * else the query's own (`keywordTerms` of `@objectstack/core`). A word of three * characters or more is matched as a phrase (`phraseto_tsquery`) on the * passage's `simple` `tsvector`, which a GIN expression index serves; a * shorter term (「出差」), or one holding a Han, kana or Hangul character — @@ -678,7 +680,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { vector = embedded; } const vectorLeg = mode !== 'keyword' && !vector.every((x) => x === 0); - const terms = mode === 'vector' ? [] : keywordTerms(query); + // The terms the knowledge service cut once (ADR-0161, the dated note of + // 2026-12-05 under K8), else this store's own cut of the question. + const terms = mode === 'vector' ? [] : [...(opts.keywordTerms ?? keywordTerms(query))]; if (!vectorLeg && terms.length === 0) return []; if (terms.length > 0) await this.ensureKeywordIndex(generation.dim); diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts index dbcc379307f..7f015360ecb 100644 --- a/packages/plugins/knowledge-pgvector/src/sql.ts +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -184,15 +184,6 @@ export function keywordIndexDdl(schema: string, dimensions: number): string { return `CREATE INDEX IF NOT EXISTS "${keywordIndexName(dimensions)}" ON ${qualified(schema, vectorTable(dimensions))} USING gin (${PASSAGE_TSVECTOR})`; } -/** - * 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; - /** The shortest term (in characters) matched on the `tsvector`; a shorter one is matched as a substring ({@link containsOperator}). */ export const WORD_MIN_CHARS = 3; @@ -204,78 +195,6 @@ export const WORD_MIN_CHARS = 3; */ export const UNSEGMENTED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3005-\u3007]/u; -/** - * 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). - */ -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 store's. - */ -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. - * The same rule as the libSQL store's. - */ -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; -} - /** Whether a term is matched on the `tsvector` (a word of three characters or more the parser splits), not as a substring. */ export function isWordTerm(term: string): boolean { return [...term].length >= WORD_MIN_CHARS && !UNSEGMENTED.test(term); diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 1a7832d31e0..64077e18a06 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -18,7 +18,8 @@ import type { AdapterContext, IDataEngine, IEmbedder } from '@objectstack/spec/c import type { ExecutionContext } from '@objectstack/spec/kernel'; import { KnowledgeService } from '@objectstack/service-knowledge'; import { KNOWLEDGE_REBUILD_REQUIRED, TursoKnowledgeAdapter } from '../index.js'; -import { KEYWORD_SEPARATORS, containsPattern, ftsPhrase, keywordTerms } from '../sql.js'; +import { KEYWORD_SEPARATORS, keywordTerms } from '@objectstack/core'; +import { containsPattern, ftsPhrase } from '../sql.js'; import { FakeEmbedder, storeOf, type StoreKind } from './turso.testkit.js'; const source = (id: string, extra: Record = {}): KnowledgeSource => diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index 7c16cd5b83b..3da5a361c48 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -379,89 +379,9 @@ export function vectorIndexShape( return found.length === own.length ? 'complete' : 'partial'; } -/** - * 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; - /** The shortest term (in characters) the trigram index can match; a shorter one is matched by `LIKE`. */ export const TRIGRAM_MIN_CHARS = 3; -/** - * 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). - */ -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 PostgreSQL store's. - */ -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(); - 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; -} - /** A term as one FTS5 phrase: double-quoted, an inner double quote doubled, so no character of it is FTS5 syntax. */ export function ftsPhrase(term: string): string { return `"${term.replace(/"/g, '""')}"`; diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index bf70d28ed00..3bbebc06eca 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -31,7 +31,6 @@ import { keywordIndexDdl, keywordIndexShape, keywordNames, - keywordTerms, legacyTable, passageTableDdl, quoted, @@ -44,6 +43,7 @@ import { vectorIndexShape, vectorLiteral, } from './sql.js'; +import { keywordTerms } from '@objectstack/core'; import { onClientQueue, type QueueSide } from './reader-writer-queue.js'; import { timedClient, timedQueueEntry, timedSearch } from './search-timing.js'; @@ -335,7 +335,9 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise x === 0); - const terms = mode === 'vector' ? [] : keywordTerms(query); + // The terms the knowledge service cut once (ADR-0161, the dated note of + // 2026-12-05 under K8), else this store's own cut of the question. + const terms = mode === 'vector' ? [] : [...(opts.keywordTerms ?? keywordTerms(query))]; if (!vectorLeg && terms.length === 0) return []; // One WHERE for both legs: the organization filter, the record scope and diff --git a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts index e3b5e657f2c..3c28a5a54c0 100644 --- a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts +++ b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.test.ts @@ -76,6 +76,11 @@ interface HarnessOptions { settings?: 'none' | 'bare' | 'real'; /** When true, the settings seam throws on attach. */ settingsAttachThrows?: boolean; + /** + * [#38710] The `knowledge` slot: `'none'` (the default), `'bare'` (no + * attachSearchTermChangePubSub), or `'real'` (exposes it and its resync seam). + */ + knowledge?: 'none' | 'bare' | 'real'; } function makeHarness(opts: HarnessOptions = {}) { @@ -84,6 +89,7 @@ function makeHarness(opts: HarnessOptions = {}) { datasourceAdmin = 'none', datasourceAttachThrows = false, automation = 'none', automationAttachThrows = false, settings = 'none', settingsAttachThrows = false, + knowledge = 'none', } = opts; const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }; @@ -109,6 +115,10 @@ function makeHarness(opts: HarnessOptions = {}) { return detachSettings; }); + const detachSearchTerms = vi.fn(); + const attachSearchTerms = vi.fn((_pubsub: unknown, _nodeId: string) => detachSearchTerms); + const resyncSearchTerms = vi.fn(); + const pubsub = { publish: vi.fn(), subscribe: vi.fn(), close: vi.fn() }; const cluster = driver === null @@ -136,6 +146,11 @@ function makeHarness(opts: HarnessOptions = {}) { : settings === 'bare' ? { get: vi.fn(), subscribe: vi.fn() } : { attachSettingsChangePubSub: attachSettings }; + const knowledgeService = + knowledge === 'none' ? undefined + : knowledge === 'bare' ? { search: vi.fn() } + : { attachSearchTermChangePubSub: attachSearchTerms, resyncSearchTermChangePubSub: resyncSearchTerms }; + const hooks = new Map Promise | void>>(); const ctx = { logger, @@ -169,6 +184,10 @@ function makeHarness(opts: HarnessOptions = {}) { if (!settingsService) throw new Error('service not found: settings'); return settingsService; } + if (name === 'knowledge') { + if (!knowledgeService) throw new Error('service not found: knowledge'); + return knowledgeService; + } throw new Error(`service not found: ${name}`); }, } as unknown as PluginContext; @@ -183,6 +202,7 @@ function makeHarness(opts: HarnessOptions = {}) { attachDatasource, detachDatasource, attachCredential, detachCredential, attachSettings, detachSettings, + attachSearchTerms, detachSearchTerms, resyncSearchTerms, }; } @@ -545,6 +565,35 @@ describe('[#27428] lane 4 — the automation service’s connector-credential.mu }); }); +describe('[#38710] lane 6 — the knowledge service’s search-term.changed fan-out', () => { + it('⭐ attaches on a cross-process driver with the cluster’s pubsub and node id, reports it, and detaches on shutdown', async () => { + const h = makeHarness({ driver: 'redis', metadata: 'none', protocol: 'none', knowledge: 'real' }); + await new MetadataClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + + expect(h.attachSearchTerms).toHaveBeenCalledTimes(1); + expect(h.attachSearchTerms).toHaveBeenCalledWith(h.pubsub, 'node-a'); + expect(infoLines(h)).toContain( + 'MetadataClusterBridgePlugin: bridged search-term.changed → cluster.pubsub (node=node-a)', + ); + await h.fire('kernel:shutdown'); + await h.fire('kernel:shutdown'); + expect(h.detachSearchTerms).toHaveBeenCalledTimes(1); + }); + + it('skips the in-process driver, and a knowledge service without the seam, saying nothing above debug', async () => { + for (const [driver, knowledge] of [['memory', 'real'], ['redis', 'bare'], ['redis', 'none']] as const) { + const h = makeHarness({ driver, knowledge }); + await new MetadataClusterBridgePlugin().init(h.ctx); + await h.fire('kernel:ready'); + + expect(h.attachSearchTerms).not.toHaveBeenCalled(); + expect(h.logger.error).not.toHaveBeenCalled(); + expect(infoLines(h).some((l) => l.includes('search-term.changed'))).toBe(false); + } + }); +}); + describe('cluster.resync — every attached lane re-reads what an outage made it miss', () => { /** The harness, with lanes 1, 3 and 4 attached and a driver liveness offered on its cluster. */ function resyncHarness(opts: { driver?: string; laneThrows?: boolean } = {}) { diff --git a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts index 5becb127614..f1693326006 100644 --- a/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts +++ b/packages/services/service-cluster/src/metadata-cluster-bridge-plugin.ts @@ -35,10 +35,10 @@ function resyncSeamOf(owner: unknown, method: string): (() => unknown) | undefin * state-owner packages only need the `IPubSub` interface, which lives in * `@objectstack/spec/contracts`. * - * FIVE lanes, late-bound independently (lanes 1 to 4 at `kernel:ready`, + * SIX lanes, late-bound independently (lanes 1 to 4 and 6 at `kernel:ready`, * lane 5 at `kernel:bootstrapped`), because the state - * that goes stale lives in five different owners (#13331, #13805, #27428, - * #31597): + * that goes stale lives in six different owners (#13331, #13805, #27428, + * #31597, #38710): * * 1. **Metadata service** (`attachClusterPubSub()` — `metadata.changed`): * replays watch events into peer `MetadataManager` caches @@ -87,6 +87,14 @@ function resyncSeamOf(owner: unknown, method: string): (() => unknown) | undefin * replicas over the Redis driver (`declaresMultiReplicaOnRedis`, cloud#3814 * R3), so a single node never sees it. * + * 6. **Knowledge service** (`attachSearchTermChangePubSub()` — + * `search-term.changed`): fans a write of the administrator's search words + * (`sys_search_term`) out to peers, which drop their cached read of them, + * so the next search on every replica cuts its question with the new + * words (objectstack#38710). The message is an address, never a value. The + * knowledge service also re-reads them after a short time, because this + * lane, like every other, delivers at most once. + * * Activates each lane only when the cluster service and that lane's state * owner are present and expose the seam. Late binding is achieved via the * `kernel:ready` lifecycle hook. @@ -100,7 +108,9 @@ function resyncSeamOf(owner: unknown, method: string): (() => unknown) | undefin * `connector-credential.mutated` — payload shape defined by * `ClusterConnectorCredentialMutationPayload` in `@objectstack/service-automation`; * `settings.changed` — payload shape defined by - * `ClusterSettingsChangePayload` in `@objectstack/service-settings`. + * `ClusterSettingsChangePayload` in `@objectstack/service-settings`; + * `search-term.changed` — payload shape defined by + * `ClusterSearchTermChangePayload` in `@objectstack/service-knowledge`. * * ## Resync after an outage * @@ -118,7 +128,8 @@ function resyncSeamOf(owner: unknown, method: string): (() => unknown) | undefin * the replica's OWN re-read of its row; a read that fails changes nothing; * 3. datasource admin service — `resyncDatasourceMutationPubSub()`; * 4. automation service — `resyncConnectorCredentialPubSub()`; - * 5. settings service — `resyncSettingsChangePubSub()`. + * 5. settings service — `resyncSettingsChangePubSub()`; + * 6. knowledge service — `resyncSearchTermChangePubSub()`. * * The in-process driver never emits the event, so the single-node path is * unchanged. @@ -135,6 +146,7 @@ export class MetadataClusterBridgePlugin implements Plugin { private detachDatasource?: () => void; private detachConnectorCredential?: () => void; private detachSettings?: () => void; + private detachSearchTerms?: () => void; private detachResync?: () => void; private readonly laneResyncs: LaneResync[] = []; @@ -153,6 +165,7 @@ export class MetadataClusterBridgePlugin implements Plugin { this.attachProtocolLane(ctx, cluster); this.attachDatasourceLane(ctx, cluster); this.attachConnectorCredentialLane(ctx, cluster); + this.attachSearchTermLane(ctx, cluster); this.subscribeResync(ctx, cluster); }); @@ -217,6 +230,15 @@ export class MetadataClusterBridgePlugin implements Plugin { ); } this.detachSettings = undefined; + try { + this.detachSearchTerms?.(); + } catch (err) { + ctx.logger.error( + 'MetadataClusterBridgePlugin: search-term-lane detach error', + err as Error, + ); + } + this.detachSearchTerms = undefined; this.detachResync?.(); this.detachResync = undefined; this.laneResyncs.length = 0; @@ -574,4 +596,58 @@ export class MetadataClusterBridgePlugin implements Plugin { ); } } + /** + * Lane 6 — the knowledge service's `search-term.changed` fan-out + * (objectstack#38710): the administrator's search words adopting the + * family lanes 2 to 5 established. + * + * Duck-typed exactly like lanes 1 to 5 feature-detect their seams: this + * package must not depend on `@objectstack/service-knowledge`. Guarded on + * {@link isInProcessClusterDriver} like lanes 2 to 4: the in-process memory + * driver fans out to nobody, and a single replica drops its own cache at + * the write. + */ + private attachSearchTermLane(ctx: PluginContext, cluster: IClusterService): void { + let knowledge: unknown; + try { + knowledge = ctx.getService('knowledge'); + } catch { + ctx.logger.debug( + 'MetadataClusterBridgePlugin: no "knowledge" service registered, skipping search-term fan-out', + ); + return; + } + + const attach = (knowledge as { attachSearchTermChangePubSub?: unknown }) + .attachSearchTermChangePubSub; + if (typeof attach !== 'function') { + ctx.logger.debug( + 'MetadataClusterBridgePlugin: knowledge service does not expose attachSearchTermChangePubSub(), skipping search-term fan-out', + ); + return; + } + + if (isInProcessClusterDriver(cluster.driver)) { + ctx.logger.debug( + `MetadataClusterBridgePlugin: cluster driver "${cluster.driver}" is in-process; search-term fan-out has no peers to reach, skipping`, + ); + return; + } + + try { + this.detachSearchTerms = (attach as ( + pubsub: IClusterService['pubsub'], + nodeId: string, + ) => () => void).call(knowledge, cluster.pubsub, cluster.nodeId); + this.registerLaneResync('search-term.changed', knowledge, 'resyncSearchTermChangePubSub'); + ctx.logger.info( + `MetadataClusterBridgePlugin: bridged search-term.changed → cluster.pubsub (node=${cluster.nodeId})`, + ); + } catch (err) { + ctx.logger.error( + 'MetadataClusterBridgePlugin: search-term-lane attach failed', + err as Error, + ); + } + } } diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index 0b68acfa628..02602ae9a7e 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -103,3 +103,11 @@ export type { KnowledgeRecordSyncReason, KnowledgeRecordSyncRetry, } from './knowledge-record-sync-queue.js'; +// [#38710] The keyword terms a search hands its adapters, and the cluster channel of the search words. +export { + SEARCH_TERMS_TTL_MS, + SEARCH_TERM_CHANGE_CLUSTER_CHANNEL, + SEARCH_TERM_OBJECT, + bindSearchTermHooks, +} from './knowledge-search-terms.js'; +export type { ClusterSearchTermChangePayload } from './knowledge-search-terms.js'; diff --git a/packages/services/service-knowledge/src/knowledge-search-terms.ts b/packages/services/service-knowledge/src/knowledge-search-terms.ts new file mode 100644 index 00000000000..029ad0b3dee --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-search-terms.ts @@ -0,0 +1,297 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The keyword terms of a search, cut once by the knowledge service (ADR-0161, + * the dated note of 2026-12-05 under K8; objectstack#38710, step 2). + * + * The service cuts the question with the kernel's segmenter + * (`ISegmenterService`, resolved where a search cuts, never at boot) and the + * administrator's 检索词条 (`sys_search_term`), and hands the terms to every + * adapter it searches as `AdapterSearchOptions.keywordTerms`. With no + * segmenter composed it hands none, and each adapter cuts the question with + * `keywordTerms` of `@objectstack/core`, as before. + * + * ## The entries a source's question is cut with + * + * Every record of `sys_search_term`, enabled or not, as the contract's + * `SegmenterEntry` (`enabled` a boolean: a disabled entry withdraws the same + * term of the same kind below it). The entries with no source (`''`, or NULL + * on a row written before the plugin stored `''`) come first, then the + * source's own, each by `created_at`, then `id`. ⛔ Never by `updated_at`: + * disabling one of two duplicates would then move it after its enabled twin + * and withdraw it. A record names a source by its face (`NAMESPACE-NAME` for a + * package's source, the bare name otherwise); one naming a source that is not + * registered is refused at write ({@link bindSearchTermHooks}), and one left + * naming a source that is gone since is said once at `warn` when it is read. + * + * ## How fresh the read is + * + * One read for the whole service, which a kernel holds once (so one per + * environment), cached and dropped: + * + * - at once on this replica, when a record is written (the engine's + * after-write hooks, {@link bindSearchTermHooks}); + * - on a peer, when the cluster channel {@link SEARCH_TERM_CHANGE_CLUSTER_CHANNEL} + * carries that write's address (lane 6 of `MetadataClusterBridgePlugin`); + * - after {@link SEARCH_TERMS_TTL_MS} in any case, because that channel + * delivers at most once. + */ + +import type { IDataEngine, IPubSub, ISegmenterService, SegmenterEntry } from '@objectstack/spec/contracts'; +import { DEFAULT_SEGMENTER_PURPOSE } from '@objectstack/spec/contracts'; +import type { KnowledgeLogger } from './knowledge-service-top-level.js'; + +/** The administrator's search words (`@objectstack/platform-objects`, registered by `SegmenterServicePlugin`). */ +export const SEARCH_TERM_OBJECT = 'sys_search_term'; + +/** The wire name of a search-term write: lane 6 of `MetadataClusterBridgePlugin`. */ +export const SEARCH_TERM_CHANGE_CLUSTER_CHANNEL = 'search-term.changed'; + +/** + * Payload for {@link SEARCH_TERM_CHANGE_CLUSTER_CHANNEL}. ⭐ A signal, never + * content: a receiver drops its cache and reads the shared table again, so a + * duplicate or re-ordered delivery converges the same. + */ +export interface ClusterSearchTermChangePayload { + /** Origin nodeId, for loopback suppression. */ + originNode?: string; + /** ISO 8601 time the write completed on the origin node. */ + at: string; +} + +/** How long a read of the entries is served before it is read again, whatever the channel said. */ +export const SEARCH_TERMS_TTL_MS = 30_000; + +/** The most entries read; past it the rest are not applied, and that is said at `warn`. */ +export const SEARCH_TERMS_READ_LIMIT = 10_000; + +const SYSTEM_CONTEXT = { positions: [], permissions: [], systemPermissions: [], isSystem: true }; + +/** An entry and the source it is scoped to (`''`: every source). */ +interface StoredEntry { + source: string; + entry: SegmenterEntry; +} + +export interface KnowledgeSearchTermsDeps { + engine?: IDataEngine; + resolveSegmenter?: () => ISegmenterService | undefined; + logger?: KnowledgeLogger; + /** The faces of the registered sources, read when entries are read. */ + sourceFaces: () => readonly string[]; +} + +/** + * A stored boolean as a boolean. A SQL driver answers a boolean column as + * `true`/`false` or as `1`/`0`; `enabled` is required with the default `true`. + */ +function storedBoolean(value: unknown): boolean { + return !(value === false || value === 0); +} + +/** A stored source: NULL and `''` both mean every source. */ +function storedSource(value: unknown): string { + return typeof value === 'string' ? value.trim() : ''; +} + +export class KnowledgeSearchTerms { + private cache: { at: number; entries: Promise } | undefined; + private pubsub: IPubSub | undefined; + private nodeId: string | undefined; + private unsubscribe: (() => void) | undefined; + private readonly unknownSourcesReported = new Set(); + private readFailureReported = false; + + constructor(private readonly deps: KnowledgeSearchTermsDeps) {} + + /** + * The terms to hand the adapter for `query` on the source whose face is + * `face`, or `undefined` when no segmenter is composed (the adapter then + * cuts the question itself). + */ + async termsFor(query: string, face: string): Promise { + try { + const segmenter = this.deps.resolveSegmenter?.(); + if (segmenter === undefined) return undefined; + const stored = await this.entries(); + const entries = [ + ...stored.filter((e) => e.source === ''), + ...stored.filter((e) => e.source === face), + ].map((e) => e.entry); + return segmenter.keywordTerms(query, { purpose: DEFAULT_SEGMENTER_PURPOSE, entries }); + } catch (err) { + // The adapter's own cut answers instead; never the adapter's failure. + this.deps.logger?.warn?.( + `[knowledge] the segmenter could not be reached or could not cut a question (${String( + (err as { message?: unknown } | undefined)?.message ?? err, + )}); the store cuts it by sliding windows instead.`, + ); + return undefined; + } + } + + /** A record was written on this replica: drop the cache, and tell the peers. */ + changed(): void { + this.cache = undefined; + const pubsub = this.pubsub; + if (!pubsub) return; + const payload: ClusterSearchTermChangePayload = { originNode: this.nodeId, at: new Date().toISOString() }; + const warn = (err: unknown): void => + this.deps.logger?.warn?.( + `[knowledge] publishing a search-term change to peer replicas failed (${String( + (err as { message?: unknown } | undefined)?.message ?? err, + )}); peers read it within ${SEARCH_TERMS_TTL_MS / 1000} s.`, + ); + try { + void pubsub.publish(SEARCH_TERM_CHANGE_CLUSTER_CHANNEL, payload).catch(warn); + } catch (err) { + warn(err); + } + } + + /** Listen to the peers' writes (lane 6 of `MetadataClusterBridgePlugin`). */ + attach(pubsub: IPubSub, nodeId: string): () => void { + this.detach(); + this.pubsub = pubsub; + this.nodeId = nodeId; + this.unsubscribe = pubsub.subscribe(SEARCH_TERM_CHANGE_CLUSTER_CHANNEL, (msg) => { + // Loopback guard: this replica dropped its cache at the write. + if (msg.payload?.originNode !== undefined && msg.payload.originNode === this.nodeId) return; + this.cache = undefined; + }); + return () => this.detach(); + } + + /** After a cluster outage: a lost message is answered by reading again. */ + resync(): void { + this.cache = undefined; + } + + private detach(): void { + this.unsubscribe?.(); + this.unsubscribe = undefined; + this.pubsub = undefined; + this.nodeId = undefined; + } + + private entries(): Promise { + const now = Date.now(); + if (this.cache !== undefined && now - this.cache.at < SEARCH_TERMS_TTL_MS) return this.cache.entries; + // A failed read (said once by `read`) cuts with the platform words alone, + // and is not served past its own search: the next one reads again. + const entries: Promise = this.read().catch(() => { + if (this.cache?.entries === entries) this.cache = undefined; + return []; + }); + this.cache = { at: now, entries }; + return entries; + } + + private async read(): Promise { + const engine = this.deps.engine; + if (engine === undefined) return []; + let rows: Array>; + try { + rows = (await engine.find(SEARCH_TERM_OBJECT, { + orderBy: [{ field: 'created_at', order: 'asc' }, { field: 'id', order: 'asc' }], + limit: SEARCH_TERMS_READ_LIMIT, + context: SYSTEM_CONTEXT, + } as never)) as Array>; + } catch (err) { + if (!this.readFailureReported) { + this.readFailureReported = true; + this.deps.logger?.warn?.( + `[knowledge] the search words (${SEARCH_TERM_OBJECT}) could not be read (${String( + (err as { message?: unknown } | undefined)?.message ?? err, + )}), so questions are cut with the platform words alone until a read succeeds.`, + ); + } + throw err; + } + this.readFailureReported = false; + if (rows.length >= SEARCH_TERMS_READ_LIMIT) { + this.deps.logger?.warn?.( + `[knowledge] ${SEARCH_TERM_OBJECT} holds ${SEARCH_TERMS_READ_LIMIT} entries or more; only the first ` + + `${SEARCH_TERMS_READ_LIMIT} by created_at are applied.`, + ); + } + const faces = new Set(this.deps.sourceFaces()); + const out: StoredEntry[] = []; + for (const row of rows) { + const source = storedSource(row.knowledge_source); + if (source !== '' && !faces.has(source) && !this.unknownSourcesReported.has(source)) { + this.unknownSourcesReported.add(source); + this.deps.logger?.warn?.( + `[knowledge] search words name the knowledge source '${source}', which is not registered, so they apply to ` + + 'no search. Correct their Knowledge Source in Setup → Search Terms, or clear it to apply them to every source.', + ); + } + out.push({ + source, + entry: { + term: String(row.term ?? ''), + kind: row.kind as SegmenterEntry['kind'], + ...(typeof row.purpose === 'string' ? { purpose: row.purpose as SegmenterEntry['purpose'] } : {}), + enabled: storedBoolean(row.enabled), + }, + }); + } + return out; + } +} + +/** The engine slice the hooks bind through: `ObjectQL`'s hook registry. */ +export interface SearchTermHookEngine { + registerHook( + event: string, + handler: (context: unknown) => Promise | void, + options?: { object?: string; packageId?: string }, + ): void; + unregisterHooksByPackage?(packageId: string): number; + runAfterOpenUnitsCommit?(body: () => void): void; +} + +/** The hook registry's package id for these hooks (unbound by it at teardown). */ +export const SEARCH_TERM_HOOK_PACKAGE = 'service-knowledge:search-terms'; + +/** The slice of `KnowledgeService` the hooks drive. */ +export interface SearchTermHookService { + describeSources(): ReadonlyArray<{ id: string }>; + searchTermsChanged(): void; +} + +/** + * Bind the knowledge service's hooks on `sys_search_term`: every write drops + * the service's cache (and tells the peers) once it commits, and a record + * naming a knowledge source no registered source answers to is refused with + * `400 VALIDATION_FAILED`, since it would apply to no search. Answers + * whether the engine takes hooks. + */ +export function bindSearchTermHooks(engine: SearchTermHookEngine | undefined, service: SearchTermHookService): boolean { + if (!engine || typeof engine.registerHook !== 'function') return false; + engine.unregisterHooksByPackage?.(SEARCH_TERM_HOOK_PACKAGE); + const options = { object: SEARCH_TERM_OBJECT, packageId: SEARCH_TERM_HOOK_PACKAGE }; + const checkSource = (context: unknown): void => { + const data = (context as { input?: { data?: Record } } | undefined)?.input?.data; + const source = storedSource(data?.knowledge_source); + if (source === '') return; + const faces = service.describeSources().map((d) => d.id); + if (faces.includes(source)) return; + const message = + `No knowledge source is named '${source}', so this search word would apply to no search. ` + + `Name one of the registered sources${faces.length > 0 ? ` (${faces.join(', ')})` : ''}, or leave Knowledge Source empty to apply it to every source.`; + throw Object.assign(new Error(message), { + code: 'VALIDATION_FAILED', + status: 400, + fields: [{ field: 'knowledge_source', code: 'invalid_reference', message }], + }); + }; + engine.registerHook('beforeInsert', checkSource, options); + engine.registerHook('beforeUpdate', checkSource, options); + const changed = (): void => { + if (typeof engine.runAfterOpenUnitsCommit === 'function') engine.runAfterOpenUnitsCommit(() => service.searchTermsChanged()); + else service.searchTermsChanged(); + }; + for (const event of ['afterInsert', 'afterUpdate', 'afterDelete']) engine.registerHook(event, changed, options); + return true; +} diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 12539d5c44c..1f5e01bff4d 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -13,7 +13,7 @@ import type { QueueMessage, } from '@objectstack/spec/contracts'; import type { KnowledgeSource } from '@objectstack/spec/ai'; -import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; +import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE, SEGMENTER_SERVICE, type ISegmenterService } from '@objectstack/spec/contracts'; import { OPENAI_COMPATIBLE_PRESETS, createOpenAIEmbedder, @@ -46,6 +46,7 @@ import { type KnowledgeRecordSyncRetry, } from './knowledge-record-sync-queue.js'; import { KnowledgeSourceLoader } from './knowledge-source-loader.js'; +import { SEARCH_TERM_HOOK_PACKAGE, bindSearchTermHooks } from './knowledge-search-terms.js'; import { KNOWLEDGE_SOURCE_TYPE } from './knowledge-source-registry.js'; import { contributeKnowledgeSettings } from './knowledge-settings-contribution.js'; import { SysKnowledgeSyncState } from '@objectstack/platform-objects/system'; @@ -705,6 +706,17 @@ export class KnowledgeServicePlugin implements Plugin { throw err; } }), + // [#38710] The kernel's segmenter, resolved where a search cuts its + // question, never here: none composed (or none yet) hands no keyword + // terms, and each store cuts the question itself. + resolveSegmenter: () => { + try { + return ctx.getService(SEGMENTER_SERVICE) ?? undefined; + } catch (err) { + if (isServiceNotRegisteredError(err, SEGMENTER_SERVICE)) return undefined; + throw err; + } + }, // The cluster lock a build runs under, so one node builds a source // (`knowledge-build.ts`). Resolved when a build starts; no `cluster` // service is a one-node composition, and a lookup that throws for any @@ -726,6 +738,13 @@ export class KnowledgeServicePlugin implements Plugin { } ctx.registerService(KNOWLEDGE_SERVICE, this.service); + // [#38710] The administrator's search words (`sys_search_term`, registered + // by the segmenter): a write drops this replica's read of them and tells + // the peers, and a word naming no registered source is refused. + const hookEngine = recordHookEngineOf(engine); + if (bindSearchTermHooks(hookEngine, this.service)) { + this.unsubscribes.push(() => hookEngine?.unregisterHooksByPackage?.(SEARCH_TERM_HOOK_PACKAGE)); + } // The knowledge settings page, the `ai` embedder section, both test // actions and the Setup entry are offered only where this service is diff --git a/packages/services/service-knowledge/src/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index 42605863334..36d5c2ff5c7 100644 --- a/packages/services/service-knowledge/src/knowledge-service-search.ts +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -133,6 +133,7 @@ export interface KnowledgeSearchHost { readonly scopeIgnoredReported: KnowledgeService['scopeIgnoredReported']; readonly searchByKey: KnowledgeService['searchByKey']; readonly searchRound: KnowledgeService['searchRound']; + readonly searchTerms: KnowledgeService['searchTerms']; readonly searchWithRefusals: KnowledgeService['searchWithRefusals']; readonly serializeRecordSync: KnowledgeService['serializeRecordSync']; readonly sourcesGroupableBy: KnowledgeService['sourcesGroupableBy']; @@ -979,7 +980,7 @@ function memoisedQuestion(embed: () => Promise): () => Promis * logged, never returned. */ export async function searchRound( - this: Pick, + this: Pick, query: string, sources: SearchTarget[], ask: (source: KnowledgeSource) => number, @@ -987,7 +988,8 @@ export async function searchRound( refused: KnowledgeSearchRefusal[], ): Promise> { const out = new Map(); - for (const { source, organizationIds, fingerprint, scope, binding, retrieval } of sources) { + for (const target of sources) { + const { source, organizationIds, fingerprint, scope, binding, retrieval } = target; // Refused like an adapter that cannot serve: the caller is told which // source was not searched and why; the boot said so at `error` // (`reportUnmountedAdapters`), so no line per search. The adapter was @@ -1010,6 +1012,12 @@ export async function searchRound( : (question.queryVector ??= memoisedQuestion(() => timedSegment('embed', () => embedQuery.call(adapter, query)))); try { + // The question's keyword terms, cut once for this source and both rounds + // (ADR-0161, the dated note of 2026-12-05 under K8); none under `vector`, + // which runs no keyword leg, and none where no segmenter is composed. + const keywordTerms = retrieval?.mode === 'vector' + ? undefined + : await (target.keywordTerms ??= this.searchTerms.termsFor(query, this.faceOfKey(source.name))); const hits = await adapter.search(query, { source, topK: ask(source), @@ -1019,6 +1027,7 @@ export async function searchRound( ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), ...(retrieval === undefined ? {} : { retrieval: { mode: retrieval.mode } }), ...(queryVector === undefined ? {} : { queryVector }), + ...(keywordTerms === undefined ? {} : { keywordTerms: [...keywordTerms] }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts index b78b6bc2dc3..c94d107665c 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -20,6 +20,7 @@ import type { IDataEngine, IKnowledgeAdapter, IQueueService, + ISegmenterService, } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { @@ -144,6 +145,15 @@ export interface KnowledgeServiceOptions { * service reads as a `single`-posture deployment. */ resolveTenancyPosture?: KnowledgeTenancyPostureResolver; + /** + * The kernel's segmenter (`ISegmenterService`, the `segmenter` slot), + * resolved each time a search cuts its question, never at boot: the slot + * may be filled later, and its absence is not a verdict to keep. Answers + * `undefined` where none is composed; the service then hands no keyword + * terms, and each adapter cuts the question itself. `KnowledgeServicePlugin` + * wires it; omitted, the service hands none. + */ + resolveSegmenter?: () => ISegmenterService | undefined; /** * The cluster lock a build runs under (`knowledge-build.ts`, "One node * builds a source"), resolved each time a build starts. Answers `undefined` @@ -402,6 +412,12 @@ export interface SearchTarget { * absent where the adapter reports no modes and the source declares none. */ retrieval?: { mode: KnowledgeRetrievalMode }; + /** + * The keyword terms this source's question is cut into, once for the whole + * search, both rounds ({@link KnowledgeService.searchRound}); `undefined` + * inside it where no segmenter is composed. + */ + keywordTerms?: Promise; } /** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index dfff0a9f5e8..4771ee9136e 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -6,6 +6,7 @@ import type { IDataEngine, IKnowledgeAdapter, IKnowledgeService, + IPubSub, KnowledgeReindexOptions, KnowledgeReindexResult, KnowledgeSearchOptions, @@ -14,6 +15,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { TenancyPosture } from '@objectstack/spec/security'; import { type KnowledgeTools, createKnowledgeTools } from './knowledge-tools.js'; +import { KnowledgeSearchTerms } from './knowledge-search-terms.js'; import type { AffinityCallerFacts } from './knowledge-affinity.js'; import { type KnowledgeSourceEntry, @@ -206,9 +208,42 @@ export class KnowledgeService implements IKnowledgeService { */ private readonly enablementWaiters: Array<(proceed: boolean) => void> = []; + /** + * The keyword terms each search hands its adapters, cut once with the + * kernel's segmenter and the administrator's search words + * (`knowledge-search-terms.ts`; ADR-0161, the dated note of 2026-12-05 under K8). + */ + private readonly searchTerms: KnowledgeSearchTerms; + constructor(private readonly options: KnowledgeServiceOptions = {}) { this.defaultTopK = options.defaultTopK ?? 10; this.enablementPending = options.enabledByConfiguration === true; + this.searchTerms = new KnowledgeSearchTerms({ + engine: options.dataEngine, + resolveSegmenter: options.resolveSegmenter, + logger: options.logger, + sourceFaces: () => this.describeSources().map((d) => d.id), + }); + } + + // ── Search words (`sys_search_term`) ───────────────────────────── + + /** A search word was written on this replica: the next search reads them again, here and on the peers. */ + searchTermsChanged(): void { + this.searchTerms.changed(); + } + + /** + * Lane 6 of `MetadataClusterBridgePlugin`: hear the peers' search-word + * writes on `search-term.changed`, and tell them of this replica's. + */ + attachSearchTermChangePubSub(pubsub: IPubSub, nodeId: string): () => void { + return this.searchTerms.attach(pubsub, nodeId); + } + + /** After a cluster outage: the search words are read again. */ + resyncSearchTermChangePubSub(): void { + this.searchTerms.resync(); } // ── Enablement (ADR-0161 K8, the dated note on item 12) ────────── @@ -1682,6 +1717,7 @@ export class KnowledgeService implements IKnowledgeService { get scopeIgnoredReported() { return service.scopeIgnoredReported; }, searchByKey: (...a) => service.searchByKey(...a), searchRound: (...a) => service.searchRound(...a), + get searchTerms() { return service.searchTerms; }, searchWithRefusals: (...a) => service.searchWithRefusals(...a), serializeRecordSync: (...a) => service.serializeRecordSync(...a), get sourceListeners() { return service.sourceListeners; }, diff --git a/packages/services/service-segmenter/README.md b/packages/services/service-segmenter/README.md index d993f185793..63cdebbb1c3 100644 --- a/packages/services/service-segmenter/README.md +++ b/packages/services/service-segmenter/README.md @@ -6,8 +6,11 @@ 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. +The knowledge service reads this slot where a search cuts its question, passes the +administrator's search words (检索词条, `sys_search_term`) as the entries, and hands the terms to +both knowledge stores (`knowledge-turso`, `knowledge-pgvector`). Without the plugin, each store +cuts the question by the sliding windows of `keywordTerms` from `@objectstack/core`. The runtime +mounts the plugin beside the knowledge service (`requires: ['knowledge']`). ## Installation @@ -62,7 +65,10 @@ jieba's dictionary and are not withdrawn. The purpose `record_search` is reserve | Export | What it is | |:---|:---| -| `SegmenterServicePlugin` | The kernel plugin; registers the service under `segmenter`. | +| `SegmenterServicePlugin` | The kernel plugin; registers the service under `segmenter`, and `sys_search_term` with its Setup entry. | +| `SEARCH_TERM_BUNDLE_ID` | The id of the manifest bundle that registers `sys_search_term` (检索词条) and its Setup entry. | +| `searchTermNavItem`, `SEARCH_TERM_KEY_HOOK_PACKAGE` | The Setup entry, and the package id of the hooks that store each record's `term_key` and an empty source as `''`. | +| `keyOf` | A term's comparison key: NFKC, trimmed, lower case. `sys_search_term` stores it as `term_key`, unique per source. | | `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`). | diff --git a/packages/services/service-segmenter/src/index.ts b/packages/services/service-segmenter/src/index.ts index 72e50d2968f..c07717881ae 100644 --- a/packages/services/service-segmenter/src/index.ts +++ b/packages/services/service-segmenter/src/index.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -export { SEARCH_TERM_BUNDLE_ID, SegmenterServicePlugin } from './segmenter-service-plugin.js'; +export { SEARCH_TERM_BUNDLE_ID, SEARCH_TERM_KEY_HOOK_PACKAGE, SegmenterServicePlugin, searchTermNavItem } from './segmenter-service-plugin.js'; export type { SegmenterServicePluginOptions } from './segmenter-service-plugin.js'; -export { SegmenterService, SERVED_PURPOSES, createSegmenterService } from './segmenter-service.js'; +export { SegmenterService, SERVED_PURPOSES, createSegmenterService, keyOf } 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/segmenter-service-plugin.ts b/packages/services/service-segmenter/src/segmenter-service-plugin.ts index a369787c80c..f886f21d412 100644 --- a/packages/services/service-segmenter/src/segmenter-service-plugin.ts +++ b/packages/services/service-segmenter/src/segmenter-service-plugin.ts @@ -4,7 +4,7 @@ import type { Plugin, PluginContext } from '@objectstack/core'; import { SEGMENTER_SERVICE } from '@objectstack/spec/contracts'; import { SysSearchTerm } from '@objectstack/platform-objects/system'; import type { SegmenterLoader } from './jieba-loader.js'; -import { createSegmenterService } from './segmenter-service.js'; +import { createSegmenterService, keyOf } from './segmenter-service.js'; /** The manifest bundle that registers `sys_search_term` (检索词条). */ export const SEARCH_TERM_BUNDLE_ID = 'com.objectstack.service.segmenter.search-terms'; @@ -26,15 +26,14 @@ export interface SegmenterServicePluginOptions { * from "failed to load" (its error is named). * * It also registers the administrator's search words, the 检索词条 object - * `sys_search_term` (`@objectstack/platform-objects`), on the manifest - * service, as the queue plugin registers `sys_job_queue`: the object exists - * only where the segmenter is mounted. No Setup entry comes with it yet. - * - * Nothing reads the slot or the object yet: the knowledge adapters keep their - * own terms until they are wired to the slot, and the knowledge service passes - * the object's records as entries then (objectstack#38710, step 2), which is - * also when the object gets its Setup entry. A record changes no search - * before that, so no administrator is shown a screen that does nothing. + * `sys_search_term` (`@objectstack/platform-objects`), with its Setup entry, + * on the manifest service, as the queue plugin registers `sys_job_queue`: the + * object exists only where the segmenter is mounted. The knowledge service + * reads its records and passes them as the entries of each search's cut + * (objectstack#38710, step 2), so the screen lands with its reader. Its hooks + * on the engine store each record's normalised key (`term_key`, {@link keyOf}) + * and an empty source as `''`, which the object's unique index reads: one + * entry per term and source, on every write door. */ export class SegmenterServicePlugin implements Plugin { name = 'com.objectstack.service.segmenter'; @@ -57,6 +56,7 @@ export class SegmenterServicePlugin implements Plugin { async init(ctx: PluginContext): Promise { registerSearchTermObject(ctx, this.version); + bindSearchTermKey(ctx); const service = await createSegmenterService({ loader: this.options.loader }); ctx.registerService(SEGMENTER_SERVICE, service); const status = service.status(); @@ -79,9 +79,10 @@ export class SegmenterServicePlugin implements Plugin { } /** - * Register `sys_search_term` on the manifest service. A kernel with no - * manifest service (a lean kernel, a test host) registers nothing: nothing - * reads the object yet, so that is said once at info, not warned. + * Register `sys_search_term` and its Setup entry on the manifest service. A + * kernel with no manifest service (a lean kernel, a test host) registers + * nothing, said once at info: the knowledge service then cuts with the + * platform words alone. */ function registerSearchTermObject(ctx: PluginContext, version: string): void { let manifest: { register?(m: unknown): void } | undefined; @@ -103,5 +104,60 @@ function registerSearchTermObject(ctx: PluginContext, version: string): void { name: 'Segmenter Service — search terms', description: "Registers sys_search_term: the administrator's search words, one set for the deployment.", objects: [SysSearchTerm], + navigationContributions: [ + // After Knowledge Sync Status (priority 251, same group: Apps & AI). + { app: 'setup', group: 'group_apps_ai', priority: 252, items: [searchTermNavItem()] }, + ], }); } + +/** The Setup entry of 检索词条, for the platform administrator. */ +export function searchTermNavItem(): Record { + return { + id: 'nav_search_terms', + type: 'object', + label: 'Search Terms', + objectName: SEARCH_TERM_OBJECT, + icon: 'text-search', + requiresObject: SEARCH_TERM_OBJECT, + requiredPermissions: ['manage_platform_settings'], + }; +} + +const SEARCH_TERM_OBJECT = 'sys_search_term'; + +/** The hook registry's package id for the key hooks. */ +export const SEARCH_TERM_KEY_HOOK_PACKAGE = 'service-segmenter:search-term-key'; + +interface KeyHookEngine { + registerHook?(event: string, handler: (context: unknown) => void, options?: { object?: string; packageId?: string }): void; + unregisterHooksByPackage?(packageId: string): number; +} + +/** + * Store each record's key, so the unique index on `term_key` and + * `knowledge_source` holds one entry per term and source on every write door + * (the Setup grid, the API, a CSV import): `term_key` is {@link keyOf} of the + * term, and an empty source is stored as `''` (NULL would be distinct to + * every unique index). An update that leaves `term` out leaves its key alone. + */ +function bindSearchTermKey(ctx: PluginContext): void { + let engine: KeyHookEngine | undefined; + try { + engine = ctx.getService('objectql'); + } catch { + engine = undefined; + } + if (typeof engine?.registerHook !== 'function') return; // no engine: the object is not registered either + engine.unregisterHooksByPackage?.(SEARCH_TERM_KEY_HOOK_PACKAGE); + const keyed = (insert: boolean) => (context: unknown): void => { + const data = (context as { input?: { data?: Record } } | undefined)?.input?.data; + if (!data || typeof data !== 'object') return; + if (typeof data.term === 'string') data.term_key = keyOf(data.term); + if (typeof data.knowledge_source === 'string') data.knowledge_source = data.knowledge_source.trim(); + else if (insert || 'knowledge_source' in data) data.knowledge_source = ''; + }; + const options = { object: SEARCH_TERM_OBJECT, packageId: SEARCH_TERM_KEY_HOOK_PACKAGE }; + engine.registerHook('beforeInsert', keyed(true), options); + engine.registerHook('beforeUpdate', keyed(false), options); +} diff --git a/packages/services/service-segmenter/src/segmenter-service.test.ts b/packages/services/service-segmenter/src/segmenter-service.test.ts index d1d8607f92d..e7f9f8eb8a6 100644 --- a/packages/services/service-segmenter/src/segmenter-service.test.ts +++ b/packages/services/service-segmenter/src/segmenter-service.test.ts @@ -7,7 +7,8 @@ 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 { SegmenterService, createSegmenterService, keyOf } from './segmenter-service.js'; +import { PLATFORM_WORDS } from './platform-words.js'; import { isNotInstalled, jiebaLoader, type SegmenterLoad } from './jieba-loader.js'; const jieba = await createSegmenterService(); @@ -224,3 +225,16 @@ describe('isNotInstalled', () => { expect(isNotInstalled(new Error('Cannot find native binding'))).toBe(false); }); }); + +describe('keyOf — the one comparison key', () => { + it('is NFKC, trimmed, lower case', () => { + expect(keyOf(' OA审批 ')).toBe('oa审批'); + }); + + it("spells every platform word as its own key, so sys_search_term's raw-text platform-word rule is the service's compare", () => { + // The object's rule compares the stored term as written; a future word in + // upper case or full-width form would let its other spelling be disabled + // past the rule. Read against the exported key itself, so it cannot drift. + for (const term of PLATFORM_WORDS) expect(keyOf(term), term).toBe(term); + }); +}); diff --git a/packages/services/service-segmenter/src/segmenter-service.ts b/packages/services/service-segmenter/src/segmenter-service.ts index ee4412d3aa3..12afd919212 100644 --- a/packages/services/service-segmenter/src/segmenter-service.ts +++ b/packages/services/service-segmenter/src/segmenter-service.ts @@ -39,8 +39,12 @@ interface Lexicon { /** 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 term's comparison key: NFKC, trimmed, lower case. Exported so the key + * `sys_search_term` stores (`term_key`, unique per source) and every pin of it + * read this one rule. + */ +export 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}\u3005-\u3007]+$/u; diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index eb1bab4ea14..6704e21d919 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -226,6 +226,23 @@ export interface AdapterSearchOptions { * verify it. */ queryVector?: () => Promise; + /** + * The question's keyword terms, cut once by the knowledge service (ADR-0161, + * the dated note of 2026-12-05 under K8) with the kernel's segmenter + * (`ISegmenterService`) and the administrator's search words, in the shape + * `keywordTerms` of `@objectstack/core` answers: distinct terms, compared + * case-insensitively, at most `MAX_KEYWORD_TERMS`. + * + * - **Present**: the keyword leg matches these terms and does not cut the + * question itself. Empty: it has nothing to match. + * - **Absent** (no segmenter is composed, or an adapter called directly): + * the adapter cuts the question with `keywordTerms` of `@objectstack/core`, + * as before this member. + * + * How a term is matched (an index, a scan, an operator) stays the adapter's. + * Never handed under the `vector` mode, which runs no keyword leg. + */ + keywordTerms?: readonly string[]; /** Trace id for correlation. */ traceId?: string; } diff --git a/packages/verify/package.json b/packages/verify/package.json index 910995bdcda..925d01750f9 100644 --- a/packages/verify/package.json +++ b/packages/verify/package.json @@ -57,6 +57,7 @@ "@objectstack/service-queue": "workspace:*", "@objectstack/service-realtime": "workspace:*", "@objectstack/service-record-context": "workspace:*", + "@objectstack/service-segmenter": "workspace:*", "@objectstack/service-settings": "workspace:*", "@objectstack/service-sms": "workspace:*", "@objectstack/service-storage": "workspace:*", diff --git a/packages/verify/src/harness.required-providers.test.ts b/packages/verify/src/harness.required-providers.test.ts index eecf2874ddb..a22512eb00c 100644 --- a/packages/verify/src/harness.required-providers.test.ts +++ b/packages/verify/src/harness.required-providers.test.ts @@ -29,7 +29,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from '@objectstack/core'; +import { CAPABILITY_PROVIDERS, KNOWLEDGE_SEGMENTER_PROVIDER, KNOWLEDGE_STORE_PROVIDERS } from '@objectstack/core'; import { composeStacks, defineStack } from '@objectstack/spec'; import { bootStack, type VerifyStack } from './harness.js'; import { constructServedProviders } from './required-providers.js'; @@ -154,6 +154,8 @@ describe('every provider the table names is a dependency of this package', () => ...Object.values(CAPABILITY_PROVIDERS).flatMap((spec) => [spec.pkg, ...(spec.extras ?? []).map((extra) => extra.pkg)]), // The stores the `knowledge` token chooses between (`resolveCapabilityExtras`), bar the optional one. ...stores.filter((store) => !store.optional).map((store) => store.pkg), + // The segmenter it mounts beside the store, whichever one. + KNOWLEDGE_SEGMENTER_PROVIDER.pkg, ]; expect(packages.length).toBeGreaterThan(0); expect(packages.filter((pkg) => !(pkg in manifest.dependencies))).toEqual([]); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7667890495b..6b4c06dbac7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -734,6 +734,9 @@ importers: '@objectstack/service-record-context': specifier: workspace:* version: link:../services/service-record-context + '@objectstack/service-segmenter': + specifier: workspace:* + version: link:../services/service-segmenter '@objectstack/service-settings': specifier: workspace:* version: link:../services/service-settings @@ -3923,6 +3926,9 @@ importers: '@objectstack/service-record-context': specifier: workspace:* version: link:../services/service-record-context + '@objectstack/service-segmenter': + specifier: workspace:* + version: link:../services/service-segmenter '@objectstack/service-settings': specifier: workspace:* version: link:../services/service-settings From a18bd8637559f10590a8d2bef1948350b69db8fb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 01:22:48 +0000 Subject: [PATCH 4/8] fix(knowledge): generic VALIDATION_ERROR for a word naming no source; term_key translations (step 2 of #38710) Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- .../src/apps/translations/ar.objects.generated.ts | 4 ++++ .../src/apps/translations/de.objects.generated.ts | 4 ++++ .../src/apps/translations/en.objects.generated.ts | 4 ++++ .../src/apps/translations/es-ES.objects.generated.ts | 4 ++++ .../src/apps/translations/fr.objects.generated.ts | 4 ++++ .../src/apps/translations/ja-JP.objects.generated.ts | 4 ++++ .../src/apps/translations/ko.objects.generated.ts | 4 ++++ .../src/apps/translations/pt-BR.objects.generated.ts | 4 ++++ .../src/apps/translations/ru.objects.generated.ts | 4 ++++ .../src/apps/translations/zh-CN.objects.generated.ts | 4 ++++ .../src/apps/translations/zh-Hant.objects.generated.ts | 4 ++++ .../platform-objects/src/system/sys-search-term.object.ts | 2 +- .../src/__tests__/search-terms-38710.test.ts | 2 +- .../services/service-knowledge/src/knowledge-search-terms.ts | 5 +++-- 14 files changed, 49 insertions(+), 4 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts index fe3c4fa23b9..92913848f34 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -4837,6 +4837,10 @@ export const arObjects: NonNullable = { both: "كلاهما" } }, + term_key: { + label: "مفتاح المصطلح", + help: "المصطلح بالصيغة التي يُقارن بها: توحيد الأشكال كاملة العرض ونصف العرض، وإزالة المسافات من الطرفين، وبأحرف صغيرة. تكتبه المنصة؛ إدخال واحد لكل مفتاح ومصدر معرفة." + }, knowledge_source: { label: "مصدر المعرفة", help: "مصدر المعرفة الوحيد الذي ينطبق عليه المصطلح، باسمه كما يسميه مستدعوه: NAMESPACE-NAME لمصدر حزمة، والاسم المجرد خلاف ذلك. فارغ: كل مصادر المعرفة في النشر." diff --git a/packages/platform-objects/src/apps/translations/de.objects.generated.ts b/packages/platform-objects/src/apps/translations/de.objects.generated.ts index d24609753a5..74176857986 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -4837,6 +4837,10 @@ export const deObjects: NonNullable = { both: "Beide" } }, + term_key: { + label: "Begriffsschlüssel", + help: "Der Begriff in der Form, in der er verglichen wird: Voll- und Halbbreitformen vereinheitlicht, ohne Leerzeichen am Rand, kleingeschrieben. Von der Plattform geschrieben; ein Eintrag je Schlüssel und Wissensquelle." + }, knowledge_source: { label: "Wissensquelle", help: "Die eine Wissensquelle, für die der Begriff gilt, so benannt wie von ihren Aufrufern: NAMESPACE-NAME für die Quelle eines Pakets, sonst der bloße Name. Leer: alle Wissensquellen der Bereitstellung." diff --git a/packages/platform-objects/src/apps/translations/en.objects.generated.ts b/packages/platform-objects/src/apps/translations/en.objects.generated.ts index 05132cf969c..33ff2dc2ab0 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -4837,6 +4837,10 @@ export const enObjects: NonNullable = { both: "Both" } }, + term_key: { + label: "Term Key", + help: "The term as it is compared: full-width and half-width forms folded, trimmed, lower case. Written by the platform; one entry per key and knowledge source." + }, knowledge_source: { label: "Knowledge Source", help: "The one knowledge source the term applies to, as callers name it: NAMESPACE-NAME for a package's source, the bare name otherwise. Empty: every knowledge source of the deployment." diff --git a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts index add41a8a8e0..edd5ea55aa0 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts @@ -4837,6 +4837,10 @@ export const esESObjects: NonNullable = { both: "Ambas" } }, + term_key: { + label: "Clave del término", + help: "El término tal como se compara: formas de ancho completo y medio unificadas, sin espacios en los extremos, en minúsculas. Lo escribe la plataforma; una entrada por clave y fuente de conocimiento." + }, knowledge_source: { label: "Fuente de conocimiento", help: "La única fuente de conocimiento a la que se aplica el término, tal como la nombran quienes la llaman: NAMESPACE-NAME para la fuente de un paquete, el nombre sin más en otro caso. Vacío: todas las fuentes de conocimiento de la implementación." diff --git a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts index 6a8fe680ba4..e4d372a04be 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -4837,6 +4837,10 @@ export const frObjects: NonNullable = { both: "Les deux" } }, + term_key: { + label: "Clé du terme", + help: "Le terme tel qu'il est comparé : formes pleine et demi-chasse unifiées, espaces de bord retirés, en minuscules. Écrit par la plateforme ; une entrée par clé et par source de connaissances." + }, knowledge_source: { label: "Source de connaissances", help: "L’unique source de connaissances à laquelle le terme s’applique, telle que ses appelants la nomment : NAMESPACE-NAME pour la source d’un paquet, le nom seul sinon. Vide : toutes les sources de connaissances du déploiement." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts index e1a2b1e4ab0..9292f05695c 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts @@ -4837,6 +4837,10 @@ export const jaJPObjects: NonNullable = { both: "両方" } }, + term_key: { + label: "用語キー", + help: "比較に使う用語の形:全角・半角を統一し、前後の空白を除き、小文字にしたもの。プラットフォームが書き込みます。キーとナレッジソースの組ごとに 1 件です。" + }, knowledge_source: { label: "ナレッジソース", help: "この語を適用する 1 つのナレッジソース。呼び出し側が使う名前で指定します:パッケージのソースは NAMESPACE-NAME、それ以外は名前のみ。空の場合:デプロイメントのすべてのナレッジソース。" diff --git a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts index 7c765b2cca7..f38ca8ffd63 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -4837,6 +4837,10 @@ export const koObjects: NonNullable = { both: "둘 다" } }, + term_key: { + label: "용어 키", + help: "비교에 쓰이는 용어 형태: 전각·반각을 통일하고 앞뒤 공백을 제거한 뒤 소문자로 바꾼 값입니다. 플랫폼이 기록하며, 키와 지식 소스마다 한 항목만 둘 수 있습니다." + }, knowledge_source: { label: "지식 소스", help: "단어가 적용되는 하나의 지식 소스이며 호출자가 부르는 이름으로 지정합니다: 패키지의 소스는 NAMESPACE-NAME, 그 외에는 이름만. 비어 있으면 배포의 모든 지식 소스입니다." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts index f378bac54f6..0e69623cda7 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts @@ -4837,6 +4837,10 @@ export const ptBRObjects: NonNullable = { both: "Ambas" } }, + term_key: { + label: "Chave do termo", + help: "O termo como é comparado: formas de largura total e meia largura unificadas, sem espaços nas pontas, em minúsculas. Escrito pela plataforma; uma entrada por chave e fonte de conhecimento." + }, knowledge_source: { label: "Fonte de conhecimento", help: "A única fonte de conhecimento à qual o termo se aplica, como quem a chama a nomeia: NAMESPACE-NAME para a fonte de um pacote, o nome simples caso contrário. Vazio: todas as fontes de conhecimento da implantação." diff --git a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts index 2a93caaeb14..c2854b90a46 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -4837,6 +4837,10 @@ export const ruObjects: NonNullable = { both: "Оба" } }, + term_key: { + label: "Ключ термина", + help: "Термин в том виде, в котором он сравнивается: полноширинные и полуширинные формы приведены к одной, пробелы по краям удалены, нижний регистр. Записывается платформой; одна запись на ключ и источник знаний." + }, knowledge_source: { label: "Источник знаний", help: "Единственный источник знаний, к которому применяется термин, в том виде, как его называют вызывающие: NAMESPACE-NAME для источника пакета, иначе просто имя. Пусто: все источники знаний развёртывания." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts index e44440ef603..8017816f52c 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts @@ -4837,6 +4837,10 @@ export const zhCNObjects: NonNullable = { both: "两者" } }, + term_key: { + label: "词条键", + help: "词条用于比较的形式:全角半角统一、去掉首尾空格、转为小写。由平台写入;每个键与知识源只能有一条。" + }, knowledge_source: { label: "知识源", help: "词条只适用的那一个知识源,按调用方的叫法:包内知识源为 NAMESPACE-NAME,否则为裸名称。为空:部署中的所有知识源。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts index 12a78f2102f..ee6fc29a851 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts @@ -4837,6 +4837,10 @@ export const zhHantObjects: NonNullable = { both: "兩者" } }, + term_key: { + label: "詞條鍵", + help: "詞條用於比較的形式:全形半形統一、去除首尾空白、轉為小寫。由平台寫入;每個鍵與知識來源只能有一筆。" + }, knowledge_source: { label: "知識來源", help: "詞條只適用的那一個知識來源,依呼叫方的稱呼:套件內知識來源為 NAMESPACE-NAME,否則為裸名稱。為空:部署中的所有知識來源。" diff --git a/packages/platform-objects/src/system/sys-search-term.object.ts b/packages/platform-objects/src/system/sys-search-term.object.ts index 8aa5a6077c2..9bc55cfb2ab 100644 --- a/packages/platform-objects/src/system/sys-search-term.object.ts +++ b/packages/platform-objects/src/system/sys-search-term.object.ts @@ -149,7 +149,7 @@ export const SysSearchTerm = ObjectSchema.create({ maxLength: 255, description: "The one knowledge source the term applies to, as callers name it: NAMESPACE-NAME for a package's source, the bare name otherwise. " + - 'Empty: every knowledge source of the deployment. A name no registered source answers to is refused.', + 'Empty: every knowledge source of the deployment.', group: 'Term', }), diff --git a/packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts b/packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts index 9db63748797..f503c407c7f 100644 --- a/packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts +++ b/packages/services/service-knowledge/src/__tests__/search-terms-38710.test.ts @@ -182,7 +182,7 @@ describe('knowledge search: the keyword terms are cut once by the service and ha () => null, (e: unknown) => e as Record, ); - expect(refusal).toMatchObject({ code: 'VALIDATION_FAILED', status: 400 }); + expect(refusal).toMatchObject({ code: 'VALIDATION_ERROR', status: 400, fields: [expect.objectContaining({ field: 'knowledge_source' })] }); // A source that existed when the entry was written, and is gone since. one.svc.registerSource(source('retired')); await write(st, { term: '明规条款', kind: 'word', knowledge_source: 'retired' }); diff --git a/packages/services/service-knowledge/src/knowledge-search-terms.ts b/packages/services/service-knowledge/src/knowledge-search-terms.ts index 029ad0b3dee..ea04a7326bb 100644 --- a/packages/services/service-knowledge/src/knowledge-search-terms.ts +++ b/packages/services/service-knowledge/src/knowledge-search-terms.ts @@ -264,7 +264,8 @@ export interface SearchTermHookService { * Bind the knowledge service's hooks on `sys_search_term`: every write drops * the service's cache (and tells the peers) once it commits, and a record * naming a knowledge source no registered source answers to is refused with - * `400 VALIDATION_FAILED`, since it would apply to no search. Answers + * `400 VALIDATION_ERROR` (ADR-0112), naming the field, since it would apply to + * no search. Answers * whether the engine takes hooks. */ export function bindSearchTermHooks(engine: SearchTermHookEngine | undefined, service: SearchTermHookService): boolean { @@ -281,7 +282,7 @@ export function bindSearchTermHooks(engine: SearchTermHookEngine | undefined, se `No knowledge source is named '${source}', so this search word would apply to no search. ` + `Name one of the registered sources${faces.length > 0 ? ` (${faces.join(', ')})` : ''}, or leave Knowledge Source empty to apply it to every source.`; throw Object.assign(new Error(message), { - code: 'VALIDATION_FAILED', + code: 'VALIDATION_ERROR', status: 400, fields: [{ field: 'knowledge_source', code: 'invalid_reference', message }], }); From a40db16f5e9d945b463733e5d196a3b03b0d8747 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 01:38:09 +0000 Subject: [PATCH 5/8] chore(knowledge): changesets, protocol docs for keywordTerms, vitest alias for the segmenter (step 2 of #38710) Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- .changeset/38710-knowledge-search-cut-once.md | 22 +++++++++++++++++++ .changeset/38710-search-terms-setup-entry.md | 16 ++++++++++++++ content/docs/protocol/knowledge.mdx | 10 +++++++++ .../test/serve-capability-identity.test.ts | 1 + .../service-knowledge/vitest.config.ts | 6 +++++ 5 files changed, 55 insertions(+) create mode 100644 .changeset/38710-knowledge-search-cut-once.md create mode 100644 .changeset/38710-search-terms-setup-entry.md diff --git a/.changeset/38710-knowledge-search-cut-once.md b/.changeset/38710-knowledge-search-cut-once.md new file mode 100644 index 00000000000..eceeb0a4946 --- /dev/null +++ b/.changeset/38710-knowledge-search-cut-once.md @@ -0,0 +1,22 @@ +--- +'@objectstack/spec': patch +'@objectstack/core': patch +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +'@objectstack/service-cluster': patch +'@objectstack/cli': patch +'@objectstack/verify': patch +--- + +fix(knowledge): a Chinese question is cut into whole words once, with the platform segmenter and the administrator's search words, before every keyword search + +Clause-②: yes (the adapter contract `AdapterSearchOptions` gains a field) +Metadata-protocol: none + +Who sees it: anyone asking the knowledge base a question in Chinese, in an environment whose knowledge search runs in keyword or hybrid mode. + +- **Whole words, not sliding windows.** The knowledge service now cuts each question once per source face with the segmenter (the Chinese dictionary plus the search words and stop words kept under Setup → Search Terms) and hands those words to the store. 「我在集团干了 12 年了,一年有几天年假?」 is matched as `集团`, `一年`, `年假`, `12` instead of sixteen overlapping fragments such as `我在集`, so 年假, 脱密, 应急采购 and 超预算 are matched whole. English questions are cut as before. +- **Adapter contract.** `AdapterSearchOptions` gains one optional member, `keywordTerms?: readonly string[]` (ADR-0161, the dated note of 2026-12-05 under K8). The Turso and pgvector stores match the words they are handed; when the member is absent (no segmenter is running, or it failed) they cut the question themselves with `keywordTerms` from `@objectstack/core`, as before. Their private copies of that function are gone. +- **A change to a search word reaches the next question.** The service caches the words per environment for 30 seconds at most; adding, editing or deleting a word clears the cache at once, and on a multi-replica deployment the change is broadcast to the other replicas on the `search-term.changed` cluster lane. +- **The segmenter is mounted with knowledge.** An environment that requires `knowledge` now also mounts `@objectstack/service-segmenter`; `@objectstack/cli` and `@objectstack/verify` depend on it. diff --git a/.changeset/38710-search-terms-setup-entry.md b/.changeset/38710-search-terms-setup-entry.md new file mode 100644 index 00000000000..b5eecc283c8 --- /dev/null +++ b/.changeset/38710-search-terms-setup-entry.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-segmenter': patch +'@objectstack/platform-objects': patch +--- + +feat(segmenter): Setup → Search Terms, with one entry per word and knowledge source + +Clause-②: yes (the adapter contract `AdapterSearchOptions` gains a field) +Metadata-protocol: none + +Who sees it: a platform administrator in Setup, and every knowledge search that reads the words they keep. + +- **Setup → Search Terms** lists the search words and stop words (`sys_search_term`) for an administrator with Manage Platform Settings. Import is offered through the console's generic import. +- **One entry per word and source.** A new read-only field, `term_key`, holds the word normalised (NFKC, trimmed, lower case), and a unique index on `term_key` with `knowledge_source` refuses a second entry for the same word and source: `OA审批` and `oa审批` are one word. An entry with no knowledge source applies to every source. +- **A source that does not exist is refused.** Saving a word for a knowledge source the environment does not have answers `VALIDATION_ERROR` (400) on `knowledge_source`; a word whose source was later removed is skipped with one warning in the log. +- `keyOf` (the normalisation) is exported from `@objectstack/service-segmenter`. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index f22a28b8366..aa2642dcb49 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -643,6 +643,16 @@ about a call and reads no vector: the question is embedded at most once for each adapter instance in a search, by the adapter. An adapter without `embedQuery` is handed nothing and embeds the question on every call, as before. +`AdapterSearchOptions.keywordTerms` is the question already cut into the +words a keyword or hybrid search matches (ADR-0161, the dated note of +2026-12-05 under K8). The service cuts the question once per source face with +the platform segmenter, the Chinese dictionary plus the search words and stop +words an administrator keeps under Setup → Search Terms, and hands the same +words to every adapter. An adapter that receives the member matches those +words; an empty list means the question has no word worth matching, and the +keyword side then finds nothing. When the member is absent (no segmenter is +running, or the segmenter failed), the adapter cuts the question itself, as +before. A search under `vector` is never handed it. `listDocuments` lists the documents the adapter holds for a source, a page of at most `limit` entries at a time, each with the `docHash` it was stored with; `nextCursor` is absent once the diff --git a/packages/cli/test/serve-capability-identity.test.ts b/packages/cli/test/serve-capability-identity.test.ts index a3646520034..1dc6fda061b 100644 --- a/packages/cli/test/serve-capability-identity.test.ts +++ b/packages/cli/test/serve-capability-identity.test.ts @@ -50,6 +50,7 @@ import '@objectstack/driver-turso'; import '@objectstack/driver-sql'; import '@objectstack/platform-objects/plugin'; import '@objectstack/plugin-security'; +import '@objectstack/spec/migrations'; const HERE = resolve(fileURLToPath(import.meta.url), '..'); diff --git a/packages/services/service-knowledge/vitest.config.ts b/packages/services/service-knowledge/vitest.config.ts index f3da4783055..8f7e214e1a5 100644 --- a/packages/services/service-knowledge/vitest.config.ts +++ b/packages/services/service-knowledge/vitest.config.ts @@ -40,6 +40,12 @@ export default defineConfig({ // The record-sync queue suite boots a real kernel over the SQL driver and // the platform's queue service; their source, like every sibling here. { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../../drivers/driver-sql/src/index.ts') }, + // The search-terms suite (#38710) boots the real segmenter plugin over the + // search-word object; its source, like every sibling here. + { + find: /^@objectstack\/service-segmenter$/, + replacement: path.resolve(__dirname, '../service-segmenter/src/index.ts'), + }, { find: /^@objectstack\/service-queue$/, replacement: path.resolve(__dirname, '../service-queue/src/index.ts') }, { find: /^@objectstack\/platform-objects\/audit$/, From fe288946e902bc7d088ac7891d8f8c91e1b6b24a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 02:08:49 +0000 Subject: [PATCH 6/8] docs(platform-objects): userActions.import shows only the console's Import entry (step 2 of #38710) Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- .changeset/38710-search-terms-setup-entry.md | 2 +- .../platform-objects/src/system/sys-search-term.object.ts | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.changeset/38710-search-terms-setup-entry.md b/.changeset/38710-search-terms-setup-entry.md index b5eecc283c8..6b17ba53e73 100644 --- a/.changeset/38710-search-terms-setup-entry.md +++ b/.changeset/38710-search-terms-setup-entry.md @@ -10,7 +10,7 @@ Metadata-protocol: none Who sees it: a platform administrator in Setup, and every knowledge search that reads the words they keep. -- **Setup → Search Terms** lists the search words and stop words (`sys_search_term`) for an administrator with Manage Platform Settings. Import is offered through the console's generic import. +- **Setup → Search Terms** lists the search words and stop words (`sys_search_term`) for an administrator with Manage Platform Settings, with the console's Import entry for loading a list from one file. - **One entry per word and source.** A new read-only field, `term_key`, holds the word normalised (NFKC, trimmed, lower case), and a unique index on `term_key` with `knowledge_source` refuses a second entry for the same word and source: `OA审批` and `oa审批` are one word. An entry with no knowledge source applies to every source. - **A source that does not exist is refused.** Saving a word for a knowledge source the environment does not have answers `VALIDATION_ERROR` (400) on `knowledge_source`; a word whose source was later removed is skipped with one warning in the log. - `keyOf` (the normalisation) is exported from `@objectstack/service-segmenter`. diff --git a/packages/platform-objects/src/system/sys-search-term.object.ts b/packages/platform-objects/src/system/sys-search-term.object.ts index 9bc55cfb2ab..144d0285d55 100644 --- a/packages/platform-objects/src/system/sys-search-term.object.ts +++ b/packages/platform-objects/src/system/sys-search-term.object.ts @@ -75,8 +75,10 @@ export const SysSearchTerm = ObjectSchema.create({ managedBy: 'system-data', // CSV import is opt-in on `system-data`; search terms opt in (the card's // "import of entries"): an administrator loads a list of policy titles and - // section names in one file through the generic import door. Who may import - // is the same capability that guards every other write. + // section names in one file through the generic import door. This flag + // shows the console's Import entry and nothing else: it opens no door and + // closes none. Who may import is the capability that guards every other + // write. userActions: { import: true }, // [ADR-0131 D7] Deployment-level: one set of words for the whole deployment, // never one organization's, so there is no organization to stamp. From 73c8d231feda79cf8f15d1dcc3fc808743a6622e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 03:05:36 +0000 Subject: [PATCH 7/8] test(service-knowledge): the contract suite's case for AdapterSearchOptions.keywordTerms (step 2 of #38710) ADR-0161 K8 rule 1: the member lands with a case in the contract test suite. A store that declares a keyword leg, under keyword mode: absent, it cuts as keywordTerms of @objectstack/core does; handed, it matches the terms and does not cut the question; empty, it answers nothing. A store without a keyword leg answers the same with or without the member. The K8 note's rule-1 sentence names the case. Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- .changeset/38710-knowledge-search-cut-once.md | 2 +- ...urn-knowledge-source-is-a-governed-type.md | 2 +- .../services/service-knowledge/src/testing.ts | 60 ++++++++++++++++++- 3 files changed, 61 insertions(+), 3 deletions(-) diff --git a/.changeset/38710-knowledge-search-cut-once.md b/.changeset/38710-knowledge-search-cut-once.md index eceeb0a4946..3fafc9c9162 100644 --- a/.changeset/38710-knowledge-search-cut-once.md +++ b/.changeset/38710-knowledge-search-cut-once.md @@ -17,6 +17,6 @@ Metadata-protocol: none Who sees it: anyone asking the knowledge base a question in Chinese, in an environment whose knowledge search runs in keyword or hybrid mode. - **Whole words, not sliding windows.** The knowledge service now cuts each question once per source face with the segmenter (the Chinese dictionary plus the search words and stop words kept under Setup → Search Terms) and hands those words to the store. 「我在集团干了 12 年了,一年有几天年假?」 is matched as `集团`, `一年`, `年假`, `12` instead of sixteen overlapping fragments such as `我在集`, so 年假, 脱密, 应急采购 and 超预算 are matched whole. English questions are cut as before. -- **Adapter contract.** `AdapterSearchOptions` gains one optional member, `keywordTerms?: readonly string[]` (ADR-0161, the dated note of 2026-12-05 under K8). The Turso and pgvector stores match the words they are handed; when the member is absent (no segmenter is running, or it failed) they cut the question themselves with `keywordTerms` from `@objectstack/core`, as before. Their private copies of that function are gone. +- **Adapter contract.** `AdapterSearchOptions` gains one optional member, `keywordTerms?: readonly string[]` (ADR-0161, the dated note of 2026-12-05 under K8). The Turso and pgvector stores match the words they are handed; when the member is absent (no segmenter is running, or it failed) they cut the question themselves with `keywordTerms` from `@objectstack/core`, as before. Their private copies of that function are gone. The adapter contract suite (`@objectstack/service-knowledge/testing`) gains the member's case: a store with a keyword leg cuts as `@objectstack/core` does when the member is absent, matches the handed words without cutting when it is present, and matches nothing when it is empty; a store without one answers the same either way. - **A change to a search word reaches the next question.** The service caches the words per environment for 30 seconds at most; adding, editing or deleting a word clears the cache at once, and on a multi-replica deployment the change is broadcast to the other replicas on the `search-term.changed` cluster lane. - **The segmenter is mounted with knowledge.** An environment that requires `knowledge` now also mounts `@objectstack/service-segmenter`; `@objectstack/cli` and `@objectstack/verify` depend on it. diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index 0016d0bd2d2..5b853cd2de6 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -517,7 +517,7 @@ Rules for every member: > - **What the service reads.** The enabled and disabled entries of `sys_search_term`, as the contract's `SegmenterEntry`: the entries with no source first, then the source's own, each by `created_at`, then `id`, never `updated_at`; `enabled` passed as a boolean. The read is cached per service, one per environment's kernel, dropped when a record changes on this replica, on a peer's message on the cluster channel `search-term.changed` (an address, never a value), and after a short time, because that channel delivers at most once. > - **Not in this note.** A segmenter inside an adapter, a tokenizer on a knowledge source (the note of 2026-11-30 above keeps it out), and record search, which the segmenter contract reserves. > -> This note registers exactly one member, `AdapterSearchOptions.keywordTerms`, and no other: the list stays closed beyond it (rules 3 and 5). It lands in the PR that builds it, with its first readers, `knowledge-turso` and `knowledge-pgvector`, and the knowledge service that hands it (rule 1). `knowledge-memory` does not read it and is searched as before (rule 2). The rules above and every earlier note are left as written. +> This note registers exactly one member, `AdapterSearchOptions.keywordTerms`, and no other: the list stays closed beyond it (rules 3 and 5). It lands in the PR that builds it, with its first readers, `knowledge-turso` and `knowledge-pgvector`, the knowledge service that hands it, and its case in the contract test suite (`packages/services/service-knowledge/src/testing.ts#runKnowledgeAdapterContract`) (rule 1): an adapter that declares a keyword leg, searched under `keyword`, answers without the member what it answers when handed the cut of `keywordTerms` of `@objectstack/core`; handed terms, it matches them and does not cut the question; handed `[]`, it answers nothing. `knowledge-memory` does not read it and is searched as before (rule 2), which the suite pins for an adapter without a keyword leg: handed or not, a search answers the same. The rules above and every earlier note are left as written. ### K9 — One `search_knowledge` definition, and every knowledge tool goes through the tool registry and the MCP seams diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 1ecea54fbe5..4c844f0bcfd 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -75,6 +75,16 @@ * hold the question's characters one by one and none of its words: the * passage is ranked. * + * The question's keyword terms (ADR-0161, the dated note of 2026-12-05 under + * K8), on the same fixture under `keyword`: an adapter that declares + * `keywordLeg`, handed no `keywordTerms`, answers what it answers when handed + * the cut of `keywordTerms` of `@objectstack/core`; handed terms, it matches + * them and does not cut the question itself, so a term no passage's own words + * reach is answered and a question whose own words rank a passage, handed + * terms no passage holds, answers nothing; handed `[]`, it answers nothing. + * An adapter that does not declare it answers the same with or without the + * member. + * * An adapter that declares `retrieval` reports its modes and default * (`capabilities.retrieval`), and the same fixture is searched under each * mode it lists: `vector` leaves that passage out, `keyword` answers it @@ -93,6 +103,7 @@ */ import { describe, expect, it, vi } from 'vitest'; +import { keywordTerms } from '@objectstack/core'; import type { IDataEngine, IKnowledgeAdapter, @@ -162,7 +173,10 @@ export interface KnowledgeAdapterContractOptions { * leg cuts a run of Han, kana or Hangul in the query into pieces, so a * question written without spaces ranks the passage that holds some of its * words, which the vector leg alone ranks below `topK`. Asserted by - * behaviour. Absent: `false`. + * behaviour. With it the adapter reads `AdapterSearchOptions.keywordTerms` + * (ADR-0161, the dated note of 2026-12-05 under K8), asserted under + * `retrieval: { mode: 'keyword' }`, so the adapter also declares + * `retrieval` and lists that mode. Absent: `false`. */ keywordLeg?: boolean; /** @@ -611,6 +625,50 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption const hits = await adapter.search('出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗', { source: a, topK: 3 }); expect(hits.map((h) => h.documentId)).toContain(`${a.name}:clause`); }); + + it('keywordTerms (ADR-0161, the dated note of 2026-12-05 under K8): absent, it cuts as `@objectstack/core` does; handed, it matches them and does not cut; empty, it matches nothing', async () => { + const adapter: IKnowledgeAdapter = await make(); + expect(adapter.capabilities?.retrieval?.modes, 'the case reads the keyword leg alone, under `keyword`').toContain('keyword'); + const a = objectSource('kw_terms'); + const spread = ['a', 'b', 'c', 'd', 'e'].map((n) => + doc(a, `spread_${n}`, `出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 ${n}`), + ); + await adapter.upsert([...spread, doc(a, 'clause', '采购单笔金额2000元以下除外,其余一律公开招标')], ctxOf(a)); + const QUESTION = '出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗'; + const keyword = { mode: 'keyword' } as const; + const ids = (hits: Array<{ documentId: string }>) => hits.map((h) => h.documentId); + + // Absent: the adapter cuts the question with core's `keywordTerms`, + // so handing that cut answers the same. + const absent = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: keyword }); + expect(ids(absent)).toEqual([`${a.name}:clause`]); + expect(await adapter.search(QUESTION, { source: a, topK: 3, retrieval: keyword, keywordTerms: keywordTerms(QUESTION) })) + .toEqual(absent); + + // Handed: the terms are matched. `zzqx` reaches no passage by its own + // words, so the passage is answered by the handed term alone. + expect(await adapter.search('zzqx', { source: a, topK: 3, retrieval: keyword })).toEqual([]); + expect(ids(await adapter.search('zzqx', { source: a, topK: 3, retrieval: keyword, keywordTerms: ['公开招标'] }))) + .toEqual([`${a.name}:clause`]); + // Handed, the question is not cut: its own words rank the passage + // (above), and the handed term no passage holds ranks nothing. + expect(await adapter.search(QUESTION, { source: a, topK: 3, retrieval: keyword, keywordTerms: ['zzqx'] })).toEqual([]); + + // Empty: the keyword leg has nothing to match. + expect(await adapter.search(QUESTION, { source: a, topK: 3, retrieval: keyword, keywordTerms: [] })).toEqual([]); + }); + }); + } else { + describe('without a keyword leg', () => { + it('keywordTerms (ADR-0161, the dated note of 2026-12-05 under K8): handed or not, a search answers the same', async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('kw_terms_none'); + await adapter.upsert([doc(a, '1', 'alpine meadow flowers'), doc(a, '2', 'harbour cranes at night')], ctxOf(a)); + const without = await adapter.search('alpine meadow', { source: a, topK: 3 }); + expect(without.length).toBeGreaterThan(0); + expect(await adapter.search('alpine meadow', { source: a, topK: 3, keywordTerms: ['harbour'] })).toEqual(without); + expect(await adapter.search('alpine meadow', { source: a, topK: 3, keywordTerms: [] })).toEqual(without); + }); }); } From 236366746f827b154cc0c6d61248b5e4fcc7f5b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 03:06:46 +0000 Subject: [PATCH 8/8] i18n(platform-objects): label the Setup entry Search Terms in every platform locale (step 2 of #38710) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nav_search_terms gains its label beside nav_knowledge_sync_states in the eleven hand-authored Setup bundles (zh-CN: 检索词条). Claude-Session: https://claude.ai/code/session_01L9qibw3sEzqFZcu4JmuGwW --- .changeset/38710-search-terms-setup-entry.md | 2 +- packages/platform-objects/src/apps/translations/ar.ts | 1 + packages/platform-objects/src/apps/translations/de.ts | 1 + packages/platform-objects/src/apps/translations/en.ts | 1 + packages/platform-objects/src/apps/translations/es-ES.ts | 1 + packages/platform-objects/src/apps/translations/fr.ts | 1 + packages/platform-objects/src/apps/translations/ja-JP.ts | 1 + packages/platform-objects/src/apps/translations/ko.ts | 1 + packages/platform-objects/src/apps/translations/pt-BR.ts | 1 + packages/platform-objects/src/apps/translations/ru.ts | 1 + packages/platform-objects/src/apps/translations/zh-CN.ts | 1 + packages/platform-objects/src/apps/translations/zh-Hant.ts | 1 + 12 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.changeset/38710-search-terms-setup-entry.md b/.changeset/38710-search-terms-setup-entry.md index 6b17ba53e73..774ae249812 100644 --- a/.changeset/38710-search-terms-setup-entry.md +++ b/.changeset/38710-search-terms-setup-entry.md @@ -10,7 +10,7 @@ Metadata-protocol: none Who sees it: a platform administrator in Setup, and every knowledge search that reads the words they keep. -- **Setup → Search Terms** lists the search words and stop words (`sys_search_term`) for an administrator with Manage Platform Settings, with the console's Import entry for loading a list from one file. +- **Setup → Search Terms** lists the search words and stop words (`sys_search_term`) for an administrator with Manage Platform Settings, with the console's Import entry for loading a list from one file. The entry is labelled in every platform locale (检索词条 in Simplified Chinese). - **One entry per word and source.** A new read-only field, `term_key`, holds the word normalised (NFKC, trimmed, lower case), and a unique index on `term_key` with `knowledge_source` refuses a second entry for the same word and source: `OA审批` and `oa审批` are one word. An entry with no knowledge source applies to every source. - **A source that does not exist is refused.** Saving a word for a knowledge source the environment does not have answers `VALIDATION_ERROR` (400) on `knowledge_source`; a word whose source was later removed is skipped with one warning in the log. - `keyOf` (the normalisation) is exported from `@objectstack/service-segmenter`. diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index 29f5a4e2c73..18b29316b9e 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -112,6 +112,7 @@ export const ar: TranslationData = { nav_settings_ai: { label: 'خدمة نماذج الذكاء الاصطناعي', keywords: ['الذكاء الاصطناعي والتضمين (Embedder)'] }, nav_settings_knowledge: { label: 'المعرفة' }, nav_knowledge_sync_states: { label: 'حالة مزامنة المعرفة' }, + nav_search_terms: { label: 'مصطلحات البحث' }, nav_settings_lifecycle: { label: 'الاحتفاظ بالبيانات', keywords: ['دورة حياة البيانات'] }, nav_recycle_bin: { label: 'سلة المحذوفات' }, nav_public_forms: { label: 'النماذج العامة' }, diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index 3de02fc4e89..e2290efab70 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -114,6 +114,7 @@ export const de: TranslationData = { nav_settings_ai: { label: 'KI-Modelldienst', keywords: ['KI und Embedder'] }, nav_settings_knowledge: { label: 'Wissen' }, nav_knowledge_sync_states: { label: 'Wissenssynchronisierung' }, + nav_search_terms: { label: 'Suchbegriffe' }, nav_settings_lifecycle: { label: 'Datenaufbewahrung', keywords: ['Datenlebenszyklus'] }, nav_recycle_bin: { label: 'Papierkorb' }, nav_public_forms: { label: 'Öffentliche Formulare' }, diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index 51089fb0872..4df5eef18f0 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -148,6 +148,7 @@ export const en: TranslationData = { nav_settings_ai: { label: 'AI Model Service' }, nav_settings_knowledge: { label: 'Knowledge' }, nav_knowledge_sync_states: { label: 'Knowledge Sync Status' }, + nav_search_terms: { label: 'Search Terms' }, nav_settings_lifecycle: { label: 'Data Retention' }, nav_recycle_bin: { label: 'Recycle Bin' }, nav_public_forms: { label: 'Public Forms' }, diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index f32fb407a9e..ba61b1c4198 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -102,6 +102,7 @@ export const esES: TranslationData = { nav_settings_ai: { label: 'Servicio de modelos de IA', keywords: ['IA y Embedder'] }, nav_settings_knowledge: { label: 'Conocimiento' }, nav_knowledge_sync_states: { label: 'Estado de sincronización del conocimiento' }, + nav_search_terms: { label: 'Términos de búsqueda' }, nav_settings_lifecycle: { label: 'Retención de datos', keywords: ['Ciclo de vida de los datos'] }, nav_recycle_bin: { label: 'Papelera' }, nav_public_forms: { label: 'Formularios públicos' }, diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index ade3a8d9423..00330ee3311 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -114,6 +114,7 @@ export const fr: TranslationData = { nav_settings_ai: { label: 'Service de modèles d’IA', keywords: ['IA et Embedder'] }, nav_settings_knowledge: { label: 'Connaissances' }, nav_knowledge_sync_states: { label: 'État de synchronisation des connaissances' }, + nav_search_terms: { label: 'Termes de recherche' }, nav_settings_lifecycle: { label: 'Conservation des données', keywords: ['Cycle de vie des données'] }, nav_recycle_bin: { label: 'Corbeille' }, nav_public_forms: { label: 'Formulaires publics' }, diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index 760b3a6291e..ae31c839c9e 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -102,6 +102,7 @@ export const jaJP: TranslationData = { nav_settings_ai: { label: 'AI モデルサービス', keywords: ['AI と Embedder'] }, nav_settings_knowledge: { label: 'ナレッジ' }, nav_knowledge_sync_states: { label: 'ナレッジ同期状況' }, + nav_search_terms: { label: '検索用語' }, nav_settings_lifecycle: { label: 'データ保持', keywords: ['データライフサイクル'] }, nav_recycle_bin: { label: 'ごみ箱' }, nav_public_forms: { label: '公開フォーム' }, diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index f4ce1d38843..f556cfcdd0d 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -113,6 +113,7 @@ export const ko: TranslationData = { nav_settings_ai: { label: 'AI 모델 서비스', keywords: ['AI 및 Embedder'] }, nav_settings_knowledge: { label: '지식' }, nav_knowledge_sync_states: { label: '지식 동기화 상태' }, + nav_search_terms: { label: '검색어' }, nav_settings_lifecycle: { label: '데이터 보존', keywords: ['데이터 수명 주기'] }, nav_recycle_bin: { label: '휴지통' }, nav_public_forms: { label: '공개 양식' }, diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index 6130c593a3e..7ceb5b28a30 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -114,6 +114,7 @@ export const ptBR: TranslationData = { nav_settings_ai: { label: 'Serviço de modelos de IA', keywords: ['IA e Embedder'] }, nav_settings_knowledge: { label: 'Conhecimento' }, nav_knowledge_sync_states: { label: 'Status de sincronização do conhecimento' }, + nav_search_terms: { label: 'Termos de pesquisa' }, nav_settings_lifecycle: { label: 'Retenção de dados', keywords: ['Ciclo de vida dos dados'] }, nav_recycle_bin: { label: 'Lixeira' }, nav_public_forms: { label: 'Formulários públicos' }, diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index d178a1af7b5..28626aee7ce 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -114,6 +114,7 @@ export const ru: TranslationData = { nav_settings_ai: { label: 'Сервис моделей ИИ', keywords: ['ИИ и Embedder'] }, nav_settings_knowledge: { label: 'Знания' }, nav_knowledge_sync_states: { label: 'Состояние синхронизации знаний' }, + nav_search_terms: { label: 'Поисковые термины' }, nav_settings_lifecycle: { label: 'Хранение данных', keywords: ['Жизненный цикл данных'] }, nav_recycle_bin: { label: 'Корзина' }, nav_public_forms: { label: 'Публичные формы' }, diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index ddec4ac1a35..e050aea0748 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -106,6 +106,7 @@ export const zhCN: TranslationData = { nav_settings_ai: { label: 'AI 模型服务', keywords: ['AI 与向量化'] }, nav_settings_knowledge: { label: '知识库' }, nav_knowledge_sync_states: { label: '知识库同步状态' }, + nav_search_terms: { label: '检索词条' }, nav_settings_lifecycle: { label: '数据保留', keywords: ['数据生命周期'] }, nav_recycle_bin: { label: '回收站' }, nav_public_forms: { label: '对外表单' }, diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index e9e485a50cd..c28912f460f 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -112,6 +112,7 @@ export const zhHant: TranslationData = { nav_settings_ai: { label: 'AI 模型服務', keywords: ['AI 與 Embedder'] }, nav_settings_knowledge: { label: '知識庫' }, nav_knowledge_sync_states: { label: '知識庫同步狀態' }, + nav_search_terms: { label: '檢索詞條' }, nav_settings_lifecycle: { label: '資料保留', keywords: ['資料生命週期'] }, nav_recycle_bin: { label: '回收站' }, nav_public_forms: { label: '對外表單' },