diff --git a/.changeset/38710-search-term-object.md b/.changeset/38710-search-term-object.md new file mode 100644 index 00000000000..3497c9db408 --- /dev/null +++ b/.changeset/38710-search-term-object.md @@ -0,0 +1,17 @@ +--- +'@objectstack/platform-objects': patch +'@objectstack/service-segmenter': patch +'@objectstack/spec': patch +'@objectstack/cli': patch +--- + +feat(platform-objects, service-segmenter): the 检索词条 object `sys_search_term`, the administrator's search words + +Clause-②: yes +Metadata-protocol: none + +`@objectstack/platform-objects` declares `sys_search_term` (检索词条, Search Term): one record per word an administrator adds to search, one set for the whole deployment (no organization column). Fields: `term`, `kind` (`word` custom word or `stop_word`), `purpose` (`knowledge`, `record_search` or `both`; default `knowledge`, the only one implemented), `knowledge_source` (one knowledge source; empty for every source), `enabled` (default on) and `note`. `term`, `kind`, `purpose` and `enabled` are the segmenter contract's `SegmenterEntry` one to one. The object is `system-data` with CSV import opted in, so New, Edit, Delete, Import, Export and record history are the platform's own; every operation, writes included, requires `manage_platform_settings`. A record that disables a platform word (年假, 脱密, 应急采购, …) is refused: those words live in the segmenter's read-only dictionary, so make one a stop word instead. A platform stop word can be disabled. The platform words move here as `PLATFORM_SEARCH_WORDS`, and the segmenter's `PLATFORM_WORDS` reads them, so the object and the service hold one list. + +`@objectstack/service-segmenter`: `SegmenterServicePlugin` registers `sys_search_term` on the manifest service (`SEARCH_TERM_BUNDLE_ID`), with no Setup entry. Nothing reads the records yet: the knowledge service passes them to the segmenter in a later release, and the object gets its Setup entry then. + +`@objectstack/spec` lists `sys_search_term` among the platform-provided object names. `@objectstack/cli` gives it a row in the organization-ownership inventory (no organization column to drop). diff --git a/packages/cli/src/utils/organization-ownership-inventory.ts b/packages/cli/src/utils/organization-ownership-inventory.ts index 08446eeeaa9..e2fbdf6c4b6 100644 --- a/packages/cli/src/utils/organization-ownership-inventory.ts +++ b/packages/cli/src/utils/organization-ownership-inventory.ts @@ -783,6 +783,14 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [ `${CENSUS_MAIN}: systemFields.tenant: false; ${D7}: one row per knowledge source, whose index serves the ` + 'whole deployment, written by the knowledge service under the system context, never by organization', }, + { + object: 'sys_search_term', + census: PMAIN, + fate: 'column-drop', + citation: + `${CENSUS_MAIN}: systemFields.tenant: false; ${D7}: the administrator's search words, one set for the ` + + 'whole deployment, written by platform administrators (manage_platform_settings), never by organization', + }, { object: 'sys_scim_connection_credential', census: P1, fate: 'attribution', citation: `${D3_ORG_ROWS}; ${D10_SINGLE}`, anchors: [] }, { object: 'sys_flow_credential', diff --git a/packages/platform-objects/scripts/i18n-extract.config.ts b/packages/platform-objects/scripts/i18n-extract.config.ts index 4550696e95a..337887f93e5 100644 --- a/packages/platform-objects/scripts/i18n-extract.config.ts +++ b/packages/platform-objects/scripts/i18n-extract.config.ts @@ -208,6 +208,7 @@ import { SysWorkCalendar, SysWorkCalendarException, SysKnowledgeSyncState, + SysSearchTerm, } from '../src/system/index.js'; // The built-in tasks and notes (`work/`): business objects every environment @@ -376,6 +377,9 @@ const config: ObjectStackDefinition = defineStack({ // [ADR-0161] Registered by the knowledge service; its labels are served // from this package's bundles, like `sys_job_queue`'s. SysKnowledgeSyncState, + // [objectstack#38710] Registered by the segmenter service; its labels are + // served from this package's bundles, like `sys_knowledge_sync_state`'s. + SysSearchTerm, SysTask, SysNote, ] as any, 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 9b40785afa5..e4a32e1b41e 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -4773,6 +4773,57 @@ export const arObjects: NonNullable = { } } }, + sys_search_term: { + label: "مصطلح البحث", + pluralLabel: "مصطلحات البحث", + description: "كلمات يضيفها المسؤول إلى البحث: كلمات مخصصة تبقى كاملة عند تقطيع السؤال، وكلمات توقف تُحذف منه. مجموعة واحدة للنشر بأكمله، فوق كلمات المنصة.", + fields: { + id: { + label: "ID" + }, + term: { + label: "المصطلح", + help: "الكلمة نفسها، وتُقارن دون تمييز بين الأشكال كاملة العرض ونصف العرض ولا بين الأحرف الكبيرة والصغيرة، مثل 明规条款 أو OA审批. المصطلح الذي يحوي علامات ترقيم غير مسافة واحدة، مثل R&D أو 《员工手册》، لا يُعثر عليه أبدًا في سؤال." + }, + kind: { + label: "النوع", + help: "كلمة مخصصة: تبقى كاملة أينما وردت في السؤال. كلمة توقف: تُحذف من المصطلحات التي يُقطّع إليها السؤال، وتُقارن كاملة.", + options: { + word: "كلمة مخصصة", + stop_word: "كلمة توقف" + } + }, + purpose: { + label: "الغرض", + help: "عمليات البحث التي ينطبق عليها المصطلح. حاليًا يقطّع البحث في المعرفة وحده الأسئلة إلى كلمات؛ والبحث في السجلات محجوز.", + options: { + knowledge: "البحث في المعرفة", + record_search: "البحث في السجلات", + both: "كلاهما" + } + }, + knowledge_source: { + label: "مصدر المعرفة", + help: "مصدر المعرفة الوحيد الذي ينطبق عليه المصطلح، باسمه كما يسميه مستدعوه: NAMESPACE-NAME لمصدر حزمة، والاسم المجرد خلاف ذلك. فارغ: كل مصادر المعرفة في النشر." + }, + enabled: { + label: "مُفعّل", + help: "إيقاف: لا أثر للسجل، وكلمة التوقف المعطّلة التي تطابق كلمة توقف في المنصة تسحب تلك الكلمة. لا يمكن تعطيل كلمة من كلمات المنصة؛ اجعلها كلمة توقف بدلًا من ذلك." + }, + note: { + label: "ملاحظة", + help: "سبب إضافة المصطلح، للمسؤول التالي." + } + }, + _validations: { + search_term_no_edge_space: { + message: "لا يمكن أن يبدأ المصطلح أو ينتهي بمسافة." + }, + search_term_platform_word_not_disabled: { + message: "هذا المصطلح من كلمات المنصة ولا يمكن تعطيله. لكي لا يُبحث عنه، اجعله كلمة توقف." + } + } + }, sys_task: { label: "مهمة", pluralLabel: "المهام", diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index bb02c8c8d54..109ca23772a 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -149,6 +149,7 @@ export const arGeneratedSourceHashes: Readonly> = { "objects.sys_oauth_application.fields.jwks.label": "b2cf79f9d66c0dbc", "objects.sys_oauth_application.fields.jwks_uri.label": "2a4339df734ab269", "objects.sys_platform_setting_audit.fields.source.options.api": "4baeeff968e192d1", + "objects.sys_search_term.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.source.options.api": "4baeeff968e192d1", "objects.sys_sso_provider._actions.edit_oidc_provider.params.scopes.placeholder": "58ac90cde28c764d", "objects.sys_sso_provider._actions.edit_saml_provider.params.logoutUrl.helpText": "e12c82bcc5ee4470", diff --git a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts index c86d8b43267..9a51ca33231 100644 --- a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts +++ b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts @@ -55,6 +55,8 @@ const OWNED_OBJECTS = new Set([ 'sys_job', 'sys_job_run', 'sys_job_queue', 'sys_import_job', // knowledge — each source's sync state (declared here, registered by the knowledge service) 'sys_knowledge_sync_state', + // search — the administrator's search words (declared here, registered by the segmenter service) + 'sys_search_term', // metadata (sys_view_definition retired as inert, ADR-0131 D13) 'sys_metadata', 'sys_metadata_history', 'sys_metadata_audit', 'sys_metadata_commit', // system 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 08eec3f0d44..7ef953de3ee 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -4773,6 +4773,57 @@ export const deObjects: NonNullable = { } } }, + sys_search_term: { + label: "Suchbegriff", + pluralLabel: "Suchbegriffe", + description: "Wörter, die ein Administrator der Suche hinzufügt: eigene Wörter, die beim Zerlegen einer Frage ganz bleiben, und Stoppwörter, die daraus entfernt werden. Ein Satz für die gesamte Bereitstellung, über den Plattformwörtern.", + fields: { + id: { + label: "ID" + }, + term: { + label: "Begriff", + help: "Das Wort, verglichen ohne Unterscheidung von voller oder halber Breite und Groß-/Kleinschreibung, etwa 明规条款 oder OA审批. Ein Begriff mit anderen Satzzeichen als einem einzelnen Leerzeichen, etwa R&D oder 《员工手册》, wird in einer Frage nie gefunden." + }, + kind: { + label: "Art", + help: "Eigenes Wort: bleibt ganz, wo immer die Frage es schreibt. Stoppwort: wird aus den Begriffen einer zerlegten Frage entfernt, als Ganzes verglichen.", + options: { + word: "Eigenes Wort", + stop_word: "Stoppwort" + } + }, + purpose: { + label: "Zweck", + help: "Die Suchen, für die der Begriff gilt. Derzeit zerlegt nur die Wissenssuche Fragen in Wörter; die Datensatzsuche ist reserviert.", + options: { + knowledge: "Wissenssuche", + record_search: "Datensatzsuche", + both: "Beide" + } + }, + knowledge_source: { + label: "Wissensquelle", + help: "Die eine Wissensquelle, für die der Begriff gilt, so benannt wie von ihren Aufrufern: NAMESPACE-NAME für die Quelle eines Pakets, sonst der bloße Name. Leer: alle Wissensquellen der Bereitstellung." + }, + enabled: { + label: "Aktiviert", + help: "Aus: Der Datensatz wirkt nicht, und ein deaktiviertes Stoppwort mit demselben Begriff wie ein Plattform-Stoppwort zieht dieses Stoppwort zurück. Ein Plattformwort kann nicht deaktiviert werden; machen Sie es stattdessen zu einem Stoppwort." + }, + note: { + label: "Notiz", + help: "Warum der Begriff hinzugefügt wurde, für den nächsten Administrator." + } + }, + _validations: { + search_term_no_edge_space: { + message: "Ein Begriff darf nicht mit einem Leerzeichen beginnen oder enden." + }, + search_term_platform_word_not_disabled: { + message: "Dieser Begriff ist ein Plattformwort und kann nicht deaktiviert werden. Damit er nicht gesucht wird, machen Sie ihn zu einem Stoppwort." + } + } + }, sys_task: { label: "Aufgabe", pluralLabel: "Aufgaben", diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 3e76081d8de..eeadca663d3 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -285,6 +285,7 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_scim_subject.fields.id.label": "00b0385c9c152888", "objects.sys_scim_subject.fields.revision.label": "9736a257b7ba380b", "objects.sys_scim_user.fields.id.label": "00b0385c9c152888", + "objects.sys_search_term.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.namespace.label": "eca03ee21fc17d64", "objects.sys_secret.fields.version.label": "b74a37c0879ec50e", 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 70150ee9a33..df3110a1add 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -4773,6 +4773,57 @@ export const enObjects: NonNullable = { } } }, + sys_search_term: { + label: "Search Term", + pluralLabel: "Search Terms", + description: "Words an administrator adds to search: custom words a question is cut to keep whole, and stop words dropped from it. One set for the whole deployment, layered over the platform words.", + fields: { + id: { + label: "ID" + }, + term: { + label: "Term", + help: "The word, compared without regard to full-width or half-width forms or to case, such as 明规条款 or OA审批. A term holding punctuation other than a single space, such as R&D or 《员工手册》, is never found in a question." + }, + kind: { + label: "Kind", + help: "Custom Word: kept whole wherever a question spells it. Stop Word: dropped from the terms a question is cut into, compared whole.", + options: { + word: "Custom Word", + stop_word: "Stop Word" + } + }, + purpose: { + label: "Purpose", + help: "The searches the term applies to. Only knowledge retrieval cuts questions into words today; record search is reserved.", + options: { + knowledge: "Knowledge Retrieval", + record_search: "Record Search", + both: "Both" + } + }, + knowledge_source: { + label: "Knowledge Source", + help: "The one knowledge source the term applies to, as callers name it: NAMESPACE-NAME for a package's source, the bare name otherwise. Empty: every knowledge source of the deployment." + }, + enabled: { + label: "Enabled", + help: "Off: the record has no effect, and a disabled stop word of the same term as a platform stop word withdraws that stop word. A platform word cannot be disabled; make it a stop word instead." + }, + note: { + label: "Note", + help: "Why the term was added, for the next administrator." + } + }, + _validations: { + search_term_no_edge_space: { + message: "A term cannot start or end with a space." + }, + search_term_platform_word_not_disabled: { + message: "This term is a platform word and cannot be disabled. To stop it from being searched, make it a stop word instead." + } + } + }, sys_task: { label: "Task", pluralLabel: "Tasks", 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 41dd4306024..d18861f87c7 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 @@ -4773,6 +4773,57 @@ export const esESObjects: NonNullable = { } } }, + sys_search_term: { + label: "Término de búsqueda", + pluralLabel: "Términos de búsqueda", + description: "Palabras que un administrador añade a la búsqueda: palabras personalizadas que se conservan enteras al dividir una pregunta y palabras vacías que se eliminan de ella. Un único conjunto para toda la implementación, superpuesto a las palabras de la plataforma.", + fields: { + id: { + label: "ID" + }, + term: { + label: "Término", + help: "La palabra, comparada sin distinguir formas de ancho completo o medio ni mayúsculas, como 明规条款 u OA审批. Un término que contiene puntuación distinta de un único espacio, como R&D o 《员工手册》, nunca se encuentra en una pregunta." + }, + kind: { + label: "Tipo", + help: "Palabra personalizada: se conserva entera dondequiera que la pregunta la escriba. Palabra vacía: se elimina de los términos en que se divide la pregunta, comparada entera.", + options: { + word: "Palabra personalizada", + stop_word: "Palabra vacía" + } + }, + purpose: { + label: "Finalidad", + help: "Las búsquedas a las que se aplica el término. Hoy solo la recuperación de conocimiento divide las preguntas en palabras; la búsqueda de registros está reservada.", + options: { + knowledge: "Recuperación de conocimiento", + record_search: "Búsqueda de registros", + both: "Ambas" + } + }, + knowledge_source: { + label: "Fuente de conocimiento", + help: "La única fuente de conocimiento a la que se aplica el término, tal como la nombran quienes la llaman: NAMESPACE-NAME para la fuente de un paquete, el nombre sin más en otro caso. Vacío: todas las fuentes de conocimiento de la implementación." + }, + enabled: { + label: "Habilitado", + help: "Desactivado: el registro no tiene efecto, y una palabra vacía desactivada con el mismo término que una palabra vacía de la plataforma retira esa palabra vacía. Una palabra de la plataforma no se puede desactivar; conviértala en palabra vacía." + }, + note: { + label: "Nota", + help: "Por qué se añadió el término, para el próximo administrador." + } + }, + _validations: { + search_term_no_edge_space: { + message: "Un término no puede empezar ni terminar con un espacio." + }, + search_term_platform_word_not_disabled: { + message: "Este término es una palabra de la plataforma y no se puede desactivar. Para que no se busque, conviértalo en palabra vacía." + } + } + }, sys_task: { label: "Tarea", pluralLabel: "Tareas", diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts index 7824b427eaa..79788328793 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts @@ -122,6 +122,7 @@ export const esESGeneratedSourceHashes: 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.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.actor_id.label": "b155813f8a7f06e3", "objects.sys_setting_audit.fields.id.label": "00b0385c9c152888", 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 e6974c4a080..cf48550c14e 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -4773,6 +4773,57 @@ export const frObjects: NonNullable = { } } }, + sys_search_term: { + label: "Terme de recherche", + pluralLabel: "Termes de recherche", + description: "Mots qu’un administrateur ajoute à la recherche : des mots personnalisés conservés entiers lors du découpage d’une question, et des mots vides qui en sont retirés. Un seul ensemble pour tout le déploiement, superposé aux mots de la plateforme.", + fields: { + id: { + label: "ID" + }, + term: { + label: "Terme", + help: "Le mot, comparé sans distinguer les formes pleine chasse ou demi-chasse ni la casse, comme 明规条款 ou OA审批. Un terme contenant une ponctuation autre qu’une espace simple, comme R&D ou 《员工手册》, n’est jamais trouvé dans une question." + }, + kind: { + label: "Type", + help: "Mot personnalisé : conservé entier partout où la question l’écrit. Mot vide : retiré des termes en lesquels la question est découpée, comparé en entier.", + options: { + word: "Mot personnalisé", + stop_word: "Mot vide" + } + }, + purpose: { + label: "Usage", + help: "Les recherches auxquelles le terme s’applique. Aujourd’hui, seule la recherche de connaissances découpe les questions en mots ; la recherche d’enregistrements est réservée.", + options: { + knowledge: "Recherche de connaissances", + record_search: "Recherche d’enregistrements", + both: "Les deux" + } + }, + knowledge_source: { + label: "Source de connaissances", + help: "L’unique source de connaissances à laquelle le terme s’applique, telle que ses appelants la nomment : NAMESPACE-NAME pour la source d’un paquet, le nom seul sinon. Vide : toutes les sources de connaissances du déploiement." + }, + enabled: { + label: "Activé", + help: "Désactivé : l’enregistrement n’a aucun effet, et un mot vide désactivé portant le même terme qu’un mot vide de la plateforme retire ce mot vide. Un mot de la plateforme ne peut pas être désactivé ; faites-en plutôt un mot vide." + }, + note: { + label: "Note", + help: "Pourquoi le terme a été ajouté, pour le prochain administrateur." + } + }, + _validations: { + search_term_no_edge_space: { + message: "Un terme ne peut pas commencer ni se terminer par une espace." + }, + search_term_platform_word_not_disabled: { + message: "Ce terme est un mot de la plateforme et ne peut pas être désactivé. Pour qu’il ne soit plus recherché, faites-en un mot vide." + } + } + }, sys_task: { label: "Tâche", pluralLabel: "Tâches", 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 3f73a5b853d..c2a88f7065e 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.fields.id.label": "00b0385c9c152888", + "objects.sys_search_term.fields.note.label": "f78f61778f71bf68", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.version.label": "b74a37c0879ec50e", "objects.sys_secret.label": "03cb32e33fa5cc45", 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 f3d4f762170..acf71568afb 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 @@ -4773,6 +4773,57 @@ export const jaJPObjects: NonNullable = { } } }, + sys_search_term: { + label: "検索語", + pluralLabel: "検索語", + description: "管理者が検索に追加する語:質問を分割するときにそのまま残すカスタム語と、質問から取り除くストップワード。デプロイメント全体で 1 セットで、プラットフォームの語の上に重ねられます。", + fields: { + id: { + label: "ID" + }, + term: { + label: "語", + help: "語そのもの。全角・半角と大文字・小文字を区別せずに比較します(例:明规条款、OA审批)。半角スペース 1 つ以外の区切り記号を含む語(R&D、《员工手册》など)は、質問の中で見つかることはありません。" + }, + kind: { + label: "種類", + help: "カスタム語:質問に現れたとき、分割せずにそのまま残します。ストップワード:質問を分割した語から取り除きます(語全体で比較)。", + options: { + word: "カスタム語", + stop_word: "ストップワード" + } + }, + purpose: { + label: "用途", + help: "この語が適用される検索。現在、質問を語に分割するのはナレッジ検索だけです。レコード検索は予約済みです。", + options: { + knowledge: "ナレッジ検索", + record_search: "レコード検索", + both: "両方" + } + }, + knowledge_source: { + label: "ナレッジソース", + help: "この語を適用する 1 つのナレッジソース。呼び出し側が使う名前で指定します:パッケージのソースは NAMESPACE-NAME、それ以外は名前のみ。空の場合:デプロイメントのすべてのナレッジソース。" + }, + enabled: { + label: "有効", + help: "オフ:このレコードは効果を持ちません。プラットフォームのストップワードと同じ語のストップワードをオフにすると、そのストップワードは取り消されます。プラットフォームの語はオフにできません。代わりにストップワードにしてください。" + }, + note: { + label: "メモ", + help: "この語を追加した理由(次の管理者のために)。" + } + }, + _validations: { + search_term_no_edge_space: { + message: "語の先頭と末尾にスペースは使えません。" + }, + search_term_platform_word_not_disabled: { + message: "この語はプラットフォームの語のため、オフにできません。検索に使われないようにするには、ストップワードにしてください。" + } + } + }, sys_task: { label: "タスク", pluralLabel: "タスク", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts index 601a8fc4340..e3075317acc 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts @@ -111,6 +111,7 @@ export const jaJPGeneratedSourceHashes: 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.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.source.options.api": "4baeeff968e192d1", 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 02890ba7d9c..d03f99bf7f2 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -4773,6 +4773,57 @@ export const koObjects: NonNullable = { } } }, + sys_search_term: { + label: "검색어", + pluralLabel: "검색어", + description: "관리자가 검색에 추가하는 단어: 질문을 자를 때 그대로 유지하는 사용자 단어와 질문에서 제외하는 불용어입니다. 배포 전체에 하나의 세트이며 플랫폼 단어 위에 적용됩니다.", + fields: { + id: { + label: "ID" + }, + term: { + label: "단어", + help: "단어 자체이며 전각/반각과 대소문자를 구분하지 않고 비교합니다(예: 明规条款, OA审批). 공백 한 칸 이외의 구두점을 포함한 단어(예: R&D, 《员工手册》)는 질문에서 절대 찾을 수 없습니다." + }, + kind: { + label: "종류", + help: "사용자 단어: 질문에 나타나면 그대로 유지합니다. 불용어: 질문을 자른 단어에서 제외하며 단어 전체로 비교합니다.", + options: { + word: "사용자 단어", + stop_word: "불용어" + } + }, + purpose: { + label: "용도", + help: "단어가 적용되는 검색입니다. 현재 질문을 단어로 자르는 것은 지식 검색뿐이며, 레코드 검색은 예약되어 있습니다.", + options: { + knowledge: "지식 검색", + record_search: "레코드 검색", + both: "둘 다" + } + }, + knowledge_source: { + label: "지식 소스", + help: "단어가 적용되는 하나의 지식 소스이며 호출자가 부르는 이름으로 지정합니다: 패키지의 소스는 NAMESPACE-NAME, 그 외에는 이름만. 비어 있으면 배포의 모든 지식 소스입니다." + }, + enabled: { + label: "사용", + help: "끄면 이 레코드는 효과가 없으며, 플랫폼 불용어와 같은 단어의 불용어를 끄면 그 플랫폼 불용어가 철회됩니다. 플랫폼 단어는 끌 수 없으며 대신 불용어로 만드십시오." + }, + note: { + label: "메모", + help: "이 단어를 추가한 이유(다음 관리자를 위해)." + } + }, + _validations: { + search_term_no_edge_space: { + message: "단어의 앞뒤에 공백을 둘 수 없습니다." + }, + search_term_platform_word_not_disabled: { + message: "이 단어는 플랫폼 단어이므로 끌 수 없습니다. 검색에 쓰이지 않게 하려면 불용어로 만드십시오." + } + } + }, sys_task: { label: "작업", pluralLabel: "작업", diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index 1fc0cb999be..962404ea868 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -173,6 +173,7 @@ export const koGeneratedSourceHashes: 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.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.source.options.api": "4baeeff968e192d1", 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 916c24dc329..0f71a007c7f 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 @@ -4773,6 +4773,57 @@ export const ptBRObjects: NonNullable = { } } }, + sys_search_term: { + label: "Termo de pesquisa", + pluralLabel: "Termos de pesquisa", + description: "Palavras que um administrador adiciona à pesquisa: palavras personalizadas mantidas inteiras ao dividir uma pergunta e palavras vazias removidas dela. Um único conjunto para toda a implantação, sobreposto às palavras da plataforma.", + fields: { + id: { + label: "ID" + }, + term: { + label: "Termo", + help: "A palavra, comparada sem distinguir formas de largura total ou meia largura nem maiúsculas, como 明规条款 ou OA审批. Um termo que contém pontuação diferente de um único espaço, como R&D ou 《员工手册》, nunca é encontrado em uma pergunta." + }, + kind: { + label: "Tipo", + help: "Palavra personalizada: mantida inteira onde quer que a pergunta a escreva. Palavra vazia: removida dos termos em que a pergunta é dividida, comparada inteira.", + options: { + word: "Palavra personalizada", + stop_word: "Palavra vazia" + } + }, + purpose: { + label: "Finalidade", + help: "As pesquisas às quais o termo se aplica. Hoje apenas a recuperação de conhecimento divide perguntas em palavras; a pesquisa de registros está reservada.", + options: { + knowledge: "Recuperação de conhecimento", + record_search: "Pesquisa de registros", + both: "Ambas" + } + }, + knowledge_source: { + label: "Fonte de conhecimento", + help: "A única fonte de conhecimento à qual o termo se aplica, como quem a chama a nomeia: NAMESPACE-NAME para a fonte de um pacote, o nome simples caso contrário. Vazio: todas as fontes de conhecimento da implantação." + }, + enabled: { + label: "Habilitado", + help: "Desligado: o registro não tem efeito, e uma palavra vazia desligada com o mesmo termo de uma palavra vazia da plataforma retira essa palavra vazia. Uma palavra da plataforma não pode ser desligada; transforme-a em palavra vazia." + }, + note: { + label: "Observação", + help: "Por que o termo foi adicionado, para o próximo administrador." + } + }, + _validations: { + search_term_no_edge_space: { + message: "Um termo não pode começar nem terminar com um espaço." + }, + search_term_platform_word_not_disabled: { + message: "Este termo é uma palavra da plataforma e não pode ser desligado. Para que não seja pesquisado, transforme-o em palavra vazia." + } + } + }, sys_task: { label: "Tarefa", pluralLabel: "Tarefas", diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index 51b6c9b7c94..1b029476264 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -217,6 +217,7 @@ export const ptBRGeneratedSourceHashes: 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.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.namespace.label": "eca03ee21fc17d64", "objects.sys_setting.fields.namespace.label": "eca03ee21fc17d64", 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 83f025f89b6..4573c24d3c7 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -4773,6 +4773,57 @@ export const ruObjects: NonNullable = { } } }, + sys_search_term: { + label: "Поисковый термин", + pluralLabel: "Поисковые термины", + description: "Слова, которые администратор добавляет в поиск: собственные слова, сохраняемые целиком при разбиении вопроса, и стоп-слова, удаляемые из него. Один набор на всё развёртывание поверх слов платформы.", + fields: { + id: { + label: "ID" + }, + term: { + label: "Термин", + help: "Само слово; сравнивается без учёта полноширинных и полуширинных форм и регистра, например 明规条款 или OA审批. Термин, содержащий знаки препинания, кроме одного пробела, например R&D или 《员工手册》, в вопросе никогда не находится." + }, + kind: { + label: "Вид", + help: "Собственное слово: сохраняется целиком везде, где оно встречается в вопросе. Стоп-слово: удаляется из терминов, на которые разбит вопрос, сравнивается целиком.", + options: { + word: "Собственное слово", + stop_word: "Стоп-слово" + } + }, + purpose: { + label: "Назначение", + help: "Поиски, к которым применяется термин. Сейчас разбивает вопросы на слова только поиск по знаниям; поиск записей зарезервирован.", + options: { + knowledge: "Поиск по знаниям", + record_search: "Поиск записей", + both: "Оба" + } + }, + knowledge_source: { + label: "Источник знаний", + help: "Единственный источник знаний, к которому применяется термин, в том виде, как его называют вызывающие: NAMESPACE-NAME для источника пакета, иначе просто имя. Пусто: все источники знаний развёртывания." + }, + enabled: { + label: "Включено", + help: "Выключено: запись не действует, а выключенное стоп-слово с тем же термином, что и стоп-слово платформы, отменяет это стоп-слово. Слово платформы нельзя выключить; вместо этого сделайте его стоп-словом." + }, + note: { + label: "Примечание", + help: "Почему термин был добавлен, для следующего администратора." + } + }, + _validations: { + search_term_no_edge_space: { + message: "Термин не может начинаться или заканчиваться пробелом." + }, + search_term_platform_word_not_disabled: { + message: "Этот термин — слово платформы, и его нельзя выключить. Чтобы он не участвовал в поиске, сделайте его стоп-словом." + } + } + }, sys_task: { label: "Задача", pluralLabel: "Задачи", diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 94dc7169b72..5bbaca93bbc 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -175,6 +175,7 @@ export const ruGeneratedSourceHashes: 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.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.source.options.api": "4baeeff968e192d1", 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 5162d94f5d1..1fcc0936cf9 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 @@ -4773,6 +4773,57 @@ export const zhCNObjects: NonNullable = { } } }, + sys_search_term: { + label: "检索词条", + pluralLabel: "检索词条", + description: "管理员为检索添加的词:提问切词时保持完整的自定义词,以及从提问中去掉的停用词。整个部署共用一份,叠加在平台词之上。", + fields: { + id: { + label: "ID" + }, + term: { + label: "词条", + help: "词本身,比较时不区分全角半角和大小写,例如 明规条款 或 OA审批。含有单个空格以外标点的词条(例如 R&D 或 《员工手册》)在提问中永远找不到。" + }, + kind: { + label: "类型", + help: "自定义词:提问中出现时保持完整。停用词:从提问切出的词中去掉,整词比较。", + options: { + word: "自定义词", + stop_word: "停用词" + } + }, + purpose: { + label: "用途", + help: "词条适用的检索。目前只有知识检索会把提问切成词;记录搜索为预留。", + options: { + knowledge: "知识检索", + record_search: "记录搜索", + both: "两者" + } + }, + knowledge_source: { + label: "知识源", + help: "词条只适用的那一个知识源,按调用方的叫法:包内知识源为 NAMESPACE-NAME,否则为裸名称。为空:部署中的所有知识源。" + }, + enabled: { + label: "启用", + help: "关闭:该记录不起作用;与平台停用词相同的停用词被关闭时,会撤销该平台停用词。平台词不能关闭,可改为停用词。" + }, + note: { + label: "备注", + help: "添加该词条的原因,留给下一位管理员。" + } + }, + _validations: { + search_term_no_edge_space: { + message: "词条首尾不能有空格。" + }, + search_term_platform_word_not_disabled: { + message: "该词条是平台词,不能关闭。如果不想让它参与检索,请将它改为停用词。" + } + } + }, sys_task: { label: "任务", pluralLabel: "任务", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts index e2e667bb54c..16efe3fa859 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts @@ -51,6 +51,7 @@ export const zhCNGeneratedSourceHashes: 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.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.source.options.api": "4baeeff968e192d1", 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 60eacb8e85f..a1e1216cd50 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 @@ -4773,6 +4773,57 @@ export const zhHantObjects: NonNullable = { } } }, + sys_search_term: { + label: "檢索詞條", + pluralLabel: "檢索詞條", + description: "管理員為檢索新增的詞:提問切詞時保持完整的自訂詞,以及從提問中去掉的停用詞。整個部署共用一份,疊加在平台詞之上。", + fields: { + id: { + label: "ID" + }, + term: { + label: "詞條", + help: "詞本身,比較時不區分全形半形和大小寫,例如 明规条款 或 OA审批。含有單個空格以外標點的詞條(例如 R&D 或 《员工手册》)在提問中永遠找不到。" + }, + kind: { + label: "類型", + help: "自訂詞:提問中出現時保持完整。停用詞:從提問切出的詞中去掉,整詞比較。", + options: { + word: "自訂詞", + stop_word: "停用詞" + } + }, + purpose: { + label: "用途", + help: "詞條適用的檢索。目前只有知識檢索會把提問切成詞;記錄搜尋為預留。", + options: { + knowledge: "知識檢索", + record_search: "記錄搜尋", + both: "兩者" + } + }, + knowledge_source: { + label: "知識來源", + help: "詞條只適用的那一個知識來源,依呼叫方的稱呼:套件內知識來源為 NAMESPACE-NAME,否則為裸名稱。為空:部署中的所有知識來源。" + }, + enabled: { + label: "啟用", + help: "關閉:該記錄不起作用;與平台停用詞相同的停用詞被關閉時,會撤銷該平台停用詞。平台詞不能關閉,可改為停用詞。" + }, + note: { + label: "備註", + help: "新增該詞條的原因,留給下一位管理員。" + } + }, + _validations: { + search_term_no_edge_space: { + message: "詞條首尾不能有空格。" + }, + search_term_platform_word_not_disabled: { + message: "此詞條是平台詞,不能關閉。如果不想讓它參與檢索,請將它改為停用詞。" + } + } + }, sys_task: { label: "任務", pluralLabel: "任務", diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index 55d55f4e207..cd05c586ce7 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -166,6 +166,7 @@ export const zhHantGeneratedSourceHashes: 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.fields.id.label": "00b0385c9c152888", "objects.sys_secret.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.id.label": "00b0385c9c152888", "objects.sys_setting_audit.fields.source.options.api": "4baeeff968e192d1", diff --git a/packages/platform-objects/src/deployment-level-no-tenant-column.test.ts b/packages/platform-objects/src/deployment-level-no-tenant-column.test.ts index fdee803bb6d..f749cd71a98 100644 --- a/packages/platform-objects/src/deployment-level-no-tenant-column.test.ts +++ b/packages/platform-objects/src/deployment-level-no-tenant-column.test.ts @@ -10,6 +10,7 @@ import { SysMigration, SysMigrationJournal, SysPlatformSettingAudit, + SysSearchTerm, SysSecret, SysSettingAudit, SysTrustedKey, @@ -54,6 +55,9 @@ const DEPLOYMENT_LEVEL = [ ['sys_lifecycle_state', SysLifecycleState], // [ADR-0161] One row per knowledge source, written by the knowledge service. ['sys_knowledge_sync_state', SysKnowledgeSyncState], + // [objectstack#38710] 检索词条: one set of search words for the deployment, + // written by platform administrators (the capability gates writes too). + ['sys_search_term', SysSearchTerm], ] as const; describe('[ADR-0131 D7] deployment-level plumbing: no tenant column, platform-only reads', () => { diff --git a/packages/platform-objects/src/system/index.ts b/packages/platform-objects/src/system/index.ts index ef96d258c10..aa5f4e49ff0 100644 --- a/packages/platform-objects/src/system/index.ts +++ b/packages/platform-objects/src/system/index.ts @@ -28,6 +28,10 @@ export { SysLifecycleState } from './sys-lifecycle-state.object.js'; // [ADR-0161] One row per knowledge source: its last build and failed syncs, // tenant-less. Registered by the knowledge service, not by this package. export { SysKnowledgeSyncState } from './sys-knowledge-sync-state.object.js'; +// [objectstack#38710] 检索词条: the administrator's search words, one set per +// deployment, tenant-less. Registered by the segmenter service, which reads +// the platform words from here. +export { SysSearchTerm, PLATFORM_SEARCH_WORDS } from './sys-search-term.object.js'; // [ADR-0148, #30237] The recycle bin: one entry per delete operation. export { SysRecycleBin } from './sys-recycle-bin.object.js'; // [#31021] Which declared seed rows landed in an organization. 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 new file mode 100644 index 00000000000..d0d4c253c7e --- /dev/null +++ b/packages/platform-objects/src/system/sys-search-term.object.test.ts @@ -0,0 +1,125 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { celEngine } from '@objectstack/formula'; +import { ObjectSchema, resolveCrudAffordances } from '@objectstack/spec/data'; +import type { SegmenterEntryKind, SegmenterEntryPurpose } from '@objectstack/spec/contracts'; +import { PLATFORM_SEARCH_WORDS, SysSearchTerm } from './sys-search-term.object.js'; + +/** + * 检索词条 (`sys_search_term`, objectstack#38710 step 1): its declaration, + * asserted on the built value. Who may read and write (the capability gate), + * the deployment-wide row and the platform-word refusal through the engine + * are pinned on a real stack in `@objectstack/service-segmenter` + * (`search-term-object.integration.test.ts`), the package that registers it. + * The import door is pinned in `@objectstack/rest` + * (`import-search-term-csv.test.ts`), the package that owns the route. + * The rules here are EVALUATED: the format rule's regex through `RegExp`, the + * cross-field predicate through the canonical CEL engine in the scope the rule + * validator binds. + */ +describe('sys_search_term — declaration', () => { + const fields = SysSearchTerm.fields as Record; + const rules = (SysSearchTerm.validations ?? []) as Array>; + const rule = (name: string): Record => { + const found = rules.find((r) => r.name === name); + if (!found) throw new Error(`no rule ${name}`); + return found; + }; + const values = (field: string): string[] => (fields[field].options as Array<{ value: string }>).map((o) => o.value); + + it('parses as an ObjectSchema', () => { + expect(() => ObjectSchema.parse(SysSearchTerm)).not.toThrow(); + }); + + it("maps onto the segmenter contract's entry one to one, plus the scope the contract leaves to its caller", () => { + expect(Object.keys(fields).sort()).toEqual(['enabled', 'id', 'kind', 'knowledge_source', 'note', 'purpose', 'term']); + // Every option is a value of the contract's type, and every value of the + // type is an option: the arrays below are typed by the contract, so a + // value the contract drops fails to compile, and the equality fails on a + // value the object adds. + const kinds: SegmenterEntryKind[] = ['word', 'stop_word']; + const purposes: SegmenterEntryPurpose[] = ['knowledge', 'record_search', 'both']; + expect(values('kind')).toEqual(kinds); + expect(values('purpose')).toEqual(purposes); + expect(fields.term).toMatchObject({ type: 'text', required: true }); + expect(fields.kind).toMatchObject({ required: true, defaultValue: 'word' }); + // The card: only knowledge retrieval is implemented, and it is the default. + expect(fields.purpose).toMatchObject({ required: true, defaultValue: 'knowledge' }); + expect(fields.enabled).toMatchObject({ type: 'boolean', required: true, defaultValue: true }); + // The scope is a knowledge source's name (a governed metadata item, not a + // record), empty for every source. + expect(fields.knowledge_source).toMatchObject({ type: 'text' }); + expect(fields.knowledge_source.required).toBeFalsy(); + }); + + it('is one set for the deployment, gated on the platform capability for every operation', () => { + expect(SysSearchTerm.systemFields).toEqual({ tenant: false }); + // The flat list form: it gates reads AND writes (create, update, delete). + expect(SysSearchTerm.requiredPermissions).toEqual(['manage_platform_settings']); + }); + + it("uses the platform's import, export and history (system-data, import opted in)", () => { + expect(SysSearchTerm.managedBy).toBe('system-data'); + expect(SysSearchTerm.userActions).toEqual({ import: true }); + expect(resolveCrudAffordances(SysSearchTerm as any)).toMatchObject({ + create: true, import: true, edit: true, delete: true, exportCsv: true, + }); + // Without the opt-in, system-data offers no import: the key above is what opens it. + const { userActions: _optIn, ...withoutOptIn } = SysSearchTerm as Record; + expect(resolveCrudAffordances(withoutOptIn as any).import).toBe(false); + expect(SysSearchTerm.enable?.trackHistory).toBe(true); + }); + + describe('a term has no space at either edge', () => { + const re = new RegExp(rule('search_term_no_edge_space').regex); + it.each(['年假', 'OA审批', 'work order', 'R&D'])('accepts %j', (term) => expect(re.test(term)).toBe(true)); + it.each([' 年假', '年假 ', '\t年假', ''])('refuses %j', (term) => expect(re.test(term)).toBe(false)); + }); + + describe('a platform word cannot be disabled; it can be made a stop word', () => { + const fails = (record: Record): boolean | string => { + const r = rule('search_term_platform_word_not_disabled'); + const source = typeof r.condition === 'string' ? r.condition : r.condition?.source; + const out = celEngine.evaluate({ dialect: 'cel', source }, { record, previous: null } as any); + if (!out.ok) return `FAULT ${out.error.message.split('\n')[0].trim()}`; + return out.value as boolean; + }; + + it('refuses every platform word disabled as a word', () => { + for (const term of PLATFORM_SEARCH_WORDS) { + expect(fails({ term, kind: 'word', enabled: false }), term).toBe(true); + } + }); + + it('admits the same words enabled, made stop words, or disabled as stop words', () => { + for (const term of PLATFORM_SEARCH_WORDS) { + expect(fails({ term, kind: 'word', enabled: true }), term).toBe(false); + expect(fails({ term, kind: 'stop_word', enabled: true }), term).toBe(false); + expect(fails({ term, kind: 'stop_word', enabled: false }), term).toBe(false); + } + }); + + it("admits an administrator's own word disabled", () => { + expect(fails({ term: '明规条款', kind: 'word', enabled: false })).toBe(false); + }); + + it("spells every platform word as its own comparison key, so the rule's raw text compare is the service's", () => { + // The rule above compares the stored term as written; the segmenter + // compares a term by its key (`keyOf` in service-segmenter's + // segmenter-service.ts: NFKC, trimmed, lower case character by + // character). For the two to agree, each platform word must already BE + // its key: a future word in upper case or full-width form would let + // its lower-case spelling be disabled past the rule. + const keyOf = (text: string): string => [...text.normalize('NFKC').trim()].map((c) => c.toLowerCase()).join(''); + for (const term of PLATFORM_SEARCH_WORDS) expect(keyOf(term), term).toBe(term); + }); + + it('spells every platform word as a plain CEL string literal', () => { + // The condition quotes each word with single quotes and no escaping. + for (const term of PLATFORM_SEARCH_WORDS) expect(term).toMatch(/^[^'\\]+$/u); + expect(PLATFORM_SEARCH_WORDS.length).toBeGreaterThan(0); + expect(Object.isFrozen(PLATFORM_SEARCH_WORDS)).toBe(true); + }); + }); +}); diff --git a/packages/platform-objects/src/system/sys-search-term.object.ts b/packages/platform-objects/src/system/sys-search-term.object.ts new file mode 100644 index 00000000000..6da20c3f9da --- /dev/null +++ b/packages/platform-objects/src/system/sys-search-term.object.ts @@ -0,0 +1,198 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +/** + * The platform's search words: terms a question is cut to keep whole, that + * the dictionary segmenter would otherwise split, or that a question names in + * a form the segmenter's dictionary does not hold (leave, expenses, + * procurement, confidentiality). + * + * `@objectstack/service-segmenter` reads them as its `PLATFORM_WORDS` and + * loads them into its one process-wide dictionary segmenter, where an entry + * cannot withdraw them. They live here, not in that package, because + * {@link SysSearchTerm} refuses a record that would disable one + * (`search_term_platform_word_not_disabled`), and the service depends on this + * package, never the other way: one list, read by both. + */ +export const PLATFORM_SEARCH_WORDS: readonly string[] = Object.freeze([ + // Leave and attendance + '年假', '年休假', '病假', '事假', '婚假', '产假', '陪产假', '丧假', '调休', '倒休', + // Expenses and budgets + '超预算', '差旅费', '住宿费', '交通费', '招待费', '报销单', + // Procurement and projects + '应急采购', '集中采购', '单一来源采购', '技改', + // Confidentiality + '脱密', '脱密期', '涉密', '保密期', +]); + +/** A CEL string literal of `term` (the platform words hold no quote or backslash; asserted by the object's test). */ +const celString = (term: string): string => `'${term}'`; + +/** + * sys_search_term — 检索词条: the administrator's search words, layered over + * the platform's (objectstack#38710, step 1). + * + * One record is one word the administrator adds (`kind: word`, kept whole + * when a question is cut) or one stop word (`kind: stop_word`, dropped from a + * question's terms). The fields are the entry of the segmenter contract + * (`SegmenterEntry`, `@objectstack/spec/contracts`) one to one: `term`, + * `kind`, `purpose` and `enabled`. `knowledge_source` is the one field the + * contract does not carry: the contract takes the entries a call applies to, + * never where they are stored, so the reader picks a source's records (its + * own and those with no source) before it passes them. + * + * Declared here and registered by `SegmenterServicePlugin` + * (`@objectstack/service-segmenter`) with its manifest: the object exists only + * where the segmenter is mounted. ⛔ Nothing reads a record yet: the knowledge + * service passes them to the segmenter in step 2, so until then a record + * changes no search, and the plugin contributes no Setup entry for it. + * + * Deployment-level: one set for the whole deployment, no organization column + * (ADR-0131 D7), so a record serves every organization's knowledge sources. + * Who may read and write is object permission: the platform-only capability + * below gates every operation, writes included. Platform-defined schema, + * administrator-maintained data (`system-data`): New, Edit, Delete and Export + * as that bucket offers them, CSV import opted in, and every change kept in + * the record history. + * + * The platform words are not disabled by a record: they live in the + * segmenter's dictionary, one read-only instance per process. A record can + * turn one into a stop word, and can disable a platform stop word. + * + * @namespace sys + */ +export const SysSearchTerm = ObjectSchema.create({ + name: 'sys_search_term', + label: 'Search Term', + pluralLabel: 'Search Terms', + icon: 'text-search', + isSystem: true, + // Platform-defined schema, administrator-maintained data. + managedBy: 'system-data', + // CSV import is opt-in on `system-data`; search terms opt in (the card's + // "import of entries"): an administrator loads a list of policy titles and + // section names in one file through the generic import door. Who may import + // is the same capability that guards every other write. + userActions: { import: true }, + // [ADR-0131 D7] Deployment-level: one set of words for the whole deployment, + // never one organization's, so there is no organization to stamp. + systemFields: { tenant: false }, + requiredPermissions: ['manage_platform_settings'], + description: + 'Words an administrator adds to search: custom words a question is cut to keep whole, and stop words dropped from it. ' + + 'One set for the whole deployment, layered over the platform words.', + nameField: 'term', // [ADR-0079] canonical primary-title pointer + highlightFields: ['term', 'kind', 'purpose', 'knowledge_source', 'enabled'], + + fields: { + id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), + + term: Field.text({ + label: 'Term', + required: true, + searchable: true, + maxLength: 64, + description: + 'The word, compared without regard to full-width or half-width forms or to case, such as 明规条款 or OA审批. ' + + 'A term holding punctuation other than a single space, such as R&D or 《员工手册》, is never found in a question.', + group: 'Term', + }), + + kind: Field.select( + [ + { value: 'word', label: 'Custom Word' }, + { value: 'stop_word', label: 'Stop Word' }, + ], + { + label: 'Kind', + required: true, + defaultValue: 'word', + description: + 'Custom Word: kept whole wherever a question spells it. Stop Word: dropped from the terms a question is cut into, compared whole.', + group: 'Term', + }, + ), + + purpose: Field.select( + [ + { value: 'knowledge', label: 'Knowledge Retrieval' }, + { value: 'record_search', label: 'Record Search' }, + { value: 'both', label: 'Both' }, + ], + { + label: 'Purpose', + required: true, + defaultValue: 'knowledge', + description: + 'The searches the term applies to. Only knowledge retrieval cuts questions into words today; record search is reserved.', + group: 'Term', + }, + ), + + knowledge_source: Field.text({ + label: 'Knowledge Source', + required: false, + maxLength: 255, + description: + "The one knowledge source the term applies to, as callers name it: NAMESPACE-NAME for a package's source, the bare name otherwise. " + + 'Empty: every knowledge source of the deployment.', + group: 'Term', + }), + + enabled: Field.boolean({ + label: 'Enabled', + required: true, + defaultValue: true, + description: + 'Off: the record has no effect, and a disabled stop word of the same term as a platform stop word withdraws that stop word. ' + + 'A platform word cannot be disabled; make it a stop word instead.', + group: 'Term', + }), + + note: Field.textarea({ + label: 'Note', + required: false, + maxLength: 1000, + description: 'Why the term was added, for the next administrator.', + group: 'Term', + }), + }, + + indexes: [{ fields: ['term'] }], + + validations: [ + { + // The service compares a term trimmed; a stored edge space would make + // the platform-word rule below miss the term it is about. + type: 'format', + name: 'search_term_no_edge_space', + field: 'term', + regex: '^\\S(?:.*\\S)?$', + severity: 'error', + message: 'A term cannot start or end with a space.', + }, + { + // The seat's cut on objectstack#38710: a platform word lives in the + // segmenter's read-only dictionary, so a record that disables one would + // change nothing. Refused loudly instead of stored silently. + type: 'cross_field', + name: 'search_term_platform_word_not_disabled', + condition: + "record.kind == 'word' && record.enabled == false && " + + `record.term in [${PLATFORM_SEARCH_WORDS.map(celString).join(', ')}]`, + fields: ['enabled'], + severity: 'error', + message: + 'This term is a platform word and cannot be disabled. To stop it from being searched, make it a stop word instead.', + }, + ], + + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + // A search term is configuration, not a discussion surface. + feeds: false, + }, +}); diff --git a/packages/rest/src/import-search-term-csv.test.ts b/packages/rest/src/import-search-term-csv.test.ts new file mode 100644 index 00000000000..20557816ea6 --- /dev/null +++ b/packages/rest/src/import-search-term-csv.test.ts @@ -0,0 +1,215 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * 检索词条 (`sys_search_term`, objectstack#38710 step 1) through the GENERIC + * async import door (`POST /data/sys_search_term/import/jobs`, + * `sys_import_job`). The object is the first to pair `systemFields: { tenant: + * false }` with `userActions.import`, and every operation on it requires + * `manage_platform_settings`. This file pins that the door serves the + * platform's real object (`@objectstack/platform-objects`, not a mirror) on a + * real sqlite engine behind the REAL security layer (`SecurityPlugin`), with + * the import's rows written under the caller's own context: + * + * - a caller holding the capability imports a file, one record per line, with + * the declared defaults and no organization stamped; + * - a line that disables a platform word is refused for that row alone + * (the object's platform-word rule, reported on `enabled`) while the other + * 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. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject, SysMetadataObject } from '@objectstack/metadata-core'; +import { SysImportJob } from '@objectstack/platform-objects/audit'; +import { SysSearchTerm } from '@objectstack/platform-objects/system'; +import { RestServer } from './rest-server'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const OBJECT = 'sys_search_term'; +const SYS_CTX = { isSystem: true, userId: 'usr_system' }; + +/** A full CRUD grant on every object, without the platform capability. */ +const MEMBER_SET = { + name: 'member_default', + label: 'Member', + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +}; +/** The same grant, plus the capability. */ +const PLATFORM_ADMIN_SET = { + name: 'platform_admin', + label: 'Platform administrator', + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + systemPermissions: ['manage_platform_settings'], +}; + +const caller = (userId: string, set: string) => ({ + userId, tenantId: DEFAULT_ORGANIZATION_ID, positions: [], permissions: [set], +}); +const ADMIN = caller('usr_admin', PLATFORM_ADMIN_SET.name); +const MEMBER = caller('usr_member', MEMBER_SET.name); + +const liveEngines: ObjectQL[] = []; +afterEach(async () => { + while (liveEngines.length) { + try { await liveEngines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + write: () => true, end: () => {}, + header: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +async function boot() { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + const engine = new ObjectQL(); + liveEngines.push(engine); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(SysSearchTerm as any); + engine.registry.registerObject(SysImportJob as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const o of [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + if (!engine.registry.getObject(o.name)) engine.registry.registerObject(o as any); + } + + // The real security layer over the same engine, as the kernel wires it. + const services: Record = { + manifest: { register: () => undefined }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? [MEMBER_SET, PLATFORM_ADMIN_SET].find((s) => s.name === name) : engine.getSchema(name)) ?? null, + list: async () => [MEMBER_SET, PLATFORM_ADMIN_SET], + }, + }; + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const ctx = { + logger, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const security = new SecurityPlugin({ fallbackPermissionSet: MEMBER_SET.name }); + await security.init(ctx as never); + await security.start(ctx as never); + (engine as unknown as Record)[Symbol.for('objectstack.objectql.securityServiceSource')] = () => + services.security; + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + + const protocol = new ObjectStackProtocolImplementation(engine as any); + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + // The request's execution context, as the kernel resolves it. + const session: { caller: Record } = { caller: ADMIN }; + (rest as any).resolveExecCtx = async () => session.caller; + rest.registerRoutes(); + const routes = rest.getRoutes(); + const find = (method: string, path: string) => { + const route = routes.find((r: any) => r.method === method && r.path === path); + if (!route) throw new Error(`route not registered: ${method} ${path}`); + return route; + }; + return { + engine, + session, + 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'), + }; +} + +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[] }> { + ctx.session.caller = as; + const res = makeRes(); + await ctx.create.handler({ params: { object: OBJECT }, body: { format: 'csv', csv } } as any, res); + expect(res._status).toBe(201); + const jobId = res._json.jobId; + for (let i = 0; i < 200; i++) { + const p = makeRes(); + await ctx.progress.handler({ params: { jobId }, query: {} } as any, p); + if (['succeeded', 'failed', 'cancelled'].includes(p._json?.status)) { + const r = makeRes(); + await ctx.results.handler({ params: { jobId }, query: {} } as any, r); + return { job: p._json, results: r._json.results }; + } + await new Promise((resolve) => setTimeout(resolve, 5)); + } + throw new Error(`import job ${jobId} did not finish`); +} + +/** Every stored search term, read as the system. */ +const terms = async (ctx: Booted) => + ((await ctx.engine.find(OBJECT, { context: SYS_CTX } as never)) as Array>) + .map((r) => ({ term: r.term, kind: r.kind, purpose: r.purpose, enabled: Boolean(r.enabled), organization_id: r.organization_id })) + .sort((a, b) => String(a.term).localeCompare(String(b.term))); + +describe('sys_search_term — CSV through the generic async import door, behind the real security layer', () => { + let ctx: Booted; + beforeEach(async () => { + ctx = await boot(); + }); + + it('lands one record per line for a caller holding manage_platform_settings, with no organization stamped', async () => { + const { job } = await importCsv(ctx, ADMIN, [ + 'term,kind', + '明规条款,word', + '制度汇编,word', + '年假,stop_word', + ].join('\n')); + + expect(job).toMatchObject({ status: 'succeeded', total: 3, created: 3, errors: 0 }); + expect(await terms(ctx)).toEqual([ + { term: '制度汇编', kind: 'word', purpose: 'knowledge', enabled: true, organization_id: undefined }, + { term: '年假', kind: 'stop_word', purpose: 'knowledge', enabled: true, organization_id: undefined }, + { term: '明规条款', kind: 'word', purpose: 'knowledge', enabled: true, organization_id: undefined }, + ].sort((a, b) => a.term.localeCompare(b.term))); + }); + + it('refuses a line that disables a platform word for that row alone, and lands the rest of the file', async () => { + const { job, results } = await importCsv(ctx, ADMIN, [ + 'term,kind,enabled', + '年假,word,false', // a platform word, disabled: refused + '是否,stop_word,false', // a platform stop word, disabled: kept by the cut + '自建词,word,false', // the administrator's own word, disabled: kept + ].join('\n')); + + expect(job).toMatchObject({ status: 'succeeded', total: 3, created: 2, errors: 1 }); + // The object's platform-word rule, reported on the field it names. + expect(results[0]).toMatchObject({ row: 1, ok: false, action: 'failed', field: 'enabled', code: 'rule_violation' }); + expect(results[1]).toMatchObject({ row: 2, ok: true, action: 'created' }); + expect(results[2]).toMatchObject({ row: 3, ok: true, action: 'created' }); + expect((await terms(ctx)).map((t) => [t.term, t.kind, t.enabled])).toEqual( + [['是否', 'stop_word', false], ['自建词', 'word', false]].sort((a, b) => String(a[0]).localeCompare(String(b[0]))), + ); + }); + + it('refuses every row to a caller without the capability, whatever its grant, and lands nothing', async () => { + const { job, results } = await importCsv(ctx, MEMBER, 'term,kind\n明规条款,word\n制度汇编,word\n'); + + expect(job).toMatchObject({ status: 'failed', total: 2, created: 0, errors: 2 }); + expect(results).toHaveLength(2); + for (const row of results) expect(row).toMatchObject({ ok: false, code: 'PERMISSION_DENIED' }); + expect(await terms(ctx)).toEqual([]); + }); +}); diff --git a/packages/services/service-segmenter/package.json b/packages/services/service-segmenter/package.json index 082fd11f291..09f99722119 100644 --- a/packages/services/service-segmenter/package.json +++ b/packages/services/service-segmenter/package.json @@ -26,12 +26,17 @@ }, "dependencies": { "@objectstack/core": "workspace:*", + "@objectstack/platform-objects": "workspace:*", "@objectstack/spec": "workspace:*" }, "optionalDependencies": { "@node-rs/jieba": "2.0.4" }, "devDependencies": { + "@objectstack/driver-sql": "workspace:*", + "@objectstack/objectql": "workspace:*", + "@objectstack/plugin-security": "workspace:*", + "@objectstack/types": "workspace:*", "@types/node": "^26.6.5", "typescript": "^6.0.3", "vitest": "^4.1.11" diff --git a/packages/services/service-segmenter/src/index.ts b/packages/services/service-segmenter/src/index.ts index e0519808b73..72e50d2968f 100644 --- a/packages/services/service-segmenter/src/index.ts +++ b/packages/services/service-segmenter/src/index.ts @@ -1,6 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -export { SegmenterServicePlugin } from './segmenter-service-plugin.js'; +export { SEARCH_TERM_BUNDLE_ID, SegmenterServicePlugin } from './segmenter-service-plugin.js'; export type { SegmenterServicePluginOptions } from './segmenter-service-plugin.js'; export { SegmenterService, SERVED_PURPOSES, createSegmenterService } from './segmenter-service.js'; export { JIEBA_CUT_MODE, isNotInstalled, jiebaLoader } from './jieba-loader.js'; diff --git a/packages/services/service-segmenter/src/platform-words.ts b/packages/services/service-segmenter/src/platform-words.ts index 4b92dd62f66..22c84eb0c4b 100644 --- a/packages/services/service-segmenter/src/platform-words.ts +++ b/packages/services/service-segmenter/src/platform-words.ts @@ -1,5 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { PLATFORM_SEARCH_WORDS } from '@objectstack/platform-objects/system'; + /** * The platform layer of words: what every deployment starts from, before any * entry a caller supplies. Both lists are for knowledge retrieval, compared @@ -14,17 +16,12 @@ * against the words around them: 一年有几天年假 keeps 年假, while 去年假期 still * cuts 去年 | 假期. On the sliding-window fallback they are windowed like any * other text. + * + * The list is `PLATFORM_SEARCH_WORDS` of `@objectstack/platform-objects`, read + * from there: the 检索词条 object (`sys_search_term`) refuses a record that + * would disable one of them, so the object and this service hold one list. */ -export const PLATFORM_WORDS: readonly string[] = Object.freeze([ - // Leave and attendance - '年假', '年休假', '病假', '事假', '婚假', '产假', '陪产假', '丧假', '调休', '倒休', - // Expenses and budgets - '超预算', '差旅费', '住宿费', '交通费', '招待费', '报销单', - // Procurement and projects - '应急采购', '集中采购', '单一来源采购', '技改', - // Confidentiality - '脱密', '脱密期', '涉密', '保密期', -]); +export const PLATFORM_WORDS: readonly string[] = PLATFORM_SEARCH_WORDS; /** * Words dropped from every answer: the function words and question words of diff --git a/packages/services/service-segmenter/src/search-term-object.integration.test.ts b/packages/services/service-segmenter/src/search-term-object.integration.test.ts new file mode 100644 index 00000000000..eb0f77a0459 --- /dev/null +++ b/packages/services/service-segmenter/src/search-term-object.integration.test.ts @@ -0,0 +1,241 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * 检索词条 (`sys_search_term`) as `SegmenterServicePlugin` registers it, on a + * REAL stack: `ObjectQL` over a real SQL driver (better-sqlite3 in memory) and + * the real security layer (`SecurityPlugin`) under the `isolated` tenancy + * wall, with the object taken from the bundle the plugin hands the manifest + * service. + * + * What is pinned: + * + * - the plugin registers the object, and no Setup entry with it (nothing reads + * a record until step 2 of objectstack#38710, so no screen is offered yet); + * - reads and writes are the platform administrator's: a caller without + * `manage_platform_settings` is refused create, update, delete and read + * with the permission envelope (`PERMISSION_DENIED`, 403), even with a full + * CRUD grant and even holding `modifyAllRecords`; a caller holding it + * creates and updates; + * - one set for the deployment: no organization column, so under a wall that + * scopes every read by organization (the system context's included), a row + * written under one organization's caller is the row another organization + * reads; + * - a platform word cannot be disabled (the seat's cut): refused by the + * engine's validation, which the HTTP boundary answers 400 + * `VALIDATION_FAILED`, while making it a stop word, disabling a platform + * stop word and disabling an administrator's own word are stored; + * - the fields are the contract's entry one to one: records read back and + * passed as `entries` change the service's answer as the contract says. + * (Who reads the records for a search, and how a source's records are + * picked, is step 2; this pins only that the shapes meet.) + */ + +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { SysSearchTerm } from '@objectstack/platform-objects/system'; +import type { SegmenterEntry } from '@objectstack/spec/contracts'; +import { resolveThrownHttpError } from '@objectstack/types'; +import { SEARCH_TERM_BUNDLE_ID, SegmenterServicePlugin } from './segmenter-service-plugin.js'; +import { createSegmenterService } from './segmenter-service.js'; + +const OBJECT = 'sys_search_term'; + +/** A full CRUD grant on every object, without the platform capability. */ +const MEMBER_SET = { + name: 'member_default', + label: 'Member', + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +}; +/** The superuser bits on every object, without the platform capability. */ +const MODIFY_ALL_SET = { + name: 'modify_all', + label: 'Modify all records', + objects: { + '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, viewAllRecords: true, modifyAllRecords: true }, + }, +}; +/** The same grant as the member's, plus the capability. */ +const PLATFORM_ADMIN_SET = { + name: 'platform_admin', + label: 'Platform administrator', + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + systemPermissions: ['manage_platform_settings'], +}; + +const SETS = [MEMBER_SET, MODIFY_ALL_SET, PLATFORM_ADMIN_SET]; + +const SYS_CTX = { isSystem: true, userId: 'usr_system' }; +const member = (tenantId = 'org_a') => ({ userId: 'usr_member', tenantId, positions: [], permissions: [MEMBER_SET.name] }); +const modifyAll = (tenantId = 'org_a') => ({ userId: 'usr_modify_all', tenantId, positions: [], permissions: [MODIFY_ALL_SET.name] }); +const admin = (tenantId = 'org_a') => ({ + userId: 'usr_admin', tenantId, positions: [], permissions: [PLATFORM_ADMIN_SET.name], +}); + +const DENIED = { name: 'PermissionDeniedError', code: 'PERMISSION_DENIED', status: 403 }; + +interface Booted { + engine: ObjectQL; + bundles: Array>; +} + +async function boot(): Promise { + const bundles: Array> = []; + const services: Record = { + manifest: { register: (m: Record) => bundles.push(m) }, + // The organization wall on: every read is scoped to the caller's + // organization, the driver's own scoping included, so a row only one + // organization's caller wrote is invisible to another organization's + // unless the object has no organization column. + tenancy: { posture: 'isolated', isolationActive: true }, + }; + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const ctx = { + logger, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + await new SegmenterServicePlugin().init(ctx as never); + + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never), + true, + ); + await engine.init(); + for (const bundle of bundles) engine.registerApp(bundle as never); + await engine.syncSchemas(); + + services.objectql = engine; + services.metadata = { + get: async (type: string, name: string) => + (type === 'permission' ? SETS.find((s) => s.name === name) : engine.getSchema(name)) ?? null, + list: async () => SETS, + }; + const security = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await security.init(ctx as never); + await security.start(ctx as never); + (engine as unknown as Record)[Symbol.for('objectstack.objectql.securityServiceSource')] = () => + services.security; + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + return { engine, bundles }; +} + +describe('sys_search_term, registered by SegmenterServicePlugin, on a real stack', () => { + let stack: Booted; + beforeAll(async () => { + stack = await boot(); + }); + + it('is registered by the plugin, with no Setup entry', () => { + const mine = stack.bundles.filter((b) => b.id === SEARCH_TERM_BUNDLE_ID); + expect(mine).toHaveLength(1); + const [bundle] = mine; + expect(bundle).toMatchObject({ id: SEARCH_TERM_BUNDLE_ID, namespace: 'sys', scope: 'system' }); + expect(bundle.objects).toEqual([SysSearchTerm]); + expect(bundle.navigationContributions).toBeUndefined(); + expect(stack.engine.getSchema(OBJECT)).toBeDefined(); + }); + + it('refuses create, update, delete and read to a caller without manage_platform_settings, whatever its grant', async () => { + const { engine } = stack; + const seeded = (await engine.insert(OBJECT, { term: '制度汇编', kind: 'word' }, { context: SYS_CTX } as never)) as { id: string }; + // A full CRUD grant, and the superuser bits: neither is the capability. + for (const [who, caller] of [['member', member()], ['modifyAllRecords', modifyAll()]] as const) { + await expect( + engine.insert(OBJECT, { term: '明规条款', kind: 'word' }, { context: caller } as never), who, + ).rejects.toMatchObject(DENIED); + await expect( + engine.update(OBJECT, { id: seeded.id, kind: 'stop_word' }, { context: caller } as never), who, + ).rejects.toMatchObject(DENIED); + await expect(engine.delete(OBJECT, { where: { id: seeded.id }, context: caller } as never), who).rejects.toMatchObject(DENIED); + await expect(engine.find(OBJECT, { context: caller } as never), who).rejects.toMatchObject(DENIED); + } + + // Nothing the refused callers sent landed, and the seeded row stands. + const rows = (await engine.find(OBJECT, { where: { term: { $in: ['制度汇编', '明规条款'] } }, context: SYS_CTX } as never)) as Array>; + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ id: seeded.id, term: '制度汇编', kind: 'word' }); + }); + + it('lets a caller holding manage_platform_settings create and update, one set for every organization', async () => { + const { engine } = stack; + const created = (await engine.insert(OBJECT, { term: '明规条款', kind: 'word', note: 'policy name' }, { context: admin('org_a') } as never)) as Record; + // The declared defaults: knowledge retrieval, enabled. + expect(created).toMatchObject({ term: '明规条款', kind: 'word', purpose: 'knowledge' }); + expect(Boolean(created.enabled)).toBe(true); + // No organization is stamped: the deployment holds one set. + expect(created.organization_id).toBeUndefined(); + + await engine.update(OBJECT, { id: created.id, kind: 'stop_word' }, { context: admin('org_a') } as never); + // Another organization reads the same row. Under the isolated wall a + // read is scoped to the caller's organization, the capability holder's + // and the system context's alike (measured: with an organization column, + // each caller below reads none). So each reads the row only because the + // object has no organization column. + for (const [who, caller] of [['org_b administrator', admin('org_b')], ['org_b system', { ...SYS_CTX, tenantId: 'org_b' }]] as const) { + const seen = (await engine.find(OBJECT, { where: { id: created.id }, context: caller } as never)) as Array>; + expect(seen, who).toHaveLength(1); + expect(seen[0], who).toMatchObject({ term: '明规条款', kind: 'stop_word' }); + } + }); + + it('refuses a record that disables a platform word, and stores what the cut keeps', async () => { + const { engine } = stack; + const refusal = await engine + .insert(OBJECT, { term: '年假', kind: 'word', enabled: false }, { context: admin() } as never) + .then(() => null, (e: unknown) => e as Record); + expect(refusal).not.toBeNull(); + // The engine's validation refusal, attached to the field the rule names, + // and the answer the HTTP boundary gives it. + expect(refusal).toMatchObject({ code: 'VALIDATION_FAILED', fields: [expect.objectContaining({ field: 'enabled' })] }); + expect(resolveThrownHttpError(refusal)).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + + // Kept by the cut: the platform word made a stop word, a platform stop + // word disabled, and an administrator's own word disabled. + for (const row of [ + { term: '年假', kind: 'stop_word' }, + { term: '是否', kind: 'stop_word', enabled: false }, + { term: '自建词', kind: 'word', enabled: false }, + ]) { + await expect(engine.insert(OBJECT, row, { context: admin() } as never)).resolves.toMatchObject({ term: row.term }); + } + // An update that disables a platform word is refused the same way. + const word = (await engine.insert(OBJECT, { term: '脱密期', kind: 'word' }, { context: admin() } as never)) as { id: string }; + const updateRefusal = await engine + .update(OBJECT, { id: word.id, enabled: false }, { context: admin() } as never) + .then(() => null, (e: unknown) => e as Record); + expect(updateRefusal).toMatchObject({ code: 'VALIDATION_FAILED', fields: [expect.objectContaining({ field: 'enabled' })] }); + expect(resolveThrownHttpError(updateRefusal)).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + }); + + it("maps a record onto the contract's entry one to one", async () => { + // Its own stack and its own rows: no order dependence on the cases above. + const { engine } = await boot(); + for (const row of [{ term: '年假', kind: 'stop_word' }, { term: '是否', kind: 'stop_word', enabled: false }]) { + await engine.insert(OBJECT, row, { context: admin() } as never); + } + const rows = (await engine.find(OBJECT, { where: { term: { $in: ['年假', '是否'] } }, context: SYS_CTX } as never)) as Array>; + const entries: SegmenterEntry[] = rows.map((r) => ({ + term: r.term, kind: r.kind, purpose: r.purpose, enabled: Boolean(r.enabled), + })); + expect(entries).toEqual(expect.arrayContaining([ + { term: '年假', kind: 'stop_word', purpose: 'knowledge', enabled: true }, + { term: '是否', kind: 'stop_word', purpose: 'knowledge', enabled: false }, + ])); + const segmenter = await createSegmenterService(); + const question = '一年有几天年假,是否可以调休'; + const before = segmenter.keywordTerms(question); + const after = segmenter.keywordTerms(question, { entries }); + // The platform word made a stop word is dropped; the platform stop word + // the administrator disabled is a term again. + expect(before).toContain('年假'); + expect(before).not.toContain('是否'); + expect(after).not.toContain('年假'); + expect(after).toContain('是否'); + }); +}); diff --git a/packages/services/service-segmenter/src/segmenter-service-plugin.test.ts b/packages/services/service-segmenter/src/segmenter-service-plugin.test.ts index 050a95dc13d..29107f77313 100644 --- a/packages/services/service-segmenter/src/segmenter-service-plugin.test.ts +++ b/packages/services/service-segmenter/src/segmenter-service-plugin.test.ts @@ -5,6 +5,8 @@ import { LiteKernel } from '@objectstack/core'; import { SEGMENTER_SERVICE, type ISegmenterService } from '@objectstack/spec/contracts'; import { SegmenterServicePlugin } from './segmenter-service-plugin.js'; import type { SegmenterLoader } from './jieba-loader.js'; +import { PLATFORM_SEARCH_WORDS } from '@objectstack/platform-objects/system'; +import { PLATFORM_WORDS } from './platform-words.js'; function context() { const services = new Map(); @@ -47,6 +49,17 @@ describe('SegmenterServicePlugin', () => { expect(broken.logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('is not installed')); }); + it('says at info, never warns, that a kernel with no manifest service gets no search-term object', async () => { + const { ctx, logger } = context(); + await new SegmenterServicePlugin().init(ctx); + expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('sys_search_term (search terms) is not registered')); + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it('reads its platform words from the search-term object, one list for both', () => { + expect(PLATFORM_WORDS).toBe(PLATFORM_SEARCH_WORDS); + }); + it('boots on a kernel and fills the slot it declares', async () => { const kernel = new LiteKernel(); kernel.use(new SegmenterServicePlugin()); diff --git a/packages/services/service-segmenter/src/segmenter-service-plugin.ts b/packages/services/service-segmenter/src/segmenter-service-plugin.ts index 63f10ded729..a369787c80c 100644 --- a/packages/services/service-segmenter/src/segmenter-service-plugin.ts +++ b/packages/services/service-segmenter/src/segmenter-service-plugin.ts @@ -2,9 +2,13 @@ import type { Plugin, PluginContext } from '@objectstack/core'; import { SEGMENTER_SERVICE } from '@objectstack/spec/contracts'; +import { SysSearchTerm } from '@objectstack/platform-objects/system'; import type { SegmenterLoader } from './jieba-loader.js'; import { createSegmenterService } from './segmenter-service.js'; +/** The manifest bundle that registers `sys_search_term` (检索词条). */ +export const SEARCH_TERM_BUNDLE_ID = 'com.objectstack.service.segmenter.search-terms'; + export interface SegmenterServicePluginOptions { /** How the dictionary segmenter is loaded. Default: `@node-rs/jieba`. For tests. */ loader?: SegmenterLoader; @@ -21,13 +25,27 @@ export interface SegmenterServicePluginOptions { * log tells "not installed" (install the optional `@node-rs/jieba`) apart * from "failed to load" (its error is named). * - * Nothing reads the slot yet: the knowledge adapters keep their own terms - * until they are wired to it (objectstack#38710, step 2). + * It also registers the administrator's search words, the 检索词条 object + * `sys_search_term` (`@objectstack/platform-objects`), on the manifest + * service, as the queue plugin registers `sys_job_queue`: the object exists + * only where the segmenter is mounted. No Setup entry comes with it yet. + * + * Nothing reads the slot or the object yet: the knowledge adapters keep their + * own terms until they are wired to the slot, and the knowledge service passes + * the object's records as entries then (objectstack#38710, step 2), which is + * also when the object gets its Setup entry. A record changes no search + * before that, so no administrator is shown a screen that does nothing. */ export class SegmenterServicePlugin implements Plugin { name = 'com.objectstack.service.segmenter'; /** Services init() registers on every path (ADR-0116). */ providesServices = [SEGMENTER_SERVICE]; + /** + * init() asks the manifest service (ObjectQL's) to register + * `sys_search_term`. Declared tolerance (ADR-0116): without the engine the + * service still registers and the object is not registered, said at info. + */ + optionalDependencies = ['com.objectstack.engine.objectql']; version = '1.0.0'; type = 'standard' as const; @@ -38,6 +56,7 @@ export class SegmenterServicePlugin implements Plugin { } async init(ctx: PluginContext): Promise { + registerSearchTermObject(ctx, this.version); const service = await createSegmenterService({ loader: this.options.loader }); ctx.registerService(SEGMENTER_SERVICE, service); const status = service.status(); @@ -58,3 +77,31 @@ export class SegmenterServicePlugin implements Plugin { } } } + +/** + * Register `sys_search_term` on the manifest service. A kernel with no + * manifest service (a lean kernel, a test host) registers nothing: nothing + * reads the object yet, so that is said once at info, not warned. + */ +function registerSearchTermObject(ctx: PluginContext, version: string): void { + let manifest: { register?(m: unknown): void } | undefined; + try { + manifest = ctx.getService<{ register?(m: unknown): void }>('manifest'); + } catch { + manifest = undefined; + } + if (typeof manifest?.register !== 'function') { + ctx.logger.info('SegmenterServicePlugin: no manifest service, so sys_search_term (search terms) is not registered'); + return; + } + manifest.register({ + id: SEARCH_TERM_BUNDLE_ID, + namespace: 'sys', + version, + type: 'plugin', + scope: 'system', + name: 'Segmenter Service — search terms', + description: "Registers sys_search_term: the administrator's search words, one set for the deployment.", + objects: [SysSearchTerm], + }); +} diff --git a/packages/services/service-segmenter/vitest.config.ts b/packages/services/service-segmenter/vitest.config.ts index 6a4f24f7b7c..e0dc53f1a7c 100644 --- a/packages/services/service-segmenter/vitest.config.ts +++ b/packages/services/service-segmenter/vitest.config.ts @@ -19,8 +19,20 @@ export default defineConfig({ resolve: { alias: [ { find: /^@objectstack\/core$/, replacement: path.resolve(import.meta.dirname, '../../core/src/index.ts') }, - { find: /^@objectstack\/spec\/api$/, replacement: path.resolve(import.meta.dirname, '../../spec/src/api/index.ts') }, - { find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(import.meta.dirname, '../../spec/src/contracts/index.ts') }, + // The search-term object's real-stack suite boots the engine, the SQL + // driver and the security layer over the object this package registers; + // their source, like every sibling here. + { find: /^@objectstack\/objectql$/, replacement: path.resolve(import.meta.dirname, '../../objectql/src/index.ts') }, + { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(import.meta.dirname, '../../drivers/driver-sql/src/index.ts') }, + { find: /^@objectstack\/plugin-security$/, replacement: path.resolve(import.meta.dirname, '../../plugins/plugin-security/src/index.ts') }, + // The HTTP status a refusal maps to at the boundary (`resolveThrownHttpError`). + { find: /^@objectstack\/types$/, replacement: path.resolve(import.meta.dirname, '../../types/src/index.ts') }, + { + find: /^@objectstack\/platform-objects\/system$/, + replacement: path.resolve(import.meta.dirname, '../../platform-objects/src/system/index.ts'), + }, + { find: /^@objectstack\/spec\/([a-z-]+)$/, replacement: `${path.resolve(import.meta.dirname, '../../spec/src')}/$1/index.ts` }, + { find: /^@objectstack\/spec$/, replacement: path.resolve(import.meta.dirname, '../../spec/src/index.ts') }, ], }, }); diff --git a/packages/spec/src/system/constants/platform-object-names.ts b/packages/spec/src/system/constants/platform-object-names.ts index 572afa39a18..50d8103944c 100644 --- a/packages/spec/src/system/constants/platform-object-names.ts +++ b/packages/spec/src/system/constants/platform-object-names.ts @@ -91,6 +91,7 @@ export const PLATFORM_OBJECTS_BY_PACKAGE: Readonly