🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(fts-search): add pg_like provider for plain PostgreSQL (#19188)
YuTengjing270a4a50cb32
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.mdindex fae7dbe3b13..6ad6c741c8e 100644--- a/.agents/skills/full-text-search/SKILL.md+++ b/.agents/skills/full-text-search/SKILL.md@@ -1,6 +1,6 @@---name: full-text-search-description: 'Use for product search: FtsSearchRepo, pg_search/Elasticsearch, mapping migrations, projections, Outbox sync, reindexing and performance. Excludes agent web search.'+description: 'Use for product search: FtsSearchRepo, pg_search/pg_like/Elasticsearch, mapping migrations, projections, Outbox sync, reindexing and performance. Excludes agent web search.'---# Product Full-Text Search@@ -36,11 +36,17 @@ router/service -> createFtsSearchRepo -> FtsSearchRepo -> selected backend -> ex## Provider and Permission Invariants-- `FTS_SEARCH_PROVIDER` is a deployment-level provider selector with current values `pg_search` and- `elasticsearch`. It is not a feature flag or a user rollout. Add another enum value only when its- provider is implemented end to end.-- Elasticsearch errors, missing configuration, and unsupported candidate behavior must remain- visible. Never silently retry through PostgreSQL or add an `ilike` fallback.+- `FTS_SEARCH_PROVIDER` is a deployment-level provider selector with current values `pg_search`,+ `elasticsearch`, and `pg_like`. It is not a feature flag or a user rollout. Add another enum value+ only when its provider covers all entities in `FTS_SEARCH_BACKEND_ENTITIES` end to end, including+ `mode: 'candidates'` when the provider enables `ftsSearchCandidateEnabled`.+- Provider errors, missing configuration, and unsupported candidate behavior must remain visible.+ Never silently retry through another provider. `pg_like` is an explicitly selected lightweight+ provider, not an implicit fallback: a missing extension or unreachable service must still fail.+- `packages/database/src/repositories/ftsSearch/postgres/` owns the query, permission, pagination,+ and hydration layer shared by PostgreSQL providers. `pgSearch/` and `pgLike/` own only their+ provider adapter, dialect, and provider-specific candidate behavior. Neither provider directory+ may import the other, so either provider can be retired without owning shared functionality.- Before selecting Elasticsearch, require coverage tests proving that it supports every entity inthe provider-neutral backend contract. Do not add per-entity routing between providers.- Preserve `userId`, `workspaceId`, and caller-agent visibility throughout every provider. Candidate@@ -53,6 +59,18 @@ router/service -> createFtsSearchRepo -> FtsSearchRepo -> selected backend -> ex## Changing a Searchable Entity+### Scope for pg\_like++`pg_like` primarily serves individual users with small datasets. Review it for correct matching,+permissions, and usable result ordering at that scale. For richer search quality or larger datasets,+recommend self-hosted Elasticsearch or Elastic Cloud. Do not add indexes or change the database+schema as part of pg\_like optimization. Keep repairs bounded; distinguish new implementation bugs+from shared provider limitations and deliberate lightweight-search trade-offs. Do not infer a+personal-user performance problem from large shared development datasets without representative+measurements.++### Entity changes+Treat an entity addition or projection change as one cross-layer change. Inspect and update everyapplicable item:@@ -167,7 +185,7 @@ schema_fingerprint}`; the alias marks the live generation. Indexes created befor`unmanaged`, `in_sync`, `drift`, `upgrade_available`, `rollback_required`), promotion, andretirement; keep them free of Cloud-specific policy.-Read `docs/self-hosting/advanced/elasticsearch-migration.mdx` or its Chinese counterpart before+Read `docs/self-hosting/advanced/neon-pg-search-migration.mdx` or its Chinese counterpart beforechanging the operational sequence. When database rollout or index cost affects the design, alsouse the `db-migrations` skill and measure the relevant operation on the actual Dev database beforeadding manual or deferred release steps.diff --git a/.agents/skills/full-text-search/references/mapping-migrations.md b/.agents/skills/full-text-search/references/mapping-migrations.mdindex 62c715a5752..ad36eb6aa09 100644--- a/.agents/skills/full-text-search/references/mapping-migrations.md+++ b/.agents/skills/full-text-search/references/mapping-migrations.md@@ -2,7 +2,7 @@Use this reference when changing Elasticsearch field definitions or operating index generations.For initial provider cutover and complete environment setup, use-`docs/self-hosting/advanced/elasticsearch-migration.mdx` from the OSS repository root.+`docs/self-hosting/advanced/neon-pg-search-migration.mdx` from the OSS repository root.## Choose the operationdiff --git a/.agents/skills/write-landing-docs/SKILL.md b/.agents/skills/write-landing-docs/SKILL.mdnew file mode 100644index 00000000000..27f9ffb8053--- /dev/null+++ b/.agents/skills/write-landing-docs/SKILL.md@@ -0,0 +1,18 @@+---+name: write-landing-docs+description: 'Use for public LobeHub website documentation under docs/**, including self-hosting, deployment, migration, and configuration guides. Excludes product changelogs and source-code API docs.'+---++# Write Landing Docs++- Public website documentation is authored under `docs/**`.+- Read the `Voice & Content` section of `../../../DESIGN.md` before drafting.+- For `docs/self-hosting/**`, read [Default Audience](references/self-hosting.md).+- Verify claims, defaults, commands, limitations, and rollback behavior from current code.+- Prefer one canonical page, a recommended path, short executable steps, and a visible verification+ result. Keep English and Simplified Chinese versions aligned.+- If a published path changes, update internal links and add a tested permanent redirect in the+ landing repository that preserves locale prefixes and query parameters.+- Run the focused documentation check for every changed page.++For `docs/changelog/**`, use `../docs-changelog/SKILL.md` instead.diff --git a/.agents/skills/write-landing-docs/references/self-hosting.md b/.agents/skills/write-landing-docs/references/self-hosting.mdnew file mode 100644index 00000000000..590033dbdc9--- /dev/null+++ b/.agents/skills/write-landing-docs/references/self-hosting.md@@ -0,0 +1,13 @@+# Default Audience++Self-hosting documentation primarily serves individuals and small teams:++- Their datasets are usually small. LobeHub Cloud is the largest deployment and a correctness+ boundary, not the default sizing model for public migration instructions.+- Prefer the supported option with the fewest extra services, persistent workers, and operational+ steps. Put Cloud-scale or high-volume procedures in advanced guidance.+- Application deployment and database capability are separate: Docker can connect to Neon, while+ non-Docker users may build in GitHub Actions or elsewhere and deploy the artifact to Vercel.+- Write for a person or agent that wants a short numbered procedure with exact settings, commands,+ and verification. Omit implementation detail that does not change a decision or action; link to+ focused technical documentation or source code instead.diff --git a/apps/server/src/services/ftsSearch/index.test.ts b/apps/server/src/services/ftsSearch/index.test.tsindex 6b2ace4fedf..ad395218081 100644--- a/apps/server/src/services/ftsSearch/index.test.ts+++ b/apps/server/src/services/ftsSearch/index.test.ts@@ -44,6 +44,52 @@ describe('full-text search provider selection', () => {).toBe(FTS_SEARCH_PROVIDERS.elasticsearch);});+ it('routes pg_like to its own backend with candidate retrieval enabled', async () => {+ const search = vi.fn<FtsSearchBackend['search']>().mockResolvedValue({+ candidates: [{ id: agentResult.id, score: 4 }],+ items: [],+ total: 1,+ });+ const createPgLikeBackend = vi.fn((): FtsSearchBackend => ({ key: 'pg_like', search }));+ const loadElasticsearchConfig = vi.fn(() => undefined);+ const repo = await createFtsSearchRepo(+ { db, userId: 'allowed-user', usage: 'unified_search' },+ {+ createPgLikeBackend,+ loadElasticsearchConfig,+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.pgLike,+ },+ );++ expect(createPgLikeBackend).toHaveBeenCalledWith(+ expect.objectContaining({ provider: FTS_SEARCH_PROVIDERS.pgLike }),+ );+ expect(loadElasticsearchConfig).not.toHaveBeenCalled();+ expect(repo.ftsSearchCandidateEnabled).toBe(true);++ await expect(+ repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: {},+ query: { text: 'candidate' },+ }),+ ).resolves.toEqual({ candidates: [{ id: agentResult.id, score: 4 }], total: 1 });+ expect(search).toHaveBeenCalledWith(expect.objectContaining({ mode: 'candidates' }));+ });++ it('keeps candidate retrieval inline for pg_search', async () => {+ const repo = await createFtsSearchRepo(+ { db, userId: 'allowed-user', usage: 'unified_search' },+ {+ createPgSearchBackend: () => ({ key: 'pg_search', search: vi.fn() }),+ loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.pgSearch,+ },+ );++ expect(repo.ftsSearchCandidateEnabled).toBe(false);+ });+it('routes the stable repository facade through the selected backend', async () => {const search = vi.fn<FtsSearchBackend['search']>().mockResolvedValue({candidates: [{ id: agentResult.id, score: 9.5 }],diff --git a/apps/server/src/services/ftsSearch/index.ts b/apps/server/src/services/ftsSearch/index.tsindex de05d3a52f4..a7d1b46fc94 100644--- a/apps/server/src/services/ftsSearch/index.ts+++ b/apps/server/src/services/ftsSearch/index.ts@@ -7,6 +7,7 @@ import {type FtsSearchBackendScope,FtsSearchRepo,type FtsSearchRepoOptions,+ PgLikeFtsSearchBackend,PgSearchFtsSearchBackend,} from '@/database/repositories/ftsSearch';import { ftsSearchEnv } from '@/envs/ftsSearch';@@ -29,6 +30,7 @@ export interface CreateFtsSearchRepoInput {export const FTS_SEARCH_PROVIDERS = {elasticsearch: 'elasticsearch',+ pgLike: 'pg_like',pgSearch: 'pg_search',} as const;@@ -48,6 +50,7 @@ interface FtsSearchBackendFactoryDependencies {config: ElasticsearchFtsSearchConfig,usage: FtsSearchUsage,) => ElasticsearchFtsSearchClient;+ createPgLikeBackend?: (context: FtsSearchBackendFactoryContext) => FtsSearchBackend;createPgSearchBackend?: (context: FtsSearchBackendFactoryContext) => FtsSearchBackend;loadElasticsearchConfig?: () => ElasticsearchFtsSearchConfig | undefined;loadFtsSearchProvider?: () => FtsSearchProvider;@@ -104,6 +107,18 @@ const createFtsSearchBackendForProvider = (return createPgSearchBackend({ db, provider, scope, usage });}+ if (provider === FTS_SEARCH_PROVIDERS.pgLike) {+ const createPgLikeBackend =+ dependencies.createPgLikeBackend ??+ ((context: FtsSearchBackendFactoryContext) =>+ new PgLikeFtsSearchBackend(context.db, context.scope));+ return createPgLikeBackend({ db, provider, scope, usage });+ }++ // Only Elasticsearch remains; keep it explicit so a future provider cannot+ // silently inherit the Elasticsearch path.+ if (provider !== FTS_SEARCH_PROVIDERS.elasticsearch) return;+const config = (dependencies.loadElasticsearchConfig ?? loadElasticsearchFtsSearchConfig)();if (!config) return;@@ -154,6 +169,8 @@ export const createFtsSearchRepo = async (return new FtsSearchRepo(input.db, input.userId, input.workspaceId, input.callerAgentVisibility, {...input.options,backend: observedBackend,- ftsSearchCandidateEnabled: provider === FTS_SEARCH_PROVIDERS.elasticsearch,+ // pg_search keeps candidate retrieval inline in the model queries; every+ // other provider answers candidate-only requests through the backend.+ ftsSearchCandidateEnabled: provider !== FTS_SEARCH_PROVIDERS.pgSearch,});};diff --git a/docs/self-hosting/advanced/elasticsearch-migration.mdx b/docs/self-hosting/advanced/elasticsearch-migration.mdxdeleted file mode 100644index 0d635901bcd..00000000000--- a/docs/self-hosting/advanced/elasticsearch-migration.mdx+++ /dev/null@@ -1,158 +0,0 @@-----title: Migrate from pg_search to Elasticsearch-description: Migrate search for a LobeHub deployment using Docker and Neon.-tags:- - Elasticsearch- - Search- - Migration- - Self-hosting------# Migrate from pg\_search to Elasticsearch--If you deploy LobeHub with Docker, use Neon for your database, and currently rely on `pg_search`, follow this guide to move search to Elasticsearch. Complete the migration before Neon disables `pg_search` for your instance.--If your database continues to support `pg_search`, you can keep using it without migrating. This migration only changes the search service. Your chat history and other source data stay in the existing database.--## 1. Prepare the configuration--Back up your Neon database, then set up Elasticsearch using the [full-text search guide](/docs/self-hosting/advanced/full-text-search).--On your server, prepare an `.env` file for the migration with the following settings. Do not commit this file to your repository.--| Variable | Setting |-| ------------------------- | ---------------------------------------------------------------------------------------------- |-| `DATABASE_URL` | Your existing Neon database's direct connection URL, without `-pooler` in the hostname |-| `DATABASE_DRIVER` | Set to `node` to use the direct connection above |-| `ES_REINDEX_STATE_DIR` | Set to `/app/.elasticsearch-reindex` and mount the progress volume as shown below |-| `KEY_VAULTS_SECRET` | Reuse the value from your existing LobeHub application; do not generate a new one |-| `ES_URL` | Elasticsearch URL, reachable from the Docker containers |-| `ES_API_KEY` | An API key with permission to create indexes and read and write data |-| `ES_INDEX_NAMESPACE` | An index prefix, such as `lobehub`; use the same value for the application and migration tools |-| `FTS_SEARCH_PROVIDER` | Keep set to `pg_search` for now |-| `FTS_SEARCH_SYNC_ENABLED` | Keep set to `false` for now |--Use HTTPS and an API key for an external Elasticsearch service. The bundled Elasticsearch node on the official Compose private network uses `ES_ALLOW_INSECURE_HTTP=true` and does not require an API key. When using that node, add `--network <elasticsearch-network-name>` to each `docker run` command below. Inside a container, `localhost` does not refer to the host machine.--These commands use the official image and connect to the database specified in this configuration, independently of Compose's bundled PostgreSQL service. Run them in the same terminal, replacing the image tag with the version you are deploying:--```bash-export LOBE_MIGRATION_IMAGE='lobehub/lobehub:<deployment-version-tag>'-docker pull "$LOBE_MIGRATION_IMAGE"-docker volume create lobehub-search-state-```--Pause use of the application and run that version's database migrations. Continue only after they succeed:--```bash-docker run --rm --env-file .env \- "$LOBE_MIGRATION_IMAGE" /app/docker.cjs-```--## 2. Import existing data--Create the search indexes and import your existing data:--```bash-docker run --rm --env-file .env \- -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs \- --apply --fresh-run --yes-```--Migration progress is saved in the `lobehub-search-state` volume. Keep this volume. Use `--fresh-run` only for the initial import; omit it when resuming after an interruption.--Check the migration status:--```bash-docker run --rm --env-file .env \- -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs --status-```--Continue when the status is `ready_for_incremental_sync` and there are no failed records.--## 3. Start continuous sync--Start the sync container so that new, updated, and deleted data are reflected in search results:--```bash-docker run -d --name lobe-fts-search-sync --restart unless-stopped \- --env-file .env \- -e FTS_SEARCH_SYNC_ENABLED=true \- -e MIGRATION_DB=1 \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-sync.cjs \- --max-steps=8 --interval-seconds=15 --yes-```--Check the logs for errors:--```bash-docker logs --tail 50 lobe-fts-search-sync-```--Run the status command from the previous step again. Wait until the queue's `pending`, `ready`, `retrying`, `inFlight`, `dead`, and `revisionLag` values are all `0` before switching search.--Keep this container running after the switch. Otherwise, subsequent data changes will not appear in search results.--## 4. Switch search--Mount the same progress volume on your LobeHub application container with `-v lobehub-search-state:/app/.elasticsearch-reindex` and set `ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex`. In the application's deployment configuration, set the same Elasticsearch connection details and index prefix, and change `FTS_SEARCH_PROVIDER` to `elasticsearch`. Recreate the application container using the same image version. Editing only the migration's `.env` file does not update the running application.--Search for an existing chat message, then create a new message and confirm that it becomes searchable. Once both checks succeed and the sync container has no errors, resume normal use.--If you encounter problems after switching, you can change the application's `FTS_SEARCH_PROVIDER` back to `pg_search` and recreate the application container, provided Neon still supports the extension and you have not removed the old search indexes.--## 5. Remove the old search indexes--Once Elasticsearch search and continuous sync are working, also change `FTS_SEARCH_PROVIDER` to `elasticsearch` in the migration's `.env` file. Inspect and remove the old search indexes and extension:--```bash-docker run --rm --env-file .env \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --status-docker run --rm --env-file .env \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --apply --yes-```--This does not delete chat history or other source data, but you cannot switch directly back to `pg_search` afterward. Complete this step before Neon's deadline for disabling the extension.--## Updating LobeHub later--Keep the application container's progress volume mount, then recreate the application and continuous sync containers using the same new image version. At startup, the application runs PostgreSQL migrations, updates any Elasticsearch indexes that need upgrading, and switches search automatically. Completed indexes are not imported again. The application starts only after migration succeeds and is unavailable during this maintenance.--The official Compose configuration shares the progress volume between the application and migration tools. With a custom Docker configuration, mount the same volume on both. If your initial migration used an existing progress directory, keep mounting that directory instead of switching to an empty volume, and ensure the application container can read and write it.--If migration fails, the application will not start. Check the application container logs and follow the recovery instructions below. Keep the continuous sync container running; a startup migration does not replace it.--The optional search capture installer records its schema version in PostgreSQL. Database migrations must run before capture installation. An older application version must not install over newer capture definitions; if the installer reports an unknown or partial definition, keep the current version running and resolve the mismatch before retrying. The capture upgrade holds source-table writes while replacing definitions, so it does not create a missed-change window or require a full reindex by itself. Existing indexed tool messages require a separate, version-aware cleanup after all sync workers use the new eligibility rule.--For an existing Elasticsearch installation, first upgrade every application and continuous-sync worker to the version that excludes tool and blank messages. Then preview the ineligible PostgreSQL source count and separately record the Elasticsearch `messages` alias's live `role=tool` count:--```bash-docker run --rm --env-file .env \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-ineligible-message-cleanup.cjs --status-```--Schedule the separate cleanup only after every sync worker is upgraded. Run bounded batches with the same volume mounted for the private checkpoint:--```bash-docker run --rm --env-file .env \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-ineligible-message-cleanup.cjs \- --apply --yes --all-workers-upgraded \- --state-file=/app/.elasticsearch-reindex/ineligible-messages.json \- --batch-size=250 --max-batches=10 --delay-ms=1000-```--Keep the checkpoint volume for resume and do not delete it between runs. A repeated batch is safe: it allocates a newer Outbox revision, and the normal sync worker writes a fenced soft tombstone or the message's current eligible projection. Wait for the Outbox to drain without dead letters, then confirm the Elasticsearch count has decreased toward zero. The command does not change PostgreSQL messages or run Elasticsearch writes itself.--## If the migration is interrupted--Keep the `lobehub-search-state` volume. For an interrupted initial manual import, resolve the error and run the import command again without `--fresh-run`. If automatic migration fails during application startup, resolve the error and any retained lock, then restart the application container. It will continue the backfill, catch-up, and switch.--If the migration lock is still held, first confirm that the previous migration process has exited and its Elasticsearch requests have finished. Run the status command to find the lock owner. Replace the import command's final arguments with `--release-lock=<owner-uuid> --yes` to release the lock, then retry the import.--Do not run multiple migration tasks at the same time, delete the progress volume, or skip failed records to bypass an error. If you need help, share the error output with sensitive information removed.diff --git a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx b/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdxdeleted file mode 100644index 8696fd927af..00000000000--- a/docs/self-hosting/advanced/elasticsearch-migration.zh-CN.mdx+++ /dev/null@@ -1,158 +0,0 @@-----title: 从 pg_search 迁移到 Elasticsearch-description: 为使用 Docker 和 Neon 的 LobeHub 部署迁移搜索服务。-tags:- - Elasticsearch- - 搜索- - 迁移- - 私有部署------# 从 pg\_search 迁移到 Elasticsearch--如果你通过 Docker 部署 LobeHub,数据库使用 Neon,并且当前搜索依赖 `pg_search`,可以按本文将搜索迁移到 Elasticsearch。请在 Neon 停用你所用实例的 `pg_search` 前完成迁移。--如果你的数据库仍支持 `pg_search`,可以继续使用,无需迁移。迁移只更换搜索服务,聊天记录等原始数据仍保存在原来的数据库中。--## 1. 准备配置--先备份 Neon 数据库,再按[全文搜索配置](/zh/docs/self-hosting/advanced/full-text-search)准备 Elasticsearch。--在服务器上准备迁移使用的 `.env` 文件,填入以下配置。不要把该文件提交到代码仓库。--| 变量 | 设置 |-| ------------------------- | ------------------------------------------ |-| `DATABASE_URL` | 当前 Neon 数据库的直连地址,不使用带 `-pooler` 的连接地址 |-| `DATABASE_DRIVER` | 设为 `node`,使用上面的直连地址 |-| `ES_REINDEX_STATE_DIR` | 设为 `/app/.elasticsearch-reindex`,并按下文挂载进度卷 |-| `KEY_VAULTS_SECRET` | 沿用当前 LobeHub 应用的值,不要重新生成 |-| `ES_URL` | Elasticsearch 地址,必须能从 Docker 容器中访问 |-| `ES_API_KEY` | 有创建索引和读写权限的 API Key |-| `ES_INDEX_NAMESPACE` | 索引前缀,例如 `lobehub`;应用和迁移工具保持一致 |-| `FTS_SEARCH_PROVIDER` | 暂时设为 `pg_search` |-| `FTS_SEARCH_SYNC_ENABLED` | 暂时设为 `false` |--外部 Elasticsearch 服务使用 HTTPS 和 API Key。官方 Compose 的私有网络内置节点使用 `ES_ALLOW_INSECURE_HTTP=true`,无需 API Key;使用该节点时,本文的 `docker run` 命令都需要加上 `--network <Elasticsearch 所在网络名>`。容器中的 `localhost` 不是宿主机地址。--以下命令直接使用官方镜像,数据库连接来自这份配置,不依赖 Compose 内置的 PostgreSQL 服务。在同一个终端执行,并把镜像标签替换为本次部署的版本:--```bash-export LOBE_MIGRATION_IMAGE='lobehub/lobehub:<本次部署的版本标签>'-docker pull "$LOBE_MIGRATION_IMAGE"-docker volume create lobehub-search-state-```--暂停使用应用,执行该版本的数据库迁移,成功后继续:--```bash-docker run --rm --env-file .env \- "$LOBE_MIGRATION_IMAGE" /app/docker.cjs-```--## 2. 导入现有数据--这一步创建搜索索引并导入现有数据:--```bash-docker run --rm --env-file .env \- -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs \- --apply --fresh-run --yes-```--迁移进度保存在 `lobehub-search-state` 数据卷中,请保留该数据卷。只有首次导入使用 `--fresh-run`,中断后重试时去掉这个参数。--检查迁移状态:--```bash-docker run --rm --env-file .env \- -e ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-reindex.cjs --status-```--当状态显示 `ready_for_incremental_sync`、没有失败记录时,继续下一步。--## 3. 启动持续同步--启动同步容器,让后续新增、修改和删除的数据反映到搜索结果中:--```bash-docker run -d --name lobe-fts-search-sync --restart unless-stopped \- --env-file .env \- -e FTS_SEARCH_SYNC_ENABLED=true \- -e MIGRATION_DB=1 \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-elasticsearch-sync.cjs \- --max-steps=8 --interval-seconds=15 --yes-```--查看日志,确认没有报错:--```bash-docker logs --tail 50 lobe-fts-search-sync-```--再执行上一步的状态检查命令。等待队列中的 `pending`、`ready`、`retrying`、`inFlight`、`dead` 和 `revisionLag` 全部为 `0`,再切换搜索。--切换完成后也要保持这个容器运行,否则后续数据变更不会同步到搜索结果。--## 4. 切换搜索--为 LobeHub 应用容器也挂载同一个进度卷:`-v lobehub-search-state:/app/.elasticsearch-reindex`,并设置 `ES_REINDEX_STATE_DIR=/app/.elasticsearch-reindex`。在应用的部署配置中填写相同的 Elasticsearch 连接信息和索引前缀,将 `FTS_SEARCH_PROVIDER` 改为 `elasticsearch`,然后使用同版本镜像重新创建应用容器。只修改迁移用的 `.env` 文件不会自动更新已运行的应用。--搜索一条已有的聊天记录,再新增一条记录并确认稍后能够搜到。两项都正常,且同步容器没有报错,就可以恢复使用。--如果切换后遇到问题,在 Neon 仍支持 `pg_search`、且旧搜索索引尚未清理的情况下,可以将应用的 `FTS_SEARCH_PROVIDER` 改回 `pg_search` 并重新创建应用容器。--## 5. 清理旧搜索--确认 Elasticsearch 搜索和持续同步正常后,将迁移用的 `.env` 中 `FTS_SEARCH_PROVIDER` 也改为 `elasticsearch`,检查并清理旧搜索索引和扩展:--```bash-docker run --rm --env-file .env \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --status-docker run --rm --env-file .env \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-pg-search-cleanup.cjs --apply --yes-```--这一步不会删除聊天记录等原始数据,但完成后不能再直接切回 `pg_search`。请在 Neon 要求停用该扩展的时间前完成。--## 后续更新 LobeHub--保留应用容器的进度卷挂载,使用同一新版本镜像重新创建应用和持续同步容器即可。应用启动时会先执行 PostgreSQL 迁移,再自动更新需要升级的 Elasticsearch 索引并切换搜索;已完成的索引不会重复导入。迁移成功后才启动应用,期间暂时无法使用。--官方 Compose 已让应用与迁移工具共享进度卷。使用自己的 Docker 配置时,两者必须挂载同一个卷;如果首次迁移使用的是已有进度目录,继续挂载该目录,不要换成空卷,并确保应用容器有读写权限。--迁移失败时应用不会启动,请查看应用容器日志并按下面的说明恢复。持续同步容器仍需保持运行,它不会由一次启动迁移替代。--可选的搜索 capture 安装器会在 PostgreSQL 中记录 schema 版本。必须先完成数据库迁移,再安装 capture。旧版本应用不得覆盖更新的 capture 定义;若安装器报告未知或不完整定义,应保持当前版本运行,查明不一致后再重试。升级期间会锁住来源表写入并在同一事务中替换定义,因此单纯升级 capture 不会漏掉变更,也无需因此重建全部索引。已建索引的 tool 消息仍需在所有同步 worker 更新资格规则后,另行进行版本化清理。--对于已有的 Elasticsearch 安装,先更新全部应用和持续同步 worker,再预览 PostgreSQL 中不合格消息的数量,并另行记录 Elasticsearch `messages` alias 中仍有效的 `role=tool` 数量:--```bash-docker run --rm --env-file .env \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-ineligible-message-cleanup.cjs --status-```--全部同步 worker 更新后,再单独安排分批清理;继续挂载同一个卷来保存私有检查点:--```bash-docker run --rm --env-file .env \- -v lobehub-search-state:/app/.elasticsearch-reindex \- "$LOBE_MIGRATION_IMAGE" /app/fts-search-ineligible-message-cleanup.cjs \- --apply --yes --all-workers-upgraded \- --state-file=/app/.elasticsearch-reindex/ineligible-messages.json \- --batch-size=250 --max-batches=10 --delay-ms=1000-```--请保留检查点卷以便恢复,不要在两次运行之间删除它。重跑同一批是安全的:它会分配更新的 Outbox revision,由正常同步 worker 写入带版本围栏的软墓碑,或写入消息当前合格的投影。等待 Outbox 清空且无死信后,确认 Elasticsearch 计数向零下降。此命令不修改 PostgreSQL 消息,也不直接向 Elasticsearch 写入。--## 迁移中断怎么办--保留 `lobehub-search-state` 数据卷。首次手动导入中断时,修正错误后重新执行导入命令,去掉 `--fresh-run`。应用启动时的自动迁移失败,则在修正错误、处理残留锁后重新启动应用容器,它会继续完成回填、追平和切换。--如果提示迁移锁仍被占用,先确认上一次迁移进程已经退出,且它发出的 Elasticsearch 请求已经结束。再运行状态检查命令,找到锁的 owner,将导入命令最后的参数替换为 `--release-lock=<owner-uuid> --yes` 释放锁,然后重试导入。--不要同时启动多个迁移任务,也不要通过删除进度数据卷或跳过失败记录来绕过错误。无法解决时,提供脱敏后的错误输出寻求帮助。diff --git a/docs/self-hosting/advanced/full-text-search.mdx b/docs/self-hosting/advanced/full-text-search.mdxindex cafb36113d0..203c8117f7f 100644--- a/docs/self-hosting/advanced/full-text-search.mdx+++ b/docs/self-hosting/advanced/full-text-search.mdx@@ -1,6 +1,6 @@---title: Full-Text Search-description: Choose and operate the pg_search or Elasticsearch backend for LobeHub product search.+description: Choose and operate the pg_search, Elasticsearch, or pg_like backend for LobeHub product search.tags:- Full-Text Search- Elasticsearch@@ -13,16 +13,17 @@ tags:LobeHub uses full-text search for product data such as agents, topics, messages, files, knowledgebases, chat groups, and memories. This is separate from the web-search tools that an agent can call.-LobeHub supports two product-search backends:+LobeHub supports three product-search backends:-| Backend | Best fit | Additional operations |-| --------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `pg_search` | A deployment that already runs PostgreSQL with the ParadeDB `pg_search` extension and wants the simplest topology | PostgreSQL maintains the BM25 indexes; no separate search-sync worker is required |-| `elasticsearch` | A deployment that wants a dedicated, independently scalable search service or must leave `pg_search` | Requires an Elasticsearch service (external, or the optional single-node service in the official Docker Compose file), an initial backfill, PostgreSQL change capture, and a continuously scheduled incremental consumer |+| Backend | Best fit | Additional operations |+| --------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `pg_search` | A deployment that already runs PostgreSQL with the ParadeDB `pg_search` extension and wants the simplest topology | PostgreSQL maintains the BM25 indexes; no separate search-sync worker is required |+| `elasticsearch` | A larger deployment that needs BM25 search quality and can operate a dedicated search service and persistent sync job | Requires an Elasticsearch service (external, or the optional single-node service in the official Docker Compose file), an initial backfill, PostgreSQL change capture, and a continuously scheduled incremental consumer |+| `pg_like` | A personal or small deployment on plain PostgreSQL that does not want to run Elasticsearch | None; substring matching runs directly against the existing tables without extensions, indexes, or sync workers |`FTS_SEARCH_PROVIDER` selects one backend for the whole deployment. The accepted values are-`pg_search` and `elasticsearch`; the default is `pg_search`. LobeHub does not silently fall back to-the other backend when the selected provider is unavailable.+`pg_search`, `elasticsearch`, and `pg_like`; the default is `pg_search`. LobeHub does not silently+fall back to another backend when the selected provider is unavailable.<Callout type="warning">`FTS_SEARCH_PROVIDER=elasticsearch` does not make historical database migrations skip@@ -49,20 +50,46 @@ migrations to install the extension and the LobeHub-managed BM25 indexes, then kFTS_SEARCH_PROVIDER=pg_search```+### Use `pg_like` on plain PostgreSQL++Choose `pg_like` when your PostgreSQL service cannot install `pg_search` (many managed providers) and+the deployment is small enough that a dedicated search service is not worth operating. It needs no+extension, no additional index, and no sync worker: every search runs as case-insensitive substring+matching (`ILIKE`) over the same tables and permission scopes as `pg_search`.++```bash+FTS_SEARCH_PROVIDER=pg_like+```++What to expect compared with the other backends:++- **Matching.** A row matches when every word of the query appears in one searchable field. There is+ no stemming, no typo tolerance, and no phrase proximity. Chinese, Japanese, and Korean text works+ without segmentation because matching is substring based.+- **Ranking.** Results are ordered by a simple relevance score: a whole-field match ranks above a+ prefix match, which ranks above a phrase match, which ranks above rows that merely contain every+ word; title-like fields weigh more than body text.+- **Performance.** Queries scan the scoped rows instead of using a search index. This is fine for+ personal and small-team instances; for large message or memory tables, prefer `pg_search` or+ Elasticsearch.++The same migration limitation as Elasticsearch applies: `pg_like` does not remove the historical+`pg_search` migrations, so a fresh database still has to run on an image that provides the+extension until those migrations become optional.+### Use ElasticsearchChoose Elasticsearch when search needs independent capacity, when you want to separate search-storage from transactional PostgreSQL, or when your PostgreSQL provider is ending `pg_search`-support.--Neon stopped offering `pg_search` to new projects on March 19, 2026. Neon has notified affected-existing customers that the extension will be removed on September 21, 2026; queries, indexes, and-applications that still depend on it will stop working after removal. Existing LobeHub deployments-on Neon should complete the-[pg\_search to Elasticsearch migration guide](/docs/self-hosting/advanced/elasticsearch-migration)-before that deadline. Check Neon's-[current pg\_search notice](https://neon.com/docs/extensions/pg_search) and-[extension catalog](https://neon.com/docs/extensions/pg-extensions) before acting.+storage from transactional PostgreSQL, and when you can keep a sync job running continuously.+Personal and small deployments whose database provider is ending `pg_search` should consider the+service-free `pg_like` backend first.++Neon stopped offering `pg_search` to new projects on March 19, 2026. Retirement timelines for+existing projects follow the notice Neon sends for that project. LobeHub users who receive such a+notice should use+[Migrate from pg\_search on Neon](/docs/self-hosting/advanced/neon-pg-search-migration) to choose+`pg_like` or Elasticsearch. Check Neon's+[current pg\_search notice](https://neon.com/docs/extensions/pg_search) before acting.There are two supported ways to run Elasticsearch. Both use the same backfill and incrementalsync commands and the same `ES_INDEX_NAMESPACE`; they differ only in how LobeHub reaches the@@ -97,8 +124,8 @@ a PostgreSQL image that can install `pg_search`, such as the bundled `paradedb/pElasticsearch then takes over search traffic after the backfill; the `pg_search` objects can beremoved later with the supported cleanup command.-See [Migrate from pg\_search to Elasticsearch](/docs/self-hosting/advanced/elasticsearch-migration)-for the complete rehearsal, backfill, cutover, and rollback procedure.+See [Migrate from pg\_search on Neon](/docs/self-hosting/advanced/neon-pg-search-migration) for+guidance on choosing a backend and starting the migration.## How Elasticsearch synchronization works@@ -216,7 +243,7 @@ Elastic Cloud path is unchanged: without this variable LobeHub still requires HT| Variable | Purpose || ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `FTS_SEARCH_PROVIDER` | Deployment-wide provider: `pg_search` or `elasticsearch` |+| `FTS_SEARCH_PROVIDER` | Deployment-wide provider: `pg_search`, `elasticsearch`, or `pg_like` || `ES_URL` | Elasticsearch endpoint. HTTPS, or plaintext HTTP only for loopback or, with `ES_ALLOW_INSECURE_HTTP=true`, a private Compose hostname such as `elasticsearch` || `ES_API_KEY` | Elasticsearch API key with index creation, bulk write, refresh, count, alias, and search permissions. Required unless `ES_ALLOW_INSECURE_HTTP=true` || `ES_ALLOW_INSECURE_HTTP` | `true` opts in to plaintext HTTP without an API key for an Elasticsearch node reachable only inside a private container network. Never sends a key over HTTP |diff --git a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx b/docs/self-hosting/advanced/full-text-search.zh-CN.mdxindex a58102e426b..09bd3d8aeb8 100644--- a/docs/self-hosting/advanced/full-text-search.zh-CN.mdx+++ b/docs/self-hosting/advanced/full-text-search.zh-CN.mdx@@ -1,6 +1,6 @@---title: 全文搜索-description: 为 LobeHub 产品搜索选择并运行 pg_search 或 Elasticsearch 后端。+description: 为 LobeHub 产品搜索选择并运行 pg_search、Elasticsearch 或 pg_like 后端。tags:- 全文搜索- Elasticsearch@@ -12,15 +12,16 @@ tags:LobeHub 使用全文搜索检索助手、话题、消息、文件、知识库、群聊和记忆等产品数据。这里的全文搜索与助手可调用的联网搜索工具无关。-LobeHub 支持两种产品搜索后端:+LobeHub 支持三种产品搜索后端:| 后端 | 适用场景 | 额外运维工作 || --------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------ || `pg_search` | PostgreSQL 已支持 ParadeDB `pg_search` 扩展,希望部署结构尽量简单 | BM25 索引由 PostgreSQL 维护,不需要单独运行搜索同步任务 |-| `elasticsearch` | 希望搜索服务独立扩容,或者数据库服务即将停止支持 `pg_search` | 需要 Elasticsearch 服务(外部服务,或官方 Docker Compose 附带的可选单节点服务)、首次全量回填、PostgreSQL 变更采集和持续运行的增量消费任务 |+| `elasticsearch` | 数据量较大、需要 BM25 搜索质量,并且能维护独立搜索服务和常驻同步任务 | 需要 Elasticsearch 服务(外部服务,或官方 Docker Compose 附带的可选单节点服务)、首次全量回填、PostgreSQL 变更采集和持续运行的增量消费任务 |+| `pg_like` | 使用普通 PostgreSQL 的个人或小型自部署,不想再运维 Elasticsearch | 无;直接在现有数据表上做子串匹配,不需要扩展、索引或同步任务 |-`FTS_SEARCH_PROVIDER` 为整个部署选择唯一的后端,可用值为 `pg_search` 和-`elasticsearch`,默认值是 `pg_search`。选中的后端不可用时,LobeHub 不会静默切换到另一个后端。+`FTS_SEARCH_PROVIDER` 为整个部署选择唯一的后端,可用值为 `pg_search`、`elasticsearch` 和+`pg_like`,默认值是 `pg_search`。选中的后端不可用时,LobeHub 不会静默切换到另一个后端。<Callout type="warning">设置 `FTS_SEARCH_PROVIDER=elasticsearch` 不会让历史数据库迁移跳过 `pg_search`。当前@@ -42,16 +43,27 @@ LobeHub 支持两种产品搜索后端:FTS_SEARCH_PROVIDER=pg_search```+### 在普通 PostgreSQL 上使用 `pg_like`++如果 PostgreSQL 服务无法安装 `pg_search`(很多托管数据库都是如此),而部署规模又小到不值得单独运维一套搜索服务,可以选择 `pg_like`。它不需要扩展、不需要额外索引、也不需要同步任务:所有搜索都以不区分大小写的子串匹配(`ILIKE`)直接在与 `pg_search` 相同的数据表和权限范围上执行。++```bash+FTS_SEARCH_PROVIDER=pg_like+```++与其他后端相比需要注意:++- **匹配方式。** 查询中的每个词都出现在同一个可搜索字段里时才算命中;没有词干还原、拼写容错和短语距离。中日韩文本无需分词即可匹配,因为匹配基于子串。+- **排序。** 结果按简单的相关度打分排序:整字段完全匹配高于前缀匹配,前缀匹配高于短语包含,短语包含高于仅包含全部词语;标题类字段的权重高于正文。+- **性能。** 查询会扫描权限范围内的数据行而不是走搜索索引。个人和小团队实例完全够用;消息或记忆表很大时,请优先考虑 `pg_search` 或 Elasticsearch。++迁移限制与 Elasticsearch 相同:`pg_like` 不会移除历史 `pg_search` 迁移,在这些迁移变为可选之前,全新建库仍必须运行在能提供该扩展的镜像上。+### 使用 Elasticsearch-如果搜索需要独立容量、希望把搜索存储从事务 PostgreSQL 中拆开,或者数据库服务即将停止支持-`pg_search`,可以选择 Elasticsearch。+如果搜索需要独立容量、希望把搜索存储从事务 PostgreSQL 中拆开,并且能够持续运行同步任务,可以选择 Elasticsearch。个人或小型部署在数据库停止支持 `pg_search` 时,应优先考虑无需额外服务的 `pg_like`。-Neon 已于 2026 年 3 月 19 日停止为新项目提供 `pg_search`,并已通知受影响的现有客户:该扩展将在-2026 年 9 月 21 日从 Neon 移除,此后依赖它的查询、索引和应用都会停止工作。已经在 Neon 上运行 LobeHub 的用户应在截止日期前完成-[从 pg\_search 迁移到 Elasticsearch](/zh/docs/self-hosting/advanced/elasticsearch-migration)。执行前请同时核对 Neon 的-[最新 pg\_search 公告](https://neon.com/docs/extensions/pg_search)和-[扩展列表](https://neon.com/docs/extensions/pg-extensions)。+Neon 已于 2026 年 3 月 19 日停止为新项目提供 `pg_search`。现有项目的停用安排以 Neon 发给该项目的通知为准;收到停用通知的 LobeHub 用户应按 [Neon pg\_search 迁移指南](/zh/docs/self-hosting/advanced/neon-pg-search-migration)选择 `pg_like` 或 Elasticsearch。执行前请核对 Neon 的[最新 pg\_search 公告](https://neon.com/docs/extensions/pg_search)。Elasticsearch 有两种受支持的运行方式。两者使用同一套回填和增量同步命令、同一个`ES_INDEX_NAMESPACE`,区别只在于 LobeHub 如何连接集群。@@ -81,8 +93,7 @@ Compose 安装)仍必须运行在能够安装 `pg_search` 的 PostgreSQL 镜`paradedb/paradedb:latest-pg17`。回填完成后由 Elasticsearch 接管搜索流量;`pg_search`相关对象可以之后通过项目提供的清理命令移除。-完整的演练、回填、切换和回滚流程,请参阅-[从 pg\_search 迁移到 Elasticsearch](/zh/docs/self-hosting/advanced/elasticsearch-migration)。+选择建议和迁移入口,请参阅 [Neon pg\_search 迁移指南](/zh/docs/self-hosting/advanced/neon-pg-search-migration)。## Elasticsearch 如何同步数据@@ -188,7 +199,7 @@ Cloud,请不要在 `COMPOSE_PROFILES` 中启用 `elasticsearch` profile,在| 变量 | 用途 || ------------------------- | ----------------------------------------------------------------------------------------------------------------- |-| `FTS_SEARCH_PROVIDER` | 整个部署使用的搜索后端:`pg_search` 或 `elasticsearch` |+| `FTS_SEARCH_PROVIDER` | 整个部署使用的搜索后端:`pg_search`、`elasticsearch` 或 `pg_like` || `ES_URL` | Elasticsearch 地址。使用 HTTPS;明文 HTTP 只允许用于回环地址,或在 `ES_ALLOW_INSECURE_HTTP=true` 时用于 `elasticsearch` 这类 Compose 内部主机名 || `ES_API_KEY` | 具备建索引、批量写入、刷新、统计、别名和搜索权限的 Elasticsearch 密钥;除 `ES_ALLOW_INSECURE_HTTP=true` 外均为必需 || `ES_ALLOW_INSECURE_HTTP` | 设为 `true` 时显式允许对只能在私有容器网络访问的 Elasticsearch 节点使用无 API 密钥的明文 HTTP;永远不会通过 HTTP 发送密钥 |diff --git a/docs/self-hosting/advanced/neon-pg-search-migration.mdx b/docs/self-hosting/advanced/neon-pg-search-migration.mdxnew file mode 100644index 00000000000..36b69cf93ff--- /dev/null+++ b/docs/self-hosting/advanced/neon-pg-search-migration.mdx@@ -0,0 +1,83 @@+---+title: Migrate from pg_search on Neon+description: Choose pg_like or Elasticsearch when Neon retires pg_search for a self-hosted deployment.+tags:+ - pg_search+ - pg_like+ - Elasticsearch+ - Migration+ - Self-hosting+---++# Migrate from pg\_search on Neon++According to [Neon's `pg_search` notice](https://neon.com/docs/extensions/pg_search), Neon no longer offers the extension to new projects. If Neon has notified you that `pg_search` will also be retired from an existing project, complete this guide before the deadline in that notice. Timelines can differ between projects, so use the notice sent for your project. This migration changes only the search backend; source data such as chat history remains in the existing PostgreSQL database.++This guide is for an existing LobeHub instance that has already applied the historical database migrations. For a new database, first read the database limitations in [Full-Text Search](/docs/self-hosting/advanced/full-text-search).++## 1. Check whether you need to migrate++| Current setup | Action |+| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |+| Neon or another database provider has told you that it will retire `pg_search` | Continue to the next step |+| PostgreSQL still supports `pg_search` | Keep the current provider; no migration is required |+| `FTS_SEARCH_PROVIDER=pg_like` or `elasticsearch` is already set | No migration is required because search no longer depends on `pg_search` |++<Callout type="info">+ Docker and Vercel describe how the LobeHub application is deployed; they do not determine whether the database supports `pg_search`. A Docker deployment can still use Neon, and a deployment built on GitHub and uploaded to Vercel can still change its search backend. Check the database referenced by `DATABASE_URL`.+</Callout>++The official Docker Compose setup uses a ParadeDB database that supports `pg_search`. If you use that bundled database and have not been asked to retire the extension, keep the default configuration and do not migrate.++## 2. Choose a migration path++| Path | Best fit | Additional services |+| ----------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------ |+| `pg_like` (recommended) | Personal and small self-hosted deployments, including Vercel or Docker applications connected to Neon | None |+| Elasticsearch | Larger datasets that need BM25 search quality and can operate a persistent sync job | Elasticsearch and a continuous sync worker |++Most personal deployments should use `pg_like`. It searches the existing PostgreSQL data directly, so there is no data copy, search-index build, or sync job.++Elastic Cloud and Docker Elasticsearch are the same search backend in different locations. Both require an initial import and a continuously running sync worker, so they use the same migration flow.++<Callout type="warning">+ The current LobeHub Elasticsearch sync worker is a persistent process and cannot run as-is inside a Vercel-only deployment. Choose `pg_like` unless you also operate a persistent server for that worker.+</Callout>++## 3. Migrate to pg\_like (recommended)++1. **Upgrade and back up.** Upgrade LobeHub to a version that includes `pg_like`, then create a backup using your database provider's normal process.++2. **Select the backend and redeploy.** Add this environment variable:++ ```bash+ FTS_SEARCH_PROVIDER=pg_like+ ```++ - **Vercel:** add the variable under the project's Environment Variables, then redeploy Production. This also applies when GitHub builds the application before it is uploaded to Vercel.++ - **Docker Compose:** add the variable to `.env`, then recreate the LobeHub container:++ ```bash+ docker compose up -d --force-recreate lobe+ ```++ - **Other platforms:** add the variable to the application's runtime environment, then redeploy through the existing release workflow.++3. **Verify search.** Search for an existing topic or message. Then send a new message with a distinctive keyword and search for it. The migration is complete when both results appear.++`pg_like` does not import or synchronize data. After verification, LobeHub search no longer calls the `pg_search` extension even if the database provider removes it later.++To roll back while the database still supports `pg_search`, restore `FTS_SEARCH_PROVIDER=pg_search` and redeploy. Do not run `DROP EXTENSION ... CASCADE` manually. Follow the database provider's notice or use the LobeHub cleanup tooling when old extension objects need to be removed.++## 4. Migrate to Elasticsearch (advanced)++Choose Elasticsearch only when the dataset or search-quality requirements exceed `pg_like` and you can keep a sync worker running continuously.++1. **Choose where Elasticsearch runs.** Docker users can enable the single-node service in the official Compose file, or use an external service such as Elastic Cloud.+2. **Import and synchronize.** Follow [Full-Text Search: Run Elasticsearch with Docker Compose](/docs/self-hosting/advanced/full-text-search#run-elasticsearch-with-docker-compose) to import existing data and start the continuous sync worker. For Elastic Cloud, omit the bundled Elasticsearch node and set `ES_URL` and `ES_API_KEY`; the remaining steps are the same.+3. **Switch and verify.** After the incremental queue reaches zero, set `FTS_SEARCH_PROVIDER=elasticsearch`, redeploy the application, then search for both an existing message and a new message.++If LobeHub runs on Vercel, the current migration and sync worker must run on a persistent host outside Vercel. Whether Elasticsearch itself runs in Elastic Cloud or Docker does not change that requirement.++See [Full-Text Search](/docs/self-hosting/advanced/full-text-search) for configuration, resource requirements, and recovery guidance.diff --git a/docs/self-hosting/advanced/neon-pg-search-migration.zh-CN.mdx b/docs/self-hosting/advanced/neon-pg-search-migration.zh-CN.mdxnew file mode 100644index 00000000000..c69deef2641--- /dev/null+++ b/docs/self-hosting/advanced/neon-pg-search-migration.zh-CN.mdx@@ -0,0 +1,83 @@+---+title: Neon pg_search 迁移指南+description: Neon 停用 pg_search 后,为个人自部署选择 pg_like 或 Elasticsearch。+tags:+ - pg_search+ - pg_like+ - Elasticsearch+ - 迁移+ - 私有部署+---++# Neon pg\_search 迁移指南++根据 [Neon 的 `pg_search` 公告](https://neon.com/docs/extensions/pg_search),Neon 已停止为新项目提供该扩展。如果 Neon 通知你的现有项目也将停用 `pg_search`,请在通知中的截止日期前完成迁移;不同项目的时间可能不同,请以 Neon 发给你的通知为准。迁移只更换搜索后端,聊天记录等原始数据仍保存在原来的 PostgreSQL 数据库中。++本文面向已经运行 LobeHub、并且已经完成历史数据库迁移的现有实例。新建数据库请先阅读[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)中的数据库限制。++## 1. 确认是否需要迁移++| 当前情况 | 是否需要迁移 |+| --------------------------------------------------- | ----------------------- |+| Neon 或其他数据库服务已通知将停用 `pg_search` | 需要,继续下一步 |+| PostgreSQL 仍支持 `pg_search` | 不需要,可以继续使用 |+| 已设置 `FTS_SEARCH_PROVIDER=pg_like` 或 `elasticsearch` | 不需要,当前搜索不依赖 `pg_search` |++<Callout type="info">+ Docker 和 Vercel 是 LobeHub 的部署方式,不决定数据库是否支持 `pg_search`。Docker 部署也可能连接 Neon;通过 GitHub 构建并上传到 Vercel 的部署也可以更换搜索后端。请以 `DATABASE_URL` 指向的数据库为准。+</Callout>++官方 Docker Compose 默认使用支持 `pg_search` 的 ParadeDB。如果你使用这套内置数据库,并且数据库服务没有要求停用扩展,可以保持默认配置,不需要迁移。++## 2. 选择迁移方案++| 方案 | 适合谁 | 额外服务 |+| ------------- | ------------------------------------- | -------------------------- |+| `pg_like`(推荐) | 个人和小型自部署,包括 Vercel 或 Docker 应用连接 Neon | 无 |+| Elasticsearch | 数据量较大、需要 BM25 搜索质量,并且能维护常驻同步任务 | Elasticsearch 和持续同步 worker |++大多数个人自部署应选择 `pg_like`。它直接搜索现有 PostgreSQL 数据,不需要复制数据、创建搜索索引或运行同步任务。++Elastic Cloud 和 Docker Elasticsearch 是同一种搜索后端,只是 Elasticsearch 的运行位置不同。两者都需要先导入历史数据,并持续运行同步 worker;其余迁移步骤相同。++<Callout type="warning">+ 当前 LobeHub 的 Elasticsearch 同步 worker 是常驻进程,纯 Vercel 部署无法直接运行它。除非你另外准备了常驻服务器,否则请选择 `pg_like`。+</Callout>++## 3. 迁移到 pg\_like(推荐)++1. **升级并备份。** 将 LobeHub 升级到包含 `pg_like` 的版本,并按数据库服务的说明创建备份。++2. **设置搜索后端并重新部署。** 添加下面的环境变量:++ ```bash+ FTS_SEARCH_PROVIDER=pg_like+ ```++ - **Vercel:** 在项目的 Environment Variables 中添加变量,然后重新部署 Production。使用 GitHub 构建后上传到 Vercel 的部署也执行这一步。++ - **Docker Compose:** 在 `.env` 中添加变量,然后重新创建 LobeHub 容器:++ ```bash+ docker compose up -d --force-recreate lobe+ ```++ - **其他部署方式:** 在应用的运行环境中添加变量,再按原来的发布流程重新部署。++3. **验证搜索。** 搜索一条已有的话题或消息,再发送一条包含独特关键词的新消息并搜索它。两项都能找到即迁移完成。++`pg_like` 不需要导入或同步数据。确认搜索正常后,即使数据库随后移除 `pg_search`,LobeHub 搜索也不会再调用该扩展。++如果需要回滚,并且数据库仍支持 `pg_search`,将环境变量改回 `FTS_SEARCH_PROVIDER=pg_search` 后重新部署即可。不要手动执行 `DROP EXTENSION ... CASCADE`;旧扩展和索引的清理由数据库服务通知或 LobeHub 提供的清理工具处理。++## 4. 迁移到 Elasticsearch(高级)++只有在 `pg_like` 无法满足数据量或搜索质量要求,并且你能持续运行同步 worker 时,才选择 Elasticsearch。++1. **选择 Elasticsearch 的运行位置。** Docker 用户可以启用官方 Compose 中的单节点 Elasticsearch;也可以使用 Elastic Cloud 等外部服务。+2. **导入并同步。** 按[全文搜索:使用 Docker Compose 运行 Elasticsearch](/zh/docs/self-hosting/advanced/full-text-search#使用-docker-compose-运行-elasticsearch)完成历史数据导入,并启动持续同步 worker。使用 Elastic Cloud 时不启动内置 Elasticsearch 节点,只需填写 `ES_URL` 和 `ES_API_KEY`;其余步骤相同。+3. **切换并验证。** 等待增量队列归零后,将应用设置为 `FTS_SEARCH_PROVIDER=elasticsearch`,重新部署,再分别搜索已有消息和新消息。++如果 LobeHub 部署在 Vercel,当前的迁移和同步 worker 必须运行在 Vercel 之外的常驻服务器上。Elasticsearch 服务本身在 Elastic Cloud 还是 Docker 中运行,不改变这一要求。++更多配置、资源要求和故障恢复说明见[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)。diff --git a/docs/self-hosting/migration/v2/breaking-changes.mdx b/docs/self-hosting/migration/v2/breaking-changes.mdxindex e37d9937d17..9772d0fb05e 100644--- a/docs/self-hosting/migration/v2/breaking-changes.mdx+++ b/docs/self-hosting/migration/v2/breaking-changes.mdx@@ -78,10 +78,11 @@ LobeHub 2.0 recommends using **PostgreSQL 17** or higher.LobeHub 2.0 introduced the [pg\_search](https://github.com/paradedb/paradedb/tree/main/pg_search)extension for full-text search. When 2.0 shipped, Neon provided it to new PostgreSQL 17 projects.-Neon has since stopped offering `pg_search` to new projects and has notified affected existing-customers that the extension will be removed on September 21, 2026. Existing Neon deployments+Neon has since stopped offering `pg_search` to new projects. Retirement timelines for existing+projects follow the notice Neon sends for each project. LobeHub users who receive such a noticeshould complete-[Migrate from pg\_search to Elasticsearch](/docs/self-hosting/advanced/elasticsearch-migration).+[Migrate from pg\_search on Neon](/docs/self-hosting/advanced/neon-pg-search-migration) before the+deadline in that notice.See [Full-Text Search](/docs/self-hosting/advanced/full-text-search) before choosing the searchbackend for a current deployment.diff --git a/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx b/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdxindex b86ef6572d2..7985fc920a6 100644--- a/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx+++ b/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx@@ -76,8 +76,8 @@ LobeHub 2.0 推荐使用 **PostgreSQL 17** 及以上版本。LobeHub 2.0 引入了 [pg\_search](https://github.com/paradedb/paradedb/tree/main/pg_search)扩展来提供全文搜索。当 2.0 发布时,Neon 会为新的 PostgreSQL 17 项目提供该扩展。此后 Neon 已停止为新项目提供-`pg_search`,并已通知受影响的现有客户:该扩展将在 2026 年 9 月 21 日移除。现有 Neon 部署应在截止日期前完成-[从 pg\_search 迁移到 Elasticsearch](/zh/docs/self-hosting/advanced/elasticsearch-migration)。当前部署在选择搜索后端前,请先阅读+`pg_search`。现有项目的停用安排以 Neon 发给该项目的通知为准;收到停用通知的 LobeHub 用户应在通知中的截止日期前完成+[Neon pg\_search 迁移](/zh/docs/self-hosting/advanced/neon-pg-search-migration)。当前部署在选择搜索后端前,请先阅读[全文搜索](/zh/docs/self-hosting/advanced/full-text-search)。如果您使用 Docker 自建数据库,推荐使用 `paradedb/paradedb:latest-pg17` 镜像。diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 227d9d1da0d..1b2d35150cf 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -14,6 +14,7 @@ import { agentOperations } from '../schemas/agentOperations';import type { NewVerifyRun, VerifyRunItem } from '../schemas/verify';import { verifyCheckResults, verifyRuns } from '../schemas/verify';import type { LobeChatDatabase } from '../type';+import { escapeLike } from '../utils/like';import { isUuid } from '../utils/uuid';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { VerifyCriterionModel } from './verifyCriterion';@@ -50,9 +51,6 @@ const decodeCursor = (cursor?: string): { createdAt: Date; id: string } | null =return { createdAt, id };};-/** Escape LIKE/ILIKE metacharacters (`\ % _`) so user input matches literally. */-const escapeLike = (value: string): string => value.replaceAll(/[\\%_]/g, (c) => `\\${c}`);-const toState = (run: VerifyRunItem | null | undefined): VerifyRunState | null =>run? {diff --git a/packages/database/src/models/workspaceMember.ts b/packages/database/src/models/workspaceMember.tsindex e5282b39c23..70408e8bc6a 100644--- a/packages/database/src/models/workspaceMember.ts+++ b/packages/database/src/models/workspaceMember.ts@@ -9,6 +9,7 @@ import { tasks } from '../schemas/task';import { users } from '../schemas/user';import { workspaceInvitations, workspaceMembers } from '../schemas/workspace';import type { LobeChatDatabase } from '../type';+import { ilikeContains as containsIgnoreCase } from '../utils/like';import { ResourcePermissionModel } from './resourcePermission';type MemberRole = 'admin' | 'member' | 'viewer';@@ -20,10 +21,6 @@ const ASSIGNABLE_MEMBER_ROLES = (['owner', 'admin', 'member', 'viewer'] as constcanWorkspaceRoleBeTaskAssignee(role),);-const escapeLike = (value: string): string => value.replaceAll(/[\\%_]/g, (c) => `\\${c}`);-const containsIgnoreCase = (column: unknown, needle: string) =>- sql<boolean>`${column} ILIKE ${`%${escapeLike(needle)}%`} ESCAPE '\\'`;-export class WorkspaceMemberModel {private readonly db: LobeChatDatabase;private readonly userId: string;diff --git a/packages/database/src/repositories/ftsSearch/__tests__/productSearchBehavior.ts b/packages/database/src/repositories/ftsSearch/__tests__/productSearchBehavior.tsnew file mode 100644index 00000000000..a90f93113aa--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/__tests__/productSearchBehavior.ts@@ -0,0 +1,1735 @@+import { eq } from 'drizzle-orm';+import { beforeEach, describe, expect, it } from 'vitest';++import { chatGroups, documents, workspaces } from '../../../schemas';+import type { NewAgent } from '../../../schemas/agent';+import { agents } from '../../../schemas/agent';+import type { NewFile } from '../../../schemas/file';+import {+ DOCUMENT_FOLDER_TYPE,+ files,+ knowledgeBaseFiles,+ knowledgeBases,+} from '../../../schemas/file';+import { messages } from '../../../schemas/message';+import type { NewTopic } from '../../../schemas/topic';+import { topics } from '../../../schemas/topic';+import { users } from '../../../schemas/user';+import type { LobeChatDatabase } from '../../../type';+import type { FtsSearchRepo, FtsSearchResult } from '../index';++export const userId = 'search-test-user';+export const otherUserId = 'other-search-user';++/**+ * Result types produced by the eight search methods whose BM25 scan was split+ * into an inner subquery. `memory` is absent on purpose — `searchMemories` is+ * user-scoped with no join, so it was left on its original single-level shape.+ */+const REWRITTEN_RESULT_TYPES = [+ 'agent',+ 'chatGroup',+ 'file',+ 'folder',+ 'knowledgeBase',+ 'message',+ 'page',+ 'topic',+] as const;++export interface FtsSearchProductBehaviorOptions {+ /** Builds the repo under test for a given scope. */+ createRepo: (+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ callerAgentVisibility?: 'private' | 'public' | null,+ ) => FtsSearchRepo;+ db: LobeChatDatabase;+}++/**+ * Provider-neutral product-search behaviour, registered as a nested suite so any+ * FTS backend (pg_search, Elasticsearch, …) can be held to the same+ * expectations. Provider-specific guards (emitted SQL shape, index mappings)+ * stay in the caller's own test file.+ */+export const describeFtsSearchProductBehavior = (options: FtsSearchProductBehaviorOptions) => {+ const { createRepo } = options;+ const serverDB = options.db;++ let ftsSearchRepo: FtsSearchRepo;++ beforeEach(async () => {+ // Clean up+ await serverDB.delete(users);++ // Create test users+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);++ // Initialize repo+ ftsSearchRepo = createRepo(serverDB, userId);+ });++ describe('search - empty query', () => {+ it('should return empty array for empty query', async () => {+ const results = await ftsSearchRepo.search({ query: '' });+ expect(results).toEqual([]);+ });++ it('should return empty array for whitespace query', async () => {+ const results = await ftsSearchRepo.search({ query: ' ' });+ expect(results).toEqual([]);+ });+ });++ describe('search - basic search', () => {+ beforeEach(async () => {+ // Create test agents+ const testAgents: NewAgent[] = [+ {+ description: 'A helpful React coding assistant',+ slug: 'react-helper',+ tags: ['react', 'frontend', 'coding'],+ title: 'React Helper',+ userId,+ },+ {+ description: 'Python development assistant',+ slug: 'python-dev',+ tags: ['python', 'backend'],+ title: 'Python Developer',+ userId,+ },+ ];+ await serverDB.insert(agents).values(testAgents);++ // Create test topics+ const testTopics: NewTopic[] = [+ {+ content: 'Discussion about React hooks and best practices',+ title: 'React Hooks Guide',+ userId,+ },+ {+ content: 'Notes on Python async programming',+ title: 'Python Async Notes',+ userId,+ },+ ];+ await serverDB.insert(topics).values(testTopics);++ // Create test files+ const testFiles: NewFile[] = [+ {+ fileType: 'application/javascript',+ name: 'react-component.jsx',+ size: 1024,+ url: 'file://react-component.jsx',+ userId,+ },+ {+ fileType: 'text/python',+ name: 'python-script.py',+ size: 2048,+ url: 'file://python-script.py',+ userId,+ },+ ];+ await serverDB.insert(files).values(testFiles);+ });++ it('should find agents by title', async () => {+ const results = await ftsSearchRepo.search({ query: 'React Helper' });++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults).toHaveLength(1);+ expect(agentResults[0].title).toBe('React Helper');+ });++ it('should find topics by title', async () => {+ const results = await ftsSearchRepo.search({ query: 'React Hooks' });++ const topicResults = results.filter((r) => r.type === 'topic');+ expect(topicResults).toHaveLength(1);+ expect(topicResults[0].title).toBe('React Hooks Guide');+ });++ // Note: ICU tokenizer treats "react-component.jsx" as a single token,+ // so we search by prefix "react" which matches via BM25+ it('should find files by name', async () => {+ const results = await ftsSearchRepo.search({ query: 'react' });++ const fileResults = results.filter((r) => r.type === 'file');+ expect(fileResults).toHaveLength(1);+ expect(fileResults[0].title).toBe('react-component.jsx');+ });++ it('should find results across all types', async () => {+ const results = await ftsSearchRepo.search({ query: 'react' });++ // Should find: 1 agent, 1 topic, 1 file+ expect(results.length).toBeGreaterThanOrEqual(3);++ const types = new Set(results.map((r) => r.type));+ expect(types.has('agent')).toBe(true);+ expect(types.has('topic')).toBe(true);+ expect(types.has('file')).toBe(true);+ });++ it('should search in agent description', async () => {+ const results = await ftsSearchRepo.search({ query: 'coding assistant' });++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBeGreaterThanOrEqual(1);+ expect(agentResults[0].description).toContain('coding');+ });++ it('should search in topic content', async () => {+ const results = await ftsSearchRepo.search({ query: 'async programming' });++ const topicResults = results.filter((r) => r.type === 'topic');+ expect(topicResults.length).toBeGreaterThanOrEqual(1);+ expect(topicResults[0].description).toContain('async');+ });++ it('should search in agent tags', async () => {+ const results = await ftsSearchRepo.search({ query: 'frontend' });++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBeGreaterThanOrEqual(1);+ expect(agentResults[0].tags).toContain('frontend');+ });+ });++ describe('search - relevance ranking', () => {+ beforeEach(async () => {+ const testAgents: NewAgent[] = [+ {+ slug: 'exact',+ title: 'test',+ userId,+ },+ {+ slug: 'prefix',+ title: 'testing',+ userId,+ },+ {+ slug: 'contains',+ title: 'my test agent',+ userId,+ },+ ];+ await serverDB.insert(agents).values(testAgents);+ });++ it('should assign relevance values in valid range', async () => {+ const results = await ftsSearchRepo.search({ query: 'test' });++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBe(3);++ // All relevance values should be in [1, 3] range+ for (const result of agentResults) {+ expect(result.relevance).toBeGreaterThanOrEqual(1);+ expect(result.relevance).toBeLessThanOrEqual(3);+ }+ });++ it('should rank results by BM25 relevance (lower = better)', async () => {+ const results = await ftsSearchRepo.search({ query: 'test' });++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBe(3);++ // Best match should have lowest relevance value+ expect(agentResults[0].relevance).toBeLessThanOrEqual(agentResults[1].relevance);+ expect(agentResults[1].relevance).toBeLessThanOrEqual(agentResults[2].relevance);+ });+ });++ describe('search - user isolation', () => {+ beforeEach(async () => {+ // Create agent for current user+ await serverDB.insert(agents).values({+ slug: 'user-agent',+ title: 'User Agent',+ userId,+ });++ // Create agent for other user+ await serverDB.insert(agents).values({+ slug: 'other-agent',+ title: 'Other Agent',+ userId: otherUserId,+ });++ // Create topic for current user+ await serverDB.insert(topics).values({+ title: 'User Topic',+ userId,+ });++ // Create topic for other user+ await serverDB.insert(topics).values({+ title: 'Other Topic',+ userId: otherUserId,+ });++ // Create file for current user+ await serverDB.insert(files).values({+ fileType: 'text/plain',+ name: 'user-file.txt',+ size: 100,+ url: 'file://user-file.txt',+ userId,+ });++ // Create file for other user+ await serverDB.insert(files).values({+ fileType: 'text/plain',+ name: 'other-file.txt',+ size: 100,+ url: 'file://other-file.txt',+ userId: otherUserId,+ });+ });++ it('should only return current user results', async () => {+ const results = await ftsSearchRepo.search({ query: 'agent' });++ expect(results.length).toBeGreaterThan(0);++ // All results should be from current user+ results.forEach((result) => {+ expect(result.title).not.toContain('Other');+ });+ });++ it('should not return other user agents', async () => {+ const results = await ftsSearchRepo.search({ query: 'agent' });++ const otherAgent = results.find((r) => r.title === 'Other Agent');+ expect(otherAgent).toBeUndefined();+ });++ it('should not return other user topics', async () => {+ const results = await ftsSearchRepo.search({ query: 'topic' });++ const otherTopic = results.find((r) => r.title === 'Other Topic');+ expect(otherTopic).toBeUndefined();+ });++ it('should not return other user files', async () => {+ const results = await ftsSearchRepo.search({ query: 'file' });++ const otherFile = results.find((r) => r.title === 'other-file.txt');+ expect(otherFile).toBeUndefined();+ });+ });++ describe('search - type filtering', () => {+ beforeEach(async () => {+ await serverDB.insert(agents).values({+ slug: 'test-agent',+ title: 'Test Agent',+ userId,+ });++ await serverDB.insert(topics).values({+ title: 'Test Topic',+ userId,+ });++ await serverDB.insert(files).values({+ fileType: 'text/plain',+ name: 'test-file.txt',+ size: 100,+ url: 'file://test-file.txt',+ userId,+ });+ });++ it('should filter by agent type', async () => {+ const results = await ftsSearchRepo.search({ query: 'test', type: 'agent' });++ expect(results.length).toBeGreaterThan(0);+ results.forEach((result) => {+ expect(result.type).toBe('agent');+ });+ });++ it('should filter by topic type', async () => {+ const results = await ftsSearchRepo.search({ query: 'test', type: 'topic' });++ expect(results.length).toBeGreaterThan(0);+ results.forEach((result) => {+ expect(result.type).toBe('topic');+ });+ });++ it('should filter by file type', async () => {+ const results = await ftsSearchRepo.search({ query: 'test', type: 'file' });++ expect(results.length).toBeGreaterThan(0);+ results.forEach((result) => {+ expect(result.type).toBe('file');+ });+ });+ });++ describe('search - limit per type', () => {+ beforeEach(async () => {+ // Create 10 agents+ const testAgents: NewAgent[] = Array.from({ length: 10 }, (_, i) => ({+ slug: `agent-${i}`,+ title: `Test Agent ${i}`,+ userId,+ }));+ await serverDB.insert(agents).values(testAgents);+ });++ it('should respect default limit of 5 per type', async () => {+ const results = await ftsSearchRepo.search({ query: 'test' });++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBeLessThanOrEqual(5);+ });++ it('should respect custom limit per type', async () => {+ const results = await ftsSearchRepo.search({ limitPerType: 3, query: 'test' });++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBeLessThanOrEqual(3);+ });+ });++ describe('search - case insensitivity', () => {+ beforeEach(async () => {+ await serverDB.insert(agents).values({+ description: 'React Development Assistant',+ slug: 'react-agent',+ title: 'React Agent',+ userId,+ });+ });++ it('should search case-insensitively', async () => {+ const upperResults = await ftsSearchRepo.search({ query: 'REACT' });+ const lowerResults = await ftsSearchRepo.search({ query: 'react' });+ const mixedResults = await ftsSearchRepo.search({ query: 'ReAcT' });++ expect(upperResults.length).toBeGreaterThan(0);+ expect(lowerResults.length).toBeGreaterThan(0);+ expect(mixedResults.length).toBeGreaterThan(0);++ // All should return the same agent+ expect(upperResults[0].id).toBe(lowerResults[0].id);+ expect(lowerResults[0].id).toBe(mixedResults[0].id);+ });+ });++ describe('search - result structure', () => {+ beforeEach(async () => {+ await serverDB.insert(agents).values({+ avatar: 'avatar-url',+ backgroundColor: '#ff0000',+ description: 'Test description',+ slug: 'test-agent',+ tags: ['tag1', 'tag2'],+ title: 'Test Agent',+ userId,+ });++ await serverDB.insert(topics).values({+ content: 'Test content',+ favorite: true,+ title: 'Test Topic',+ userId,+ });++ await serverDB.insert(files).values({+ fileType: 'text/plain',+ name: 'test report',+ size: 100,+ url: 'file://test-report',+ userId,+ });+ });++ it('should return correct agent result structure', async () => {+ const results = await ftsSearchRepo.search({ query: 'test', type: 'agent' });++ expect(results.length).toBeGreaterThan(0);+ const agent = results[0];++ expect(agent.type).toBe('agent');+ expect(agent.id).toBeDefined();+ expect(agent.title).toBeDefined();+ expect(agent.relevance).toBeGreaterThan(0);+ expect(agent.createdAt).toBeInstanceOf(Date);+ expect(agent.updatedAt).toBeInstanceOf(Date);++ if (agent.type === 'agent') {+ expect(agent.slug).toBeDefined();+ expect(agent.tags).toBeInstanceOf(Array);+ }+ });++ it('should return correct topic result structure', async () => {+ const results = await ftsSearchRepo.search({ query: 'test', type: 'topic' });++ expect(results.length).toBeGreaterThan(0);+ const topic = results[0];++ expect(topic.type).toBe('topic');+ expect(topic.id).toBeDefined();+ expect(topic.title).toBeDefined();+ expect(topic.relevance).toBeGreaterThan(0);+ expect(topic.createdAt).toBeInstanceOf(Date);+ expect(topic.updatedAt).toBeInstanceOf(Date);++ if (topic.type === 'topic') {+ expect(topic.favorite).toBeDefined();+ }+ });++ it('should return correct file result structure', async () => {+ const results = await ftsSearchRepo.search({ query: 'test', type: 'file' });++ expect(results.length).toBeGreaterThan(0);+ const file = results[0];++ expect(file.type).toBe('file');+ expect(file.id).toBeDefined();+ expect(file.title).toBeDefined();+ expect(file.relevance).toBeGreaterThan(0);+ expect(file.createdAt).toBeInstanceOf(Date);+ expect(file.updatedAt).toBeInstanceOf(Date);++ if (file.type === 'file') {+ expect(file.name).toBeDefined();+ expect(file.fileType).toBeDefined();+ expect(file.size).toBeGreaterThanOrEqual(0);+ }+ });+ });++ describe('search - agent context awareness', () => {+ let testAgentId: string;+ let otherAgentId: string;++ beforeEach(async () => {+ // Create test agents+ const [agent1, agent2] = await serverDB+ .insert(agents)+ .values([+ {+ slug: 'test-agent',+ title: 'Test Agent',+ userId,+ },+ {+ slug: 'other-agent',+ title: 'Other Agent',+ userId,+ },+ ])+ .returning();++ testAgentId = agent1.id;+ otherAgentId = agent2.id;++ // Create topics for test agent+ await serverDB.insert(topics).values([+ {+ agentId: testAgentId,+ title: 'React Testing Guide',+ userId,+ },+ {+ agentId: testAgentId,+ title: 'Testing Best Practices',+ userId,+ },+ ]);++ // Create topics for other agent+ await serverDB.insert(topics).values([+ {+ agentId: otherAgentId,+ title: 'Testing Strategies',+ userId,+ },+ ]);++ // Create topic without agent+ await serverDB.insert(topics).values([+ {+ agentId: null,+ title: 'General Testing Tips',+ userId,+ },+ ]);+ });++ it('should only return topics of the current agent when agentId is provided', async () => {+ const results = await ftsSearchRepo.search({+ agentId: testAgentId,+ query: 'testing',+ });++ const topicResults = results.filter((r) => r.type === 'topic');++ expect(topicResults.length).toBeGreaterThan(0);+ topicResults.forEach((topic) => {+ if (topic.type === 'topic') {+ expect(topic.agentId).toBe(testAgentId);+ }+ });+ });++ it('should include topics from all agents when agentId is not provided', async () => {+ const results = await ftsSearchRepo.search({+ query: 'testing',+ });++ const topicResults = results.filter((r) => r.type === 'topic');+ const agentIds = new Set(topicResults.map((t) => (t.type === 'topic' ? t.agentId : null)));++ expect(agentIds.has(testAgentId)).toBe(true);+ expect(agentIds.has(otherAgentId)).toBe(true);+ });++ it('should populate agent metadata on topic results', async () => {+ // Add avatar/background to an existing agent so we can assert join output+ const [decoratedAgent] = await serverDB+ .insert(agents)+ .values({+ avatar: '🤖',+ backgroundColor: '#123456',+ slug: 'decorated-agent',+ title: 'Decorated Agent',+ userId,+ })+ .returning();++ await serverDB.insert(topics).values({+ agentId: decoratedAgent.id,+ title: 'Testing Decorated Agent',+ userId,+ });++ const results = await ftsSearchRepo.search({ query: 'decorated' });+ const topicResults = results.filter((r) => r.type === 'topic');+ const decoratedTopic = topicResults.find(+ (t) => t.type === 'topic' && t.agentId === decoratedAgent.id,+ );++ expect(decoratedTopic).toBeDefined();+ if (decoratedTopic && decoratedTopic.type === 'topic') {+ expect(decoratedTopic.agent).toEqual({+ avatar: '🤖',+ backgroundColor: '#123456',+ title: 'Decorated Agent',+ });+ }++ // Topic without an agent should have a null agent field+ const orphanTopic = topicResults.find((t) => t.type === 'topic' && t.agentId === null);+ if (orphanTopic && orphanTopic.type === 'topic') {+ expect(orphanTopic.agent).toBeNull();+ }+ });++ it('should not leak agent metadata when topic.agentId points to another user', async () => {+ // Foreign agent owned by a different user+ const [foreignAgent] = await serverDB+ .insert(agents)+ .values({+ avatar: '🕵️',+ backgroundColor: '#abcdef',+ slug: 'foreign-agent',+ title: 'Foreign Agent',+ userId: otherUserId,+ })+ .returning();++ // Topic owned by the current user but carrying the foreign agent id —+ // simulates state reachable via crafted/migrated rows (e.g. topic+ // creation persists input.agentId even when resolveContext fails).+ await serverDB.insert(topics).values({+ agentId: foreignAgent.id,+ title: 'Cross-tenant probe',+ userId,+ });++ const results = await ftsSearchRepo.search({ query: 'cross-tenant' });+ const topicResults = results.filter((r) => r.type === 'topic');+ const probeTopic = topicResults.find(+ (t) => t.type === 'topic' && t.title === 'Cross-tenant probe',+ );++ expect(probeTopic).toBeDefined();+ if (probeTopic && probeTopic.type === 'topic') {+ // The raw agentId is preserved (used for navigation), but no+ // foreign agent metadata is surfaced to the renderer.+ expect(probeTopic.agentId).toBe(foreignAgent.id);+ expect(probeTopic.agent).toBeNull();+ }+ });++ it('should return 6 topics in agent context', async () => {+ // Create additional topics to test limit+ await serverDB.insert(topics).values(+ Array.from({ length: 12 }, (_, i) => ({+ agentId: i < 6 ? testAgentId : otherAgentId,+ title: `Test Topic ${i}`,+ userId,+ })),+ );++ const results = await ftsSearchRepo.search({+ agentId: testAgentId,+ query: 'test',+ });++ const topicResults = results.filter((r) => r.type === 'topic');+ expect(topicResults.length).toBe(6);+ });++ it('should return 3 agents and 3 files in agent context', async () => {+ // Create test agents+ await serverDB.insert(agents).values(+ Array.from({ length: 5 }, (_, i) => ({+ slug: `agent-${i}`,+ title: `Test Agent ${i}`,+ userId,+ })),+ );++ // Create test files+ await serverDB.insert(files).values(+ Array.from({ length: 5 }, (_, i) => ({+ fileType: 'text/plain',+ name: `test-file-${i}.txt`,+ size: 100,+ url: `file://test-file-${i}.txt`,+ userId,+ })),+ );++ const results = await ftsSearchRepo.search({+ agentId: testAgentId,+ query: 'test',+ });++ const agentResults = results.filter((r) => r.type === 'agent');+ const fileResults = results.filter((r) => r.type === 'file');++ expect(agentResults.length).toBeLessThanOrEqual(3);+ expect(fileResults.length).toBeLessThanOrEqual(3);+ });++ it('should use normal limits without agent context', async () => {+ const results = await ftsSearchRepo.search({+ query: 'testing',+ });++ const topicResults = results.filter((r) => r.type === 'topic');++ // Should use default limit of 3 per type+ expect(topicResults.length).toBeLessThanOrEqual(3);+ });++ it('should return topics with normal relevance range (1-3) when agentId is not provided', async () => {+ const results = await ftsSearchRepo.search({+ query: 'testing',+ });++ const topicResults = results.filter((r) => r.type === 'topic');++ topicResults.forEach((topic) => {+ expect(topic.relevance).toBeGreaterThanOrEqual(1);+ expect(topic.relevance).toBeLessThanOrEqual(3);+ });+ });+ });++ describe('search - folder search', () => {+ beforeEach(async () => {+ // Create test folders (documents with file_type='custom/folder')+ await serverDB.insert(documents).values([+ {+ description: 'My project files',+ fileType: 'custom/folder',+ filename: 'project-folder',+ slug: 'project-folder-slug',+ source: 'internal://folder-1',+ sourceType: 'file',+ title: 'Project Documents',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ },+ {+ description: 'Archive folder for old files',+ fileType: 'custom/folder',+ filename: 'archive',+ slug: 'archive-slug',+ source: 'internal://folder-2',+ sourceType: 'file',+ title: 'Archive Folder',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ },+ ]);+ });++ it('should find folders by title', async () => {+ const results = await ftsSearchRepo.search({ query: 'Project', type: 'folder' });++ expect(results.length).toBeGreaterThan(0);+ results.forEach((result) => {+ expect(result.type).toBe('folder');+ });+ });++ it('should find folders by description', async () => {+ const results = await ftsSearchRepo.search({ query: 'archive', type: 'folder' });++ expect(results.length).toBeGreaterThan(0);+ const folder = results[0];+ if (folder.type === 'folder') {+ expect(folder.title.toLowerCase()).toContain('archive');+ }+ });++ it('should return correct folder structure', async () => {+ const results = await ftsSearchRepo.search({ query: 'project', type: 'folder' });++ expect(results.length).toBeGreaterThan(0);+ const folder = results[0];++ expect(folder.type).toBe('folder');+ expect(folder.id).toBeDefined();+ expect(folder.title).toBeDefined();+ expect(folder.relevance).toBeGreaterThan(0);+ expect(folder.createdAt).toBeInstanceOf(Date);+ expect(folder.updatedAt).toBeInstanceOf(Date);++ if (folder.type === 'folder') {+ expect(folder.slug).toBeDefined();+ }+ });+ });++ describe('search - page search', () => {+ beforeEach(async () => {+ // Create test pages (documents with file_type='custom/document')+ await serverDB.insert(documents).values([+ {+ content: 'This is the content of my notes page',+ fileType: 'custom/document',+ filename: 'my-notes.md',+ source: 'internal://page-1',+ sourceType: 'file',+ title: 'My Notes Page',+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ },+ {+ content: 'Documentation for the project',+ fileType: 'custom/document',+ filename: 'readme.md',+ source: 'internal://page-2',+ sourceType: 'file',+ title: 'Project README',+ totalCharCount: 200,+ totalLineCount: 20,+ userId,+ },+ ]);+ });++ it('should find pages by title', async () => {+ const results = await ftsSearchRepo.search({ query: 'Notes', type: 'page' });++ expect(results.length).toBeGreaterThan(0);+ results.forEach((result) => {+ expect(result.type).toBe('page');+ });+ });++ it('should find pages by filename', async () => {+ const results = await ftsSearchRepo.search({ query: 'readme', type: 'page' });++ expect(results.length).toBeGreaterThan(0);+ expect(results[0].type).toBe('page');+ });++ it('should return correct page structure', async () => {+ const results = await ftsSearchRepo.search({ query: 'notes', type: 'page' });++ expect(results.length).toBeGreaterThan(0);+ const page = results[0];++ expect(page.type).toBe('page');+ expect(page.id).toBeDefined();+ expect(page.title).toBeDefined();+ expect(page.relevance).toBeGreaterThan(0);+ expect(page.createdAt).toBeInstanceOf(Date);+ expect(page.updatedAt).toBeInstanceOf(Date);+ });+ });++ describe('searchKnowledgeBaseDocuments', () => {+ const kbA = 'kb-search-a';+ const kbB = 'kb-search-b';++ beforeEach(async () => {+ // Create two KBs for the test user + one for the other user+ await serverDB.insert(knowledgeBases).values([+ { id: kbA, name: 'Knowledge Base A', userId },+ { id: kbB, name: 'Knowledge Base B', userId },+ { id: 'kb-other-1', name: 'Other User KB', userId: otherUserId },+ ]);++ // Documents in KB-A+ await serverDB.insert(documents).values([+ {+ content:+ 'Machine learning algorithms can be supervised, unsupervised, or reinforcement-based. ' ++ 'Common supervised methods include linear regression, decision trees, and neural networks.',+ fileType: 'custom/document',+ filename: 'ml-overview.md',+ knowledgeBaseId: kbA,+ source: 'internal://document/placeholder',+ sourceType: 'api',+ title: 'Machine Learning Overview',+ totalCharCount: 200,+ totalLineCount: 5,+ userId,+ },+ {+ content: 'Documentation about cooking — completely unrelated topic.',+ fileType: 'custom/document',+ filename: 'cooking.md',+ knowledgeBaseId: kbA,+ source: 'internal://document/placeholder',+ sourceType: 'api',+ title: 'Cooking Notes',+ totalCharCount: 50,+ totalLineCount: 2,+ userId,+ },+ // Document in KB-B (must NOT be returned when searching KB-A)+ {+ content:+ 'This document is in a different knowledge base and should not match KB-A scope.',+ fileType: 'custom/document',+ filename: 'ml-other-kb.md',+ knowledgeBaseId: kbB,+ source: 'internal://document/placeholder',+ sourceType: 'api',+ title: 'Machine Learning in KB-B',+ totalCharCount: 100,+ totalLineCount: 3,+ userId,+ },+ // Document for other user (cross-user isolation check)+ {+ content: 'Machine learning notes from another user.',+ fileType: 'custom/document',+ filename: 'ml-other-user.md',+ knowledgeBaseId: 'kb-other-1',+ source: 'internal://document/placeholder',+ sourceType: 'api',+ title: 'Other user ML notes',+ totalCharCount: 50,+ totalLineCount: 2,+ userId: otherUserId,+ },+ ]);+ });++ it('should return [] for empty query', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('', [kbA]);+ expect(results).toEqual([]);+ });++ it('should return [] when no knowledgeBaseIds provided', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', []);+ expect(results).toEqual([]);+ });++ it('should match documents within KB scope by content', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);+ expect(results.length).toBeGreaterThan(0);+ // Should hit ML overview, not cooking+ expect(results.some((r) => r.title === 'Machine Learning Overview')).toBe(true);+ expect(results.every((r) => r.knowledgeBaseId === kbA)).toBe(true);+ });++ it('should respect KB scope (KB-A query does not return KB-B docs)', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);+ expect(results.every((r) => r.title !== 'Machine Learning in KB-B')).toBe(true);+ });++ it('should isolate across users', async () => {+ // Searching with otherUserId's KB should not leak to current user+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [+ 'kb-other-1',+ ]);+ // Current user (`userId`) does not own kb-other-1, so query against it returns []+ expect(results).toEqual([]);+ });++ it('should hide caller-private workspace documents from a public agent', async () => {+ const workspaceId = 'kb-search-workspace';+ const privateKbId = 'kb-search-private';+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Search Workspace',+ primaryOwnerId: userId,+ slug: 'search-workspace',+ });+ await serverDB.insert(knowledgeBases).values({+ id: privateKbId,+ name: 'Private Knowledge Base',+ userId,+ visibility: 'private',+ workspaceId,+ });+ await serverDB.insert(documents).values({+ content: 'Confidential launch details for the private workspace project.',+ fileType: 'custom/document',+ filename: 'private-launch.md',+ knowledgeBaseId: privateKbId,+ source: 'internal://document/private-launch',+ sourceType: 'api',+ title: 'Private Launch Plan',+ totalCharCount: 62,+ totalLineCount: 1,+ userId,+ visibility: 'private',+ workspaceId,+ });++ const privateAgentResults = await createRepo(+ serverDB,+ userId,+ workspaceId,+ 'private',+ ).searchKnowledgeBaseDocuments('confidential launch', [privateKbId]);+ const publicAgentResults = await createRepo(+ serverDB,+ userId,+ workspaceId,+ 'public',+ ).searchKnowledgeBaseDocuments('confidential launch', [privateKbId]);++ expect(privateAgentResults).toHaveLength(1);+ expect(publicAgentResults).toEqual([]);+ });++ it('should produce snippet ≤ 300 characters', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);+ results.forEach((r) => {+ expect(r.snippet.length).toBeLessThanOrEqual(303); // 300 + '...' suffix+ });+ });++ it('should produce relevance in [1, 3] range', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);+ results.forEach((r) => {+ expect(r.relevance).toBeGreaterThanOrEqual(1);+ expect(r.relevance).toBeLessThanOrEqual(3);+ });+ });++ describe('file-backed documents (PDF / parsed files)', () => {+ const pdfFileId = 'file-bm25-pdf-1';+ const pdfDocId = 'docs-bm25-pdf-1';+ const folderDocId = 'docs-bm25-folder-1';+ const otherUserFileId = 'file-bm25-other-1';+ const otherUserDocId = 'docs-bm25-other-1';++ beforeEach(async () => {+ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ id: pdfFileId,+ name: 'transformers-paper.pdf',+ size: 2048,+ url: 's3://bucket/transformers-paper.pdf',+ userId,+ },+ {+ fileType: 'application/pdf',+ id: otherUserFileId,+ name: 'leak-check.pdf',+ size: 2048,+ url: 's3://bucket/leak-check.pdf',+ userId: otherUserId,+ },+ ]);++ await serverDB.insert(knowledgeBaseFiles).values([+ { fileId: pdfFileId, knowledgeBaseId: kbA, userId },+ { fileId: otherUserFileId, knowledgeBaseId: 'kb-other-1', userId: otherUserId },+ ]);++ await serverDB.insert(documents).values([+ {+ content:+ 'Attention is all you need. The Transformer architecture relies on self-attention ' ++ 'and replaces recurrence with parallel multi-head attention layers.',+ fileId: pdfFileId,+ fileType: 'application/pdf',+ filename: 'transformers-paper.pdf',+ id: pdfDocId,+ source: 's3://bucket/transformers-paper.pdf',+ sourceType: 'file',+ title: 'Attention Is All You Need',+ totalCharCount: 200,+ totalLineCount: 5,+ userId,+ },+ {+ content: '',+ fileType: 'custom/folder',+ filename: 'a folder',+ id: folderDocId,+ knowledgeBaseId: kbA,+ source: 'internal://folder/placeholder',+ sourceType: 'api',+ title: 'Transformer Folder',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ },+ {+ content:+ 'Attention paper in another user knowledge base — must never surface for current user.',+ fileId: otherUserFileId,+ fileType: 'application/pdf',+ filename: 'leak-check.pdf',+ id: otherUserDocId,+ source: 's3://bucket/leak-check.pdf',+ sourceType: 'file',+ title: 'Attention Leak Check',+ totalCharCount: 100,+ totalLineCount: 3,+ userId: otherUserId,+ },+ ]);+ });++ it('returns a PDF-backed document hit via knowledge_base_files join', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('attention transformer', [+ kbA,+ ]);+ const pdfHit = results.find((r) => r.documentId === pdfDocId);+ expect(pdfHit).toBeDefined();+ expect(pdfHit?.knowledgeBaseId).toBe(kbA);+ expect(pdfHit?.fileId).toBe(pdfFileId);+ expect(pdfHit?.title).toBe('Attention Is All You Need');+ });++ it('still matches inline custom/document hits in the same call', async () => {+ await serverDB.insert(documents).values({+ content: 'Attention transformer notes written inline for KB-A',+ fileType: 'custom/document',+ filename: 'inline-notes.md',+ knowledgeBaseId: kbA,+ source: 'internal://document/placeholder',+ sourceType: 'api',+ title: 'Inline Attention Notes',+ totalCharCount: 60,+ totalLineCount: 2,+ userId,+ });++ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('attention', [kbA]);+ expect(results.some((r) => r.title === 'Inline Attention Notes')).toBe(true);+ expect(results.some((r) => r.documentId === pdfDocId)).toBe(true);+ });++ it('excludes folder documents even when they match the query', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('transformer folder', [+ kbA,+ ]);+ expect(results.every((r) => r.documentId !== folderDocId)).toBe(true);+ });++ it('does not surface another user PDF when querying their KB', async () => {+ const results = await ftsSearchRepo.searchKnowledgeBaseDocuments('attention', [+ 'kb-other-1',+ ]);+ expect(results).toEqual([]);+ });+ });+ });++ describe('search - context types', () => {+ beforeEach(async () => {+ // Create test data for context testing+ await serverDB.insert(agents).values(+ Array.from({ length: 5 }, (_, i) => ({+ slug: `ctx-agent-${i}`,+ title: `Context Test Agent ${i}`,+ userId,+ })),+ );++ await serverDB.insert(topics).values(+ Array.from({ length: 5 }, (_, i) => ({+ title: `Context Test Topic ${i}`,+ userId,+ })),+ );++ await serverDB.insert(files).values(+ Array.from({ length: 8 }, (_, i) => ({+ fileType: 'text/plain',+ name: `context-test-file-${i}.txt`,+ size: 100,+ url: `file://context-test-file-${i}.txt`,+ userId,+ })),+ );++ await serverDB.insert(documents).values([+ ...Array.from({ length: 8 }, (_, i) => ({+ fileType: 'custom/folder',+ filename: `context-test-folder-${i}`,+ source: `internal://ctx-folder-${i}`,+ sourceType: 'file' as const,+ title: `Context Test Folder ${i}`,+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ })),+ ...Array.from({ length: 8 }, (_, i) => ({+ fileType: 'custom/document',+ filename: `context-test-page-${i}.md`,+ source: `internal://ctx-page-${i}`,+ sourceType: 'file' as const,+ title: `Context Test Page ${i}`,+ totalCharCount: 100,+ totalLineCount: 10,+ userId,+ })),+ ]);+ });++ it('should expand pages to 6 in page context', async () => {+ const results = await ftsSearchRepo.search({+ contextType: 'page',+ query: 'context test',+ });++ const pageResults = results.filter((r) => r.type === 'page');+ expect(pageResults.length).toBe(6);+ });++ it('should limit other types to 3 in page context', async () => {+ const results = await ftsSearchRepo.search({+ contextType: 'page',+ query: 'context test',+ });++ const agentResults = results.filter((r) => r.type === 'agent');+ const topicResults = results.filter((r) => r.type === 'topic');+ const fileResults = results.filter((r) => r.type === 'file');+ const folderResults = results.filter((r) => r.type === 'folder');++ expect(agentResults.length).toBeLessThanOrEqual(3);+ expect(topicResults.length).toBeLessThanOrEqual(3);+ expect(fileResults.length).toBeLessThanOrEqual(3);+ expect(folderResults.length).toBeLessThanOrEqual(3);+ });++ it('should expand files and folders to 6 in resource context', async () => {+ const results = await ftsSearchRepo.search({+ contextType: 'resource',+ query: 'context-test',+ });++ const fileResults = results.filter((r) => r.type === 'file');+ const folderResults = results.filter((r) => r.type === 'folder');++ expect(fileResults.length).toBe(6);+ expect(folderResults.length).toBe(6);+ });++ it('should limit other types to 3 in resource context', async () => {+ const results = await ftsSearchRepo.search({+ contextType: 'resource',+ query: 'context test',+ });++ const agentResults = results.filter((r) => r.type === 'agent');+ const topicResults = results.filter((r) => r.type === 'topic');+ const pageResults = results.filter((r) => r.type === 'page');++ expect(agentResults.length).toBeLessThanOrEqual(3);+ expect(topicResults.length).toBeLessThanOrEqual(3);+ expect(pageResults.length).toBeLessThanOrEqual(3);+ });++ it('should use agent context limits with contextType=agent', async () => {+ const results = await ftsSearchRepo.search({+ contextType: 'agent',+ query: 'context test',+ });++ const topicResults = results.filter((r) => r.type === 'topic');+ expect(topicResults.length).toBeLessThanOrEqual(6);++ const agentResults = results.filter((r) => r.type === 'agent');+ expect(agentResults.length).toBeLessThanOrEqual(3);+ });+ });++ describe('search - message search', () => {+ beforeEach(async () => {+ // Create test messages with different roles+ await serverDB.insert(messages).values([+ {+ content: 'Hello, I need help with React hooks',+ role: 'user',+ userId,+ },+ {+ content: 'Sure, I can help you with React hooks and state management',+ role: 'assistant',+ userId,+ },+ {+ content: 'Tool call result for React documentation lookup',+ role: 'tool',+ userId,+ },+ {+ content: 'Another tool message about hooks',+ role: 'tool',+ userId,+ },+ ]);+ });++ it('should find messages by content', async () => {+ const results = await ftsSearchRepo.search({ query: 'React hooks', type: 'message' });++ expect(results.length).toBeGreaterThan(0);+ results.forEach((result) => {+ expect(result.type).toBe('message');+ });+ });++ it('should filter out messages with role=tool', async () => {+ const results = await ftsSearchRepo.search({ query: 'tool', type: 'message' });++ // Should not find any tool messages even though they contain "tool" in content+ const toolMessages = results.filter((r) => r.type === 'message' && r.role === 'tool');+ expect(toolMessages.length).toBe(0);+ });++ it('should return user and assistant messages but not tool messages', async () => {+ const results = await ftsSearchRepo.search({ query: 'hooks' });++ const messageResults = results.filter((r) => r.type === 'message');++ // Should find user and assistant messages+ expect(messageResults.length).toBeGreaterThan(0);++ // Verify all returned messages are not tool messages+ messageResults.forEach((msg) => {+ if (msg.type === 'message') {+ expect(msg.role).not.toBe('tool');+ }+ });+ });++ it('should return correct message structure', async () => {+ const results = await ftsSearchRepo.search({ query: 'help', type: 'message' });++ expect(results.length).toBeGreaterThan(0);+ const message = results[0];++ expect(message.type).toBe('message');+ expect(message.id).toBeDefined();+ expect(message.title).toBeDefined();+ expect(message.relevance).toBeGreaterThan(0);+ expect(message.createdAt).toBeInstanceOf(Date);+ expect(message.updatedAt).toBeInstanceOf(Date);++ if (message.type === 'message') {+ expect(message.content).toBeDefined();+ expect(message.role).toBeDefined();+ expect(['user', 'assistant']).toContain(message.role);+ }+ });+ });++ // Agent-share visitor conversations are persisted under the CREATOR's+ // `userId` and are only distinguishable by `topics.senderId`, so the+ // ownership/workspace scope alone would surface them in the creator's own+ // full-text search.+ describe('search - agent share visitor isolation', () => {+ beforeEach(async () => {+ await serverDB.insert(topics).values([+ {+ content: 'Visitor asked about quantum entanglement in depth',+ id: 'fts-visitor-topic',+ senderId: 'fts-visitor-user',+ title: 'Visitor quantum session',+ userId,+ },+ {+ content: 'Creator notes about quantum entanglement',+ id: 'fts-creator-topic',+ title: 'Creator quantum session',+ userId,+ },+ ]);+ await serverDB.insert(messages).values([+ {+ content: 'my quantum password is hunter2',+ id: 'fts-visitor-message',+ role: 'user',+ topicId: 'fts-visitor-topic',+ userId,+ },+ {+ content: 'my quantum notes are public',+ id: 'fts-creator-message',+ role: 'user',+ topicId: 'fts-creator-topic',+ userId,+ },+ ]);+ });++ it('does not return an agent-share visitor topic', async () => {+ const results = await ftsSearchRepo.search({ query: 'quantum', type: 'topic' });++ expect(results.map((result) => result.id)).toContain('fts-creator-topic');+ expect(results.map((result) => result.id)).not.toContain('fts-visitor-topic');+ });++ it('does not return an agent-share visitor message', async () => {+ const results = await ftsSearchRepo.search({ query: 'quantum', type: 'message' });++ expect(results.map((result) => result.id)).toContain('fts-creator-message');+ expect(results.map((result) => result.id)).not.toContain('fts-visitor-message');+ });+ });++ // Regression guard: the BM25 scans were split into an inner+ // single-table subquery (so ParadeDB can pick its TopN custom scan) with the+ // joins and — in personal mode — the `workspace_id IS NULL` check moved above+ // it. These tests pin the two things that split could break: rows leaking+ // across the personal/workspace boundary, and enrichment lost with the joins.+ describe('search - workspace scoping', () => {+ const workspaceId = 'search-test-workspace';+ let workspaceAgentId: string;+ let personalAgentId: string;++ beforeEach(async () => {+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Search Test Workspace',+ primaryOwnerId: userId,+ slug: 'search-test-workspace',+ });++ const insertedAgents = await serverDB+ .insert(agents)+ .values([+ { title: 'Kubernetes Personal Agent', userId, workspaceId: null },+ { title: 'Kubernetes Workspace Agent', userId, workspaceId },+ ])+ .returning({ id: agents.id, workspaceId: agents.workspaceId });++ personalAgentId = insertedAgents.find((a) => !a.workspaceId)!.id;+ workspaceAgentId = insertedAgents.find((a) => a.workspaceId)!.id;++ await serverDB.insert(topics).values([+ { agentId: personalAgentId, title: 'Kubernetes personal topic', userId, workspaceId: null },+ { agentId: workspaceAgentId, title: 'Kubernetes workspace topic', userId, workspaceId },+ ]);++ await serverDB.insert(messages).values([+ {+ agentId: personalAgentId,+ content: 'Kubernetes personal message',+ role: 'user',+ userId,+ workspaceId: null,+ },+ {+ agentId: workspaceAgentId,+ content: 'Kubernetes workspace message',+ role: 'user',+ userId,+ workspaceId,+ },+ ]);++ await serverDB.insert(files).values([+ {+ fileType: 'text/plain',+ name: 'kubernetes-personal.txt',+ size: 10,+ url: 'file://kubernetes-personal.txt',+ userId,+ workspaceId: null,+ },+ {+ fileType: 'text/plain',+ name: 'kubernetes-workspace.txt',+ size: 10,+ url: 'file://kubernetes-workspace.txt',+ userId,+ workspaceId,+ },+ ]);++ await serverDB.insert(documents).values([+ {+ content: 'Kubernetes personal page body',+ fileType: 'custom/document',+ filename: 'kubernetes-personal-page',+ source: 'internal://ws-page-1',+ sourceType: 'file',+ title: 'Kubernetes personal page',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ workspaceId: null,+ },+ {+ content: 'Kubernetes workspace page body',+ fileType: 'custom/document',+ filename: 'kubernetes-workspace-page',+ source: 'internal://ws-page-2',+ sourceType: 'file',+ title: 'Kubernetes workspace page',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ workspaceId,+ },+ {+ fileType: DOCUMENT_FOLDER_TYPE,+ filename: 'kubernetes-personal-folder',+ source: 'internal://ws-folder-1',+ sourceType: 'file',+ title: 'Kubernetes personal folder',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ workspaceId: null,+ },+ {+ fileType: DOCUMENT_FOLDER_TYPE,+ filename: 'kubernetes-workspace-folder',+ source: 'internal://ws-folder-2',+ sourceType: 'file',+ title: 'Kubernetes workspace folder',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ workspaceId,+ },+ ]);++ await serverDB.insert(chatGroups).values([+ { title: 'Kubernetes personal group', userId, workspaceId: null },+ { title: 'Kubernetes workspace group', userId, workspaceId },+ ]);++ await serverDB.insert(knowledgeBases).values([+ { name: 'Kubernetes personal base', userId, workspaceId: null },+ { name: 'Kubernetes workspace base', userId, workspaceId },+ ]);+ });++ /**+ * Every fixture titles itself after the scope it belongs to, so asserting+ * that each hit *is* from the expected scope catches a leak whatever its+ * title says — stricter than asserting the other scope's word is absent,+ * which a differently-worded row could slip past. Case is normalised+ * because the fixtures are not consistently cased.+ */+ const expectEveryHitScopedTo = (+ results: FtsSearchResult[],+ scope: 'personal' | 'workspace',+ ) => {+ expect(results.length).toBeGreaterThan(0);++ const foreign = results.filter((r) => !r.title.toLowerCase().includes(scope));+ expect(foreign.map((r) => `${r.type}: ${r.title}`)).toEqual([]);++ // every rewritten search method is represented+ expect(new Set(results.map((r) => r.type))).toEqual(new Set(REWRITTEN_RESULT_TYPES));+ };++ it('should never surface workspace-scoped rows in personal mode', async () => {+ const results = await createRepo(serverDB, userId).search({ query: 'Kubernetes' });++ expectEveryHitScopedTo(results, 'personal');+ });++ it('should never surface personal rows in workspace mode', async () => {+ const results = await createRepo(serverDB, userId, workspaceId).search({+ query: 'Kubernetes',+ });++ expectEveryHitScopedTo(results, 'workspace');+ });++ it('keeps agent-scoped search exact in workspace mode', async () => {+ const results = await createRepo(serverDB, userId, workspaceId).search({+ agentId: workspaceAgentId,+ query: 'Kubernetes',+ });++ const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');+ expect(scoped.length).toBeGreaterThan(0);+ for (const r of scoped) {+ if (r.type === 'topic' || r.type === 'message') expect(r.agentId).toBe(workspaceAgentId);+ }+ });++ it('should keep joined agent metadata on topics and messages after the scan split', async () => {+ const results = await createRepo(serverDB, userId).search({ query: 'Kubernetes' });++ const topic = results.find((r) => r.type === 'topic');+ expect(topic).toBeDefined();+ if (topic?.type === 'topic') {+ expect(topic.agentId).toBe(personalAgentId);+ expect(topic.agent?.title).toBe('Kubernetes Personal Agent');+ }++ const message = results.find((r) => r.type === 'message');+ expect(message).toBeDefined();+ if (message?.type === 'message') {+ expect(message.agentId).toBe(personalAgentId);+ // messages render the owning agent's title as their subtitle+ expect(message.description).toBe('Kubernetes Personal Agent');+ }+ });++ it('should keep knowledgeBaseId on files after the scan split', async () => {+ const [file] = await serverDB+ .select({ id: files.id })+ .from(files)+ .where(eq(files.name, 'kubernetes-personal.txt'));+ const [base] = await serverDB+ .select({ id: knowledgeBases.id })+ .from(knowledgeBases)+ .where(eq(knowledgeBases.name, 'Kubernetes personal base'));++ await serverDB+ .insert(knowledgeBaseFiles)+ .values({ fileId: file.id, knowledgeBaseId: base.id, userId });++ const results = await createRepo(serverDB, userId).search({+ query: 'kubernetes',+ type: 'file',+ });++ const hit = results.find((r) => r.type === 'file' && r.id === file.id);+ expect(hit).toBeDefined();+ if (hit?.type === 'file') expect(hit.knowledgeBaseId).toBe(base.id);+ });+ });+ // Regression guard: the agent filter on topics/messages moved+ // from inside the BM25 scan to above it (over-fetching through a deep+ // candidate pool). These tests pin the result semantics that move could+ // break: rows leaking across agents, and the filter being lost entirely.+ describe('search - agent scoping', () => {+ let agentAId: string;+ let agentBId: string;++ beforeEach(async () => {+ const insertedAgents = await serverDB+ .insert(agents)+ .values([+ { title: 'Terraform Agent A', userId },+ { title: 'Terraform Agent B', userId },+ ])+ .returning({ id: agents.id, title: agents.title });++ agentAId = insertedAgents.find((a) => a.title === 'Terraform Agent A')!.id;+ agentBId = insertedAgents.find((a) => a.title === 'Terraform Agent B')!.id;++ await serverDB.insert(topics).values([+ { agentId: agentAId, title: 'Terraform topic from agent A', userId },+ { agentId: agentBId, title: 'Terraform topic from agent B', userId },+ { title: 'Terraform topic without agent', userId },+ ]);++ await serverDB.insert(messages).values([+ { agentId: agentAId, content: 'Terraform message from agent A', role: 'user', userId },+ { agentId: agentBId, content: 'Terraform message from agent B', role: 'user', userId },+ { content: 'Terraform message without agent', role: 'user', userId },+ ]);+ });++ it('should only surface the requested agent rows in topics and messages', async () => {+ const results = await ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' });++ const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');+ expect(scoped.length).toBeGreaterThan(0);++ const foreign = scoped.filter(+ (r) => (r.type === 'topic' || r.type === 'message') && r.agentId !== agentAId,+ );+ expect(foreign.map((r) => `${r.type}: ${r.title}`)).toEqual([]);+ });++ it('should not leak rows between two agent-scoped searches', async () => {+ const [forA, forB] = await Promise.all([+ ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' }),+ ftsSearchRepo.search({ agentId: agentBId, query: 'Terraform' }),+ ]);++ const idsOf = (results: FtsSearchResult[]) =>+ results.filter((r) => r.type === 'topic' || r.type === 'message').map((r) => r.id);++ expect(idsOf(forA)).toHaveLength(2);+ expect(idsOf(forB)).toHaveLength(2);+ expect(idsOf(forA).filter((id) => idsOf(forB).includes(id))).toEqual([]);+ });++ it('should keep agent-less rows reachable without an agent filter', async () => {+ const results = await ftsSearchRepo.search({ query: 'Terraform' });++ const scoped = results.filter((r) => r.type === 'topic' || r.type === 'message');+ const agentIds = new Set(+ scoped.map((r) => (r.type === 'topic' || r.type === 'message' ? r.agentId : null)),+ );+ expect(agentIds).toEqual(new Set([agentAId, agentBId, null]));+ });++ it('should keep joined agent metadata after the agent filter moved above the scan', async () => {+ const results = await ftsSearchRepo.search({ agentId: agentAId, query: 'Terraform' });++ const topic = results.find((r) => r.type === 'topic');+ expect(topic).toBeDefined();+ if (topic?.type === 'topic') expect(topic.agent?.title).toBe('Terraform Agent A');++ const message = results.find((r) => r.type === 'message');+ expect(message).toBeDefined();+ if (message?.type === 'message') expect(message.description).toBe('Terraform Agent A');+ });+ });+};diff --git a/packages/database/src/repositories/ftsSearch/index.ts b/packages/database/src/repositories/ftsSearch/index.tsindex 8acc0b32a44..a858c28d5b1 100644--- a/packages/database/src/repositories/ftsSearch/index.ts+++ b/packages/database/src/repositories/ftsSearch/index.ts@@ -17,6 +17,7 @@ import type {} from './types';export * from './elasticsearch';+export { PgLikeFtsSearchBackend } from './pgLike';export { PgSearchFtsSearchBackend } from './pgSearch';export * from './types';diff --git a/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts b/packages/database/src/repositories/ftsSearch/pgLike/candidates.tsnew file mode 100644index 00000000000..6b6218a4603--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgLike/candidates.ts@@ -0,0 +1,612 @@+import { LIBRARY_HIDDEN_FILE_SOURCES } from '@lobechat/types';+import type { SQL } from 'drizzle-orm';+import {+ and,+ arrayContains,+ eq,+ gte,+ inArray,+ isNull,+ lte,+ ne,+ not,+ notInArray,+ or,+ sql,+} from 'drizzle-orm';+import type { AnyPgColumn, PgTable } from 'drizzle-orm/pg-core';++import {+ agents,+ chatGroups,+ DOCUMENT_FOLDER_TYPE,+ documents,+ files,+ knowledgeBaseFiles,+ knowledgeBases,+ messages,+ topics,+ userMemories,+ userMemoriesActivities,+ userMemoriesContexts,+ userMemoriesExperiences,+ userMemoriesIdentities,+ userMemoriesPreferences,+ userPersonaDocuments,+} from '../../../schemas';+import { searchableMessage } from '../../../utils/searchableMessage';+import { buildWorkspaceWhere } from '../../../utils/workspace';+import type { PostgresFtsSearchContext } from '../postgres/context';+import type { PostgresFtsSearchField } from '../postgres/dialect';+import type {+ FtsSearchBackendCandidate,+ FtsSearchBackendEntity,+ FtsSearchBackendFilters,+ FtsSearchBackendRequest,+ FtsSearchBackendResponse,+ FtsSearchBackendScope,+} from '../types';++/**+ * Bounded candidate requests over-fetch so authorization hydration can still fill+ * the requested page; matches the Elasticsearch candidate multiplier.+ */+const CANDIDATE_MULTIPLIER = 4;++type MemoryTimeField = NonNullable<+ NonNullable<FtsSearchBackendFilters['memoryTimeRange']>['field']+>;++type MemoryTimeColumns = Partial<Record<MemoryTimeField, AnyPgColumn>>;++interface CandidateTarget {+ /** Field names used when the request does not narrow `query.fields`. */+ defaultFields: string[] | ((filters: FtsSearchBackendFilters) => string[]);+ /** Elasticsearch document field name → searchable columns backing it. */+ fields: Record<string, PostgresFtsSearchField[]>;+ id: AnyPgColumn;+ /** Join predicate for layer tables whose document embeds parent memory text. */+ parentJoin?: SQL;+ table: PgTable;+ where: (+ scope: FtsSearchBackendScope,+ filters: FtsSearchBackendFilters,+ db: PostgresFtsSearchContext['db'],+ ) => (SQL | undefined)[];+}++const parentMemoryFields = {+ parent_details: [{ column: userMemories.details }],+ parent_summary: [{ column: userMemories.summary }],+ parent_title: [{ column: userMemories.title, weight: 4 }],+} satisfies Record<string, PostgresFtsSearchField[]>;++/** Memory-context documents flatten every linked parent's text into one logical search field. */+const contextParentText = sql`COALESCE((+ SELECT string_agg(+ concat_ws(' ', ${userMemories.title}, ${userMemories.summary}, ${userMemories.details}),+ ' '+ )+ FROM ${userMemories}+ WHERE ${userMemories.userId} = ${userMemoriesContexts.userId}+ AND COALESCE(${userMemoriesContexts.userMemoryIds}, '[]'::jsonb) ? (${userMemories.id})::text+), '')`;++const parentMemoryJoin = (layer: { userId: AnyPgColumn; userMemoryId: AnyPgColumn }): SQL =>+ and(eq(userMemories.id, layer.userMemoryId), eq(userMemories.userId, layer.userId)) as SQL;++/**+ * Each requested tag may come from the layer row or its parent memory, matching+ * the SQL the memory models apply after hydration. `all` requires every tag+ * (AND of per-tag clauses); `any` requires one.+ *+ * Elasticsearch additionally admits layers whose document has no `parent_tags`+ * field, an allowance for documents indexed before that field existed. This+ * provider reads live rows, so that branch would only add untagged false+ * positives that consume bounded pool slots.+ */+const memoryTagFilter = (+ layerTags: AnyPgColumn,+ parentTags: AnyPgColumn | undefined,+ filters: FtsSearchBackendFilters,+): SQL | undefined => {+ const tags = filters.memoryTags;+ if (!tags?.length) return;++ const clauses = tags.map((tag) =>+ parentTags+ ? (or(arrayContains(layerTags, [tag]), arrayContains(parentTags, [tag])) as SQL)+ : arrayContains(layerTags, [tag]),+ );++ return (filters.memoryTagMatch === 'any' ? or(...clauses) : and(...clauses)) as SQL;+};++/**+ * Bounded candidate pools are cut by score before hydration, so the time range+ * must narrow the pool here as well; otherwise higher-scoring rows outside the+ * range could exhaust it. A field the table does not store is left to hydration.+ */+const memoryTimeFilter = (+ columns: MemoryTimeColumns | undefined,+ filters: FtsSearchBackendFilters,+): SQL | undefined => {+ const range = filters.memoryTimeRange;+ const column = columns?.[range?.field ?? 'capturedAt'];+ if (!range || !column) return;++ return and(+ range.start ? gte(column, range.start) : undefined,+ range.end ? lte(column, range.end) : undefined,+ );+};++const memoryTimeColumns = (+ table: { capturedAt: AnyPgColumn; createdAt: AnyPgColumn; updatedAt: AnyPgColumn },+ extra: MemoryTimeColumns = {},+): MemoryTimeColumns => ({+ capturedAt: table.capturedAt,+ createdAt: table.createdAt,+ updatedAt: table.updatedAt,+ ...extra,+});++/**+ * Topic-scope pruning for topics and messages, mirroring Elasticsearch. Topics+ * own their scope columns; topic-bound messages may carry only `topic_id`, so a+ * missing message scope column must survive until PostgreSQL applies the+ * authoritative parent-topic scope.+ */+const topicScopeWhere = (+ table: { agentId: AnyPgColumn; groupId: AnyPgColumn; sessionId: AnyPgColumn },+ filters: FtsSearchBackendFilters,+ legacyMissingAllowed: boolean,+): (SQL | undefined)[] => {+ const exactOrMissing = (column: AnyPgColumn, value: string) =>+ legacyMissingAllowed ? (or(eq(column, value), isNull(column)) as SQL) : eq(column, value);+ const scope = filters.topicScope;+ const clauses: (SQL | undefined)[] = [+ filters.agentId ? eq(table.agentId, filters.agentId) : undefined,+ ];++ if (scope?.groupId) {+ clauses.push(exactOrMissing(table.groupId, scope.groupId));+ } else if (scope?.agentId) {+ clauses.push(exactOrMissing(table.agentId, scope.agentId));+ } else if (scope?.containerId) {+ clauses.push(+ or(+ eq(table.sessionId, scope.containerId),+ eq(table.groupId, scope.containerId),+ legacyMissingAllowed ? and(isNull(table.sessionId), isNull(table.groupId)) : undefined,+ ) as SQL,+ );+ }++ return clauses;+};++/**+ * Memory-layer filters mirrored from the Elasticsearch candidate query. Every+ * consumer re-applies its filters in PostgreSQL, but bounded pools are cut by+ * score first, so every filter Elasticsearch applies is applied here too.+ */+const memoryLayerWhere =+ (layer: {+ relationship?: AnyPgColumn;+ status?: AnyPgColumn;+ tags: AnyPgColumn;+ timeColumns: MemoryTimeColumns;+ type?: AnyPgColumn;+ userId: AnyPgColumn;+ }) =>+ (scope: FtsSearchBackendScope, filters: FtsSearchBackendFilters): (SQL | undefined)[] => [+ eq(layer.userId, scope.userId),+ filters.memoryCategories?.length+ ? inArray(userMemories.memoryCategory, filters.memoryCategories)+ : undefined,+ layer.type && filters.memoryTypes?.length+ ? inArray(layer.type, filters.memoryTypes)+ : undefined,+ layer.relationship && filters.memoryRelationships?.length+ ? inArray(layer.relationship, filters.memoryRelationships)+ : undefined,+ layer.status && filters.memoryStatus?.length+ ? inArray(layer.status, filters.memoryStatus)+ : undefined,+ memoryTagFilter(layer.tags, userMemories.tags, filters),+ memoryTimeFilter(layer.timeColumns, filters),+ ];++/** Files whose membership in a restricted knowledge base hides them entirely. */+const restrictedKnowledgeBaseFileIds = (db: PostgresFtsSearchContext['db'], kbIds: string[]) =>+ db+ .select({ fileId: knowledgeBaseFiles.fileId })+ .from(knowledgeBaseFiles)+ .where(inArray(knowledgeBaseFiles.knowledgeBaseId, kbIds));++/**+ * Mirrors the Elasticsearch `knowledge_base_ids` exclusion: a document is hidden+ * when its own knowledge base or the knowledge base of its backing file is+ * restricted.+ */+const documentKnowledgeBaseExclusion = (+ db: PostgresFtsSearchContext['db'],+ filters: FtsSearchBackendFilters,+): SQL | undefined => {+ const kbIds = filters.excludeKnowledgeBaseIds;+ if (!kbIds?.length) return;++ return and(+ or(isNull(documents.knowledgeBaseId), notInArray(documents.knowledgeBaseId, kbIds)),+ or(+ isNull(documents.fileId),+ notInArray(documents.fileId, restrictedKnowledgeBaseFileIds(db, kbIds)),+ ),+ );+};++const documentKindWhere = (+ db: PostgresFtsSearchContext['db'],+ filters: FtsSearchBackendFilters,+): (SQL | undefined)[] => {+ const { documentKind } = filters;+ if (documentKind === 'folder') {+ return [+ eq(documents.fileType, DOCUMENT_FOLDER_TYPE),+ documentKnowledgeBaseExclusion(db, filters),+ ];+ }+ if (documentKind === 'page') {+ return [eq(documents.fileType, 'custom/document'), documentKnowledgeBaseExclusion(db, filters)];+ }+ if (documentKind === 'knowledgeBaseDocument') {+ const kbIds = filters.knowledgeBaseIds ?? [];+ return [+ ne(documents.fileType, DOCUMENT_FOLDER_TYPE),+ kbIds.length > 0+ ? (or(+ inArray(documents.knowledgeBaseId, kbIds),+ inArray(documents.fileId, restrictedKnowledgeBaseFileIds(db, kbIds)),+ ) as SQL)+ : sql`false`,+ ];+ }++ throw new Error(`Unsupported document kind: ${String(documentKind)}`);+};++const DOCUMENT_FOLDER_DEFAULT_FIELDS = ['title', 'slug', 'description'];+const DOCUMENT_PAGE_DEFAULT_FIELDS = ['title', 'slug', 'content'];++const CANDIDATE_TARGETS: Record<FtsSearchBackendEntity, CandidateTarget | undefined> = {+ agents: {+ defaultFields: ['title', 'slug', 'tags', 'description', 'system_role'],+ fields: {+ description: [{ column: agents.description, weight: 2 }],+ slug: [{ column: agents.slug, weight: 4 }],+ system_role: [{ column: agents.systemRole }],+ tags: [{ column: agents.tags, jsonb: true, weight: 3 }],+ title: [{ column: agents.title, weight: 5 }],+ },+ id: agents.id,+ table: agents,+ where: (scope, filters) => [+ buildWorkspaceWhere(scope, agents),+ filters.excludeVirtual ? not(eq(agents.virtual, true)) : undefined,+ ],+ },+ chatGroups: {+ defaultFields: ['title', 'description', 'content'],+ fields: {+ content: [{ column: chatGroups.content }],+ description: [{ column: chatGroups.description, weight: 2 }],+ title: [{ column: chatGroups.title, weight: 4 }],+ },+ id: chatGroups.id,+ table: chatGroups,+ where: (scope) => [buildWorkspaceWhere(scope, chatGroups)],+ },+ documents: {+ defaultFields: (filters) =>+ filters.documentKind === 'folder'+ ? DOCUMENT_FOLDER_DEFAULT_FIELDS+ : DOCUMENT_PAGE_DEFAULT_FIELDS,+ fields: {+ content: [{ column: documents.content }],+ description: [{ column: documents.description, weight: 2 }],+ slug: [{ column: documents.slug, weight: 3 }],+ title: [{ column: documents.title, weight: 4 }],+ },+ id: documents.id,+ table: documents,+ where: (scope, filters, db) => [+ buildWorkspaceWhere(scope, documents),+ ...documentKindWhere(db, filters),+ ],+ },+ files: {+ defaultFields: ['name'],+ fields: {+ // Elasticsearch scores the raw, analyzed, and word-split name separately;+ // one substring predicate covers all three here.+ 'name': [{ column: files.name, weight: 4 }],+ 'name.raw': [{ column: files.name, weight: 8 }],+ 'name.words': [{ column: files.name, weight: 2 }],+ },+ id: files.id,+ table: files,+ where: (scope, filters, db) => [+ buildWorkspaceWhere(scope, files),+ ne(files.fileType, 'custom/document'),+ or(isNull(files.source), notInArray(files.source, LIBRARY_HIDDEN_FILE_SOURCES)),+ filters.excludeKnowledgeBaseIds?.length+ ? notInArray(files.id, restrictedKnowledgeBaseFileIds(db, filters.excludeKnowledgeBaseIds))+ : undefined,+ ],+ },+ knowledgeBases: {+ defaultFields: ['name', 'description'],+ fields: {+ description: [{ column: knowledgeBases.description }],+ name: [{ column: knowledgeBases.name, weight: 4 }],+ },+ id: knowledgeBases.id,+ table: knowledgeBases,+ where: (scope, filters) => [+ buildWorkspaceWhere(scope, knowledgeBases),+ filters.excludeKnowledgeBaseIds?.length+ ? notInArray(knowledgeBases.id, filters.excludeKnowledgeBaseIds)+ : undefined,+ ],+ },+ memoryActivities: {+ defaultFields: [+ 'parent_title',+ 'parent_summary',+ 'parent_details',+ 'narrative',+ 'notes',+ 'feedback',+ ],+ fields: {+ ...parentMemoryFields,+ feedback: [{ column: userMemoriesActivities.feedback }],+ narrative: [{ column: userMemoriesActivities.narrative }],+ notes: [{ column: userMemoriesActivities.notes }],+ },+ id: userMemoriesActivities.id,+ parentJoin: parentMemoryJoin(userMemoriesActivities),+ table: userMemoriesActivities,+ where: memoryLayerWhere({+ ...userMemoriesActivities,+ timeColumns: memoryTimeColumns(userMemoriesActivities, {+ endsAt: userMemoriesActivities.endsAt,+ startsAt: userMemoriesActivities.startsAt,+ }),+ }),+ },+ memoryContexts: {+ defaultFields: ['parent_text', 'title', 'description', 'current_status'],+ fields: {+ current_status: [{ column: userMemoriesContexts.currentStatus }],+ description: [{ column: userMemoriesContexts.description }],+ parent_text: [+ {+ // Elasticsearch flattens every linked parent's text into one field,+ // so terms may span columns and different parents.+ column: contextParentText,+ },+ ],+ title: [{ column: userMemoriesContexts.title, weight: 2 }],+ },+ id: userMemoriesContexts.id,+ // Contexts link to several parents through a jsonb id list instead of a+ // scalar foreign key; jsonb key existence keeps the GIN index usable.+ parentJoin: and(+ eq(userMemories.userId, userMemoriesContexts.userId),+ sql`COALESCE(${userMemoriesContexts.userMemoryIds}, '[]'::jsonb) ? (${userMemories.id})::text`,+ ) as SQL,+ table: userMemoriesContexts,+ where: memoryLayerWhere({+ status: userMemoriesContexts.currentStatus,+ tags: userMemoriesContexts.tags,+ timeColumns: memoryTimeColumns(userMemoriesContexts),+ type: userMemoriesContexts.type,+ userId: userMemoriesContexts.userId,+ }),+ },+ memoryExperiences: {+ defaultFields: [+ 'parent_title',+ 'parent_summary',+ 'parent_details',+ 'situation',+ 'reasoning',+ 'possible_outcome',+ 'action',+ 'key_learning',+ ],+ fields: {+ ...parentMemoryFields,+ action: [{ column: userMemoriesExperiences.action }],+ key_learning: [{ column: userMemoriesExperiences.keyLearning }],+ possible_outcome: [{ column: userMemoriesExperiences.possibleOutcome }],+ reasoning: [{ column: userMemoriesExperiences.reasoning }],+ situation: [{ column: userMemoriesExperiences.situation }],+ },+ id: userMemoriesExperiences.id,+ parentJoin: parentMemoryJoin(userMemoriesExperiences),+ table: userMemoriesExperiences,+ where: memoryLayerWhere({+ ...userMemoriesExperiences,+ timeColumns: memoryTimeColumns(userMemoriesExperiences),+ }),+ },+ memoryIdentities: {+ defaultFields: ['parent_title', 'parent_summary', 'parent_details', 'description', 'role'],+ fields: {+ ...parentMemoryFields,+ description: [{ column: userMemoriesIdentities.description }],+ role: [{ column: userMemoriesIdentities.role }],+ },+ id: userMemoriesIdentities.id,+ parentJoin: parentMemoryJoin(userMemoriesIdentities),+ table: userMemoriesIdentities,+ where: memoryLayerWhere({+ ...userMemoriesIdentities,+ timeColumns: memoryTimeColumns(userMemoriesIdentities, {+ episodicDate: userMemoriesIdentities.episodicDate,+ }),+ }),+ },+ memoryPreferences: {+ defaultFields: [+ 'parent_title',+ 'parent_summary',+ 'parent_details',+ 'conclusion_directives',+ 'suggestions',+ ],+ fields: {+ ...parentMemoryFields,+ conclusion_directives: [{ column: userMemoriesPreferences.conclusionDirectives }],+ suggestions: [{ column: userMemoriesPreferences.suggestions }],+ },+ id: userMemoriesPreferences.id,+ parentJoin: parentMemoryJoin(userMemoriesPreferences),+ table: userMemoriesPreferences,+ where: memoryLayerWhere({+ ...userMemoriesPreferences,+ timeColumns: memoryTimeColumns(userMemoriesPreferences),+ }),+ },+ messages: {+ defaultFields: ['content', 'summary'],+ fields: {+ content: [{ column: messages.content, weight: 2 }],+ summary: [{ column: messages.summary }],+ },+ id: messages.id,+ table: messages,+ where: (scope, filters) => [+ buildWorkspaceWhere(scope, messages),+ // Elasticsearch never indexes tool or blank messages, so its candidates+ // exclude them before the bounded pool is cut; mirror that here or such+ // rows crowd out eligible hits that hydration would have kept.+ searchableMessage(),+ ...topicScopeWhere(messages, filters, true),+ ],+ },+ personaDocuments: {+ defaultFields: ['tagline', 'persona'],+ fields: {+ persona: [{ column: userPersonaDocuments.persona }],+ tagline: [{ column: userPersonaDocuments.tagline }],+ },+ id: userPersonaDocuments.id,+ table: userPersonaDocuments,+ where: (scope, filters) => [+ eq(userPersonaDocuments.userId, scope.userId),+ memoryTimeFilter(memoryTimeColumns(userPersonaDocuments), filters),+ ],+ },+ topics: {+ defaultFields: ['title', 'content', 'description'],+ fields: {+ content: [{ column: topics.content }],+ description: [{ column: topics.description }],+ title: [{ column: topics.title, weight: 2 }],+ },+ id: topics.id,+ table: topics,+ where: (scope, filters) => [+ buildWorkspaceWhere(scope, topics),+ ...topicScopeWhere(topics, filters, false),+ ],+ },+ userMemories: {+ defaultFields: ['title', 'summary', 'details'],+ fields: {+ details: [{ column: userMemories.details }],+ summary: [{ column: userMemories.summary, weight: 2 }],+ title: [{ column: userMemories.title, weight: 4 }],+ },+ id: userMemories.id,+ table: userMemories,+ where: (scope, filters) => [+ eq(userMemories.userId, scope.userId),+ filters.memoryCategories?.length+ ? inArray(userMemories.memoryCategory, filters.memoryCategories)+ : undefined,+ filters.memoryTypes?.length+ ? inArray(userMemories.memoryType, filters.memoryTypes)+ : undefined,+ filters.memoryStatus?.length ? inArray(userMemories.status, filters.memoryStatus) : undefined,+ memoryTagFilter(userMemories.tags, undefined, filters),+ memoryTimeFilter(memoryTimeColumns(userMemories), filters),+ ],+ },+};++/** Requested field names may carry Elasticsearch boost suffixes such as `title^5`. */+const resolveFields = (+ target: CandidateTarget,+ filters: FtsSearchBackendFilters,+ requested?: string[],+): PostgresFtsSearchField[] => {+ const defaultFields =+ typeof target.defaultFields === 'function'+ ? target.defaultFields(filters)+ : target.defaultFields;+ const names = (requested?.length ? requested : defaultFields).map((name) => name.split('^')[0]);+ const fields = names.flatMap((name) => target.fields[name] ?? []);++ return fields.length > 0 ? fields : defaultFields.flatMap((name) => target.fields[name] ?? []);+};++/**+ * Candidate-only retrieval for model paths that hydrate and re-authorize the ids+ * themselves. Returns ids ordered by the dialect score; `items` stays empty.+ */+export async function searchCandidates(+ context: PostgresFtsSearchContext,+ request: FtsSearchBackendRequest,+): Promise<FtsSearchBackendResponse> {+ const target = CANDIDATE_TARGETS[request.entity];+ if (!target)+ throw new Error(`Unsupported ${context.dialect.key} candidate entity: ${request.entity}`);++ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(request.query.text);+ const fields = resolveFields(target, request.filters, request.query.fields);+ const rowScore = dialect.score(target.id, fields, preparedQuery);+ // A multi-parent join (memory contexts) repeats a row per matching parent, so+ // collapse to one row per id with its best score before any limit applies;+ // otherwise one heavily linked row could fill the whole bounded pool.+ const score = target.parentJoin ? sql<number>`max(${rowScore})` : rowScore;+ let query = db.select({ id: target.id, score }).from(target.table).$dynamic();+ if (target.parentJoin) {+ query = query.leftJoin(userMemories, target.parentJoin).groupBy(target.id);+ }+ query = query+ .where(+ and(+ ...target.where(request.scope, request.filters, db),+ dialect.match(fields, preparedQuery),+ ),+ )+ .orderBy(sql`${score} DESC`);+ // An omitted limit is the unbounded contract: consumers filter and order the+ // whole candidate set themselves, so no cap may hide matches from them.+ if (request.pagination.limit)+ query = query.limit(request.pagination.limit * CANDIDATE_MULTIPLIER);++ const rows = await query;+ const candidates: FtsSearchBackendCandidate[] = rows.map((row) => ({+ id: String(row.id),+ score: row.score,+ }));++ return { candidates, items: [], total: candidates.length };+}diff --git a/packages/database/src/repositories/ftsSearch/pgLike/dialect.test.ts b/packages/database/src/repositories/ftsSearch/pgLike/dialect.test.tsnew file mode 100644index 00000000000..2b358b91042--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgLike/dialect.test.ts@@ -0,0 +1,59 @@+import { PgDialect } from 'drizzle-orm/pg-core';+import { describe, expect, it } from 'vitest';++import { agents } from '../../../schemas/agent';+import { pgLikeDialect } from './dialect';++const render = (query: Parameters<PgDialect['sqlToQuery']>[0]) => new PgDialect().sqlToQuery(query);++describe('pgLikeDialect', () => {+ it('rejects blank queries', () => {+ expect(() => pgLikeDialect.prepare(' ')).toThrow('Query is empty after sanitization');+ expect(pgLikeDialect.prepare(' kube ')).toBe('kube');+ });++ it('requires every term inside one field and escapes LIKE wildcards', () => {+ const match = render(+ pgLikeDialect.match(+ [{ column: agents.title }, { column: agents.tags, jsonb: true }],+ '100% a_b',+ ),+ );++ expect(match.sql).toBe(+ `(("agents"."title" ILIKE $1 ESCAPE '\\' AND "agents"."title" ILIKE $2 ESCAPE '\\') OR ("agents"."tags"::text ILIKE $3 ESCAPE '\\' AND "agents"."tags"::text ILIKE $4 ESCAPE '\\'))`,+ );+ expect(match.params).toEqual(['%100\\%%', '%a\\_b%', '%100\\%%', '%a\\_b%']);+ });++ it('bounds the number of expanded terms so bind parameters stay under the PostgreSQL limit', () => {+ const fields = [agents.id, agents.title, agents.description, agents.slug, agents.tags].map(+ (column) => ({ column }),+ );+ const query = Array.from({ length: 5000 }, (_, index) => `term${index}`).join(' ');++ const match = render(pgLikeDialect.match(fields, query));+ expect(match.params).toHaveLength(fields.length * 48);+ expect(match.params[0]).toBe('%term0%');+ expect(match.params[47]).toBe('%term47%');++ const score = render(pgLikeDialect.score(agents.id, fields, query));+ expect(score.params).toHaveLength(fields.length * (48 + 3));+ });++ it('weights exact, prefix, phrase, and all-terms matches per field', () => {+ const score = render(+ pgLikeDialect.score(agents.id, [{ column: agents.title, weight: 5 }], 'kube ops'),+ );++ expect(score.sql).toContain('WHEN "agents"."title" ILIKE $1');+ expect(score.sql).toContain('THEN 20');+ expect(score.sql).toContain('THEN 15');+ expect(score.sql).toContain('THEN 10');+ expect(score.sql).toContain('THEN 5');+ expect(score.sql).toContain('ELSE 0');+ expect(score.params[0]).toBe('kube ops');+ expect(score.params).toContain('kube ops%');+ expect(score.params).toContain('%kube ops%');+ });+});diff --git a/packages/database/src/repositories/ftsSearch/pgLike/dialect.ts b/packages/database/src/repositories/ftsSearch/pgLike/dialect.tsnew file mode 100644index 00000000000..b1f5ef9cb2c--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgLike/dialect.ts@@ -0,0 +1,62 @@+import { sql } from 'drizzle-orm';++import { SAFE_BM25_QUERY_OPTIONS } from '../../../utils/bm25';+import { escapeLike } from '../../../utils/like';+import type { PostgresFtsSearchDialect, PostgresFtsSearchField } from '../postgres/dialect';++const LIKE_ESCAPE = sql.raw(`ESCAPE '\\'`);+const LIKE_MAX_TERMS = SAFE_BM25_QUERY_OPTIONS.maxTerms;++const splitLikeTerms = (query: string) => {+ const trimmed = query.trim();+ const terms = trimmed.replaceAll('-', ' ').split(/\s+/).filter(Boolean).slice(0, LIKE_MAX_TERMS);++ return terms.length > 0 ? terms : [trimmed];+};++const likeTextExpression = (field: PostgresFtsSearchField) =>+ field.jsonb ? sql`${field.column}::text` : sql`${field.column}`;++/** Every term must appear somewhere in the same field. */+const likeAllTerms = (field: PostgresFtsSearchField, terms: string[]) =>+ sql`(${sql.join(+ terms.map(+ (term) => sql`${likeTextExpression(field)} ILIKE ${`%${escapeLike(term)}%`} ${LIKE_ESCAPE}`,+ ),+ sql` AND `,+ )})`;++/** Plain PostgreSQL substring matching without an extension or external service. */+export const pgLikeDialect: PostgresFtsSearchDialect = {+ isolatesScoredScan: false,+ key: 'pg_like',+ match: (fields, preparedQuery) => {+ const terms = splitLikeTerms(preparedQuery);++ return sql`(${sql.join(+ fields.map((field) => likeAllTerms(field, terms)),+ sql` OR `,+ )})`;+ },+ prepare: (query) => {+ const prepared = query.trim();+ if (!prepared) throw new Error('Query is empty after sanitization');++ return prepared;+ },+ score: (_keyColumn, fields, preparedQuery) => {+ const phrase = escapeLike(preparedQuery);+ const terms = splitLikeTerms(preparedQuery);++ return sql<number>`(${sql.join(+ fields.map((field) => {+ const text = likeTextExpression(field);+ const weight = field.weight ?? 1;+ const weighted = (multiplier: number) => sql.raw(String(weight * multiplier));++ return sql`(CASE WHEN ${text} ILIKE ${phrase} ${LIKE_ESCAPE} THEN ${weighted(4)} WHEN ${text} ILIKE ${`${phrase}%`} ${LIKE_ESCAPE} THEN ${weighted(3)} WHEN ${text} ILIKE ${`%${phrase}%`} ${LIKE_ESCAPE} THEN ${weighted(2)} WHEN ${likeAllTerms(field, terms)} THEN ${weighted(1)} ELSE 0 END)`;+ }),+ sql` + `,+ )})`;+ },+};diff --git a/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts b/packages/database/src/repositories/ftsSearch/pgLike/index.test.tsnew file mode 100644index 00000000000..654478eb62e--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgLike/index.test.ts@@ -0,0 +1,962 @@+// @vitest-environment node+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents } from '../../../schemas/agent';+import { chatGroups } from '../../../schemas/chatGroup';+import { documents, files, knowledgeBaseFiles, knowledgeBases } from '../../../schemas/file';+import { messages } from '../../../schemas/message';+import { sessions } from '../../../schemas/session';+import { topics } from '../../../schemas/topic';+import { users } from '../../../schemas/user';+import {+ userMemories,+ userMemoriesActivities,+ userMemoriesContexts,+} from '../../../schemas/userMemories';+import { workspaces } from '../../../schemas/workspace';+import type { LobeChatDatabase } from '../../../type';+import {+ describeFtsSearchProductBehavior,+ otherUserId,+ userId,+} from '../__tests__/productSearchBehavior';+import { FtsSearchRepo } from '../index';+import { PgLikeFtsSearchBackend } from './index';++const serverDB: LobeChatDatabase = await getTestDB();++const createRepo = (+ db: LobeChatDatabase,+ scopedUserId: string,+ workspaceId?: string,+ callerAgentVisibility?: 'private' | 'public' | null,+) =>+ new FtsSearchRepo(db, scopedUserId, workspaceId, callerAgentVisibility, {+ backend: new PgLikeFtsSearchBackend(db, {+ callerAgentVisibility,+ userId: scopedUserId,+ workspaceId,+ }),+ ftsSearchCandidateEnabled: true,+ });++/**+ * pg_like needs no PostgreSQL extension, so the full product-search behaviour+ * suite runs under PGlite instead of the ParadeDB container used by pg_search.+ */+describe('FtsSearchRepo (pg_like)', () => {+ describeFtsSearchProductBehavior({ createRepo, db: serverDB });++ describe('LIKE wildcard escaping', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(agents).values([+ { title: 'Discount 100% agent', userId },+ { title: 'snake_case agent', userId },+ { title: 'Plain agent', userId },+ { title: 'Backslash \\ agent', userId },+ ]);+ });++ it('treats % and _ in the query literally', async () => {+ const repo = createRepo(serverDB, userId);++ const percent = await repo.search({ query: '100%', type: 'agent' });+ expect(percent.map((item) => item.title)).toEqual(['Discount 100% agent']);++ const underscore = await repo.search({ query: 'snake_case', type: 'agent' });+ expect(underscore.map((item) => item.title)).toEqual(['snake_case agent']);++ const lonelyUnderscore = await repo.search({ query: '_', type: 'agent' });+ expect(lonelyUnderscore.map((item) => item.title)).toEqual(['snake_case agent']);+ });++ it('treats a backslash in the query literally', async () => {+ const repo = createRepo(serverDB, userId);++ const results = await repo.search({ query: '\\', type: 'agent' });+ expect(results.map((item) => item.title)).toEqual(['Backslash \\ agent']);+ });++ it('requires every whitespace-separated term to match within one field', async () => {+ const repo = createRepo(serverDB, userId);++ const results = await repo.search({ query: 'agent plain', type: 'agent' });+ expect(results.map((item) => item.title)).toEqual(['Plain agent']);+ });+ });++ describe('restricted knowledge base exclusions', () => {+ const restrictedKb = 'pg-like-restricted-kb';+ const allowedKb = 'pg-like-allowed-kb';++ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(knowledgeBases).values([+ // whole-name match: outranks the allowed knowledge base+ { id: restrictedKb, name: 'Kubernetes', userId },+ { id: allowedKb, name: 'Kubernetes docs', userId },+ ]);+ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ id: 'pg-like-restricted-file',+ name: 'kubernetes',+ size: 1,+ url: 's3://bucket/restricted.pdf',+ userId,+ },+ {+ fileType: 'application/pdf',+ id: 'pg-like-allowed-file',+ name: 'kubernetes notes',+ size: 1,+ url: 's3://bucket/allowed.pdf',+ userId,+ },+ ]);+ await serverDB+ .insert(knowledgeBaseFiles)+ .values([{ fileId: 'pg-like-restricted-file', knowledgeBaseId: restrictedKb, userId }]);+ await serverDB.insert(documents).values([+ {+ content: '',+ fileType: 'custom/folder',+ filename: 'restricted folder',+ id: 'pg-like-restricted-folder',+ knowledgeBaseId: restrictedKb,+ source: 'internal://folder/restricted',+ sourceType: 'api',+ title: 'Kubernetes',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ },+ {+ content: '',+ fileType: 'custom/folder',+ filename: 'allowed folder',+ id: 'pg-like-allowed-folder',+ source: 'internal://folder/allowed',+ sourceType: 'api',+ title: 'Kubernetes runbooks',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ },+ {+ content: 'restricted page',+ fileType: 'custom/document',+ filename: 'restricted page',+ id: 'pg-like-restricted-page',+ knowledgeBaseId: restrictedKb,+ source: 'internal://page/restricted',+ sourceType: 'api',+ title: 'Kubernetes',+ totalCharCount: 15,+ totalLineCount: 1,+ userId,+ },+ {+ content: 'page bound to a restricted file',+ fileId: 'pg-like-restricted-file',+ fileType: 'custom/document',+ filename: 'restricted file page',+ id: 'pg-like-restricted-file-page',+ source: 'internal://page/restricted-file',+ sourceType: 'api',+ title: 'Kubernetes',+ totalCharCount: 30,+ totalLineCount: 1,+ userId,+ },+ {+ content: 'allowed page',+ fileType: 'custom/document',+ filename: 'allowed page',+ id: 'pg-like-allowed-page',+ source: 'internal://page/allowed',+ sourceType: 'api',+ title: 'Kubernetes upgrade page',+ totalCharCount: 12,+ totalLineCount: 1,+ userId,+ },+ ]);+ });++ it.each([+ ['knowledgeBase', 'Kubernetes docs'],+ ['file', 'kubernetes notes'],+ ['folder', 'Kubernetes runbooks'],+ ['page', 'Kubernetes upgrade page'],+ ] as const)(+ 'does not let a restricted %s hit consume the only slot',+ async (type, expectedTitle) => {+ const repo = createRepo(serverDB, userId);++ const results = await repo.search({+ excludeKnowledgeBaseIds: [restrictedKb],+ limitPerType: 1,+ query: 'kubernetes',+ type,+ });++ expect(results.map((item) => item.title)).toEqual([expectedTitle]);+ },+ );+ });++ describe('recency within relevance ties', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }]);+ });++ it.each(['topic', 'message'] as const)(+ 'keeps the newest tied %s before limiting the candidate pool',+ async (type) => {+ const records = Array.from({ length: 12 }, (_, index) => ({+ createdAt: new Date(Date.UTC(2026, 0, index + 1)),+ id: `recency-${index}`,+ // Editing older messages must not displace newly created messages.+ updatedAt: new Date(Date.UTC(2026, 0, type === 'message' ? 12 - index : index + 1)),+ userId,+ }));+ if (type === 'topic') {+ await serverDB+ .insert(topics)+ .values(records.map((record) => ({ ...record, title: 'Kubernetes notes' })));+ } else {+ await serverDB.insert(messages).values(+ records.map((record) => ({+ ...record,+ content: 'Kubernetes notes',+ role: 'user',+ })),+ );+ }++ const results = await createRepo(serverDB, userId).search({+ limitPerType: 1,+ query: 'kubernetes',+ type,+ });++ expect(results.map((item) => item.id)).toEqual(['recency-11']);+ },+ );+ });++ describe('candidates mode', () => {+ const workspaceId = 'pg-like-workspace';+ const now = new Date();++ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'pg_like workspace',+ primaryOwnerId: userId,+ slug: 'pg-like-workspace',+ });+ });++ it('returns scoped agent ids ordered by score with an empty item list', async () => {+ const [exact, prefix, contains, description] = await serverDB+ .insert(agents)+ .values([+ { title: 'Kubernetes', userId },+ { title: 'Kubernetes operator', userId },+ { title: 'Managed Kubernetes cluster', userId },+ { description: 'Talks about kubernetes', title: 'Infra helper', userId },+ { title: 'Kubernetes other user', userId: otherUserId },+ { title: 'Kubernetes workspace agent', userId, workspaceId },+ ])+ .returning({ id: agents.id });++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: {},+ query: { text: 'kubernetes' },+ });++ expect(response.candidates.map((candidate) => candidate.id)).toEqual([+ exact.id,+ prefix.id,+ contains.id,+ description.id,+ ]);+ expect(response.total).toBe(4);+ expect(response.candidates.every((candidate) => (candidate.score ?? 0) > 0)).toBe(true);+ });++ it('scopes workspace requests to the workspace', async () => {+ const [, workspaceAgent] = await serverDB+ .insert(agents)+ .values([+ { title: 'Kubernetes personal', userId },+ { title: 'Kubernetes workspace', userId, workspaceId },+ ])+ .returning({ id: agents.id });++ const repo = createRepo(serverDB, userId, workspaceId);+ const response = await repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: {},+ query: { text: 'kubernetes' },+ });++ expect(response.candidates.map((candidate) => candidate.id)).toEqual([workspaceAgent.id]);+ });++ it('honours Elasticsearch-style field names with boost suffixes', async () => {+ const [titled, described] = await serverDB+ .insert(agents)+ .values([+ { description: 'nothing here', title: 'Kubernetes', userId },+ { description: 'kubernetes in description', title: 'Other', userId },+ ])+ .returning({ id: agents.id });++ const repo = createRepo(serverDB, userId);++ const titleOnly = await repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: {},+ query: { fields: ['title^5'], text: 'kubernetes' },+ });+ expect(titleOnly.candidates.map((candidate) => candidate.id)).toEqual([titled.id]);++ const both = await repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: {},+ query: { fields: ['title^5', 'description^2'], text: 'kubernetes' },+ });+ expect(both.candidates.map((candidate) => candidate.id).sort()).toEqual(+ [titled.id, described.id].sort(),+ );+ });++ it('applies memory category, type, status, and tag filters', async () => {+ const [project, personal] = await serverDB+ .insert(userMemories)+ .values([+ {+ lastAccessedAt: now,+ memoryCategory: 'project',+ memoryType: 'workflow',+ status: 'active',+ tags: ['typescript', 'search'],+ title: 'Search rollout plan',+ userId,+ },+ {+ lastAccessedAt: now,+ memoryCategory: 'personal',+ memoryType: 'workflow',+ status: 'active',+ tags: ['typescript'],+ title: 'Search hobby notes',+ userId,+ },+ {+ lastAccessedAt: now,+ memoryCategory: 'project',+ title: 'Search other user',+ userId: otherUserId,+ },+ ])+ .returning({ id: userMemories.id });++ const repo = createRepo(serverDB, userId);++ const byCategory = await repo.ftsSearchCandidates({+ entity: 'userMemories',+ filters: { memoryCategories: ['project'] },+ pagination: {},+ query: { text: 'search' },+ });+ expect(byCategory.candidates.map((candidate) => candidate.id)).toEqual([project.id]);++ const allTags = await repo.ftsSearchCandidates({+ entity: 'userMemories',+ filters: { memoryTagMatch: 'all', memoryTags: ['typescript', 'search'] },+ pagination: {},+ query: { text: 'search' },+ });+ expect(allTags.candidates.map((candidate) => candidate.id)).toEqual([project.id]);++ const anyTag = await repo.ftsSearchCandidates({+ entity: 'userMemories',+ filters: { memoryTagMatch: 'any', memoryTags: ['typescript'] },+ pagination: {},+ query: { text: 'search' },+ });+ expect(anyTag.candidates.map((candidate) => candidate.id).sort()).toEqual(+ [project.id, personal.id].sort(),+ );+ });++ it('requires every tag in all mode across layer tags, parent tags, or an untagged parent', async () => {+ const [taggedParent, untaggedParent, otherParent] = await serverDB+ .insert(userMemories)+ .values([+ { lastAccessedAt: now, tags: ['project'], title: 'Kubernetes rollout', userId },+ { lastAccessedAt: now, title: 'Kubernetes notes', userId },+ { lastAccessedAt: now, tags: ['personal'], title: 'Kubernetes hobby', userId },+ ])+ .returning({ id: userMemories.id });+ const [split, ownOnly, mismatch, untagged] = await serverDB+ .insert(userMemoriesActivities)+ .values([+ // typescript on the layer, project on the parent: every tag is present+ {+ narrative: 'Split tags',+ tags: ['typescript'],+ type: 'event',+ userId,+ userMemoryId: taggedParent.id,+ },+ // an untagged parent contributes nothing: only one required tag present+ {+ narrative: 'Own only',+ tags: ['typescript'],+ type: 'event',+ userId,+ userMemoryId: untaggedParent.id,+ },+ // parent carries tags but not the required one+ {+ narrative: 'Mismatch',+ tags: ['typescript'],+ type: 'event',+ userId,+ userMemoryId: otherParent.id,+ },+ // neither the layer nor the tagged parent carries `typescript`+ {+ narrative: 'Untagged layer',+ type: 'event',+ userId,+ userMemoryId: taggedParent.id,+ },+ ])+ .returning({ id: userMemoriesActivities.id });++ const repo = createRepo(serverDB, userId);++ const all = await repo.ftsSearchCandidates({+ entity: 'memoryActivities',+ filters: { memoryTagMatch: 'all', memoryTags: ['typescript', 'project'] },+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(all.candidates.map((candidate) => candidate.id)).toEqual([split.id]);+ expect(all.candidates.map((candidate) => candidate.id)).not.toContain(ownOnly.id);++ const any = await repo.ftsSearchCandidates({+ entity: 'memoryActivities',+ filters: { memoryTagMatch: 'any', memoryTags: ['project'] },+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(any.candidates.map((candidate) => candidate.id).sort()).toEqual(+ [split.id, untagged.id].sort(),+ );+ expect(any.candidates.map((candidate) => candidate.id)).not.toContain(mismatch.id);+ expect(any.candidates.map((candidate) => candidate.id)).not.toContain(ownOnly.id);+ });++ it('applies the memory time range before the candidate limit', async () => {+ const day = (offset: number) => new Date(Date.UTC(2026, 0, 1 + offset));+ const [, inRange] = await serverDB+ .insert(userMemories)+ .values([+ // stronger match (whole-field) but outside the range+ { capturedAt: day(0), lastAccessedAt: now, title: 'Kubernetes', userId },+ { capturedAt: day(5), lastAccessedAt: now, title: 'Kubernetes cluster notes', userId },+ { capturedAt: day(9), lastAccessedAt: now, title: 'Kubernetes upgrade notes', userId },+ ])+ .returning({ id: userMemories.id });++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'userMemories',+ filters: { memoryTimeRange: { end: day(7), start: day(3) } },+ pagination: { limit: 1 },+ query: { text: 'kubernetes' },+ });++ expect(response.candidates.map((candidate) => candidate.id)).toEqual([inRange.id]);+ });++ it('applies an activity time range on the requested field', async () => {+ const day = (offset: number) => new Date(Date.UTC(2026, 0, 1 + offset));+ const [early, late] = await serverDB+ .insert(userMemoriesActivities)+ .values([+ { narrative: 'Kubernetes early', startsAt: day(1), type: 'event', userId },+ { narrative: 'Kubernetes late', startsAt: day(8), type: 'event', userId },+ ])+ .returning({ id: userMemoriesActivities.id });++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'memoryActivities',+ filters: { memoryTimeRange: { field: 'startsAt', start: day(5) } },+ pagination: {},+ query: { text: 'kubernetes' },+ });++ expect(response.candidates.map((candidate) => candidate.id)).toEqual([late.id]);+ expect(response.candidates.map((candidate) => candidate.id)).not.toContain(early.id);+ });++ it('applies topic scope to topics and messages before the candidate limit', async () => {+ const [agentA, agentB] = await serverDB+ .insert(agents)+ .values([+ { title: 'Agent A', userId },+ { title: 'Agent B', userId },+ ])+ .returning({ id: agents.id });+ const [group] = await serverDB+ .insert(chatGroups)+ .values([{ title: 'Group', userId }])+ .returning({ id: chatGroups.id });+ const [session] = await serverDB+ .insert(sessions)+ .values([{ userId }])+ .returning({ id: sessions.id });+ const [topicA, topicB, topicGroup, topicSession] = await serverDB+ .insert(topics)+ .values([+ { agentId: agentA.id, title: 'Kubernetes topic A', userId },+ { agentId: agentB.id, title: 'Kubernetes topic B', userId },+ { groupId: group.id, title: 'Kubernetes topic group', userId },+ { sessionId: session.id, title: 'Kubernetes topic session', userId },+ ])+ .returning({ id: topics.id });+ const [messageA, messageB, messageLegacy] = await serverDB+ .insert(messages)+ .values([+ { agentId: agentA.id, content: 'Kubernetes message A', role: 'user', userId },+ { agentId: agentB.id, content: 'Kubernetes message B', role: 'user', userId },+ { content: 'Kubernetes message legacy', role: 'user', topicId: topicA.id, userId },+ ])+ .returning({ id: messages.id });++ const repo = createRepo(serverDB, userId);+ const ids = (response: { candidates: { id: string }[] }) =>+ response.candidates.map((candidate) => candidate.id).sort();++ const topicsByAgent = await repo.ftsSearchCandidates({+ entity: 'topics',+ filters: { topicScope: { agentId: agentA.id } },+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(ids(topicsByAgent)).toEqual([topicA.id]);++ const topicsByGroup = await repo.ftsSearchCandidates({+ entity: 'topics',+ filters: { topicScope: { groupId: group.id } },+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(ids(topicsByGroup)).toEqual([topicGroup.id]);++ const topicsByContainer = await repo.ftsSearchCandidates({+ entity: 'topics',+ filters: { topicScope: { containerId: session.id } },+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(ids(topicsByContainer)).toEqual([topicSession.id]);+ expect(ids(topicsByContainer)).not.toContain(topicB.id);++ // Topic-bound messages may carry no agent id; they survive scope pruning so+ // the consumer can resolve their parent topic.+ const messagesByAgent = await repo.ftsSearchCandidates({+ entity: 'messages',+ filters: { topicScope: { agentId: agentA.id } },+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(ids(messagesByAgent)).toEqual([messageA.id, messageLegacy.id].sort());++ const messagesByAgentFilter = await repo.ftsSearchCandidates({+ entity: 'messages',+ filters: { agentId: agentB.id },+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(ids(messagesByAgentFilter)).toEqual([messageB.id]);+ });++ it('excludes ineligible messages before the candidate limit', async () => {+ const [eligible] = await serverDB+ .insert(messages)+ .values([+ { content: 'Kubernetes rollout notes', role: 'user', userId },+ { content: 'Kubernetes tool output', role: 'tool', userId },+ { content: ' ', role: 'assistant', summary: 'Kubernetes', userId },+ ])+ .returning({ id: messages.id });++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'messages',+ filters: {},+ pagination: { limit: 1 },+ query: { text: 'kubernetes' },+ });++ // Only the tool row is ineligible: the blank-content row is still+ // searchable through its summary, matching the Elasticsearch projection.+ const candidateIds = response.candidates.map((candidate) => candidate.id);+ expect(candidateIds).toContain(eligible.id);+ expect(candidateIds).toHaveLength(2);+ });++ it('matches memory layers through their parent memory text', async () => {+ const [parent] = await serverDB+ .insert(userMemories)+ .values([+ { lastAccessedAt: now, memoryCategory: 'project', title: 'Kubernetes migration', userId },+ ])+ .returning({ id: userMemories.id });+ const [activity, unrelated] = await serverDB+ .insert(userMemoriesActivities)+ .values([+ { narrative: 'Ran the cutover', type: 'event', userId, userMemoryId: parent.id },+ { narrative: 'Unrelated activity', type: 'event', userId, userMemoryId: null },+ ])+ .returning({ id: userMemoriesActivities.id });++ const repo = createRepo(serverDB, userId);++ const viaParent = await repo.ftsSearchCandidates({+ entity: 'memoryActivities',+ filters: {},+ pagination: {},+ query: { text: 'kubernetes' },+ });+ expect(viaParent.candidates.map((candidate) => candidate.id)).toEqual([activity.id]);++ const viaOwnText = await repo.ftsSearchCandidates({+ entity: 'memoryActivities',+ filters: {},+ pagination: {},+ query: { text: 'unrelated' },+ });+ expect(viaOwnText.candidates.map((candidate) => candidate.id)).toEqual([unrelated.id]);+ });++ it('matches parent_text terms across parent title and details without leaking other users', async () => {+ const [parent, foreignParent] = await serverDB+ .insert(userMemories)+ .values([+ { details: 'Ingress migration', lastAccessedAt: now, title: 'Kubernetes', userId },+ {+ details: 'Ingress migration',+ lastAccessedAt: now,+ title: 'Kubernetes',+ userId: otherUserId,+ },+ ])+ .returning({ id: userMemories.id });+ const [context] = await serverDB+ .insert(userMemoriesContexts)+ .values([+ { title: 'Infrastructure', userId, userMemoryIds: [parent.id] },+ { title: 'Foreign reference', userId, userMemoryIds: [foreignParent.id] },+ ])+ .returning({ id: userMemoriesContexts.id });++ const response = await createRepo(serverDB, userId).ftsSearchCandidates({+ entity: 'memoryContexts',+ filters: {},+ pagination: {},+ query: { fields: ['parent_text'], text: 'kubernetes ingress' },+ });++ expect(response.candidates.map((candidate) => candidate.id)).toEqual([context.id]);+ });++ it('matches parent_text terms distributed across several parents', async () => {+ const parents = await serverDB+ .insert(userMemories)+ .values([+ { lastAccessedAt: now, title: 'Project planning', userId },+ { details: 'Apollo launch notes', lastAccessedAt: now, userId },+ ])+ .returning({ id: userMemories.id });+ const [context] = await serverDB+ .insert(userMemoriesContexts)+ .values({+ title: 'Space program',+ userId,+ userMemoryIds: parents.map((parent) => parent.id),+ })+ .returning({ id: userMemoriesContexts.id });++ const response = await createRepo(serverDB, userId).ftsSearchCandidates({+ entity: 'memoryContexts',+ filters: {},+ pagination: {},+ query: { fields: ['parent_text'], text: 'project apollo' },+ });++ expect(response.candidates.map((candidate) => candidate.id)).toEqual([context.id]);+ });++ it('deduplicates memory contexts joined to several parent memories', async () => {+ const parents = await serverDB+ .insert(userMemories)+ .values([+ { lastAccessedAt: now, title: 'Kubernetes cluster', userId },+ { lastAccessedAt: now, title: 'Kubernetes upgrade', userId },+ ])+ .returning({ id: userMemories.id });+ const [context] = await serverDB+ .insert(userMemoriesContexts)+ .values([+ {+ title: 'Platform work',+ userId,+ userMemoryIds: parents.map((parent) => parent.id),+ },+ ])+ .returning({ id: userMemoriesContexts.id });++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'memoryContexts',+ filters: {},+ pagination: {},+ query: { fields: ['parent_text', 'title'], text: 'kubernetes' },+ });++ expect(response.candidates.map((candidate) => candidate.id)).toEqual([context.id]);+ expect(response.total).toBe(1);+ });++ it('collapses multi-parent contexts before applying the candidate limit', async () => {+ const parents = await serverDB+ .insert(userMemories)+ .values(+ Array.from({ length: 8 }, (_, index) => ({+ lastAccessedAt: now,+ title: `Kubernetes parent ${index}`,+ userId,+ })),+ )+ .returning({ id: userMemories.id });+ const [heavy, light] = await serverDB+ .insert(userMemoriesContexts)+ .values([+ { title: 'Heavily linked', userId, userMemoryIds: parents.map((parent) => parent.id) },+ { title: 'Lightly linked', userId, userMemoryIds: [parents[0].id] },+ ])+ .returning({ id: userMemoriesContexts.id });++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'memoryContexts',+ filters: {},+ // pool of 4 rows: without grouping, the heavy context's 8 joined rows fill it+ pagination: { limit: 1 },+ query: { fields: ['parent_text', 'title'], text: 'kubernetes' },+ });++ expect(response.candidates.map((candidate) => candidate.id).sort()).toEqual(+ [heavy.id, light.id].sort(),+ );+ expect(response.total).toBe(2);+ });++ it('over-fetches bounded requests so hydration can fill the page', async () => {+ await serverDB+ .insert(agents)+ .values(+ Array.from({ length: 10 }, (_, index) => ({ title: `Kubernetes ${index}`, userId })),+ );++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: { limit: 2 },+ query: { text: 'kubernetes' },+ });++ expect(response.candidates).toHaveLength(8);+ });++ it('returns every match when the request is unbounded', async () => {+ await serverDB+ .insert(agents)+ .values(+ Array.from({ length: 10 }, (_, index) => ({ title: `Kubernetes ${index}`, userId })),+ );++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: {},+ query: { text: 'kubernetes' },+ });++ expect(response.candidates).toHaveLength(10);+ expect(response.total).toBe(10);+ });++ it('serves file, knowledge base, and document candidates with their exclusions', async () => {+ const restrictedKb = 'pg-like-cand-restricted-kb';+ const allowedKb = 'pg-like-cand-allowed-kb';+ await serverDB.insert(knowledgeBases).values([+ { id: restrictedKb, name: 'Kubernetes restricted', userId },+ { id: allowedKb, name: 'Kubernetes allowed', userId },+ ]);+ await serverDB.insert(files).values([+ {+ fileType: 'application/pdf',+ id: 'cand-restricted-file',+ name: 'kubernetes restricted',+ size: 1,+ url: 's3://bucket/r.pdf',+ userId,+ },+ {+ fileType: 'application/pdf',+ id: 'cand-allowed-file',+ name: 'kubernetes allowed',+ size: 1,+ url: 's3://bucket/a.pdf',+ userId,+ },+ {+ fileType: 'custom/document',+ id: 'cand-page-file',+ name: 'kubernetes page backing file',+ size: 1,+ url: 's3://bucket/p',+ userId,+ },+ ]);+ await serverDB.insert(knowledgeBaseFiles).values([+ { fileId: 'cand-restricted-file', knowledgeBaseId: restrictedKb, userId },+ { fileId: 'cand-allowed-file', knowledgeBaseId: allowedKb, userId },+ ]);+ const document = (+ id: string,+ fileType: string,+ extra: Partial<typeof documents.$inferInsert> = {},+ ) => ({+ content: 'kubernetes body',+ fileType,+ filename: id,+ id,+ source: `internal://${id}`,+ sourceType: 'api' as const,+ title: `Kubernetes ${id}`,+ totalCharCount: 15,+ totalLineCount: 1,+ userId,+ ...extra,+ });+ await serverDB.insert(documents).values([+ document('cand-folder', 'custom/folder'),+ document('cand-folder-restricted', 'custom/folder', { knowledgeBaseId: restrictedKb }),+ document('cand-page', 'custom/document'),+ document('cand-page-restricted', 'custom/document', { knowledgeBaseId: restrictedKb }),+ document('cand-page-file-restricted', 'custom/document', {+ fileId: 'cand-restricted-file',+ }),+ document('cand-kb-doc-inline', 'application/pdf', { knowledgeBaseId: allowedKb }),+ document('cand-kb-doc-file', 'application/pdf', { fileId: 'cand-allowed-file' }),+ ]);++ const repo = createRepo(serverDB, userId);+ const ids = async (+ entity: 'documents' | 'files' | 'knowledgeBases',+ filters: Record<string, unknown>,+ ) => {+ const response = await repo.ftsSearchCandidates({+ entity,+ filters,+ pagination: {},+ query: { text: 'kubernetes' },+ });+ return response.candidates.map((candidate) => candidate.id).sort();+ };++ expect(await ids('files', {})).toEqual(['cand-allowed-file', 'cand-restricted-file']);+ expect(await ids('files', { excludeKnowledgeBaseIds: [restrictedKb] })).toEqual([+ 'cand-allowed-file',+ ]);++ expect(await ids('knowledgeBases', { excludeKnowledgeBaseIds: [restrictedKb] })).toEqual([+ allowedKb,+ ]);++ expect(await ids('documents', { documentKind: 'folder' })).toEqual([+ 'cand-folder',+ 'cand-folder-restricted',+ ]);+ expect(+ await ids('documents', {+ documentKind: 'folder',+ excludeKnowledgeBaseIds: [restrictedKb],+ }),+ ).toEqual(['cand-folder']);+ expect(+ await ids('documents', {+ documentKind: 'page',+ excludeKnowledgeBaseIds: [restrictedKb],+ }),+ ).toEqual(['cand-page']);+ expect(+ await ids('documents', {+ documentKind: 'knowledgeBaseDocument',+ knowledgeBaseIds: [allowedKb],+ }),+ ).toEqual(['cand-kb-doc-file', 'cand-kb-doc-inline']);++ await expect(+ repo.ftsSearchCandidates({+ entity: 'documents',+ filters: {},+ pagination: {},+ query: { text: 'kubernetes' },+ }),+ ).rejects.toThrow('Candidate search provider failed');+ });++ it('returns nothing for a blank query', async () => {+ await serverDB.insert(agents).values([{ title: 'Kubernetes', userId }]);++ const repo = createRepo(serverDB, userId);+ const response = await repo.ftsSearchCandidates({+ entity: 'agents',+ filters: {},+ pagination: {},+ query: { text: ' ' },+ });++ expect(response).toEqual({ candidates: [], total: 0 });+ });+ });+});diff --git a/packages/database/src/repositories/ftsSearch/pgLike/index.ts b/packages/database/src/repositories/ftsSearch/pgLike/index.tsnew file mode 100644index 00000000000..bebe8183f3f--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgLike/index.ts@@ -0,0 +1,36 @@+import type { LobeChatDatabase } from '../../../type';+import { PostgresFtsSearchBackend } from '../postgres/backend';+import type {+ FtsSearchBackendRequest,+ FtsSearchBackendResponse,+ FtsSearchBackendScope,+} from '../types';+import { searchCandidates } from './candidates';+import { pgLikeDialect } from './dialect';++/**+ * Extension-free PostgreSQL provider built on `ILIKE` substring matching.+ *+ * It is an explicit deployment choice for small self-hosted instances and preview+ * environments, never an implicit fallback: it runs on any PostgreSQL without+ * `pg_search` or Elasticsearch, serves the same product entities through the shared+ * query modules, and also answers candidate-only requests so no model path needs+ * ParadeDB operators.+ */+export class PgLikeFtsSearchBackend extends PostgresFtsSearchBackend {+ readonly key = 'pg_like';++ constructor(db: LobeChatDatabase, scope: FtsSearchBackendScope) {+ super(db, scope, pgLikeDialect);+ }++ async search(request: FtsSearchBackendRequest): Promise<FtsSearchBackendResponse> {+ if (request.mode === 'candidates') {+ if (!request.query.text.trim()) return { candidates: [], items: [], total: 0 };++ return searchCandidates(this.context, request);+ }++ return super.search(request);+ }+}diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/dialect.test.ts b/packages/database/src/repositories/ftsSearch/pgSearch/dialect.test.tsnew file mode 100644index 00000000000..6f3c0142718--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgSearch/dialect.test.ts@@ -0,0 +1,21 @@+import { PgDialect } from 'drizzle-orm/pg-core';+import { describe, expect, it } from 'vitest';++import { agents } from '../../../schemas/agent';+import { pgSearchDialect } from './dialect';++const render = (query: Parameters<PgDialect['sqlToQuery']>[0]) => new PgDialect().sqlToQuery(query);++describe('pgSearchDialect', () => {+ it('keeps the ParadeDB match and score shape', () => {+ const fields = [{ column: agents.title }, { column: agents.description }];+ const prepared = pgSearchDialect.prepare('kube');++ const match = render(pgSearchDialect.match(fields, prepared));+ expect(match.sql).toBe('("agents"."title" @@@ $1 OR "agents"."description" @@@ $2)');+ expect(match.params).toEqual([prepared, prepared]);++ const score = render(pgSearchDialect.score(agents.id, fields, prepared));+ expect(score.sql).toBe('paradedb.score("agents"."id")');+ });+});diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/dialect.ts b/packages/database/src/repositories/ftsSearch/pgSearch/dialect.tsnew file mode 100644index 00000000000..e8690aa5659--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgSearch/dialect.ts@@ -0,0 +1,17 @@+import { sql } from 'drizzle-orm';++import { sanitizeBm25Query } from '../../../utils/bm25';+import type { PostgresFtsSearchDialect } from '../postgres/dialect';++/** ParadeDB `pg_search`: BM25 match operator and index-backed scores. */+export const pgSearchDialect: PostgresFtsSearchDialect = {+ isolatesScoredScan: true,+ key: 'pg_search',+ match: (fields, preparedQuery) =>+ sql`(${sql.join(+ fields.map((field) => sql`${field.column} @@@ ${preparedQuery}`),+ sql` OR `,+ )})`,+ prepare: (query) => sanitizeBm25Query(query),+ score: (keyColumn) => sql<number>`paradedb.score(${keyColumn})`,+};diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/index.ts b/packages/database/src/repositories/ftsSearch/pgSearch/index.tsnew file mode 100644index 00000000000..6a153e239ee--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgSearch/index.ts@@ -0,0 +1,13 @@+import type { LobeChatDatabase } from '../../../type';+import { PostgresFtsSearchBackend } from '../postgres/backend';+import type { FtsSearchBackendScope } from '../types';+import { pgSearchDialect } from './dialect';++/** ParadeDB adapter over the shared PostgreSQL query layer. */+export class PgSearchFtsSearchBackend extends PostgresFtsSearchBackend {+ readonly key = 'pg_search';++ constructor(db: LobeChatDatabase, scope: FtsSearchBackendScope) {+ super(db, scope, pgSearchDialect);+ }+}diff --git a/packages/database/src/repositories/ftsSearch/pgSearch.ts b/packages/database/src/repositories/ftsSearch/postgres/backend.tssimilarity index 64%rename from packages/database/src/repositories/ftsSearch/pgSearch.tsrename to packages/database/src/repositories/ftsSearch/postgres/backend.tsindex 60ce13a643a..4f644a6f8af 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/backend.ts@@ -1,4 +1,10 @@-import type { LobeChatDatabase } from '../../type';+import type { LobeChatDatabase } from '../../../type';+import type {+ FtsSearchBackend,+ FtsSearchBackendRequest,+ FtsSearchBackendResponse,+ FtsSearchBackendScope,+} from '../types';import {searchAgents,searchChatGroups,@@ -6,26 +12,28 @@ import {searchKnowledgeBases,searchMessages,searchTopics,-} from './pgSearch/command-menu';-import { searchFolders, searchKnowledgeBaseDocuments, searchPages } from './pgSearch/documents';-import { searchMemories } from './pgSearch/memories';-import type { PgSearchFtsSearchContext } from './pgSearch/scope';-import { createPgSearchFtsSearchContext } from './pgSearch/scope';-import type {- FtsSearchBackend,- FtsSearchBackendRequest,- FtsSearchBackendResponse,- FtsSearchBackendScope,-} from './types';+} from './command-menu';+import type { PostgresFtsSearchContext } from './context';+import { createPostgresFtsSearchContext } from './context';+import type { PostgresFtsSearchDialect } from './dialect';+import { searchFolders, searchKnowledgeBaseDocuments, searchPages } from './documents';+import { searchMemories } from './memories';-/** pg_search adapter that preserves the existing query and hydration shape. */-export class PgSearchFtsSearchBackend implements FtsSearchBackend {- readonly key = 'pg_search';+/**+ * Product search over the shared PostgreSQL query modules. Each subclass only+ * supplies the dialect; query shape, permissions, and hydration stay identical.+ */+export abstract class PostgresFtsSearchBackend implements FtsSearchBackend {+ abstract readonly key: string;- private readonly context: PgSearchFtsSearchContext;+ protected readonly context: PostgresFtsSearchContext;- constructor(db: LobeChatDatabase, scope: FtsSearchBackendScope) {- this.context = createPgSearchFtsSearchContext(db, scope);+ protected constructor(+ db: LobeChatDatabase,+ scope: FtsSearchBackendScope,+ dialect: PostgresFtsSearchDialect,+ ) {+ this.context = createPostgresFtsSearchContext(db, scope, dialect);}async search(request: FtsSearchBackendRequest): Promise<FtsSearchBackendResponse> {@@ -34,7 +42,7 @@ export class PgSearchFtsSearchBackend implements FtsSearchBackend {const { entity, filters, pagination } = request;const limit = pagination.limit;- if (!limit) throw new Error('pg_search product search requires a positive limit');+ if (!limit) throw new Error(`${this.key} product search requires a positive limit`);if (entity === 'agents') return searchAgents(this.context, query, limit);if (entity === 'chatGroups') return searchChatGroups(this.context, query, limit);@@ -65,6 +73,6 @@ export class PgSearchFtsSearchBackend implements FtsSearchBackend {}}- throw new Error(`Unsupported pg_search entity: ${entity}`);+ throw new Error(`Unsupported ${this.key} entity: ${entity}`);}}diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts b/packages/database/src/repositories/ftsSearch/postgres/command-menu.tssimilarity index 74%rename from packages/database/src/repositories/ftsSearch/pgSearch/command-menu.tsrename to packages/database/src/repositories/ftsSearch/postgres/command-menu.tsindex 51384a8574a..1eed5b4abbd 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch/command-menu.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts@@ -1,3 +1,4 @@+import type { SQLWrapper } from 'drizzle-orm';import { and, desc, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';import {@@ -10,7 +11,6 @@ import {messages,topics,} from '../../../schemas';-import { sanitizeBm25Query } from '../../../utils/bm25';import {libraryVisibleFileSource,notAgentShareFileReference,@@ -28,21 +28,55 @@ import type {FtsSearchMessageResult,FtsSearchTopicResult,} from '../types';+import type { PostgresFtsSearchContext } from './context';+import { AGENT_SCOPE_CANDIDATE_POOL } from './context';+import type { PostgresFtsSearchField } from './dialect';import { buildResponse, buildSelectedResponse, mapScoresToRelevance, truncate } from './results';-import type { PgSearchFtsSearchContext } from './scope';-import { AGENT_SCOPE_CANDIDATE_POOL } from './scope';-/** Topics and messages are displayed by recency after a larger BM25 candidate pool is fetched. */+/** Topics and messages are displayed by recency after a larger scored candidate pool is fetched. */const RECENCY_CANDIDATE_MULTIPLIER = 4;+/**+ * Searchable fields per table. Field order is part of the emitted BM25 SQL, and+ * the weights mirror the Elasticsearch boosts so synthesized scores rank alike.+ */+const AGENT_FIELDS: PostgresFtsSearchField[] = [+ { column: agents.title, weight: 5 },+ { column: agents.description, weight: 2 },+ { column: agents.slug, weight: 4 },+ { column: agents.tags, jsonb: true, weight: 3 },+ { column: agents.systemRole },+];++const TOPIC_FIELDS: PostgresFtsSearchField[] = [+ { column: topics.title, weight: 2 },+ { column: topics.content },+ { column: topics.description },+];++const MESSAGE_FIELDS: PostgresFtsSearchField[] = [{ column: messages.content }];++const FILE_FIELDS: PostgresFtsSearchField[] = [{ column: files.name, weight: 4 }];++const CHAT_GROUP_FIELDS: PostgresFtsSearchField[] = [+ { column: chatGroups.title, weight: 4 },+ { column: chatGroups.description, weight: 2 },+];++const KNOWLEDGE_BASE_FIELDS: PostgresFtsSearchField[] = [+ { column: knowledgeBases.name, weight: 4 },+ { column: knowledgeBases.description },+];+/** Search agents by title, description, slug, tags, and system role. */export async function searchAgents(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,): Promise<FtsSearchBackendResponse<FtsSearchAgentResult>> {- const bm25Query = sanitizeBm25Query(query);- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(agents.id, AGENT_FIELDS, preparedQuery);const hits = db.select({@@ -52,7 +86,7 @@ export async function searchAgents(description: agents.description,id: agents.id,name: agents.name,- score: sql<number>`paradedb.score(${agents.id})`.as('score'),+ score: score.as('score'),slug: agents.slug,tags: agents.tags,title: agents.title,@@ -60,13 +94,8 @@ export async function searchAgents(workspaceId: agents.workspaceId,}).from(agents)- .where(- and(- context.scanScopeWhere(agents),- sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query} OR ${agents.slug} @@@ ${bm25Query} OR ${agents.tags} @@@ ${bm25Query} OR ${agents.systemRole} @@@ ${bm25Query})`,- ),- )- .orderBy(sql`paradedb.score(${agents.id}) DESC`)+ .where(and(context.scanScopeWhere(agents), dialect.match(AGENT_FIELDS, preparedQuery)))+ .orderBy(sql`${score} DESC`).limit(context.scanCandidateLimit(limit)).as('agent_hits');@@ -112,14 +141,15 @@ export async function searchAgents(/** Search topics by title, content, and description. */export async function searchTopics(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,agentId?: string,): Promise<FtsSearchBackendResponse<FtsSearchTopicResult>> {- const bm25Query = sanitizeBm25Query(query);const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(topics.id, TOPIC_FIELDS, preparedQuery);const hits = db.select({@@ -129,7 +159,7 @@ export async function searchTopics(favorite: topics.favorite,groupId: topics.groupId,id: topics.id,- score: sql<number>`paradedb.score(${topics.id})`.as('score'),+ score: score.as('score'),sessionId: topics.sessionId,title: topics.title,updatedAt: topics.updatedAt,@@ -144,10 +174,15 @@ export async function searchTopics(// the creator's command-menu search.notShareVisitorTopic(),agentId && !context.liftsAgentFilter ? eq(topics.agentId, agentId) : undefined,- sql`(${topics.title} @@@ ${bm25Query} OR ${topics.content} @@@ ${bm25Query} OR ${topics.description} @@@ ${bm25Query})`,+ dialect.match(TOPIC_FIELDS, preparedQuery),),)- .orderBy(sql`paradedb.score(${topics.id}) DESC`)+ // LIKE scores tie frequently; keep recent hits before the candidate cutoff.+ // ParadeDB retains its score-only ordering to preserve the TopN scan.+ .orderBy(+ sql`${score} DESC`,+ ...(dialect.isolatesScoredScan ? [] : [desc(topics.updatedAt), topics.id]),+ )// `agent_id` is not a BM25 field, so when score ordering is valid its// filter lives above the scan and the pool deepens to compensate..limit(@@ -223,14 +258,15 @@ export async function searchTopics(/** Search messages by content. */export async function searchMessages(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,agentId?: string,): Promise<FtsSearchBackendResponse<FtsSearchMessageResult>> {- const bm25Query = sanitizeBm25Query(query);const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(messages.id, MESSAGE_FIELDS, preparedQuery);const hits = db.select({@@ -241,7 +277,7 @@ export async function searchMessages(id: messages.id,model: messages.model,role: messages.role,- score: sql<number>`paradedb.score(${messages.id})`.as('score'),+ score: score.as('score'),summary: messages.summary,topicId: messages.topicId,updatedAt: messages.updatedAt,@@ -256,10 +292,15 @@ export async function searchMessages(// userId and are only identifiable through their parent topic.notShareVisitorMessage(),agentId && !context.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,- sql`${messages.content} @@@ ${bm25Query}`,+ dialect.match(MESSAGE_FIELDS, preparedQuery),),)- .orderBy(sql`paradedb.score(${messages.id}) DESC`)+ // Message recency follows creation time, even when older messages are edited.+ // Preserve ParadeDB's score-only TopN scan.+ .orderBy(+ sql`${score} DESC`,+ ...(dialect.isolatesScoredScan ? [] : [desc(messages.createdAt), messages.id]),+ )// `agent_id` is not a BM25 field, so when score ordering is valid its// filter lives above the scan and the pool deepens to compensate..limit(@@ -326,13 +367,26 @@ export async function searchMessages(/** Search files by name. */export async function searchFiles(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,excludeKbIds?: string[],): Promise<FtsSearchBackendResponse<FtsSearchFileResult>> {- const bm25Query = sanitizeBm25Query(query);- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(files.id, FILE_FIELDS, preparedQuery);+ // A file linked to any restricted KB is fully hidden. The subquery avoids+ // leaking it through a different joined membership row.+ const excludeKb = (fileId: SQLWrapper) =>+ excludeKbIds && excludeKbIds.length > 0+ ? notInArray(+ fileId,+ db+ .select({ fileId: knowledgeBaseFiles.fileId })+ .from(knowledgeBaseFiles)+ .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),+ )+ : undefined;const hits = db.select({@@ -340,7 +394,7 @@ export async function searchFiles(fileType: files.fileType,id: files.id,name: files.name,- score: sql<number>`paradedb.score(${files.id})`.as('score'),+ score: score.as('score'),size: files.size,updatedAt: files.updatedAt,url: files.url,@@ -353,10 +407,11 @@ export async function searchFiles(ne(files.fileType, 'custom/document'),// Keep non-library files out of command-menu search.libraryVisibleFileSource(files.source),- sql`${files.name} @@@ ${bm25Query}`,+ context.liftsExclusionFilter ? undefined : excludeKb(files.id),+ dialect.match(FILE_FIELDS, preparedQuery),),)- .orderBy(sql`paradedb.score(${files.id}) DESC`)+ .orderBy(sql`${score} DESC`).limit(context.scanCandidateLimit(limit)).as('file_hits');@@ -381,17 +436,7 @@ export async function searchFiles(context.liftedScopeWhere(hits.workspaceId),// ParadeDB only supports indexed predicates inside its BM25 scan.notAgentShareFileReference(db, hits.id),- // A file linked to any restricted KB is fully hidden. The subquery- // avoids leaking it through a different joined membership row.- excludeKbIds && excludeKbIds.length > 0- ? notInArray(- hits.id,- db- .select({ fileId: knowledgeBaseFiles.fileId })- .from(knowledgeBaseFiles)- .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),- )- : undefined,+ context.liftsExclusionFilter ? excludeKb(hits.id) : undefined,),).orderBy(desc(hits.score))@@ -415,12 +460,13 @@ export async function searchFiles(/** Search chat groups by title and description. */export async function searchChatGroups(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,): Promise<FtsSearchBackendResponse<FtsSearchChatGroupResult>> {- const bm25Query = sanitizeBm25Query(query);- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(chatGroups.id, CHAT_GROUP_FIELDS, preparedQuery);const hits = db.select({@@ -429,19 +475,14 @@ export async function searchChatGroups(createdAt: chatGroups.createdAt,description: chatGroups.description,id: chatGroups.id,- score: sql<number>`paradedb.score(${chatGroups.id})`.as('score'),+ score: score.as('score'),title: chatGroups.title,updatedAt: chatGroups.updatedAt,workspaceId: chatGroups.workspaceId,}).from(chatGroups)- .where(- and(- context.scanScopeWhere(chatGroups),- sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,- ),- )- .orderBy(sql`paradedb.score(${chatGroups.id}) DESC`)+ .where(and(context.scanScopeWhere(chatGroups), dialect.match(CHAT_GROUP_FIELDS, preparedQuery)))+ .orderBy(sql`${score} DESC`).limit(context.scanCandidateLimit(limit)).as('chat_group_hits');@@ -476,13 +517,16 @@ export async function searchChatGroups(/** Search knowledge bases by name and description. */export async function searchKnowledgeBases(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,excludeIds?: string[],): Promise<FtsSearchBackendResponse<FtsSearchKnowledgeBaseResult>> {- const bm25Query = sanitizeBm25Query(query);- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(knowledgeBases.id, KNOWLEDGE_BASE_FIELDS, preparedQuery);+ const excludeIdsWhere = (id: SQLWrapper) =>+ excludeIds && excludeIds.length > 0 ? notInArray(id, excludeIds) : undefined;const hits = db.select({@@ -491,7 +535,7 @@ export async function searchKnowledgeBases(description: knowledgeBases.description,id: knowledgeBases.id,name: knowledgeBases.name,- score: sql<number>`paradedb.score(${knowledgeBases.id})`.as('score'),+ score: score.as('score'),updatedAt: knowledgeBases.updatedAt,workspaceId: knowledgeBases.workspaceId,})@@ -499,10 +543,11 @@ export async function searchKnowledgeBases(.where(and(context.scanScopeWhere(knowledgeBases),- sql`(${knowledgeBases.name} @@@ ${bm25Query} OR ${knowledgeBases.description} @@@ ${bm25Query})`,+ context.liftsExclusionFilter ? undefined : excludeIdsWhere(knowledgeBases.id),+ dialect.match(KNOWLEDGE_BASE_FIELDS, preparedQuery),),)- .orderBy(sql`paradedb.score(${knowledgeBases.id}) DESC`)+ .orderBy(sql`${score} DESC`).limit(context.scanCandidateLimit(limit)).as('knowledge_base_hits');@@ -520,9 +565,9 @@ export async function searchKnowledgeBases(.where(and(context.liftedScopeWhere(hits.workspaceId),- // Keep excluded knowledge bases out of the inner BM25 scan so TopN- // ranking remains intact; restricted rows only consume pool slots.- excludeIds && excludeIds.length > 0 ? notInArray(hits.id, excludeIds) : undefined,+ // ParadeDB keeps excluded knowledge bases out of the inner scored scan so+ // TopN ranking remains intact; restricted rows only consume pool slots.+ context.liftsExclusionFilter ? excludeIdsWhere(hits.id) : undefined,),).orderBy(desc(hits.score))diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/scope.ts b/packages/database/src/repositories/ftsSearch/postgres/context.tssimilarity index 68%rename from packages/database/src/repositories/ftsSearch/pgSearch/scope.tsrename to packages/database/src/repositories/ftsSearch/postgres/context.tsindex ceee11fbb53..174ddd7d0c6 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch/scope.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/context.ts@@ -5,22 +5,33 @@ import type { AnyPgColumn } from 'drizzle-orm/pg-core';import type { LobeChatDatabase } from '../../../type';import { buildWorkspaceWhere } from '../../../utils/workspace';import type { FtsSearchBackendScope } from '../types';+import type { PostgresFtsSearchDialect } from './dialect';-/** Columns shared by the workspace-aware tables searched by pg_search. */-export interface PgSearchFtsSearchWorkspaceScopedColumns {+/** Columns shared by the workspace-aware tables searched by the PostgreSQL providers. */+export interface PostgresFtsSearchWorkspaceScopedColumns {userId: AnyPgColumn;visibility?: AnyPgColumn;workspaceId: AnyPgColumn;}-/** Shared state and query-shaping helpers used by the pg_search provider modules. */-export interface PgSearchFtsSearchContext {+/**+ * Shared state and query-shaping helpers used by the PostgreSQL provider modules.+ */+export interface PostgresFtsSearchContext {db: LobeChatDatabase;+ dialect: PostgresFtsSearchDialect;liftedScopeWhere: (workspaceIdColumn: SQLWrapper) => SQL | undefined;liftsAgentFilter: boolean;+ /**+ * Whether non-indexed exclusions (restricted knowledge bases) sit above the+ * scored scan. ParadeDB keeps them out of its TopN scan and lets restricted+ * rows consume pool slots; plain PostgreSQL applies them inside the exact+ * scan so a restricted top hit cannot take a slot from an authorized one.+ */+ liftsExclusionFilter: boolean;liftsWorkspaceFilter: boolean;scanCandidateLimit: (limit: number) => number;- scanScopeWhere: (cols: PgSearchFtsSearchWorkspaceScopedColumns) => SQL;+ scanScopeWhere: (cols: PostgresFtsSearchWorkspaceScopedColumns) => SQL;scope: FtsSearchBackendScope;userId: string;}@@ -56,10 +67,11 @@ const AGENT_SCOPE_CANDIDATE_POOL = 20_000;*/const WORKSPACE_ID_IN_BM25_INDEX = false;-export function createPgSearchFtsSearchContext(+export function createPostgresFtsSearchContext(db: LobeChatDatabase,scope: FtsSearchBackendScope,-): PgSearchFtsSearchContext {+ dialect: PostgresFtsSearchDialect,+): PostgresFtsSearchContext {// The original backend copied scope fields in its constructor. Keep the same// snapshot semantics instead of retaining a caller-owned mutable object.const normalizedScope: FtsSearchBackendScope = {@@ -67,14 +79,21 @@ export function createPgSearchFtsSearchContext(userId: scope.userId,workspaceId: scope.workspaceId,};- const liftsWorkspaceFilter = !WORKSPACE_ID_IN_BM25_INDEX && !normalizedScope.workspaceId;- const liftsAgentFilter = WORKSPACE_ID_IN_BM25_INDEX || !normalizedScope.workspaceId;+ // Lifting filters above the scan only pays off for ParadeDB's TopN scan. A plain+ // PostgreSQL dialect keeps every filter inline, which collapses each query to a+ // single exact stage with the requested limit.+ const liftsWorkspaceFilter =+ dialect.isolatesScoredScan && !WORKSPACE_ID_IN_BM25_INDEX && !normalizedScope.workspaceId;+ const liftsAgentFilter =+ dialect.isolatesScoredScan && (WORKSPACE_ID_IN_BM25_INDEX || !normalizedScope.workspaceId);return {db,+ dialect,liftedScopeWhere: (workspaceIdColumn) =>liftsWorkspaceFilter ? (isNull(workspaceIdColumn) as SQL) : undefined,liftsAgentFilter,+ liftsExclusionFilter: dialect.isolatesScoredScan,liftsWorkspaceFilter,scanCandidateLimit: (limit) =>liftsWorkspaceFilterdiff --git a/packages/database/src/repositories/ftsSearch/postgres/dialect.ts b/packages/database/src/repositories/ftsSearch/postgres/dialect.tsnew file mode 100644index 00000000000..38e0a5f2b8d--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/postgres/dialect.ts@@ -0,0 +1,29 @@+import type { SQL } from 'drizzle-orm';+import type { AnyPgColumn } from 'drizzle-orm/pg-core';++/** One searchable PostgreSQL field expression together with its ranking weight. */+export interface PostgresFtsSearchField {+ column: AnyPgColumn | SQL;+ /** Cast JSONB fields to text for providers that cannot match JSONB natively. */+ jsonb?: boolean;+ /** Relative ranking weight for providers that synthesize scores; defaults to 1. */+ weight?: number;+}++/** Provider-specific SQL fragments consumed by the shared PostgreSQL query layer. */+export interface PostgresFtsSearchDialect {+ /** Whether ranking relies on an isolated single-table scored scan. */+ isolatesScoredScan: boolean;+ /** Provider identity reported through backend measurements. */+ key: string;+ /** Row qualifies when at least one field matches the whole prepared query. */+ match: (fields: PostgresFtsSearchField[], preparedQuery: string) => SQL;+ /** Normalize raw user text once per request; throws when nothing searchable remains. */+ prepare: (query: string) => string;+ /** Ranking expression where a higher value is more relevant. */+ score: (+ keyColumn: AnyPgColumn,+ fields: PostgresFtsSearchField[],+ preparedQuery: string,+ ) => SQL<number>;+}diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts b/packages/database/src/repositories/ftsSearch/postgres/documents.tssimilarity index 69%rename from packages/database/src/repositories/ftsSearch/pgSearch/documents.tsrename to packages/database/src/repositories/ftsSearch/postgres/documents.tsindex 589d85168b9..1bf7028bda2 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch/documents.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/documents.ts@@ -1,7 +1,7 @@+import type { SQLWrapper } from 'drizzle-orm';import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';import { DOCUMENT_FOLDER_TYPE, documents, knowledgeBaseFiles } from '../../../schemas';-import { sanitizeBm25Query } from '../../../utils/bm25';import { notAgentShareFileReference } from '../../../utils/fileVisibility';import { buildWorkspaceWhere } from '../../../utils/workspace';import type {@@ -10,18 +10,38 @@ import type {FtsSearchKnowledgeBaseDocumentHit,FtsSearchPageResult,} from '../types';+import type { PostgresFtsSearchContext } from './context';+import type { PostgresFtsSearchField } from './dialect';import { buildResponse, truncate } from './results';-import type { PgSearchFtsSearchContext } from './scope';++const FOLDER_FIELDS: PostgresFtsSearchField[] = [+ { column: documents.title, weight: 4 },+ { column: documents.slug, weight: 3 },+ { column: documents.description, weight: 2 },+];++const PAGE_FIELDS: PostgresFtsSearchField[] = [+ { column: documents.title, weight: 4 },+ { column: documents.slug, weight: 3 },+ { column: documents.content },+];++const KNOWLEDGE_BASE_DOCUMENT_FIELDS = PAGE_FIELDS;/** Search folders (documents with `file_type=DOCUMENT_FOLDER_TYPE`). */export async function searchFolders(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,excludeKbIds?: string[],): Promise<FtsSearchBackendResponse<FtsSearchFolderResult>> {- const bm25Query = sanitizeBm25Query(query);- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(documents.id, FOLDER_FIELDS, preparedQuery);+ const excludeKb = (column: SQLWrapper) =>+ excludeKbIds && excludeKbIds.length > 0+ ? or(isNull(column), notInArray(column, excludeKbIds))+ : undefined;const hits = db.select({@@ -30,7 +50,7 @@ export async function searchFolders(filename: documents.filename,id: documents.id,knowledgeBaseId: documents.knowledgeBaseId,- score: sql<number>`paradedb.score(${documents.id})`.as('score'),+ score: score.as('score'),slug: documents.slug,title: documents.title,updatedAt: documents.updatedAt,@@ -41,10 +61,11 @@ export async function searchFolders(and(context.scanScopeWhere(documents),eq(documents.fileType, DOCUMENT_FOLDER_TYPE),- sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.description} @@@ ${bm25Query})`,+ context.liftsExclusionFilter ? undefined : excludeKb(documents.knowledgeBaseId),+ dialect.match(FOLDER_FIELDS, preparedQuery),),)- .orderBy(sql`paradedb.score(${documents.id}) DESC`)+ .orderBy(sql`${score} DESC`).limit(context.scanCandidateLimit(limit)).as('folder_hits');@@ -64,9 +85,7 @@ export async function searchFolders(.where(and(context.liftedScopeWhere(hits.workspaceId),- excludeKbIds && excludeKbIds.length > 0- ? or(isNull(hits.knowledgeBaseId), notInArray(hits.knowledgeBaseId, excludeKbIds))- : undefined,+ context.liftsExclusionFilter ? excludeKb(hits.knowledgeBaseId) : undefined,),).orderBy(desc(hits.score))@@ -90,13 +109,32 @@ export async function searchFolders(/** Search pages (documents with `file_type='custom/document'`). */export async function searchPages(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,excludeKbIds?: string[],): Promise<FtsSearchBackendResponse<FtsSearchPageResult>> {- const bm25Query = sanitizeBm25Query(query);- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(documents.id, PAGE_FIELDS, preparedQuery);+ const excludeKb = (knowledgeBaseId: SQLWrapper, fileId: SQLWrapper) =>+ excludeKbIds && excludeKbIds.length > 0+ ? and(+ or(isNull(knowledgeBaseId), notInArray(knowledgeBaseId, excludeKbIds)),+ // Parsed-file pages store KB membership on file_id instead of the+ // document row, so check the join table as well.+ or(+ isNull(fileId),+ notInArray(+ fileId,+ db+ .select({ fileId: knowledgeBaseFiles.fileId })+ .from(knowledgeBaseFiles)+ .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),+ ),+ ),+ )+ : undefined;const hits = db.select({@@ -105,7 +143,7 @@ export async function searchPages(filename: documents.filename,id: documents.id,knowledgeBaseId: documents.knowledgeBaseId,- score: sql<number>`paradedb.score(${documents.id})`.as('score'),+ score: score.as('score'),title: documents.title,updatedAt: documents.updatedAt,workspaceId: documents.workspaceId,@@ -115,10 +153,13 @@ export async function searchPages(and(context.scanScopeWhere(documents),eq(documents.fileType, 'custom/document'),- sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`,+ context.liftsExclusionFilter+ ? undefined+ : excludeKb(documents.knowledgeBaseId, documents.fileId),+ dialect.match(PAGE_FIELDS, preparedQuery),),)- .orderBy(sql`paradedb.score(${documents.id}) DESC`)+ .orderBy(sql`${score} DESC`).limit(context.scanCandidateLimit(limit)).as('page_hits');@@ -136,23 +177,7 @@ export async function searchPages(and(context.liftedScopeWhere(hits.workspaceId),notAgentShareFileReference(db, hits.fileId),- excludeKbIds && excludeKbIds.length > 0- ? or(isNull(hits.knowledgeBaseId), notInArray(hits.knowledgeBaseId, excludeKbIds))- : undefined,- // Parsed-file pages store KB membership on file_id instead of the- // document row, so check the join table as well.- excludeKbIds && excludeKbIds.length > 0- ? or(- isNull(hits.fileId),- notInArray(- hits.fileId,- db- .select({ fileId: knowledgeBaseFiles.fileId })- .from(knowledgeBaseFiles)- .where(inArray(knowledgeBaseFiles.knowledgeBaseId, excludeKbIds)),- ),- )- : undefined,+ context.liftsExclusionFilter ? excludeKb(hits.knowledgeBaseId, hits.fileId) : undefined,),).orderBy(desc(hits.score))@@ -179,7 +204,7 @@ export async function searchPages(* ParadeDB rejects a disjunctive shape spanning BM25 and non-BM25 predicates.*/export async function searchKnowledgeBaseDocuments(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,knowledgeBaseIds: string[],limit: number = 20,@@ -189,9 +214,10 @@ export async function searchKnowledgeBaseDocuments(return { candidates: [], items: [] };}- const bm25Query = sanitizeBm25Query(query);- const { db } = context;- const matchClause = sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(documents.id, KNOWLEDGE_BASE_DOCUMENT_FIELDS, preparedQuery);+ const matchClause = dialect.match(KNOWLEDGE_BASE_DOCUMENT_FIELDS, preparedQuery);const folderClause = ne(documents.fileType, DOCUMENT_FOLDER_TYPE);const userClause = buildWorkspaceWhere(context.scope, documents);@@ -202,7 +228,7 @@ export async function searchKnowledgeBaseDocuments(filename: documents.filename,id: documents.id,knowledgeBaseId: documents.knowledgeBaseId,- score: sql<number>`paradedb.score(${documents.id})`,+ score,title: documents.title,updatedAt: documents.updatedAt,})@@ -216,7 +242,7 @@ export async function searchKnowledgeBaseDocuments(matchClause,),)- .orderBy(sql`paradedb.score(${documents.id}) DESC`)+ .orderBy(sql`${score} DESC`).limit(limit);const fileBackedRowsPromise = db@@ -226,7 +252,7 @@ export async function searchKnowledgeBaseDocuments(filename: documents.filename,id: documents.id,knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,- score: sql<number>`paradedb.score(${documents.id})`,+ score,title: documents.title,updatedAt: documents.updatedAt,})@@ -242,7 +268,7 @@ export async function searchKnowledgeBaseDocuments(.where(and(userClause, folderClause, notAgentShareFileReference(db, documents.fileId), matchClause),)- .orderBy(sql`paradedb.score(${documents.id}) DESC`)+ .orderBy(sql`${score} DESC`).limit(limit);const [inlineRows, fileBackedRows] = await Promise.all([diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/memories.ts b/packages/database/src/repositories/ftsSearch/postgres/memories.tssimilarity index 61%rename from packages/database/src/repositories/ftsSearch/pgSearch/memories.tsrename to packages/database/src/repositories/ftsSearch/postgres/memories.tsindex 93c8572ea9d..634ccd89612 100644--- a/packages/database/src/repositories/ftsSearch/pgSearch/memories.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/memories.ts@@ -1,40 +1,44 @@import { and, eq, sql } from 'drizzle-orm';import { userMemories } from '../../../schemas';-import { sanitizeBm25Query } from '../../../utils/bm25';import type { FtsSearchBackendResponse, FtsSearchMemoryResult } from '../types';+import type { PostgresFtsSearchContext } from './context';+import type { PostgresFtsSearchField } from './dialect';import { buildResponse, truncate } from './results';-import type { PgSearchFtsSearchContext } from './scope';++const MEMORY_FIELDS: PostgresFtsSearchField[] = [+ { column: userMemories.title, weight: 4 },+ { column: userMemories.summary, weight: 2 },+ { column: userMemories.details },+];/** Search user memories by title, summary, and details. */export async function searchMemories(- context: PgSearchFtsSearchContext,+ context: PostgresFtsSearchContext,query: string,limit: number,): Promise<FtsSearchBackendResponse<FtsSearchMemoryResult>> {- const bm25Query = sanitizeBm25Query(query);- const { db } = context;+ const { db, dialect } = context;+ const preparedQuery = dialect.prepare(query);+ const score = dialect.score(userMemories.id, MEMORY_FIELDS, preparedQuery);// Memories are user-scoped and have no workspace column, so the ownership- // predicate can remain in the single-table BM25 scan.+ // predicate can remain in the single-table scored scan.const rows = await db.select({createdAt: userMemories.createdAt,id: userMemories.id,memoryLayer: userMemories.memoryLayer,- score: sql<number>`paradedb.score(${userMemories.id})`,+ score,summary: userMemories.summary,title: userMemories.title,updatedAt: userMemories.updatedAt,}).from(userMemories).where(- and(- eq(userMemories.userId, context.userId),- sql`(${userMemories.title} @@@ ${bm25Query} OR ${userMemories.summary} @@@ ${bm25Query} OR ${userMemories.details} @@@ ${bm25Query})`,- ),+ and(eq(userMemories.userId, context.userId), dialect.match(MEMORY_FIELDS, preparedQuery)),)- .orderBy(sql`paradedb.score(${userMemories.id}) DESC`)+ .orderBy(sql`${score} DESC`).limit(limit);return buildResponse(rows, (row) => ({diff --git a/packages/database/src/repositories/ftsSearch/pgSearch/results.ts b/packages/database/src/repositories/ftsSearch/postgres/results.tssimilarity index 100%rename from packages/database/src/repositories/ftsSearch/pgSearch/results.tsrename to packages/database/src/repositories/ftsSearch/postgres/results.tsdiff --git a/packages/database/src/repositories/ftsSearch/provider-boundary.test.ts b/packages/database/src/repositories/ftsSearch/provider-boundary.test.tsnew file mode 100644index 00000000000..7da61248e48--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/provider-boundary.test.ts@@ -0,0 +1,35 @@+// @vitest-environment node+import { readdir, readFile } from 'node:fs/promises';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const importTargets = async (directory: string) => {+ const filenames = (await readdir(path.join(__dirname, directory))).filter((name) =>+ name.endsWith('.ts'),+ );+ const sources = await Promise.all(+ filenames.map((filename) => readFile(path.join(__dirname, directory, filename), 'utf8')),+ );++ return sources.flatMap((source) =>+ [...source.matchAll(/(?:from\s|import\s*\()\s*['"]([^'"]+)['"]/g)].map((match) => match[1]),+ );+};++describe('PostgreSQL provider boundaries', () => {+ it.each([+ ['pgLike', 'pgSearch'],+ ['pgSearch', 'pgLike'],+ ])('%s does not depend on %s', async (provider, forbiddenProvider) => {+ const imports = await importTargets(provider);++ expect(imports.filter((target) => target.includes(`/${forbiddenProvider}`))).toEqual([]);+ });++ it('keeps the shared PostgreSQL layer provider-independent', async () => {+ const imports = await importTargets('postgres');++ expect(imports.filter((target) => /\/(?:pgLike|pgSearch)/.test(target))).toEqual([]);+ });+});diff --git a/packages/database/src/utils/like.test.ts b/packages/database/src/utils/like.test.tsnew file mode 100644index 00000000000..96ae4fa1da7--- /dev/null+++ b/packages/database/src/utils/like.test.ts@@ -0,0 +1,13 @@+import { describe, expect, it } from 'vitest';++import { escapeLike } from './like';++describe('escapeLike', () => {+ it('escapes LIKE metacharacters so they match literally', () => {+ expect(escapeLike('100%_done\\')).toBe('100\\%\\_done\\\\');+ });++ it('leaves ordinary text untouched', () => {+ expect(escapeLike('搜索 hooks')).toBe('搜索 hooks');+ });+});diff --git a/packages/database/src/utils/like.ts b/packages/database/src/utils/like.tsnew file mode 100644index 00000000000..4730daa5118--- /dev/null+++ b/packages/database/src/utils/like.ts@@ -0,0 +1,13 @@+import type { SQL, SQLWrapper } from 'drizzle-orm';+import { sql } from 'drizzle-orm';++/** Escape LIKE/ILIKE metacharacters (`\ % _`) so user input matches literally. */+export const escapeLike = (value: string): string =>+ value.replaceAll(/[\\%_]/g, (character) => `\\${character}`);++/**+ * Case-insensitive substring predicate with an explicit escape character, so the+ * behavior does not depend on the session's `standard_conforming_strings` setting.+ */+export const ilikeContains = (column: SQLWrapper, needle: string): SQL<boolean> =>+ sql<boolean>`${column} ILIKE ${`%${escapeLike(needle)}%`} ESCAPE '\\'`;diff --git a/packages/env/src/__tests__/ftsSearch.test.ts b/packages/env/src/__tests__/ftsSearch.test.tsindex c4410ff25fa..0ccf0054a8b 100644--- a/packages/env/src/__tests__/ftsSearch.test.ts+++ b/packages/env/src/__tests__/ftsSearch.test.ts@@ -40,6 +40,24 @@ describe('getFtsSearchConfig', () => {});});+ it('accepts the lightweight pg_like provider', () => {+ vi.stubEnv('FTS_SEARCH_PROVIDER', 'pg_like');++ expect(getFtsSearchConfig().FTS_SEARCH_PROVIDER).toBe('pg_like');+ });++ it('lets distributions override the default provider without overriding an explicit value', () => {+ vi.stubEnv('FTS_SEARCH_PROVIDER', undefined);+ expect(getFtsSearchConfig({ defaultProvider: 'elasticsearch' }).FTS_SEARCH_PROVIDER).toBe(+ 'elasticsearch',+ );++ vi.stubEnv('FTS_SEARCH_PROVIDER', 'pg_like');+ expect(getFtsSearchConfig({ defaultProvider: 'elasticsearch' }).FTS_SEARCH_PROVIDER).toBe(+ 'pg_like',+ );+ });+it('rejects unsupported search backends', () => {vi.stubEnv('FTS_SEARCH_PROVIDER', 'opensearch');diff --git a/packages/env/src/ftsSearch.ts b/packages/env/src/ftsSearch.tsindex 6c2a2a164d9..315c392468c 100644--- a/packages/env/src/ftsSearch.ts+++ b/packages/env/src/ftsSearch.ts@@ -25,13 +25,32 @@ export const getElasticsearchFtsSearchConfig = () => {});};-export const getFtsSearchConfig = () => {+/**+ * Deployment-selected full-text search implementation.+ *+ * - `pg_search`: ParadeDB BM25 (self-host default).+ * - `elasticsearch`: managed Elasticsearch cluster.+ * - `pg_like`: extension-free PostgreSQL `ILIKE` matching for lightweight deployments;+ * an explicit choice, never an implicit fallback for a missing extension.+ */+export const FTS_SEARCH_PROVIDER_VALUES = ['elasticsearch', 'pg_search', 'pg_like'] as const;++export type FtsSearchProviderName = (typeof FTS_SEARCH_PROVIDER_VALUES)[number];++export interface FtsSearchConfigOptions {+ /** Provider used when `FTS_SEARCH_PROVIDER` is unset; distributions override it. */+ defaultProvider?: FtsSearchProviderName;+}++export const getFtsSearchConfig = ({+ defaultProvider = 'pg_search',+}: FtsSearchConfigOptions = {}) => {const providerConfig = createEnv({runtimeEnv: {FTS_SEARCH_PROVIDER: process.env.FTS_SEARCH_PROVIDER,},server: {- FTS_SEARCH_PROVIDER: z.enum(['elasticsearch', 'pg_search']).default('pg_search'),+ FTS_SEARCH_PROVIDER: z.enum(FTS_SEARCH_PROVIDER_VALUES).default(defaultProvider),},});