diff --git a/.changeset/38710-search-term-preview.md b/.changeset/38710-search-term-preview.md new file mode 100644 index 00000000000..d7409e6105b --- /dev/null +++ b/.changeset/38710-search-term-preview.md @@ -0,0 +1,19 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-segmenter': patch +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +'@objectstack/platform-objects': patch +--- + +feat(knowledge): Setup → Search Terms previews how a question is cut, and how many passages each term matches + +Clause-②: yes (the contracts `ISegmenterService` and `IKnowledgeAdapter` each gain one optional member) +Metadata-protocol: none + +Who sees it: a platform administrator in Setup → Search Terms, checking which words a question is matched by before or after adding a search word. + +- **Preview Terms.** The Search Terms list has a Preview Terms action, for an administrator with Manage Platform Settings. It takes a question and, optionally, a knowledge source, and answers the terms a knowledge search would match, the words it drops as stop words, and, for a named source, how many passages of the source each term matches beside the source's passage total. The action is labelled in every platform locale (预览切词 in Simplified Chinese). +- **One cut for search and preview.** `ISegmenterService` gains an optional `cut(query, options?)` answering `{ terms, stopWords }`; the platform segmenter's `keywordTerms` now answers `cut(...).terms`, so the preview shows exactly the terms a search is handed. `SegmenterCut` is exported from `@objectstack/spec/contracts`. +- **Adapter contract.** `IKnowledgeAdapter` gains one optional member, `countKeywordMatches(ctx, terms)` answering `{ passages, matches }` (ADR-0161, the second dated note of 2026-12-05 under K8): the passages of the source's active generation, and per term the passages a keyword search of that term matches, with the same operator. The Turso and pgvector stores implement it; a store without it answers the preview's terms uncounted. The counts are not filtered by record permissions, so `KnowledgeService.previewTerms` answers only a system context or a caller holding `manage_platform_settings` (`options.executionContext`), and refuses any other with `403 PERMISSION_DENIED`. The adapter contract suite (`@objectstack/service-knowledge/testing`) gains `implements.keywordCounts` and its case. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 9c417afe767..15adcfa35c9 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -194,6 +194,7 @@ One of the largest consumers of the flag; | 45a | The `sys_comment` participant keeper lets a system update write `participants` and `thread_root_id` (#39081, #39142), and reads a new reply's parent as the system | plugin-audit | Get: the platform's own rewrite of a thread's stored participant list and of each reply's stored thread root — the after-write reconcile on a reply, a mention edit, a re-point or a delete, and `os migrate comment-participants --apply` — lands under `preserveAudit` with the row's `updated_at` kept; and the create stamp reads the parent of each new reply (its id, parent, discussion and root) to stamp the reply's root. Lose: nothing a user held — every other update has `participants` and `thread_root_id` dropped before the write (reported in `droppedFields` on an ordinary update, dropped unreported under `preserveAudit`), except the engine's removal of a deleted user from `participants` (`referentialFieldClear`), and a create is stamped by the platform over any value the caller sends; the parent read serves only the stamp, never the caller | `installCommentParticipants` | | 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core, runtime | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for. Lose at the package duplicate door: the same admission asked for the caller, for each knowledge source the copy would save. Lose at the package move-in door: the same admission asked for the caller, for each selected knowledge source the move saves again under the package | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal`, `refuseDuplicatedKnowledgeSources`, `handlePackagesRequest` | | 46a | Knowledge search under the system identity is not ordered for the asker: a source's `affinity` entries move nothing | service-knowledge | Get: every hit in the order its store answered, and no read of a user or business unit. Lose: nothing a user held. The system identity is no person, so it has no unit to order by; every other caller's user id and unit chain are read as that caller may read them | `resolveAffinityFacts` | +| 46b | The knowledge term preview admits the system context without `manage_platform_settings` | service-knowledge | Get: `previewTerms` answers a question's terms and, for a named source, how many of its passages each term matches, counted over every passage of the source: the counts are NOT filtered by record permissions. Lose: nothing a user held. Every other caller must hold `manage_platform_settings`, or is refused (`PERMISSION_DENIED`) before the question or the source is read; the `preview_terms` action's handler hands it the caller's own capabilities, never the action door's elevation | `callerRefusal` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | @@ -720,6 +721,7 @@ and CI refuses one that differs from what the tree produces. | `packages/services/service-knowledge/src/knowledge-service-admission.ts#admitSources` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service-admission.ts#applyPermissionFilter` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service-search.ts#searchByKey` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-term-preview.ts#callerRefusal` | 1 | 46b | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b | | `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 | diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index aa2642dcb49..3ae85bbc0bf 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -653,6 +653,18 @@ 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. +An administrator keeps those words as records of `sys_search_term`: one at a +time, or many through the object's csv and xlsx import, and downloads them +through its csv and xlsx export; the file an export writes imports again with +a mapping that names its columns. The list's **Preview Terms** action answers +how one question is cut: the terms a search would match, the words dropped as +stop words, and, for a named knowledge source whose adapter implements the +optional `countKeywordMatches`, the passages of its active generation each +term matches with the operator the keyword search uses, beside the source's +passage total (ADR-0161, the second dated note of 2026-12-05 under K8). It +counts only what the adapter holds and reads no passage text; an adapter +without the member answers the terms uncounted. The cut comes from the +segmenter's optional `cut`, the same call the search's terms come from. `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 @@ -707,7 +719,10 @@ keeps generations, the switch at the end of a build; and, for an adapter that de `keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words; and, for an adapter that declares `embedQuery`, that a search handed a function answering its own `embedQuery` answers as without it and makes no embedding call of its own, and that one answering -a vector of another width is rejected. `implements` declares the optional members, and the suite +a vector of another width is rejected; and, for an adapter that declares `keywordCounts`, that +`countKeywordMatches` counts per term exactly the passages a keyword search of that one term +finds in the source, and that the term preview of a real service counts nothing for one that does +not. `implements` declares the optional members, and the suite checks the declaration against the adapter. `./testing` is a test-only, ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it. `knowledge-memory` runs it as the reference implementation; `knowledge-pgvector` 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 5b853cd2de6..04a0179004a 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 @@ -27,6 +27,7 @@ - **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. +- **Amended** (2026-12-05, [#38710](https://github.com/objectstack-ai/objectstack/issues/38710)): a twelfth dated note, under "Rules for every member" in [K8](#k8--the-contract-additions-decided-item-by-item), below the eleventh, registers one contract member, optional: `IKnowledgeAdapter.countKeywordMatches`, by which an adapter counts, for each term it is handed, the passages of a source's active generation its keyword leg matches, with its own operator, and the passages of that generation. It is read by the administrator's term preview of `sys_search_term`. It amends no row of [K1](#k1--the-boundary): how a term is matched stays the adapter's. Written on the seat's ruling F2 = A (amendment `7433690089` of claim `7433544945` on #38710), read from the card body's item 5 and ruling `7272241375`. The status line above is left as it is. --- @@ -519,6 +520,16 @@ Rules for every member: > > 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. +> **Note (2026-12-05, [#38710](https://github.com/objectstack-ai/objectstack/issues/38710), second) — one member, `IKnowledgeAdapter.countKeywordMatches`: an adapter counts, for each term it is handed, the passages its keyword leg matches, so an administrator sees how common a term of a question is.** The card's body, item 5, asks that an administrator can tune the search words: type a question and see its terms, the words dropped as stop words, and how many passages each term matches. On that item the seat ruled, in amendment `7433690089` of claim `7433544945` on #38710, for an optional counting member on the adapter, read from ruling `7272241375` 「这次就做」. Its reason, from the measurement report `7433667519`: a stop-word judgement needs how common a term is, and a capped search cannot tell 21 passages from 18,000. +> +> - **The member.** `countKeywordMatches?(ctx: AdapterContext, terms: readonly string[]): Promise`, on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`, answering `{ passages, matches }`: the passages of `ctx.source`'s active generation, the one `search` reads, and for each term, in the order handed, the passages of that generation the keyword leg matches for that term alone, by the operator its `search` matches the term with (in `knowledge-turso` the trigram index or `LIKE`; in `knowledge-pgvector` the `tsvector` or `LIKE` / `ILIKE`). One expression of the match serves the count and the search, so the two cannot drift. +> - **What it does not read.** No organization filter and no record scope: the preview is a deployment-level tool for the holder of `manage_platform_settings`, as the search words are one set per deployment. A count, never a passage's text. `ctx.index` is not compared: matching a word reads no vector. +> - **Not filtered by record permissions, so answered to the administrator alone.** A count reads every passage of the generation, whoever may read the record behind it. The knowledge service's preview (`KnowledgeService.previewTerms`) is the member's one reader, and it refuses, at the service and before it reads the question, every caller that is neither a system context nor holds `manage_platform_settings` (`403 PERMISSION_DENIED`); the action door's own `requiredPermissions` stands in front of it, and is not leaned on alone. No end-user door reads the member: not search, not `search_knowledge` on either MCP transport, not the knowledge settings actions. Written on the seat's note in the card's decision thread on 2026-12-05. +> - **Absent.** An adapter without a keyword leg, such as `knowledge-memory`, does not implement it, and the preview says the terms are not counted, never 0 (rule 2). +> - **Beside it, not in this record.** The words dropped as stop words come from the segmenter contract (`ISegmenterService.cut`, optional), which no row of K8 governs. +> +> This note registers exactly one member, `IKnowledgeAdapter.countKeywordMatches`, 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's term preview that reads it, and its case in the contract test suite (`packages/services/service-knowledge/src/testing.ts#runKnowledgeAdapterContract`) (rule 1): for an adapter that declares it, each term's count equals the passages its search under `keyword`, handed that term alone, answers, and the passage total is the source's own; an adapter without it is pinned through a real `KnowledgeService`, whose preview answers the terms uncounted. 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`). 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 92913848f34..8fc0de0e5ad 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -4854,6 +4854,38 @@ export const arObjects: NonNullable = { help: "سبب إضافة المصطلح، للمسؤول التالي." } }, + _actions: { + preview_terms: { + label: "معاينة المصطلحات", + params: { + question: { + label: "السؤال", + helpText: "سؤال كما يطرحه المستخدم، يُقسَّم كما يقسّمه البحث في المعرفة." + }, + knowledge_source: { + label: "مصدر المعرفة", + helpText: "NAMESPACE-NAME لمصدر الحزمة، وإلا فالاسم وحده. عند تحديده تُطبَّق مصطلحات البحث الخاصة به، وتُحصى فيه المقاطع التي يطابقها كل مصطلح." + } + }, + resultDialog: { + title: "مصطلحات السؤال", + acknowledge: "تم", + fields: { + source: "مصدر المعرفة", + terms: "المصطلحات", + stopWords: "محذوفة ككلمات توقف", + passages: "المقاطع في المصدر", + note: "ملاحظة" + }, + columns: { + terms: { + term: "المصطلح", + passages: "المقاطع المطابقة" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "لا يمكن أن يبدأ المصطلح أو ينتهي بمسافة." 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 74176857986..ae53b87ac62 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -4854,6 +4854,38 @@ export const deObjects: NonNullable = { help: "Warum der Begriff hinzugefügt wurde, für den nächsten Administrator." } }, + _actions: { + preview_terms: { + label: "Vorschau der Begriffe", + params: { + question: { + label: "Frage", + helpText: "Eine Frage, wie ein Benutzer sie stellen würde, zerlegt wie die Wissenssuche sie zerlegt." + }, + knowledge_source: { + label: "Wissensquelle", + helpText: "NAMESPACE-NAME für die Quelle eines Pakets, sonst der bloße Name. Angegeben, gelten ihre eigenen Suchbegriffe, und die Passagen jedes Begriffs werden dort gezählt." + } + }, + resultDialog: { + title: "Begriffe der Frage", + acknowledge: "Fertig", + fields: { + source: "Wissensquelle", + terms: "Begriffe", + stopWords: "Als Stoppwörter entfernt", + passages: "Passagen in der Quelle", + note: "Notiz" + }, + columns: { + terms: { + term: "Begriff", + passages: "Passende Passagen" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "Ein Begriff darf nicht mit einem Leerzeichen beginnen oder enden." 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 33ff2dc2ab0..f8285fc1e5c 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -4854,6 +4854,38 @@ export const enObjects: NonNullable = { help: "Why the term was added, for the next administrator." } }, + _actions: { + preview_terms: { + label: "Preview Terms", + params: { + question: { + label: "Question", + helpText: "A question as a user would ask it, cut the way knowledge search cuts it." + }, + knowledge_source: { + label: "Knowledge Source", + helpText: "NAMESPACE-NAME for a package's source, the bare name otherwise. Named, its own search terms apply and each term's passages are counted there." + } + }, + resultDialog: { + title: "Terms of the Question", + acknowledge: "Done", + fields: { + source: "Knowledge Source", + terms: "Terms", + stopWords: "Dropped as Stop Words", + passages: "Passages in the Source", + note: "Note" + }, + columns: { + terms: { + term: "Term", + passages: "Passages Matched" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "A term cannot start or end with a space." 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 edd5ea55aa0..60edd0c1e8c 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 @@ -4854,6 +4854,38 @@ export const esESObjects: NonNullable = { help: "Por qué se añadió el término, para el próximo administrador." } }, + _actions: { + preview_terms: { + label: "Vista previa de términos", + params: { + question: { + label: "Pregunta", + helpText: "Una pregunta tal como la haría un usuario, dividida como la divide la búsqueda de conocimiento." + }, + knowledge_source: { + label: "Fuente de conocimiento", + helpText: "NAMESPACE-NAME para la fuente de un paquete; si no, el nombre sin más. Si se indica, se aplican sus propios términos de búsqueda y se cuentan allí los pasajes de cada término." + } + }, + resultDialog: { + title: "Términos de la pregunta", + acknowledge: "Hecho", + fields: { + source: "Fuente de conocimiento", + terms: "Términos", + stopWords: "Descartadas como palabras vacías", + passages: "Pasajes en la fuente", + note: "Nota" + }, + columns: { + terms: { + term: "Término", + passages: "Pasajes coincidentes" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "Un término no puede empezar ni terminar con un espacio." 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 e4d372a04be..2f181b4c1c4 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -4854,6 +4854,38 @@ export const frObjects: NonNullable = { help: "Pourquoi le terme a été ajouté, pour le prochain administrateur." } }, + _actions: { + preview_terms: { + label: "Aperçu des termes", + params: { + question: { + label: "Question", + helpText: "Une question telle qu'un utilisateur la poserait, découpée comme la recherche de connaissances la découpe." + }, + knowledge_source: { + label: "Source de connaissances", + helpText: "NAMESPACE-NAME pour la source d'un paquet, le nom seul sinon. Indiquée, ses propres termes de recherche s'appliquent et les passages de chaque terme y sont comptés." + } + }, + resultDialog: { + title: "Termes de la question", + acknowledge: "Terminé", + fields: { + source: "Source de connaissances", + terms: "Termes", + stopWords: "Retirés comme mots vides", + passages: "Passages dans la source", + note: "Note" + }, + columns: { + terms: { + term: "Terme", + passages: "Passages trouvés" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "Un terme ne peut pas commencer ni se terminer par une espace." diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index c2a88f7065e..e0c49a81257 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -321,6 +321,8 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_scim_projection_grant.fields.id.label": "00b0385c9c152888", "objects.sys_scim_subject.fields.id.label": "00b0385c9c152888", "objects.sys_scim_user.fields.id.label": "00b0385c9c152888", + "objects.sys_search_term._actions.preview_terms.params.question.label": "abb43d0d67cd24ef", + "objects.sys_search_term._actions.preview_terms.resultDialog.fields.note": "f78f61778f71bf68", "objects.sys_search_term.fields.id.label": "00b0385c9c152888", "objects.sys_search_term.fields.note.label": "f78f61778f71bf68", "objects.sys_secret.fields.id.label": "00b0385c9c152888", 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 9292f05695c..219be9caa57 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 @@ -4854,6 +4854,38 @@ export const jaJPObjects: NonNullable = { help: "この語を追加した理由(次の管理者のために)。" } }, + _actions: { + preview_terms: { + label: "語の分割をプレビュー", + params: { + question: { + label: "質問", + helpText: "ユーザーが尋ねるとおりに質問を入力すると、ナレッジ検索と同じ方法で分割します。" + }, + knowledge_source: { + label: "ナレッジソース", + helpText: "パッケージのソースは NAMESPACE-NAME、それ以外は名前のみ。指定すると、そのソース独自の検索語が適用され、各語に一致するパッセージ数がそこで数えられます。" + } + }, + resultDialog: { + title: "質問の分割結果", + acknowledge: "完了", + fields: { + source: "ナレッジソース", + terms: "検索語", + stopWords: "ストップワードとして除外", + passages: "ソース内のパッセージ数", + note: "メモ" + }, + columns: { + terms: { + term: "語", + passages: "一致したパッセージ数" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "語の先頭と末尾にスペースは使えません。" 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 f38ca8ffd63..611d86a1065 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -4854,6 +4854,38 @@ export const koObjects: NonNullable = { help: "이 단어를 추가한 이유(다음 관리자를 위해)." } }, + _actions: { + preview_terms: { + label: "단어 분할 미리 보기", + params: { + question: { + label: "질문", + helpText: "사용자가 묻는 그대로 질문을 입력하면 지식 검색과 같은 방식으로 나눕니다." + }, + knowledge_source: { + label: "지식 소스", + helpText: "패키지의 소스는 NAMESPACE-NAME, 그 외에는 이름만 씁니다. 지정하면 그 소스의 검색어가 적용되고 각 단어가 일치하는 구절 수를 그 소스에서 셉니다." + } + }, + resultDialog: { + title: "질문의 분할 결과", + acknowledge: "완료", + fields: { + source: "지식 소스", + terms: "검색어", + stopWords: "불용어로 제외됨", + passages: "소스의 구절 수", + note: "메모" + }, + columns: { + terms: { + term: "단어", + passages: "일치한 구절 수" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "단어의 앞뒤에 공백을 둘 수 없습니다." 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 0e69623cda7..9e80413f61e 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 @@ -4854,6 +4854,38 @@ export const ptBRObjects: NonNullable = { help: "Por que o termo foi adicionado, para o próximo administrador." } }, + _actions: { + preview_terms: { + label: "Pré-visualizar termos", + params: { + question: { + label: "Pergunta", + helpText: "Uma pergunta como um usuário a faria, dividida como a pesquisa de conhecimento a divide." + }, + knowledge_source: { + label: "Fonte de conhecimento", + helpText: "NAMESPACE-NAME para a fonte de um pacote; caso contrário, o nome simples. Informada, seus próprios termos de pesquisa se aplicam e os trechos de cada termo são contados nela." + } + }, + resultDialog: { + title: "Termos da pergunta", + acknowledge: "Concluído", + fields: { + source: "Fonte de conhecimento", + terms: "Termos", + stopWords: "Removidas como palavras vazias", + passages: "Trechos na fonte", + note: "Observação" + }, + columns: { + terms: { + term: "Termo", + passages: "Trechos encontrados" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "Um termo não pode começar nem terminar com um espaç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 c2854b90a46..a76bcd893f8 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -4854,6 +4854,38 @@ export const ruObjects: NonNullable = { help: "Почему термин был добавлен, для следующего администратора." } }, + _actions: { + preview_terms: { + label: "Предпросмотр терминов", + params: { + question: { + label: "Вопрос", + helpText: "Вопрос в том виде, в каком его задаст пользователь; он разбивается так же, как при поиске по знаниям." + }, + knowledge_source: { + label: "Источник знаний", + helpText: "NAMESPACE-NAME для источника пакета, иначе просто имя. Если указан, применяются его собственные поисковые термины, и фрагменты каждого термина считаются в нём." + } + }, + resultDialog: { + title: "Термины вопроса", + acknowledge: "Готово", + fields: { + source: "Источник знаний", + terms: "Термины", + stopWords: "Отброшены как стоп-слова", + passages: "Фрагментов в источнике", + note: "Примечание" + }, + columns: { + terms: { + term: "Термин", + passages: "Совпавших фрагментов" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "Термин не может начинаться или заканчиваться пробелом." 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 8017816f52c..2b0670cf436 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 @@ -4854,6 +4854,38 @@ export const zhCNObjects: NonNullable = { help: "添加该词条的原因,留给下一位管理员。" } }, + _actions: { + preview_terms: { + label: "预览切词", + params: { + question: { + label: "问题", + helpText: "按用户的问法输入一个问题,按知识检索的方式切词。" + }, + knowledge_source: { + label: "知识源", + helpText: "包内知识源为 NAMESPACE-NAME,否则为裸名称。填写后,该知识源自己的词条生效,并在其中统计每个词命中的段落数。" + } + }, + resultDialog: { + title: "问题的切词", + acknowledge: "完成", + fields: { + source: "知识源", + terms: "检索词", + stopWords: "作为停用词去掉", + passages: "知识源中的段落数", + note: "备注" + }, + columns: { + terms: { + term: "词", + passages: "命中段落数" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "词条首尾不能有空格。" 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 ee6fc29a851..17b8918d1b2 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 @@ -4854,6 +4854,38 @@ export const zhHantObjects: NonNullable = { help: "新增該詞條的原因,留給下一位管理員。" } }, + _actions: { + preview_terms: { + label: "預覽切詞", + params: { + question: { + label: "問題", + helpText: "依使用者的問法輸入一個問題,按知識檢索的方式切詞。" + }, + knowledge_source: { + label: "知識來源", + helpText: "套件內的知識來源為 NAMESPACE-NAME,否則為裸名稱。填寫後,該知識來源自己的詞條生效,並在其中統計每個詞命中的段落數。" + } + }, + resultDialog: { + title: "問題的切詞", + acknowledge: "完成", + fields: { + source: "知識來源", + terms: "檢索詞", + stopWords: "作為停用詞去掉", + passages: "知識來源中的段落數", + note: "備註" + }, + columns: { + terms: { + term: "詞", + passages: "命中段落數" + } + } + } + } + }, _validations: { search_term_no_edge_space: { message: "詞條首尾不能有空格。" 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 c81ce4baee4..d0bc6f4655a 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 @@ -116,3 +116,33 @@ describe('sys_search_term — declaration', () => { }); }); }); + +describe('sys_search_term — Preview Terms, the administrator\'s split preview', () => { + const action = (SysSearchTerm.actions ?? []).find((a: any) => a.name === 'preview_terms') as Record | undefined; + + it('is a list-toolbar script action, gated at the action door on the capability that guards the object', () => { + expect(action).toBeDefined(); + expect(action).toMatchObject({ + type: 'script', + target: 'preview_terms', + locations: ['list'], + requiredPermissions: ['manage_platform_settings'], + }); + // Read-only: it writes no record, so nothing is refreshed and no AI tool is exposed. + expect(action!.refreshAfter).toBeFalsy(); + expect(action!.ai).toBeUndefined(); + }); + + it('asks the question, and optionally one knowledge source, as dialog params', () => { + const params = action!.params as Array>; + expect(params.map((p) => [p.name, p.required === true])).toEqual([['question', true], ['knowledge_source', false]]); + }); + + it('draws the terms as a table with their passage counts, and the dropped stop words as a list', () => { + const fields = action!.resultDialog.fields as Array>; + const terms = fields.find((f) => f.path === 'terms'); + expect(terms).toMatchObject({ format: 'table' }); + expect(terms!.columns.map((c: any) => c.path)).toEqual(['term', 'passages']); + expect(fields.find((f) => f.path === 'stopWords')).toMatchObject({ format: 'code-list' }); + }); +}); 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 144d0285d55..00d9d3f7d71 100644 --- a/packages/platform-objects/src/system/sys-search-term.object.ts +++ b/packages/platform-objects/src/system/sys-search-term.object.ts @@ -210,6 +210,63 @@ export const SysSearchTerm = ObjectSchema.create({ }, ], + actions: [ + { + // [#38710 step 3] The administrator's split preview: a question's terms, + // cut by the one cut search makes, the stop words dropped, and the + // passages each term matches in a named source. The handler is the + // knowledge service's (`knowledge-term-preview.ts`), registered under + // `target` by its plugin; it reads and writes nothing. The door enforces + // `requiredPermissions` (ADR-0066 D4). Human-only: no `ai` block. + name: 'preview_terms', + label: 'Preview Terms', + icon: 'search', + variant: 'secondary', + locations: ['list'], + type: 'script', + target: 'preview_terms', + requiredPermissions: ['manage_platform_settings'], + params: [ + { + name: 'question', + type: 'textarea', + label: 'Question', + required: true, + helpText: 'A question as a user would ask it, cut the way knowledge search cuts it.', + }, + { + name: 'knowledge_source', + type: 'text', + label: 'Knowledge Source', + required: false, + helpText: + "NAMESPACE-NAME for a package's source, the bare name otherwise. Named, its own search terms apply and each term's passages are counted there.", + }, + ], + resultDialog: { + title: 'Terms of the Question', + acknowledge: 'Done', + // A field the answer leaves out (no source named, nothing counted, no + // stop word reported) is skipped; `note` says why. + fields: [ + { path: 'source', label: 'Knowledge Source', format: 'text' }, + { + path: 'terms', + label: 'Terms', + format: 'table', + columns: [ + { path: 'term', label: 'Term' }, + { path: 'passages', label: 'Passages Matched', format: 'text' }, + ], + }, + { path: 'stopWords', label: 'Dropped as Stop Words', format: 'code-list' }, + { path: 'passages', label: 'Passages in the Source', format: 'text' }, + { path: 'note', label: 'Note', format: 'text' }, + ], + }, + }, + ], + enable: { trackHistory: true, searchable: false, diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts index fe94f59c438..023c0efc0ea 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -32,6 +32,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { keywordLeg: true, retrieval: true, embedQuery: true, + keywordCounts: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/keyword-counts.ts b/packages/plugins/knowledge-pgvector/src/keyword-counts.ts new file mode 100644 index 00000000000..fd9aca94b64 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/keyword-counts.ts @@ -0,0 +1,56 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The keyword leg's match of one term, and the statement that counts it + * (`IKnowledgeAdapter.countKeywordMatches`; ADR-0161, the second dated note of + * 2026-12-05 under K8). One expression serves the search's keyword leg + * (`PgvectorKnowledgeAdapter.search`) and the count, so the count an + * administrator reads is exactly what a search matches: a word of three + * characters or more the `simple` parser splits, on the passage's `tsvector` + * (its GIN index serves it); any other term as a substring, by `LIKE` or + * `ILIKE` ({@link containsOperator}). + */ + +import type { AdapterKeywordCounts } from '@objectstack/spec/contracts'; +import { PASSAGE_TSVECTOR, TS_CONFIG, containsOperator, containsPattern, isWordTerm } from './sql.js'; + +/** + * The match of `term`, its value bound by appending it to `params` (`$N`): + * `onRow` on a passage row's columns, where the index can serve it, and + * `onCandidate` on a candidate `c` whose `tsvector` was computed once as `v.tsv`. + */ +export function keywordTermMatch(term: string, params: unknown[]): { onRow: string; onCandidate: string } { + if (isWordTerm(term)) { + params.push(term); + const query = `phraseto_tsquery(${TS_CONFIG}, $${params.length}::text)`; + return { onRow: `${PASSAGE_TSVECTOR} @@ ${query}`, onCandidate: `v.tsv @@ ${query}` }; + } + params.push(containsPattern(term)); + const op = containsOperator(term); + return { onRow: `content ${op} $${params.length}::text`, onCandidate: `c.content ${op} $${params.length}::text` }; +} + +/** + * One statement, one row: the passages of one generation of one source in + * `table` (`n`) and, per term, those its match holds for (`d0`, `d1`, …), each + * its own subquery so the keyword index serves a word. + */ +export function keywordCountStatement( + table: string, + sourceId: string, + generation: number, + terms: readonly string[], +): { text: string; params: unknown[] } { + const params: unknown[] = [sourceId, generation]; + const of = `FROM ${table} WHERE source_id = $1 AND generation = $2`; + const counts = terms.map((term, i) => `(SELECT count(*) ${of} AND ${keywordTermMatch(term, params).onRow}) AS d${i}`); + return { text: `SELECT ${[`(SELECT count(*) ${of}) AS n`, ...counts].join(', ')}`, params }; +} + +/** The answer of {@link keywordCountStatement}'s row; PostgreSQL answers a `count` as text. */ +export function readKeywordCounts(row: Record | undefined, terms: number): AdapterKeywordCounts { + return { + passages: Number(row?.n ?? 0), + matches: Array.from({ length: terms }, (_, i) => Number(row?.[`d${i}`] ?? 0)), + }; +} diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 341647312a0..dfc682dc868 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -5,6 +5,7 @@ import type { AdapterContext, AdapterEmbeddingDescriptor, AdapterIndexStatus, + AdapterKeywordCounts, AdapterListDocumentsOptions, AdapterListDocumentsPage, AdapterSearchOptions, @@ -18,10 +19,6 @@ import { type GenerationState, PASSAGE_TSVECTOR, SAFE_IDENTIFIER, - TS_CONFIG, - containsOperator, - containsPattern, - isWordTerm, keywordIndexDdl, keywordIndexName, metadataIndexDdl, @@ -34,6 +31,7 @@ import { vectorTableDdl, } from './sql.js'; import { keywordTerms } from '@objectstack/core'; +import { keywordCountStatement, keywordTermMatch, readKeywordCounts } from './keyword-counts.js'; import { searchRefusalOf } from './errors.js'; /** One answer of a query: its rows. */ @@ -762,18 +760,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { // can serve it, and on the candidate's tsvector, computed once per row. const onRow: string[] = []; const onCandidate: string[] = []; + // One expression with the count (`keyword-counts.ts`), so the administrator's preview counts what this matches. for (const term of terms) { - if (isWordTerm(term)) { - params.push(term); - const query = `phraseto_tsquery(${TS_CONFIG}, $${params.length}::text)`; - onRow.push(`${PASSAGE_TSVECTOR} @@ ${query}`); - onCandidate.push(`v.tsv @@ ${query}`); - } else { - params.push(containsPattern(term)); - const op = containsOperator(term); - onRow.push(`content ${op} $${params.length}::text`); - onCandidate.push(`c.content ${op} $${params.length}::text`); - } + const match = keywordTermMatch(term, params); + onRow.push(match.onRow); + onCandidate.push(match.onCandidate); } // Each term's IDF is computed once per search, in `idf`, and a candidate's // score multiplies its hits by those weights: written per row, the 16 @@ -841,6 +832,25 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { })); } + /** + * Each term's passages in the source's active generation, matched as the + * keyword leg of {@link search} matches it, and the generation's passages + * (ADR-0161, the second dated note of 2026-12-05 under K8; + * `keyword-counts.ts`), under the store's time limit. A source with no + * active generation counts 0. + */ + async countKeywordMatches(ctx: AdapterContext, terms: readonly string[]): Promise { + this.requirePool(); + await this.ready(); + const { active: generation } = await this.generations(ctx.source.name); + if (!generation || !(await this.tableExists(generation.dim))) return readKeywordCounts(undefined, terms.length); + if (terms.length > 0) await this.ensureKeywordIndex(generation.dim); + const table = qualified(this.schema, vectorTable(generation.dim)); + const { text, params } = keywordCountStatement(table, ctx.source.name, generation.generation, terms); + const result = await this.searchStatement>(text, params); + return readKeywordCounts(result.rows[0], terms.length); + } + async indexStatus(ctx: AdapterContext): Promise { this.requirePool(); await this.ready(); diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts index 81e73a20bf7..13de7cbb99f 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -30,6 +30,7 @@ for (const kind of ['memory', 'file'] as const) { keywordLeg: true, retrieval: true, embedQuery: true, + keywordCounts: true, }, }); }); diff --git a/packages/plugins/knowledge-turso/src/keyword-counts.ts b/packages/plugins/knowledge-turso/src/keyword-counts.ts new file mode 100644 index 00000000000..a1d76bf8210 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/keyword-counts.ts @@ -0,0 +1,46 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The keyword leg's match of one term, and the statement that counts it + * (`IKnowledgeAdapter.countKeywordMatches`; ADR-0161, the second dated note of + * 2026-12-05 under K8). One expression serves the search's keyword leg + * (`TursoKnowledgeAdapter.search`) and the count, so the count an + * administrator reads is exactly what a search matches: a term of three + * characters or more on the trigram index, a shorter one by `LIKE` over the + * passage's text. + */ + +import type { InArgs, InStatement, Row } from '@libsql/client'; +import type { AdapterKeywordCounts } from '@objectstack/spec/contracts'; +import { TRIGRAM_MIN_CHARS, containsPattern, ftsPhrase, keywordNames, quoted } from './sql.js'; + +/** + * The match of `term` on a row of the passage table `table`, its value bound + * by appending it to `args` (`?N`, numbered after the values already there). + */ +export function keywordMatchSql(table: string, term: string, args: unknown[]): string { + if ([...term].length >= TRIGRAM_MIN_CHARS) { + const { map, fts } = keywordNames(table); + args.push(ftsPhrase(term)); + return `(chunk_id IN (SELECT k.chunk_id FROM ${quoted(fts)} JOIN ${quoted(map)} k ON k.id = ${quoted(fts)}.rowid + WHERE ${quoted(fts)} MATCH ?${args.length}))`; + } + args.push(containsPattern(term)); + return `(content LIKE ?${args.length} ESCAPE '\\')`; +} + +/** One statement, one row: the passages of `table` (`n`) and, per term, the passages its match holds for (`d0`, `d1`, …). */ +export function keywordCountStatement(table: string, terms: readonly string[]): InStatement { + const args: unknown[] = []; + const t = quoted(table); + const counts = terms.map((term, i) => `(SELECT count(*) FROM ${t} WHERE ${keywordMatchSql(table, term, args)}) AS d${i}`); + return { sql: `SELECT ${[`(SELECT count(*) FROM ${t}) AS n`, ...counts].join(', ')}`, args: args as InArgs }; +} + +/** The answer of {@link keywordCountStatement}'s row. */ +export function readKeywordCounts(row: Row | undefined, terms: number): AdapterKeywordCounts { + return { + passages: Number(row?.n ?? 0), + matches: Array.from({ length: terms }, (_, i) => Number(row?.[`d${i}`] ?? 0)), + }; +} diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 3bbebc06eca..7abf05bbcc0 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -6,6 +6,7 @@ import type { AdapterContext, AdapterEmbeddingDescriptor, AdapterIndexStatus, + AdapterKeywordCounts, AdapterListDocumentsOptions, AdapterListDocumentsPage, AdapterSearchOptions, @@ -17,15 +18,12 @@ import { GENERATION_TABLE, METADATA_VALUE_JSON, SCOPE_SCALAR_TYPES, - TRIGRAM_MIN_CHARS, type KeywordIndexShape, type TableShape, type VectorIndexShape, tableShape, assertSourceId, - containsPattern, dropKeywordIndexDdl, - ftsPhrase, generationDdl, generationTable, keywordIndexDdl, @@ -44,6 +42,7 @@ import { vectorLiteral, } from './sql.js'; import { keywordTerms } from '@objectstack/core'; +import { keywordCountStatement, keywordMatchSql, readKeywordCounts } from './keyword-counts.js'; import { onClientQueue, type QueueSide } from './reader-writer-queue.js'; import { timedClient, timedQueueEntry, timedSearch } from './search-timing.js'; @@ -854,17 +853,9 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { if (vectorLeg) legs.push('SELECT chunk_id, pos AS vpos, NULL AS kpos FROM vec'); if (terms.length > 0) { // A term's match: the trigram index for three characters or more, LIKE - // over the rows in scope below that. - const { map, fts } = keywordNames(tableName); - const matches = terms.map((term) => { - if ([...term].length >= TRIGRAM_MIN_CHARS) { - args.push(ftsPhrase(term)); - return `(chunk_id IN (SELECT k.chunk_id FROM ${quoted(fts)} JOIN ${quoted(map)} k ON k.id = ${quoted(fts)}.rowid - WHERE ${quoted(fts)} MATCH ?${args.length}))`; - } - args.push(containsPattern(term)); - return `(content LIKE ?${args.length} ESCAPE '\\')`; - }); + // over the rows in scope below that. One expression with the count + // (`keyword-counts.ts`), so the administrator's preview counts what this matches. + const matches = terms.map((term) => keywordMatchSql(tableName, term, args)); const idf = matches .map((_, i) => `h${i} * ln(1.0 + (stats.n - stats.d${i} + 0.5) / (stats.d${i} + 0.5))`) .join(' + '); @@ -1016,6 +1007,35 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { return status; } + /** + * Each term's passages in the source's active generation, matched as the + * keyword leg of {@link search} matches it, and the generation's passages + * (ADR-0161, the second dated note of 2026-12-05 under K8; + * `keyword-counts.ts`). A source with no generation counts 0; one that holds + * only a table of before generations is refused as {@link search} refuses it. + */ + async countKeywordMatches(ctx: AdapterContext, terms: readonly string[]): Promise { + const client = this.requireClient(); + assertSourceId(ctx.source.name); + await this.ready(); + const { active, building } = await this.queued(client, 'shared', () => this.generations(ctx.source.name)); + if (!active) { + if (await this.queued(client, 'shared', () => this.hasLegacy(ctx.source.name))) { + throw rebuildRequired(ctx.source.name, building !== undefined); + } + return readKeywordCounts(undefined, terms.length); + } + const tableName = generationTable(ctx.source.name, active.generation); + if (terms.length > 0 && !this.keyed.has(tableName)) { + await this.queued(client, 'exclusive', async () => { + const now = await this.generations(ctx.source.name); + if (now.active?.generation === active.generation) await this.ensureKeywordIndex(tableName); + }); + } + const answered = await this.queued(client, 'shared', () => client.execute(keywordCountStatement(tableName, terms))); + return readKeywordCounts(answered.rows[0], terms.length); + } + async beginBuild(ctx: AdapterContext): Promise { const index = requireIndex(ctx, 'beginBuild'); const client = this.requireClient(); diff --git a/packages/rest/src/import-search-term-csv.test.ts b/packages/rest/src/import-search-term-csv.test.ts index 20557816ea6..355bbaa6e7d 100644 --- a/packages/rest/src/import-search-term-csv.test.ts +++ b/packages/rest/src/import-search-term-csv.test.ts @@ -17,6 +17,11 @@ * lines of the same file land; * - a caller with a full CRUD grant but without the capability gets a job * whose every row is refused `PERMISSION_DENIED`, and no record lands. + * + * And the export half (step 3): the generic export door writes the store as + * csv and as xlsx with the same rows, an xlsx export goes back through the + * async door into an empty store record for record, and a caller without the + * capability gets a 403 and no file. */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; @@ -28,6 +33,7 @@ import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObje import { SysImportJob } from '@objectstack/platform-objects/audit'; import { SysSearchTerm } from '@objectstack/platform-objects/system'; import { RestServer } from './rest-server'; +import { loadXlsxWorkbook } from './xlsx-test-loader.js'; import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; const OBJECT = 'sys_search_term'; @@ -133,16 +139,21 @@ async function boot() { create: find('POST', '/api/v1/data/:object/import/jobs'), progress: find('GET', '/api/v1/data/import/jobs/:jobId'), results: find('GET', '/api/v1/data/import/jobs/:jobId/results'), + exportFile: find('GET', '/api/v1/data/:object/export'), }; } type Booted = Awaited>; /** POST the CSV to the async door as `as`, and wait for the job's terminal state. */ -async function importCsv(ctx: Booted, as: Record, csv: string): Promise<{ job: any; results: any[] }> { +const importCsv = (ctx: Booted, as: Record, csv: string) => + importFile(ctx, as, { format: 'csv', csv }); + +/** POST a file body to the async door as `as`, and wait for the job's terminal state. */ +async function importFile(ctx: Booted, as: Record, body: Record): Promise<{ job: any; results: any[] }> { ctx.session.caller = as; const res = makeRes(); - await ctx.create.handler({ params: { object: OBJECT }, body: { format: 'csv', csv } } as any, res); + await ctx.create.handler({ params: { object: OBJECT }, body } as any, res); expect(res._status).toBe(201); const jobId = res._json.jobId; for (let i = 0; i < 200; i++) { @@ -213,3 +224,146 @@ describe('sys_search_term — CSV through the generic async import door, behind expect(await terms(ctx)).toEqual([]); }); }); + +/** A response that keeps the bytes a file door streams. */ +function makeFileRes() { + const chunks: Buffer[] = []; + const res: any = { + write: (c: any) => { chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(String(c))); return true; }, + end: () => {}, + header: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return { res, buffer: () => Buffer.concat(chunks) }; +} + +/** GET the object's export in `format` as `as`. */ +async function exportAs(ctx: Booted, as: Record, format: 'csv' | 'xlsx') { + ctx.session.caller = as; + const out = makeFileRes(); + await ctx.exportFile.handler({ params: { object: OBJECT }, query: { format }, headers: {} } as any, out.res); + return { status: out.res._status as number | undefined, json: out.res._json, buffer: out.buffer() }; +} + +/** The rows of a csv export, past its byte-order mark. */ +const csvRows = (buffer: Buffer): string[][] => + buffer.toString('utf8').replace(/^/, '').split('\r\n').filter((l) => l.length > 0).map((l) => l.split(',')); + +/** The rows of an xlsx export's first sheet, as text. */ +async function xlsxRows(buffer: Buffer): Promise { + const ws = (await loadXlsxWorkbook(buffer)).worksheets[0]; + const out: string[][] = []; + ws.eachRow((row) => { + out.push(Array.from((row.values as unknown[]).slice(1), (v) => (v == null ? '' : String(v)))); + }); + return out; +} + +/** The export's header labels for the fields an administrator writes, and the field each names. */ +const AUTHORED_COLUMNS: Record = { + 'Term': 'term', + 'Kind': 'kind', + 'Purpose': 'purpose', + 'Knowledge Source': 'knowledge_source', + 'Enabled': 'enabled', + 'Note': 'note', +}; + +/** + * Every header the export writes, and the field each names, its system columns + * included: the door renames the headers a mapping names and passes any other + * through as a field name, so a column left out of it is refused INVALID_FIELD. + */ +const EXPORT_COLUMNS: Record = { + 'Created At': 'created_at', + 'Created By': 'created_by', + 'Last Modified At': 'updated_at', + 'Last Modified By': 'updated_by', + 'ID': 'id', + 'Term Key': 'term_key', + ...AUTHORED_COLUMNS, +}; + +/** Three terms covering both kinds, a scoped term, a disabled stop word and a note. */ +const SEED_CSV = [ + 'term,kind,purpose,knowledge_source,enabled,note', + '明规条款,word,knowledge,,true,制度标题', + '是否,stop_word,knowledge,,false,撤回平台停用词', + 'OA审批,word,both,hr_policies,true,', +].join('\n'); + +/** The authored columns of an export's rows, keyed by header, sorted by term. */ +function authoredRows(rows: string[][]): Array> { + const [header, ...body] = rows; + const columns = Object.keys(AUTHORED_COLUMNS).map((label): [string, number] => [label, header.indexOf(label)]); + const out: Array> = []; + for (const cells of body) { + const row: Record = {}; + for (const [label, at] of columns) row[label] = cells[at] ?? ''; + out.push(row); + } + return out.sort((a, b) => a.Term.localeCompare(b.Term)); +} + +const EXPORTED = [ + { 'Term': 'OA审批', 'Kind': 'Custom Word', 'Purpose': 'Both', 'Knowledge Source': 'hr_policies', 'Enabled': 'yes', 'Note': '' }, + { 'Term': '明规条款', 'Kind': 'Custom Word', 'Purpose': 'Knowledge Retrieval', 'Knowledge Source': '', 'Enabled': 'yes', 'Note': '制度标题' }, + { 'Term': '是否', 'Kind': 'Stop Word', 'Purpose': 'Knowledge Retrieval', 'Knowledge Source': '', 'Enabled': 'no', 'Note': '撤回平台停用词' }, +].sort((a, b) => a.Term.localeCompare(b.Term)); + +/** Every stored term with every authored field, read as the system. */ +const authored = async (ctx: Booted) => + ((await ctx.engine.find(OBJECT, { context: SYS_CTX } as never)) as Array>) + .map((r) => ({ + id: r.id, term: r.term, kind: r.kind, purpose: r.purpose, knowledge_source: r.knowledge_source ?? null, + enabled: Boolean(r.enabled), note: r.note ?? null, organization_id: r.organization_id, + })) + .sort((a, b) => String(a.term).localeCompare(String(b.term))); + +/** + * The other half of the card's "import and export of entries": the generic + * export door (`GET /data/sys_search_term/export`) writes the store as csv and + * as xlsx, and the xlsx a caller downloads goes back through the same async + * import door the csv does, record for record. The export reads under the + * caller's own context, so the capability that guards every other operation + * on the object guards it too. + */ +describe('sys_search_term — csv and xlsx export, and an xlsx back through the async import door', () => { + let ctx: Booted; + beforeEach(async () => { + ctx = await boot(); + expect((await importCsv(ctx, ADMIN, SEED_CSV)).job).toMatchObject({ status: 'succeeded', created: 3, errors: 0 }); + }); + + it('exports every term as csv and as xlsx to a caller holding manage_platform_settings, the same rows in both', async () => { + const csv = await exportAs(ctx, ADMIN, 'csv'); + expect(csv.status).toBeUndefined(); + expect(authoredRows(csvRows(csv.buffer))).toEqual(EXPORTED); + + const xlsx = await exportAs(ctx, ADMIN, 'xlsx'); + expect(xlsx.status).toBeUndefined(); + expect(authoredRows(await xlsxRows(xlsx.buffer))).toEqual(EXPORTED); + }); + + it('re-imports its own xlsx export into an empty store, every authored field and id as it was', async () => { + const before = await authored(ctx); + const xlsxBase64 = (await exportAs(ctx, ADMIN, 'xlsx')).buffer.toString('base64'); + + const target = await boot(); + const { job, results } = await importFile(target, ADMIN, { format: 'xlsx', xlsxBase64, mapping: EXPORT_COLUMNS }); + expect(job).toMatchObject({ status: 'succeeded', total: 3, created: 3, errors: 0 }); + for (const row of results) expect(row).toMatchObject({ ok: true, action: 'created' }); + expect(await authored(target)).toEqual(before); + expect(before.map((t) => t.organization_id)).toEqual([undefined, undefined, undefined]); + }); + + it('refuses the export to a caller without the capability, whatever its grant, and writes no file', async () => { + for (const format of ['csv', 'xlsx'] as const) { + const out = await exportAs(ctx, MEMBER, format); + expect(out.status).toBe(403); + expect(out.json).toMatchObject({ code: 'PERMISSION_DENIED' }); + expect(out.buffer.length).toBe(0); + } + }); +}); 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 f503c407c7f..a7ac7cea6c5 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 @@ -31,8 +31,14 @@ import { SEARCH_TERMS_TTL_MS, bindSearchTermHooks, } from '../knowledge-search-terms.js'; +import { SEARCH_TERM_PREVIEW_ACTION, registerTermPreviewAction, termPreviewActionHandler } from '../knowledge-term-preview.js'; +import { keywordTerms } from '@objectstack/core'; +import { SysSearchTerm } from '@objectstack/platform-objects/system'; const SYSTEM = { positions: [], permissions: [], isSystem: true }; +/** The preview's caller: an administrator holds `manage_platform_settings`; a member holds none. */ +const ADMIN = { userId: 'u_admin', positions: [], permissions: [], systemPermissions: ['manage_platform_settings'], isSystem: false }; +const MEMBER = { userId: 'u_member', positions: [], permissions: [], systemPermissions: [], isSystem: false }; const OBJECT = 'sys_search_term'; const QUESTION = '我在集团干了 12 年了,一年有几天年假?'; const WINDOWS = ['我在集', '在集团', '集团干', '团干了', '一年有', '年有几', '有几天', '几天年', '天年假']; @@ -245,3 +251,134 @@ describe('knowledge search terms across replicas', () => { }); }); }); + +describe('the term preview (Setup → Search Terms → Preview Terms): the one cut search makes, its stop words, and the passages each term matches', () => { + let st: Stack; + beforeEach(async () => { + st = await stack(); + }); + + /** A replica whose adapter counts, recording what it is handed. */ + function counting(sources: KnowledgeSource[], answer: (terms: readonly string[]) => Promise<{ passages: number; matches: number[] }>) { + const one = replica(st, sources); + const asked: Array<{ ctx: unknown; terms: readonly string[] }> = []; + one.rec.adapter.countKeywordMatches = vi.fn(async (ctx, terms) => { + asked.push({ ctx, terms }); + return answer(terms); + }); + bindSearchTermHooks(st.engine as never, one.svc); + return { ...one, asked }; + } + + it('shows the terms search hands the adapter, the stop words dropped, and each term counted in the source named', async () => { + const one = counting([source('handbook'), source('contracts')], async (terms) => ({ passages: 120, matches: terms.map((_, i) => i * 10) })); + await write(st, { term: '集团', kind: 'stop_word', knowledge_source: 'handbook' }); + await write(st, { term: '几天年假', kind: 'word' }); + + const preview = await one.svc.previewTerms(QUESTION, { source: 'handbook', executionContext: ADMIN }); + const searched = await one.terms(QUESTION, 'handbook'); + expect(preview.cutBy).toBe('segmenter'); + expect(preview.source).toBe('handbook'); + expect(preview.terms.map((t) => t.term)).toEqual(searched); + expect(preview.stopWords).toEqual(expect.arrayContaining(['我', '集团'])); + expect(preview.stopWords).not.toContain('几天年假'); + // Counted by the source's own adapter, handed exactly the cut, with the source as the service hands it. + expect(one.asked).toHaveLength(1); + expect(one.asked[0]!.terms).toEqual(searched); + expect(one.asked[0]!.ctx).toMatchObject({ source: { name: 'handbook' }, index: { fingerprint: expect.any(String) } }); + expect(preview.passages).toBe(120); + expect(preview.terms.map((t) => t.passages)).toEqual(searched!.map((_, i) => i * 10)); + // The declared dialog reads exactly these keys: a renamed key would draw an empty dialog. + const dialog = (SysSearchTerm.actions ?? []).find((a) => a.name === SEARCH_TERM_PREVIEW_ACTION)?.resultDialog; + for (const field of dialog?.fields ?? []) if (field.path !== 'note') expect(preview, field.path).toHaveProperty(field.path); + const columns = dialog?.fields?.find((f) => f.path === 'terms')?.columns ?? []; + expect(columns).toHaveLength(2); + for (const column of columns) expect(preview.terms[1], column.path).toHaveProperty(column.path); + }); + + it('with no source named: the unscoped words alone, and nothing counted', async () => { + const one = counting([source('handbook')], async () => ({ passages: 1, matches: [] })); + await write(st, { term: '集团', kind: 'stop_word', knowledge_source: 'handbook' }); + const preview = await one.svc.previewTerms(QUESTION, { executionContext: ADMIN }); + expect(preview.source).toBeUndefined(); + expect(preview.terms.map((t) => t.term)).toContain('集团'); + expect(one.asked).toHaveLength(0); + expect(preview.passages).toBeUndefined(); + for (const term of preview.terms) expect(term.passages).toBeUndefined(); + expect(preview.note).toEqual(expect.any(String)); + }); + + it('without a segmenter: the cut each store makes (keywordTerms of core), its stop words not reported', async () => { + const one = replica(st, [source('handbook')], { segmenter: false }); + const preview = await one.svc.previewTerms(QUESTION, { source: 'handbook', executionContext: ADMIN }); + expect(preview.cutBy).toBe('store'); + expect(preview.terms.map((t) => t.term)).toEqual(keywordTerms(QUESTION)); + expect(preview.stopWords).toBeUndefined(); + }); + + it('a count the store refuses leaves the terms uncounted and says why, never 0', async () => { + const one = counting([source('handbook')], async () => { + throw Object.assign(new Error('The index of this source must be rebuilt.'), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + }); + const preview = await one.svc.previewTerms(QUESTION, { source: 'handbook', executionContext: ADMIN }); + expect(preview.terms.length).toBeGreaterThan(0); + for (const term of preview.terms) expect(term.passages).toBeUndefined(); + expect(preview.passages).toBeUndefined(); + expect(preview.note).toEqual(expect.any(String)); + }); + + it('refuses an empty question and a source nothing registers with the ADR-0112 envelope', async () => { + const one = replica(st, [source('handbook')]); + const refusal = (p: Promise) => p.then(() => null, (e: unknown) => e); + expect(await refusal(one.svc.previewTerms(' ', { executionContext: ADMIN }))).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(await refusal(one.svc.previewTerms(QUESTION, { source: 'hand_book', executionContext: ADMIN }))).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + }); + + it('is the handler of sys_search_term.preview_terms: the dialog params in (beside the door\'s recordId and objectName), the preview out', async () => { + const one = replica(st, [source('handbook')]); + const registered: Array<[string, string, (ctx: unknown) => Promise, string | undefined]> = []; + registerTermPreviewAction({ registerAction: (o, n, h, p) => { registered.push([o, n, h as never, p]); } }, one.svc, 'com.objectstack.service.knowledge'); + expect(registered.map(([o, n, , p]) => [o, n, p])).toEqual([[OBJECT, SEARCH_TERM_PREVIEW_ACTION, 'com.objectstack.service.knowledge']]); + const handler = registered[0]![2]; + const door = { recordId: undefined, objectName: OBJECT }; + // The action door hands every body the caller's context elevated (`buildActionExecutionContext`, runtime). + const executionContext = { ...ADMIN, isSystem: true }; + expect(await handler({ params: { ...door, question: QUESTION, knowledge_source: 'handbook' }, executionContext })) + .toEqual(await one.svc.previewTerms(QUESTION, { source: 'handbook', executionContext: ADMIN })); + expect(await handler({ params: { ...door, question: QUESTION, knowledge_source: '' }, executionContext })) + .toEqual(await one.svc.previewTerms(QUESTION, { executionContext: ADMIN })); + const refused = await handler({ params: { ...door }, executionContext }).then(() => null, (e: unknown) => e); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + }); + + // The passage counts are not filtered by record permissions (`IKnowledgeAdapter.countKeywordMatches`): + // the service itself answers only an administrator or the system, whatever door reached it. + it('refuses, at the service, a caller that neither is the system nor holds manage_platform_settings, before the store is asked', async () => { + const one = counting([source('handbook')], async (terms) => ({ passages: 9, matches: terms.map(() => 1) })); + const refusal = (p: Promise) => p.then(() => null, (e: unknown) => e); + for (const executionContext of [undefined, MEMBER, { ...MEMBER, systemPermissions: ['setup.access'] }]) { + const refused = await refusal(one.svc.previewTerms(QUESTION, { source: 'handbook', ...(executionContext ? { executionContext } : {}) })); + expect(refused, JSON.stringify(executionContext)).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + // Refused before the question or the source is read: the refusal names no registered source. + expect(await refusal(one.svc.previewTerms(QUESTION, { source: 'hand_book', ...(executionContext ? { executionContext } : {}) }))) + .toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + } + expect(one.asked).toHaveLength(0); + expect((await one.svc.previewTerms(QUESTION, { source: 'handbook', executionContext: SYSTEM })).passages).toBe(9); + expect((await one.svc.previewTerms(QUESTION, { source: 'handbook', executionContext: ADMIN })).passages).toBe(9); + }); + + it("the action's handler judges the caller by its own capabilities, never by the door's elevation", async () => { + const one = counting([source('handbook')], async (terms) => ({ passages: 9, matches: terms.map(() => 1) })); + const handler = termPreviewActionHandler(one.svc); + const params = { recordId: undefined, objectName: OBJECT, question: QUESTION, knowledge_source: 'handbook' }; + // A member reaching the handler past the door (another engine caller, a body's `execute`) carries the + // elevation the door gives every body, `isSystem: true`, and still holds no capability. + for (const executionContext of [undefined, { ...MEMBER, isSystem: true }]) { + const refused = await handler({ params, ...(executionContext ? { executionContext } : {}) }).then(() => null, (e: unknown) => e); + expect(refused, JSON.stringify(executionContext)).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + } + expect(one.asked).toHaveLength(0); + expect(await handler({ params, executionContext: { ...ADMIN, isSystem: true } })).toMatchObject({ passages: 9 }); + }); +}); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index 02602ae9a7e..4839ac20e29 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -111,3 +111,5 @@ export { bindSearchTermHooks, } from './knowledge-search-terms.js'; export type { ClusterSearchTermChangePayload } from './knowledge-search-terms.js'; +export { SEARCH_TERM_PREVIEW_ACTION, registerTermPreviewAction } from './knowledge-term-preview.js'; +export type { KnowledgeTermPreview, KnowledgeTermPreviewOptions, KnowledgeTermPreviewTerm } from './knowledge-term-preview.js'; diff --git a/packages/services/service-knowledge/src/knowledge-search-terms.ts b/packages/services/service-knowledge/src/knowledge-search-terms.ts index ea04a7326bb..00addd96477 100644 --- a/packages/services/service-knowledge/src/knowledge-search-terms.ts +++ b/packages/services/service-knowledge/src/knowledge-search-terms.ts @@ -110,15 +110,28 @@ export class KnowledgeSearchTerms { * cuts the question itself). */ async termsFor(query: string, face: string): Promise { + return (await this.cutFor(query, face))?.terms; + } + + /** + * {@link termsFor}'s one cut, with the stop words it dropped when the + * segmenter reports them (`ISegmenterService.cut`; absent: `stopWords` is + * absent, not reported). `face` `''` cuts with the unscoped entries alone. + * The administrator's term preview reads it (`knowledge-term-preview.ts`), + * so the preview and search cannot cut a question two ways. + */ + async cutFor(query: string, face: string): Promise<{ terms: string[]; stopWords?: string[] } | undefined> { 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), + ...(face === '' ? [] : stored.filter((e) => e.source === face)), ].map((e) => e.entry); - return segmenter.keywordTerms(query, { purpose: DEFAULT_SEGMENTER_PURPOSE, entries }); + const options = { purpose: DEFAULT_SEGMENTER_PURPOSE, entries }; + if (typeof segmenter.cut === 'function') return segmenter.cut(query, options); + return { terms: segmenter.keywordTerms(query, options) }; } catch (err) { // The adapter's own cut answers instead; never the adapter's failure. this.deps.logger?.warn?.( diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 1f5e01bff4d..ffe9ec56ba3 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -47,6 +47,7 @@ import { } 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 { registerTermPreviewAction } from './knowledge-term-preview.js'; import { KNOWLEDGE_SOURCE_TYPE } from './knowledge-source-registry.js'; import { contributeKnowledgeSettings } from './knowledge-settings-contribution.js'; import { SysKnowledgeSyncState } from '@objectstack/platform-objects/system'; @@ -745,6 +746,14 @@ export class KnowledgeServicePlugin implements Plugin { if (bindSearchTermHooks(hookEngine, this.service)) { this.unsubscribes.push(() => hookEngine?.unregisterHooksByPackage?.(SEARCH_TERM_HOOK_PACKAGE)); } + // [#38710 step 3] The handler of `sys_search_term.preview_terms` (Setup → + // Search Terms → Preview Terms), which the segmenter's object declares and + // the platform action door gates on `manage_platform_settings`: it reads + // through this service's own cut and the stores' counts. + const actionEngine = engine as { registerAction?: (o: string, n: string, h: (ctx: never) => unknown, p?: string) => void } | undefined; + if (typeof actionEngine?.registerAction === 'function') { + registerTermPreviewAction(actionEngine as Parameters[0], this.service, this.name); + } // 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.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 4771ee9136e..cde6f761dd3 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -68,6 +68,7 @@ import * as KnowledgeIndexingFacet from './knowledge-service-indexing.js'; import * as KnowledgeRecordSyncFacet from './knowledge-service-record-sync.js'; import * as KnowledgeSearchFacet from './knowledge-service-search.js'; import * as KnowledgeAdmissionFacet from './knowledge-service-admission.js'; +import { previewTerms, type KnowledgeTermPreview, type KnowledgeTermPreviewOptions } from './knowledge-term-preview.js'; // [#38660] Every top-level declaration this module held beside the class lives in // `knowledge-service-top-level.ts`; what it exported is still exported from here, under the same names. @@ -246,6 +247,15 @@ export class KnowledgeService implements IKnowledgeService { this.searchTerms.resync(); } + /** + * The administrator's term preview (objectstack#38710 step 3): `question`'s terms, stop words and per-term + * passage counts in `options.source`, NOT filtered by record permissions, so only a system or + * `manage_platform_settings` caller is answered. `knowledge-term-preview.ts` holds the body and its contract. + */ + previewTerms(question: string, options: KnowledgeTermPreviewOptions = {}): Promise { + return previewTerms.call(knowledgeServiceHost.of(this), question, options); + } + // ── Enablement (ADR-0161 K8, the dated note on item 12) ────────── /** diff --git a/packages/services/service-knowledge/src/knowledge-term-preview.ts b/packages/services/service-knowledge/src/knowledge-term-preview.ts new file mode 100644 index 00000000000..b508dab70f1 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-term-preview.ts @@ -0,0 +1,248 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The administrator's term preview (objectstack#38710, step 3; the card + * body's item 5): Setup → Search Terms → Preview Terms. An administrator types + * a question, optionally names one knowledge source, and reads: + * + * - its keyword terms, cut by the ONE cut search makes + * (`KnowledgeSearchTerms.cutFor`, the function `termsFor` answers from), + * with the unscoped search words and, when a source is named, its own; + * - the words dropped as stop words, when the segmenter reports them + * (`ISegmenterService.cut`); + * - when a source is named, how many of its passages each term matches, and + * how many it holds, counted by its store with the operator its keyword leg + * matches with (`IKnowledgeAdapter.countKeywordMatches`, ADR-0161, the + * second dated note of 2026-12-05 under K8). + * + * What cannot be answered is said in `note`, never answered as empty or 0: + * no segmenter (each store then cuts the question itself, by `keywordTerms` + * of `@objectstack/core`), a segmenter that does not report its stop words, + * no source named, a held service, a store that does not count or refuses. + * + * It reads; it writes nothing. The action that serves it is declared on + * `sys_search_term` (`@objectstack/platform-objects`) with + * `requiredPermissions: ['manage_platform_settings']`, which the platform + * action door enforces (ADR-0066 D4); the knowledge plugin registers its + * handler ({@link registerTermPreviewAction}). + * + * The passage counts are NOT filtered by record permissions: a store counts + * every passage of the source, whoever may read the record behind it. So the + * service itself answers only a system context or a caller holding + * `manage_platform_settings`, and refuses every other caller, an absent one + * included, before it reads the question or the source; it does not lean on + * the door alone. No end-user door reaches it: search, `search_knowledge` + * and the knowledge settings actions call neither this nor + * `countKeywordMatches`. + */ + +import { keywordTerms, missingCapabilities } from '@objectstack/core'; +import type { AdapterKeywordCounts } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { SEARCH_TERM_OBJECT } from './knowledge-search-terms.js'; +import type { KnowledgeServiceHost } from './knowledge-service-host.js'; +import type { KnowledgeService } from './knowledge-service.js'; +import { codedRefusalOf, heldSourcesText, operatorText } from './knowledge-service-top-level.js'; +import { resolveRetrievalMode } from './knowledge-retrieval-mode.js'; +import type { KnowledgeSourceEntry } from './knowledge-source-registry.js'; + +/** The action on `sys_search_term`, and the handler key its declaration's `target` names. */ +export const SEARCH_TERM_PREVIEW_ACTION = 'preview_terms'; + +/** The longest question previewed, in characters. */ +export const TERM_PREVIEW_MAX_QUESTION_CHARS = 2000; + +/** The capability a caller of the preview holds, unless it is a system context. */ +export const TERM_PREVIEW_CAPABILITY = 'manage_platform_settings'; + +export interface KnowledgeTermPreviewOptions { + /** One knowledge source, as callers name it; absent or blank: none. */ + source?: string; + /** + * The caller. Answered only when `isSystem` or holding + * {@link TERM_PREVIEW_CAPABILITY}; absent or any other caller: refused + * `403 PERMISSION_DENIED`, as the counts read every passage unfiltered. + */ + executionContext?: Partial>; +} + +/** One term of a preview. */ +export interface KnowledgeTermPreviewTerm { + term: string; + /** The passages of the named source it matches; absent: not counted (`note` says why). */ + passages?: number; +} + +/** What {@link previewTerms} answers. */ +export interface KnowledgeTermPreview { + /** The question, trimmed. */ + question: string; + /** The source named, as callers name it; absent: none. */ + source?: string; + /** + * Who cut the question: `segmenter` (the kernel's segmenter with the search + * words, as search hands each store), or `store` (no segmenter: each store + * cuts it by `keywordTerms` of `@objectstack/core`, the terms shown). + */ + cutBy: 'segmenter' | 'store'; + /** The keyword terms, in the order search hands them. */ + terms: KnowledgeTermPreviewTerm[]; + /** The words dropped as stop words; absent: not reported. */ + stopWords?: string[]; + /** The passages the named source holds; absent: not counted. */ + passages?: number; + /** Why something above is absent, in sentences; absent when nothing is. */ + note?: string; +} + +type PreviewHost = Pick; + +/** `403 PERMISSION_DENIED` for a caller that is neither the system nor holds {@link TERM_PREVIEW_CAPABILITY}; `null` otherwise. */ +function callerRefusal(caller: KnowledgeTermPreviewOptions['executionContext']): Error | null { + if (caller?.isSystem === true) return null; + const missing = missingCapabilities([TERM_PREVIEW_CAPABILITY], caller ?? undefined); + if (missing.length === 0) return null; + return Object.assign( + new Error( + `Previewing search terms requires capability [${TERM_PREVIEW_CAPABILITY}]: its passage counts are not filtered by record permissions.`, + ), + { code: 'PERMISSION_DENIED', status: 403 }, + ); +} + +function invalid(field: string, message: string): Error { + return Object.assign(new Error(message), { + code: 'VALIDATION_ERROR', + status: 400, + fields: [{ field, code: 'invalid', message }], + }); +} + +/** The body of `KnowledgeService.previewTerms`; the member's docblock there is its contract. */ +export async function previewTerms( + this: PreviewHost, + question: string, + options: KnowledgeTermPreviewOptions = {}, +): Promise { + // First, before the question or the source is read: a refusal names no registered source. + const refused = callerRefusal(options.executionContext); + if (refused) throw refused; + const asked = typeof question === 'string' ? question.trim() : ''; + if (asked === '') throw invalid('question', 'Type a question to preview the terms it is cut into.'); + if ([...asked].length > TERM_PREVIEW_MAX_QUESTION_CHARS) { + throw invalid('question', `A previewed question holds at most ${TERM_PREVIEW_MAX_QUESTION_CHARS} characters.`); + } + const named = typeof options.source === 'string' ? options.source.trim() : ''; + const entry = named === '' ? undefined : this.registry.resolve(named); + if (named !== '' && entry === undefined) { + const faces = this.registry.entries().map((e) => e.face); + throw invalid( + 'knowledge_source', + `No knowledge source is named '${named}'. Name one of the registered sources` + + `${faces.length > 0 ? ` (${faces.join(', ')})` : ''}, or leave Knowledge Source empty.`, + ); + } + + const notes: string[] = []; + const cut = await this.searchTerms.cutFor(asked, entry?.face ?? ''); + const terms = cut?.terms ?? keywordTerms(asked); + if (cut === undefined) { + notes.push( + 'No segmenter cut this question, so each knowledge store cuts it by sliding windows, as shown, and no search word applies.', + ); + } else if (cut.stopWords === undefined) { + notes.push('The segmenter does not report the stop words it drops.'); + } + const preview: KnowledgeTermPreview = { + question: asked, + ...(entry === undefined ? {} : { source: entry.face }), + cutBy: cut === undefined ? 'store' : 'segmenter', + terms: terms.map((term) => ({ term })), + ...(cut?.stopWords === undefined ? {} : { stopWords: [...cut.stopWords] }), + }; + if (entry === undefined) { + notes.push("Name a knowledge source to count the passages each term matches there, and to apply that source's own search terms."); + } else { + const counted = await countFor.call(this, entry, terms, notes); + if (counted !== undefined) { + preview.passages = counted.passages; + preview.terms = terms.map((term, i) => ({ term, passages: counted.matches[i] })); + } + } + if (notes.length > 0) preview.note = notes.join(' '); + return preview; +} + +/** The named source's counts, or `undefined` with the reason pushed onto `notes`. */ +async function countFor( + this: PreviewHost, + entry: KnowledgeSourceEntry, + terms: readonly string[], + notes: string[], +): Promise { + // A held service calls no store (ADR-0161 K8, the dated note on item 12). + if (this.held) { + notes.push(`Not counted: ${heldSourcesText(this.held)}`); + return undefined; + } + const source = entry.handed; + let adapter; + try { + adapter = this.adapterFor(source); + } catch (err) { + notes.push(`Not counted: ${codedRefusalOf(err)?.message ?? `the store of '${entry.face}' could not be resolved.`}`); + return undefined; + } + const retrieval = resolveRetrievalMode(source, adapter); + if (!retrieval.refused && retrieval.mode === 'vector') { + notes.push(`'${entry.face}' is searched by vectors alone, so its searches match none of these terms.`); + } + if (typeof adapter.countKeywordMatches !== 'function') { + notes.push(`Not counted: the store '${adapter.id}' does not count keyword matches.`); + return undefined; + } + try { + const plan = await this.planIndex(source, adapter); + const counts = await adapter.countKeywordMatches(plan.context('term-preview'), terms); + if (counts.matches.length !== terms.length) { + throw new Error(`answered ${counts.matches.length} counts for ${terms.length} terms`); + } + return counts; + } catch (err) { + const coded = codedRefusalOf(err); + this.options.logger?.warn?.( + `[knowledge] the store '${adapter.id}' did not count the terms of a preview of '${entry.face}': ${operatorText(err)}`, + ); + notes.push(`Not counted: ${coded?.message ?? `the store '${adapter.id}' failed; the server log names why.`}`); + return undefined; + } +} + +/** + * The handler of `sys_search_term.preview_terms`: the dialog's params in, the preview out. + * + * The action door hands every body the caller's context elevated, `isSystem: true` + * (`buildActionExecutionContext`, runtime), so `isSystem` there is the door's and never the + * caller's: the handler hands the service the caller's capabilities alone, and a caller that + * reaches it past the door (another engine caller, a body's `execute`) is judged the same. + */ +export function termPreviewActionHandler(service: Pick) { + return async ( + ctx: { params?: Record; executionContext?: Partial> } | undefined, + ): Promise => { + const params = ctx?.params ?? {}; + const question = typeof params.question === 'string' ? params.question : ''; + const source = typeof params.knowledge_source === 'string' ? params.knowledge_source : undefined; + const executionContext = { isSystem: false, systemPermissions: ctx?.executionContext?.systemPermissions ?? [] }; + return service.previewTerms(question, source === undefined ? { executionContext } : { source, executionContext }); + }; +} + +/** Register {@link termPreviewActionHandler} on the engine, owned by the knowledge plugin. */ +export function registerTermPreviewAction( + ql: { registerAction(objectName: string, actionName: string, handler: (ctx: never) => unknown, packageName?: string): void }, + service: Pick, + owner: string, +): void { + ql.registerAction(SEARCH_TERM_OBJECT, SEARCH_TERM_PREVIEW_ACTION, termPreviewActionHandler(service) as (ctx: never) => unknown, owner); +} diff --git a/packages/services/service-knowledge/src/testing-keyword-counts.ts b/packages/services/service-knowledge/src/testing-keyword-counts.ts new file mode 100644 index 00000000000..936b44b50e6 --- /dev/null +++ b/packages/services/service-knowledge/src/testing-keyword-counts.ts @@ -0,0 +1,87 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `countKeywordMatches` case of the adapter contract suite (ADR-0161, + * the second dated note of 2026-12-05 under K8; rule 1), called by + * `runKnowledgeAdapterContract` (`testing.ts`) with that suite's helpers. + * TEST-ONLY, published through `./testing` with the suite. + * + * - An adapter that declares `keywordCounts` counts, for each term, exactly + * the passages its own `search` answers under `keyword` handed that term + * alone: the count and the search match with one operator. The passage + * total is the source's own; a source the adapter holds nothing for counts + * 0; a removed passage is no longer counted. + * - An adapter that does not is read through a real `KnowledgeService`: its + * term preview answers the terms uncounted, never 0. + */ + +import { describe, expect, it } from 'vitest'; +import { keywordTerms } from '@objectstack/core'; +import type { AdapterContext, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeService } from './knowledge-service.js'; + +/** What the suite hands this case. */ +export interface KeywordCountCaseHarness { + make: () => IKnowledgeAdapter | Promise; + doc: (source: KnowledgeSource, n: string, content: string) => KnowledgeDocument; + objectSource: (id: string) => KnowledgeSource; + ctxOf: (source: KnowledgeSource) => AdapterContext; + /** `countKeywordMatches` is declared; needs `keywordLeg` and `retrieval` with `keyword` listed. */ + keywordCounts: boolean; +} + +/** Terms of three characters or more and of fewer, Han and Latin, matched or not. */ +const TERMS = ['公开招标', '采购', 'alpine', 'ALPINE', 'zzqx', '2000', '的范']; + +export function keywordCountCases(h: KeywordCountCaseHarness): void { + if (h.keywordCounts) { + describe('countKeywordMatches (ADR-0161, the second dated note of 2026-12-05 under K8)', () => { + it('counts each term as its own search under keyword matches it, and the passages of the source alone', async () => { + const adapter = await h.make(); + expect(adapter.capabilities?.retrieval?.modes, 'the count is checked against the keyword leg').toContain('keyword'); + const count = adapter.countKeywordMatches!.bind(adapter); + const a = h.objectSource('kw_count'); + const b = h.objectSource('kw_count_other'); + await adapter.upsert([ + h.doc(a, '1', '采购单笔金额2000元以下除外,其余一律公开招标'), + h.doc(a, '2', '公开招标的范围由采购部门确定'), + h.doc(a, '3', 'Alpine meadow flowers'), + h.doc(a, '4', 'harbour cranes at night'), + ], h.ctxOf(a)); + await adapter.upsert([h.doc(b, '1', '公开招标 alpine meadow')], h.ctxOf(b)); + + const counts = await count(h.ctxOf(a), TERMS); + expect(counts.passages).toBe(4); + expect(counts.matches).toHaveLength(TERMS.length); + for (const [i, term] of TERMS.entries()) { + const hits = await adapter.search(term, { source: a, topK: 50, retrieval: { mode: 'keyword' }, keywordTerms: [term] }); + expect(counts.matches[i], `'${term}' is counted as the keyword leg matches it`).toBe(hits.length); + } + // Read on any store: the whole Han word, a piece of two, a Latin word, and none. + expect(counts.matches.slice(0, 3)).toEqual([2, 2, 1]); + expect(counts.matches[4]).toBe(0); + + expect(await count(h.ctxOf(a), [])).toEqual({ passages: 4, matches: [] }); + expect(await count(h.ctxOf(h.objectSource('kw_count_none')), ['公开招标'])).toEqual({ passages: 0, matches: [0] }); + await adapter.delete([`${a.name}:2`], h.ctxOf(a)); + expect(await count(h.ctxOf(a), ['公开招标'])).toEqual({ passages: 3, matches: [1] }); + }); + }); + return; + } + describe('without countKeywordMatches', () => { + it('the term preview through KnowledgeService answers the terms uncounted, never 0', async () => { + const adapter = await h.make(); + const source = h.objectSource('kw_count_absent'); + const service = new KnowledgeService(); + service.registerAdapter('under_test', adapter); + service.registerSource(source); + await adapter.upsert([h.doc(source, '1', 'alpine meadow flowers')], h.ctxOf(source)); + const preview = await service.previewTerms('alpine meadow flowers', { source: source.name, executionContext: { isSystem: true } }); + expect(preview.terms.map((t) => t.term)).toEqual(keywordTerms('alpine meadow flowers')); + for (const term of preview.terms) expect(term.passages).toBeUndefined(); + expect(preview.passages).toBeUndefined(); + }); + }); +} diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 4c844f0bcfd..ddbceea51c0 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -100,6 +100,9 @@ * and makes no embedding call of its own, counted by a spy on the instance's * `embedQuery`; handed one that answers a vector of another width, its * search rejects. + * + * `countKeywordMatches` (ADR-0161, the second dated note of 2026-12-05 under + * K8) is `testing-keyword-counts.ts`'s case, run from here. */ import { describe, expect, it, vi } from 'vitest'; @@ -118,6 +121,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; import { KnowledgeService, type KnowledgeLogger } from './knowledge-service.js'; import { resolveSplit, splitDocument } from './split/index.js'; +import { keywordCountCases } from './testing-keyword-counts.js'; /** Input of {@link runKnowledgeAdapterContract}. */ export interface KnowledgeAdapterContractOptions { @@ -206,6 +210,13 @@ export interface KnowledgeAdapterContractOptions { * fails for one that embeds by another path. Absent: `false`. */ embedQuery?: boolean; + /** + * `countKeywordMatches` (ADR-0161, the second dated note of 2026-12-05 + * under K8): each term counted as the adapter's own keyword leg matches it. + * Needs `keywordLeg` and `retrieval`. Absent: `false`, and the service's + * term preview is pinned to answer the terms uncounted. + */ + keywordCounts?: boolean; }; } @@ -570,6 +581,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect(typeof adapter.dropSource === 'function').toBe(opts.implements.dropSource); expect(adapter.capabilities?.retrieval !== undefined).toBe(opts.implements.retrieval === true); expect(typeof adapter.embedQuery === 'function').toBe(opts.implements.embedQuery === true); + expect(typeof adapter.countKeywordMatches === 'function').toBe(opts.implements.keywordCounts === true); if (opts.implements.generations) { expect(opts.implements.builds && opts.implements.refusesOtherFingerprint).toBe(true); } @@ -672,6 +684,8 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + keywordCountCases({ make, doc, objectSource, ctxOf, keywordCounts: opts.implements.keywordCounts === true }); + if (opts.implements.retrieval === true) { describe('retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8)', () => { it('reports the modes it runs, each once and each one of the three, and a default it lists', async () => { diff --git a/packages/services/service-segmenter/src/segmenter-service.test.ts b/packages/services/service-segmenter/src/segmenter-service.test.ts index e7f9f8eb8a6..951b6063382 100644 --- a/packages/services/service-segmenter/src/segmenter-service.test.ts +++ b/packages/services/service-segmenter/src/segmenter-service.test.ts @@ -201,6 +201,46 @@ describe('SegmenterService — supplied entries over the platform defaults', () }); }); +describe('SegmenterService — cut: the terms and the stop words dropped, one cut with keywordTerms', () => { + const QUESTIONS = ['出差住宿费2000元以下需要审批吗', '涉密人员脱密期是多久', '我在集团干了12年了,一年有几天年假?', 'X-200 leave policy']; + const ENTRIES: SegmenterEntry[] = [{ term: '审批', kind: 'stop_word' }, { term: '明规条款', kind: 'word' }]; + + it('answers as terms exactly what keywordTerms answers, on the dictionary and the fallback, with entries or none', () => { + for (const service of [jieba, windows]) { + for (const q of QUESTIONS) { + expect(service.cut(q).terms, q).toEqual(service.keywordTerms(q)); + expect(service.cut(q, { entries: ENTRIES }).terms, q).toEqual(service.keywordTerms(q, { entries: ENTRIES })); + } + } + }); + + it('reports the platform and the supplied stop words it dropped, once each, in question order', () => { + expect(jieba.cut('出差住宿费2000元以下需要审批吗').stopWords).toEqual(['需要', '吗']); + expect(jieba.cut('出差住宿费2000元以下需要审批吗', { entries: ENTRIES }).stopWords).toEqual(['需要', '审批', '吗']); + expect(jieba.cut('需要什么?需要多久?').stopWords).toEqual(['需要', '什么', '多久']); + // The fallback takes a stop word of two characters out of the run before it windows it. + expect(windows.cut('涉密人员脱密期是多久').stopWords).toEqual(['多久']); + // A question with no stop word reports none. + expect(jieba.cut('X-200 leave policy').stopWords).toEqual([]); + }); + + it('does not report a platform stop word a disabled entry withdraws: it is a term again', () => { + const withdrawn = jieba.cut('需要审批吗', { entries: [{ term: '需要', kind: 'stop_word', enabled: false }] }); + expect(withdrawn.stopWords).toEqual(['吗']); + expect(withdrawn.terms).toContain('需要'); + }); + + it('refuses record_search as keywordTerms does', () => { + let thrown: unknown; + try { + jieba.cut('年假', { purpose: 'record_search' }); + } catch (e) { + thrown = e; + } + expect(thrown).toMatchObject({ code: 'NOT_IMPLEMENTED', status: 501 }); + }); +}); + describe('SegmenterService — purpose', () => { it('defaults to knowledge and refuses record_search with NOT_IMPLEMENTED', () => { expect(jieba.keywordTerms('年假', { purpose: 'knowledge' })).toEqual(jieba.keywordTerms('年假')); diff --git a/packages/services/service-segmenter/src/segmenter-service.ts b/packages/services/service-segmenter/src/segmenter-service.ts index 12afd919212..da0f7d03df5 100644 --- a/packages/services/service-segmenter/src/segmenter-service.ts +++ b/packages/services/service-segmenter/src/segmenter-service.ts @@ -5,6 +5,7 @@ import { StandardErrorCode } from '@objectstack/spec/api'; import { DEFAULT_SEGMENTER_PURPOSE, type ISegmenterService, + type SegmenterCut, type SegmenterEntry, type SegmenterPurpose, type SegmenterStatus, @@ -146,6 +147,17 @@ function takeOut(text: string, matcher: Matcher, found: Placed[], at = 0): strin return rest; } +/** Each dropped stop word once (case-insensitively), in the order the question first holds it. */ +function inQuestionOrder(dropped: readonly string[], question: string): string[] { + const lowered = lower(question); + const firsts = new Map(); + for (const term of dropped) { + const key = lower(term); + if (!firsts.has(key)) firsts.set(key, { term, at: lowered.indexOf(key) }); + } + return [...firsts.values()].sort((a, b) => a.at - b.at).map((f) => f.term); +} + /** * The service. Every instance in a process shares the one load of its * dictionary segmenter (`jiebaLoader`), which is never retried: what @@ -175,6 +187,9 @@ function takeOut(text: string, matcher: Matcher, found: Placed[], at = 0): strin * 6. Stop words are dropped from the whole answer; the terms are deduplicated * case-insensitively and capped at `MAX_KEYWORD_TERMS`, the words of steps * 2–4 first, in query order, then those of step 5 in its own order. + * + * `cut` is that one rule, with the stop words it dropped at steps 3 and 6 + * (the administrator's term preview); `keywordTerms` answers its terms. */ export class SegmenterService implements ISegmenterService { private readonly segmenter: DictionarySegmenter | undefined; @@ -199,17 +214,20 @@ export class SegmenterService implements ISegmenterService { } keywordTerms(query: string, options: SegmenterTermsOptions = {}): string[] { + return this.cut(query, options).terms; + } + + cut(query: string, options: SegmenterTermsOptions = {}): SegmenterCut { const purpose = options.purpose ?? DEFAULT_SEGMENTER_PURPOSE; if (!SERVED_PURPOSES.includes(purpose)) throw notImplemented(purpose); // Read afresh on every call: the contract promises a changed entry takes effect on the next call. const lexicon = options.entries && options.entries.length > 0 ? lexiconOf(options.entries, purpose) : this.platformLexicon; const placed: Placed[] = []; - const text = takeOut( - query.split(KEYWORD_SEPARATORS).map((piece) => piece.normalize('NFKC')).join(' '), - lexicon.words, - placed, - ); + // Every stop word dropped, wherever the rule drops it (steps 3 and 6). + const dropped: string[] = []; + const normalized = query.split(KEYWORD_SEPARATORS).map((piece) => piece.normalize('NFKC')).join(' '); + const text = takeOut(normalized, lexicon.words, placed); let residual = ''; let at = 0; @@ -224,7 +242,7 @@ export class SegmenterService implements ISegmenterService { residual += `${text.slice(at, run.at)} `; } else { if (!PURE_HAN_RUN.test(run.chars)) continue; // it holds kana or Hangul: the sliding windows, as today - residual += text.slice(at, run.at) + this.hanRun(run.chars, run.at, lexicon, placed); + residual += text.slice(at, run.at) + this.hanRun(run.chars, run.at, lexicon, placed, dropped); } at = run.at + run.chars.length; } @@ -236,12 +254,12 @@ export class SegmenterService implements ISegmenterService { const ordered = placed.sort((a, b) => a.at - b.at).map((p) => p.term); for (const term of [...ordered, ...slidingWindowTerms(residual)]) { const key = term.toLowerCase(); - if (seen.has(key) || stop(term)) continue; + if (stop(term)) dropped.push(term); + if (seen.has(key) || stop(term) || terms.length === MAX_KEYWORD_TERMS) continue; seen.add(key); terms.push(term); - if (terms.length === MAX_KEYWORD_TERMS) break; } - return terms; + return { terms, stopWords: inQuestionOrder(dropped, normalized) }; } /** @@ -249,10 +267,13 @@ export class SegmenterService implements ISegmenterService { * what of it the sliding windows still cut (with the dictionary segmenter, * nothing: a separator keeps the run's neighbours apart). */ - private hanRun(run: string, at: number, lexicon: Lexicon, out: Placed[]): string { + private hanRun(run: string, at: number, lexicon: Lexicon, out: Placed[], dropped: string[]): string { if (!this.segmenter) { // The sliding-window fallback: stop words of two characters or more out, the rest windowed as today. - return ` ${takeOut(run, lexicon.stops, [], at)} `; + const stops: Placed[] = []; + const rest = takeOut(run, lexicon.stops, stops, at); + for (const stop of stops) dropped.push(stop.term); + return ` ${rest} `; } let singles: Placed[] = []; const flush = (): void => { @@ -263,7 +284,10 @@ export class SegmenterService implements ISegmenterService { for (const token of this.segmenter.cut(run)) { const here = offset; offset += token.length; - if (lexicon.kinds.get(lower(token)) === 'stop_word') flush(); + if (lexicon.kinds.get(lower(token)) === 'stop_word') { + dropped.push(token); + flush(); + } else if ([...token].length === 1) singles.push({ at: here, term: token }); else { flush(); diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 1fd36946141..aed63649914 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -41,6 +41,7 @@ "AdapterEmbeddingDescriptor (interface)", "AdapterIndexExpectation (interface)", "AdapterIndexStatus (interface)", + "AdapterKeywordCounts (interface)", "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", @@ -377,6 +378,7 @@ "SecurityContext (type)", "SeedSettlementSnapshot (interface)", "SeedSuppressionReason (type)", + "SegmenterCut (interface)", "SegmenterEngine (type)", "SegmenterEntry (interface)", "SegmenterEntryKind (type)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 23a43b01341..c72a85fce36 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -41,6 +41,7 @@ "AdapterEmbeddingDescriptor": "src/contracts/knowledge-adapter.ts#AdapterEmbeddingDescriptor (interface)", "AdapterIndexExpectation": "src/contracts/knowledge-adapter.ts#AdapterIndexExpectation (interface)", "AdapterIndexStatus": "src/contracts/knowledge-adapter.ts#AdapterIndexStatus (interface)", + "AdapterKeywordCounts": "src/contracts/knowledge-adapter.ts#AdapterKeywordCounts (interface)", "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", @@ -377,6 +378,7 @@ "SecurityContext": "src/contracts/security-service.ts#SecurityContext (type)", "SeedSettlementSnapshot": "src/contracts/seed-settlement.ts#SeedSettlementSnapshot (interface)", "SeedSuppressionReason": "src/contracts/seed-settlement.ts#SeedSuppressionReason (type)", + "SegmenterCut": "src/contracts/segmenter-service.ts#SegmenterCut (interface)", "SegmenterEngine": "src/contracts/segmenter-service.ts#SegmenterEngine (type)", "SegmenterEntry": "src/contracts/segmenter-service.ts#SegmenterEntry (interface)", "SegmenterEntryKind": "src/contracts/segmenter-service.ts#SegmenterEntryKind (type)", diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 6704e21d919..65278bec961 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -297,6 +297,17 @@ export interface AdapterListDocumentsPage { nextCursor?: string; } +/** + * What `IKnowledgeAdapter.countKeywordMatches` answers (ADR-0161, the second + * dated note of 2026-12-05 under K8). + */ +export interface AdapterKeywordCounts { + /** The passages of the source's active generation. */ + passages: number; + /** For each term handed, in its order, the passages of that generation its keyword leg matches. */ + matches: number[]; +} + /** * What an adapter declares it accepts beyond whole documents (ADR-0161 K8, * item 5). A method that is absent is the capability signal for everything @@ -500,6 +511,27 @@ export interface IKnowledgeAdapter { */ dropSource?(ctx: AdapterContext): Promise; + /** + * Count, for each of `terms`, the passages of `ctx.source`'s active + * generation (the one `search` reads) that the keyword leg matches for that + * term alone, by the operator its `search` matches the term with; and the + * passages of that generation (ADR-0161, the second dated note of 2026-12-05 + * under K8). Read by the knowledge service's term preview, so an + * administrator sees how common each term of a question is. + * + * Every passage of the generation counts: no organization filter, no record + * scope, and no passage text is answered. The counts are NOT filtered by + * record permissions, so they are for the administrator's preview alone: + * the knowledge service answers them only to a system context or a caller + * holding `manage_platform_settings`, and no end-user door reads this member. + * `ctx.index` is not compared: matching a word reads no vector. A source the adapter holds nothing for + * answers `passages: 0` and a 0 for each term. + * + * Absent: the adapter does not count (it has no keyword leg, or does not + * implement it), and the preview says the terms are not counted, never 0. + */ + countKeywordMatches?(ctx: AdapterContext, terms: readonly string[]): Promise; + /** * Optional liveness probe. When implemented, used by the service's * health endpoint and Studio "test connection" actions. diff --git a/packages/spec/src/contracts/segmenter-service.ts b/packages/spec/src/contracts/segmenter-service.ts index 2e191f71346..9233a31cb97 100644 --- a/packages/spec/src/contracts/segmenter-service.ts +++ b/packages/spec/src/contracts/segmenter-service.ts @@ -112,6 +112,19 @@ export interface SegmenterStatus { purposes: readonly SegmenterPurpose[]; } +/** One cut of a question, as {@link ISegmenterService.cut} answers it. */ +export interface SegmenterCut { + /** The keyword terms: exactly what `keywordTerms` answers for the same call. */ + terms: string[]; + /** + * The words of the question dropped as stop words, the platform's and the + * supplied ones alike: each once (compared case-insensitively), in the order + * the question holds them, spelled as the question writes them after NFKC + * normalisation. Empty: the cut dropped none. + */ + stopWords: string[]; +} + export interface ISegmenterService { /** * The keyword terms of `query`. Throws an error with `code` @@ -119,6 +132,14 @@ export interface ISegmenterService { * serve. */ keywordTerms(query: string, options?: SegmenterTermsOptions): string[]; + /** + * The cut `keywordTerms` makes of `query`, with the stop words it dropped, + * for an administrator who asks why a word is not searched. `terms` is + * `keywordTerms(query, options)`: one cut, never a second rule. Refuses what + * `keywordTerms` refuses. Optional: a provider without it reports no dropped + * words, and a caller says they are not reported, never that there are none. + */ + cut?(query: string, options?: SegmenterTermsOptions): SegmenterCut; status(): SegmenterStatus; }