Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(search): add contains match mode and MessageSearch MCP tool

Luisc21516fd61f9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6ae451c06..1b0c3f950 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -272,7 +272,7 @@ jobs:
# spec's own two-migrator race is in-file (Promise.all) and unaffected by runInBand. The
# synchronize spec additionally CREATEs and DROPs a scratch database of its own, which is
# only safe serialized.
- run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.ts src/database/postgres-utc.pg.spec.ts src/modules/webhook/webhook-recovery.pg.spec.ts src/modules/message/idempotency/send-idempotency.service.pg.spec.ts src/modules/infra/infra-data.import.pg.spec.ts src/modules/session/session-content-lifetime.spec.ts
+ run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.ts src/database/postgres-utc.pg.spec.ts src/modules/webhook/webhook-recovery.pg.spec.ts src/modules/message/idempotency/send-idempotency.service.pg.spec.ts src/modules/infra/infra-data.import.pg.spec.ts src/modules/session/session-content-lifetime.spec.ts
env:
TZ: Asia/Jakarta
DATABASE_TYPE: postgres
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 30dcbd2c4..5aca03f9b 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -243,7 +243,7 @@ jobs:
# tree CI had passed minutes earlier). The lock spec's own two-migrator race is in-file
# (Promise.all) and unaffected by runInBand. The synchronize spec additionally CREATEs and
# DROPs a scratch database of its own, which is only safe serialized.
- run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.ts src/database/postgres-utc.pg.spec.ts src/modules/webhook/webhook-recovery.pg.spec.ts src/modules/message/idempotency/send-idempotency.service.pg.spec.ts src/modules/infra/infra-data.import.pg.spec.ts src/modules/session/session-content-lifetime.spec.ts
+ run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.ts src/database/postgres-utc.pg.spec.ts src/modules/webhook/webhook-recovery.pg.spec.ts src/modules/message/idempotency/send-idempotency.service.pg.spec.ts src/modules/infra/infra-data.import.pg.spec.ts src/modules/session/session-content-lifetime.spec.ts
env:
TZ: Asia/Jakarta
DATABASE_TYPE: postgres
diff --git a/CHANGELOG.md b/CHANGELOG.md
index df94bcee4..678c38733 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add Number Checker page in dashboard for single and bulk WhatsApp recipient pre-validation.
- Add the opt-in `message.receipt` event for per-recipient group and status receipts on Baileys (#1748).
+- Add `match=contains` to `GET /api/search`: case- and accent-insensitive substring search on a trigram index (an FTS5 trigram table on SQLite, `pg_trgm` and `unaccent` on PostgreSQL). It ranks the 1,000 most recently stored matches by match quality in two bounded phases, so `total` is at most 1,000 in this mode; `match=word` stays the default. The SDKs accept `match`.
+- Add the `MessageSearch` MCP tool, which runs the global message search behind `GET /api/search` for agents, with `match=contains` by default.
### Changed
diff --git a/README.md b/README.md
index 8fe19e24c..c0d7857cd 100644
--- a/README.md
+++ b/README.md
@@ -412,7 +412,7 @@ curl -X POST http://localhost:2785/api/sessions/{sessionId}/webhooks \
OpenWA can expose a **curated set of tools over the [Model Context Protocol](https://modelcontextprotocol.io)** so AI agents (Claude, Cursor, …) can drive WhatsApp. It is **off by default** and **additive** — every REST route keeps working unchanged.
-Set `MCP_ENABLED=true` to mount a stateless Streamable-HTTP transport at **`POST /mcp`** on the existing server (same port, no extra process). It mounts **25 read-only tools** by default — session, message, contact, group, webhook, label and automation-rule _reads_ — because the surface is read-only unless you opt out. Add `MCP_READONLY=false` to mount all **51 tools**, adding the write tier (send, reply, group operations). Either way it is a focused surface rather than the full API, so agents aren't overwhelmed.
+Set `MCP_ENABLED=true` to mount a stateless Streamable-HTTP transport at **`POST /mcp`** on the existing server (same port, no extra process). It mounts **26 read-only tools** by default — session, message, contact, group, webhook, label and automation-rule _reads_ — because the surface is read-only unless you opt out. Add `MCP_READONLY=false` to mount all **52 tools**, adding the write tier (send, reply, group operations). Either way it is a focused surface rather than the full API, so agents aren't overwhelmed.
```bash
MCP_ENABLED=true npm run start:prod # or set MCP_ENABLED in your .env / compose
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 534531da9..58b7dce56 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -725,7 +725,7 @@ The data connection also owns:
- **`lid_mappings`** — LID↔phone-number identity mappings (`src/engine/identity/lid-mapping.entity.ts`).
- **`chat_states`** (engine): per-session mute, archive and pin state of each Baileys chat (`src/engine/adapters/baileys-chat-state.entity.ts`), keyed `(sessionId, chatId)`. `chatId` is the person's phone JID (`<phone>@s.whatsapp.net`) whenever their lid resolves, so a state WhatsApp syncs under the lid and one set through the phone number land on the same row; it stays `<lid>@lid` while the lid is unresolved, and a row found under the lid later is folded onto the phone JID on the chat's next change (reads and the fold take each field from the newest row that observed it: `observed` lists the fields a row has seen, and null, on a row not written since the column was added, means the fields it holds a set value for; the next write that can read the row records the list). WhatsApp does not re-deliver that state, so it is kept in backups. A chat deleted on the phone or through the API loses its row, so a later message starts it clean.
-Additionally, the `AddMessagesFts` migration creates the full-text-search structures over `messages` (a FTS5 virtual table on SQLite, a generated `body_ts` `tsvector` column plus GIN index on PostgreSQL) that back the `/search` endpoint.
+Additionally, the `AddMessagesFts` migration creates the full-text-search structures over `messages` (a FTS5 virtual table on SQLite, a generated `body_ts` `tsvector` column plus GIN index on PostgreSQL) that back the `/search` endpoint, and the `AddMessagesTrigramSearch` migration adds the trigram index behind `/search?match=contains` (a `messages_trgm` FTS5 trigram table on SQLite; the `pg_trgm` and `unaccent` extensions, an `openwa_unaccent(text)` function, a GIN trigram index and a `("createdAt", "id")` b-tree on PostgreSQL).
> [!NOTE]
> **Tables that do _not_ exist.** Earlier drafts referenced `contacts`, `session_logs`, `webhook_logs`, `api_key_logs`, `webhook_idempotency`, and `ip_whitelist`. None of these are implemented. Contacts are read live from the engine; auditing is the single `audit_logs` table; webhook idempotency is not a persisted table; and per-key IP restrictions are stored inline on `api_keys."allowedIps"` (a `simple-array`), not in a separate `ip_whitelist` table.
@@ -927,7 +927,8 @@ src/database/migrations/ # data connection (pluggable)
├── 1787100000000-AddSendIdempotencyKeys.ts # send_idempotency_keys (opt-in send retry guard)
├── 1787200000000-DeduplicateTerminalWebhookFailures.ts # one terminal record per webhook and idempotency key
├── 1790812800000-AddMessageWindowIndexes.ts # compound timestamp indexes for message-time pagination
-└── 1791100000000-AddIntegrationDeliveryFailureDeliveryIndex.ts # (pluginId, instanceId, deliveryId) index for the dead-letter guards
+├── 1791100000000-AddIntegrationDeliveryFailureDeliveryIndex.ts # (pluginId, instanceId, deliveryId) index for the dead-letter guards
+└── 1792400000000-AddMessagesTrigramSearch.ts # match=contains indexes: FTS5 trigram (SQLite) / pg_trgm + unaccent GIN and (createdAt, id) b-tree (Postgres)
```
> [!NOTE]
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index d0f8823c8..599a7c3f6 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -6512,18 +6512,19 @@ Search messages across sessions (active search provider).
**Query parameters**
-| Name | Type | Required | Default | Description |
-| ----------- | ------------------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `q` | string | **Yes** | — | Search term. Must be non-empty after trim; `400` for whitespace-only, over 1000 characters, or over 32 words (punctuation separates words, a symbol or emoji that stands apart counts as a word, a whitespace-separated word said again counts once). Passed to the active provider's native full-text matcher. |
-| `sessionId` | string | No | — | Restrict to a single session id (intersected with the key's `allowedSessions` scope). |
-| `chatId` | string | No | — | Restrict to a single chat id. For a key restricted to selected chats this must name an allowed chat (`403` otherwise), and its hits are additionally narrowed to the allowlist. |
-| `direction` | enum (`incoming` \| `outgoing`) | No | — | Filter by message direction. |
-| `type` | string | No | — | Filter by stored message `type` (e.g. `text`, `image`, `video`). Compared against `messages.type`; not an enum validation, any string is accepted and unmatched values simply return no hits. |
-| `from` | string | No | — | Filter by sender. |
-| `dateFrom` | integer (epoch ms) | No | — | Inclusive lower bound on `timestamp`. A non-numeric value is rejected with `400`. |
-| `dateTo` | integer (epoch ms) | No | — | Inclusive upper bound on `timestamp`. A non-numeric value is rejected with `400`. |
-| `limit` | integer (≥ 1) | No | `50` | Max hits to return. Clamped to `SEARCH_LIMIT_MAX` (default `100`). A non-integer value is rejected with `400`. |
-| `offset` | integer (≥ 0) | No | `0` | Pagination offset, at most `100000`. A non-integer or larger value is rejected with `400`. |
+| Name | Type | Required | Default | Description |
+| ----------- | ------------------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `q` | string | **Yes** | — | Search term. Must be non-empty after trim; `400` for whitespace-only, over 1000 characters, or over 32 words (punctuation separates words, a symbol or emoji that stands apart counts as a word, a whitespace-separated word said again counts once). Passed to the active provider's native full-text matcher. |
+| `match` | enum (`word` \| `contains`) | No | `word` | `word` matches whole words. `contains` matches any part of a word, ignoring case and accents (`voic` finds "Invoice", `cafe` finds "Café"); every term must appear, at least one term needs 3+ characters (`400` otherwise), and `%`/`_` match literally. It ranks the 1,000 most recently stored matches by match quality (whole word, then word start, then inside a word; newest first within a score), so `total` is at most 1,000. On PostgreSQL it needs the `pg_trgm` and `unaccent` extensions (`501` otherwise). See [26 - Global Search](./26-global-search.md#match-modes). |
+| `sessionId` | string | No | — | Restrict to a single session id (intersected with the key's `allowedSessions` scope). |
+| `chatId` | string | No | — | Restrict to a single chat id. For a key restricted to selected chats this must name an allowed chat (`403` otherwise), and its hits are additionally narrowed to the allowlist. |
+| `direction` | enum (`incoming` \| `outgoing`) | No | — | Filter by message direction. |
+| `type` | string | No | — | Filter by stored message `type` (e.g. `text`, `image`, `video`). Compared against `messages.type`; not an enum validation, any string is accepted and unmatched values simply return no hits. |
+| `from` | string | No | — | Filter by sender. |
+| `dateFrom` | integer (epoch ms) | No | — | Inclusive lower bound on `timestamp`. A non-numeric value is rejected with `400`. |
+| `dateTo` | integer (epoch ms) | No | — | Inclusive upper bound on `timestamp`. A non-numeric value is rejected with `400`. |
+| `limit` | integer (≥ 1) | No | `50` | Max hits to return. Clamped to `SEARCH_LIMIT_MAX` (default `100`). A non-integer value is rejected with `400`. |
+| `offset` | integer (≥ 0) | No | `0` | Pagination offset, at most `100000`. A non-integer or larger value is rejected with `400`. |
**Response** `200` — `SearchResults`
@@ -6553,18 +6554,23 @@ Search messages across sessions (active search provider).
- `snippet` is a text excerpt with `<mark>`/`</mark>` highlight markers around the matched term (both
dialects emit the same markers). The body text inside it is not HTML-escaped: split on the literal
markers and render each segment as text, never the raw snippet as HTML.
-- `total` is an exact count for pagination, computed lazily only when the returned page could be full.
+- `total` is an exact count for pagination, computed lazily only when the returned page could be full. With
+ `match=contains` it counts the ranked window, at most 1,000 matches.
- `provider` names which backend answered (e.g. `builtin-fts`); it is the registered `SearchProvider`
id, so it changes when a plugin backend is selected via `SEARCH_PROVIDER`.
- `score` is optional and provider-specific (rank ordering is stable within a provider; cross-provider
scores are not comparable). The built-in provider on SQLite leaves it out for a key restricted to
- selected sessions or chats, since it is computed over the whole index.
+ selected sessions or chats, since it is computed over the whole index. With `match=contains` it is
+ the match quality on both dialects (3 per term found as a whole word, 2 at a word start, 1 inside a
+ word) and every key gets it, since it reads only its own message.
-**Errors:** `400` empty/whitespace `q`, a non-numeric `dateFrom`/`dateTo`/`limit`/`offset`, an `offset` above `100000`, or a malformed
+**Errors:** `400` empty/whitespace `q`, a non-numeric `dateFrom`/`dateTo`/`limit`/`offset`, an `offset` above `100000`, an unknown `match`, a
+`match=contains` query whose terms are all shorter than 3 characters, or a malformed
SQLite FTS5 query (unbalanced quote/paren, bare operator) — Postgres's `websearch_to_tsquery` is
tolerant and has no equivalent · `401` missing/invalid `X-API-Key` · `403` key role below `OPERATOR`, or a chat-restricted key
that names a `chatId` outside its allowlist or uses a plugin provider ·
-`501` no search provider configured (including a non-FTS5 SQLite build, where the provider is absent) ·
+`501` no search provider configured (including a non-FTS5 SQLite build, where the provider is absent), or for
+`match=contains` the trigram index is absent (PostgreSQL without `pg_trgm` and `unaccent`, or SQLite older than 3.45) ·
`502` the active plugin provider returned an invalid result shape (not retryable until the plugin is fixed) ·
`503` the active plugin provider did not answer (worker not running, timed out, or reported a failure;
retryable). The built-in provider returns neither `502` nor `503`.
diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.md
index d71c68245..764dd4cfc 100644
--- a/docs/24-mcp-integration.md
+++ b/docs/24-mcp-integration.md
@@ -14,7 +14,7 @@
| **Tool registry (`ToolDescriptor`)** | ✅ Implemented | `src/core/agent-tools/tool-descriptor.ts` |
| **Tool invoker (auth → chat gate → validate → chat arguments → service)** | ✅ Implemented | `src/core/agent-tools/tool-invoker.ts` |
| **Registry service** | ✅ Implemented | `src/core/agent-tools/tool-registry.service.ts` |
-| **Curated tool tables (51 tools)** | ✅ Implemented | `src/core/agent-tools/tools/*.tools.ts` |
+| **Curated tool tables (52 tools)** | ✅ Implemented | `src/core/agent-tools/tools/*.tools.ts` |
| **MCP transport adapter** | ✅ Implemented | `src/modules/mcp/mcp.server.ts` |
| **Opt-in module gate** | ✅ Implemented | `src/modules/mcp/mcp.module.ts`, `src/app.module.ts` |
| **Per-key rate limiter** | ✅ Implemented | `src/modules/mcp/mcp-rate-limit.ts` |
@@ -85,7 +85,7 @@ flowchart TB
flowchart LR
Client[MCP client] -->|POST /mcp| Adapter
subgraph Core["src/core/agent-tools (SDK-free)"]
- Registry[ToolRegistryService<br/>51 ToolDescriptors]
+ Registry[ToolRegistryService<br/>52 ToolDescriptors]
Invoker[invokeTool<br/>auth → chat gate → validate → chat arguments → handler]
end
subgraph Adapter["src/modules/mcp (SDK, opt-in)"]
@@ -133,7 +133,7 @@ The surface is an **allowlist by construction** — a capability is exposed only
`ToolDescriptor` is written for it. There is no automatic route reflection. Each tool
declares a `tier` (`read` | `write`) and a `requiredRole` when the call warrants one: every
write carries its privilege level, and a read carries the role its REST twin requires. The
-reads at OPERATOR are `WebhooksList`, `WebhookFindBySession` and `WebhookFindOne`,
+reads at OPERATOR are `MessageSearch`, `WebhooksList`, `WebhookFindBySession` and `WebhookFindOne`,
`AutomationRuleFindAll` and `AutomationRuleFindOne`, `GroupGetInviteCode` (the invite
code is a transferable join capability, so it sits at OPERATOR like the QR endpoint), and
`ContactCheckNumber` (each call queries WhatsApp about a third party).
@@ -141,7 +141,7 @@ code is a transferable join capability, so it sits at OPERATOR like the QR endpo
| Domain | Read tools | Write tools |
| -------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| **Session** | list, get, chats, stats, presence | mark read/unread, typing, subscribe presence |
-| **Message** | list, history, reactions | send text/image/video/audio/document/location/contact/sticker/template, reply, forward, react |
+| **Message** | list, history, reactions, search (OPERATOR) | send text/image/video/audio/document/location/contact/sticker/template, reply, forward, react |
| **Contact** | list, get, check-number (OPERATOR), resolve-phone, profile-picture | block, unblock |
| **Group** | list, get, invite-code (OPERATOR) | create, add participants, set subject, set description |
| **Webhook** | list, get (OPERATOR) | — |
@@ -213,7 +213,7 @@ only when an agent genuinely needs to send messages / mutate state.
### Threat model: untrusted message content
The read tools return what other WhatsApp users wrote, verbatim: message bodies and captions
-(`MessageList`, `MessageHistory`), last-message previews and chat names (`SessionGetChats`,
+(`MessageList`, `MessageHistory`, `MessageSearch`), last-message previews and chat names (`SessionGetChats`,
`LabelListChats`), push names and contact names (`ContactFindAll`, `ContactFindOne`), and group
subjects and descriptions (`GroupFindAll`, `GroupFindOne`). Treat any read tool that returns a name
or message text the same way. Anyone who can message the account, or join or rename a group it is
diff --git a/docs/26-global-search.md b/docs/26-global-search.md
index 399d4a3e5..ad5d140ce 100644
--- a/docs/26-global-search.md
+++ b/docs/26-global-search.md
@@ -65,6 +65,54 @@ HTML-escaped: split on the literal `<mark>`/`</mark>` markers and render each se
dashboard does this with `renderHighlightedSnippet` in `dashboard/src/utils/search-highlight.ts`), and
never assign the raw snippet to `innerHTML`.
+### Match modes
+
+The `match` query parameter picks how `q` matches a message body. Each mode has its own DB-maintained
+index, so both are index lookups, never table scans:
+
+| `match` | Matches | Index | Ranking |
+| ---------------- | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
+| `word` (default) | whole words, as described above | `body_ts` (Postgres) / `messages_fts` (SQLite) | `ts_rank` / FTS5 `rank`, over every match |
+| `contains` | any part of a word of 3+ characters, ignoring case and accents (`voic` finds "Invoice", `cafe` finds "Café") | a `pg_trgm` GIN index on `openwa_unaccent(body)` (Postgres) / an FTS5 `trigram` table with `remove_diacritics`, `messages_trgm` (SQLite) | match quality, over the 1,000 most recently stored matches |
+
+`contains` finds everything `word` finds, plus partial words. Every whitespace-separated term must
+appear, as with `word`; a repeated term (also one that differs only in case or accents) runs once. A
+trigram index cannot look up a term shorter than three characters, so such a term (`id`, `pm`) only
+narrows what a longer term found, and a query made of short terms alone answers `400`. The query
+grammar of `word` mode (quoted phrases, `OR`, `-` on Postgres) does not apply: every term, `%` and `_`
+included, matches literally.
+
+**Ranking runs in two phases.** Ranking every match in SQL costs time in proportion to the number of
+matches: measured on 1M messages with a term found in 200k of them, about 100 ms on SQLite (where that
+time blocks the event loop every session shares) and 1.6 s on Postgres. So `contains` bounds the work:
+
+1. The database returns at most **1,000 candidates**: the most recently stored messages that contain
+ every term, newest first. Both dialects answer that order from an index and stop at 1,000, however
+ many messages match. SQLite reads its trigram index in insertion order; Postgres walks the
+ `idx_messages_created_at_id` b-tree backward for a common term, or reads the few matches of a rare
+ one from the GIN index.
+2. The application ranks the candidates and pages them: each term scores **3** as a whole word, **2**
+ at the start of a word and **1** inside a word (compared without case or accents), the hit's `score`
+ is the sum over the terms, and ties go to the newest message, then to `messageId`. The same code
+ ranks both dialects, so they return the same order.
+
+Both phases together take about 2 ms on SQLite and 10 to 20 ms on Postgres at that size. The trade-off is that relevance orders the window, not the whole history: `total` is at most
+1,000 in this mode, and pages past it are empty. Reach older matches by narrowing the query (more
+terms, `chatId`, `dateTo`). Because a score reads only its own message, it is returned to scoped keys
+as well (unlike the SQLite `word` score, see below).
+
+A `contains` snippet is built by the application rather than the database (FTS5's `snippet()` counts
+its window in trigrams, and Postgres has no headline function for a substring), so both dialects return
+the same text, under the same `<mark>` contract and the same "not HTML-escaped" rule.
+
+**Requirements.** On SQLite, `contains` needs FTS5 and SQLite 3.45+ (the first with `remove_diacritics`
+for the trigram tokenizer); the bundled `better-sqlite3` ships both. On Postgres it needs the
+`pg_trgm` and `unaccent` extensions, which the migration creates when the database role may (both are
+trusted extensions from PostgreSQL 13, so a database owner can). When it may not, the migration skips
+them without failing the boot, only `match=contains` answers `501` (with the `CREATE EXTENSION`
+statements to run), and `match=word` keeps working; once an operator installs the extensions, the next
+boot builds the wrapper function and the indexes.
+
## 26.4 Dual-database switching safety
Search is designed to work identically on SQLite and PostgreSQL and to survive repeated switching
@@ -129,10 +177,13 @@ See [06 - API Specification §6.4.12](./06-api-specification.md) for the full pa
In brief:
```
-GET /api/search?q=<term>&sessionId=<id>&chatId=<id>&direction=<incoming|outgoing>&type=<type>
- &from=<sender>&dateFrom=<ms>&dateTo=<ms>&limit=<n>&offset=<n>
+GET /api/search?q=<term>&match=<word|contains>&sessionId=<id>&chatId=<id>&direction=<incoming|outgoing>
+ &type=<type>&from=<sender>&dateFrom=<ms>&dateTo=<ms>&limit=<n>&offset=<n>
```
+- **`match`** is `word` (the default) or `contains`; see [Match modes](#match-modes). Any other value
+ is a `400`.
+
- **`q`** is required and must be non-empty (whitespace-only is rejected with `400`, and so is one
longer than 1000 characters or with more than 32 words, punctuation separating words as whitespace does and a symbol or emoji that stands apart counting as one; a whitespace-separated word said again counts once). Numeric params
are coerced and validated; a non-numeric `limit`/`offset`/`dateFrom`/`dateTo` surfaces as `400`,
@@ -145,18 +196,21 @@ GET /api/search?q=<term>&sessionId=<id>&chatId=<id>&direction=<incoming|outgoing
- **Chat scope applies the same way.** A key with a non-empty `allowedChats` searches only those
chats: the built-in provider narrows its hits before `limit`, `offset` and `total` apply, an explicit
`chatId` outside the allowlist answers `403`, and a plugin provider answers `403` for such a key
- (set `SEARCH_PROVIDER=builtin-fts` to allow scoped search). On SQLite the hits of a key scoped to
- sessions or chats carry no `score`, because the value is computed over the whole index and would
- reflect messages outside its scope; the hits stay in relevance order.
+ (set `SEARCH_PROVIDER=builtin-fts` to allow scoped search). On SQLite the `match=word` hits of a key
+ scoped to sessions or chats carry no `score`, because the value is computed over the whole index and
+ would reflect messages outside its scope; the hits stay in relevance order. A `match=contains` score
+ reads only its own message, so every key gets it.
- **Response** is a `SearchResults` object: `{ hits: SearchHit[], total, tookMs, provider }`. Each hit
carries `messageId`, `waMessageId`, `sessionId`, `chatId`, `body`, `snippet`, `timestamp`, `type`,
`direction`, `from`, and optional `score`. `total` is an exact count (bounded; computed lazily only
when the page could be full). `tookMs` is the provider-side query time. `provider` names which
backend answered (e.g. `builtin-fts`).
-- **Errors:** `400` empty/whitespace `q` or a non-numeric numeric param (an FTS5 query-grammar error is
- also mapped to `400`, but since the SQLite path quotes every token ordinary input no longer reaches
+- **Errors:** `400` empty/whitespace `q`, a non-numeric numeric param, an unknown `match`, or a
+ `match=contains` query whose terms are all shorter than three characters (an FTS5 query-grammar error
+ is also mapped to `400`, but since the SQLite path quotes every token ordinary input no longer reaches
that fallback) · `401`/`403` auth · `501` no provider configured / FTS schema absent (e.g. a non-FTS5
- SQLite build) · `502` a plugin provider returned a malformed `SearchResults` payload · `503` a plugin
+ SQLite build) / for `match=contains`, the trigram index absent (e.g. Postgres without `pg_trgm` and
+ `unaccent`) · `502` a plugin provider returned a malformed `SearchResults` payload · `503` a plugin
provider whose worker timed out or failed (the built-in provider does not return it).
The endpoint requires at least `OPERATOR` role.
@@ -164,9 +218,9 @@ The endpoint requires at least `OPERATOR` role.
## 26.7 When to use a plugin backend
The built-in DB full-text provider is the right default for the common case: moderate volume, Latin and
-mixed-Script text, whole-token matching (phrase and boolean operators only on Postgres — see §26.3),
-and no extra infrastructure. Reach for a plugin provider when you need capabilities the SQL engines do
-not give you:
+mixed-Script text, whole-token matching (phrase and boolean operators only on Postgres — see §26.3) or
+case- and accent-insensitive substring matching (`match=contains`), and no extra infrastructure. Reach
+for a plugin provider when you need capabilities the SQL engines do not give you:
- **CJK word-segmentation and morphological analysis** — Postgres `'simple'` and SQLite FTS5 tokenize
on whitespace/punctuation, which does not segment Chinese/Japanese/Korean. A dedicated engine
@@ -212,6 +266,20 @@ Adding search to an existing deployment runs the one-time `1782400000000-AddMess
The migration is safe to re-run (idempotent guards) and has a `down` path that drops the FTS schema on
both dialects. After it applies, search works immediately — no separate reindex command.
+`match=contains` adds the one-time `1792400000000-AddMessagesTrigramSearch` migration:
+
+- **PostgreSQL** creates the `pg_trgm` and `unaccent` extensions inside a savepoint (a role that may
+ not create them rolls back to it and the migration stops there, see [Match modes](#match-modes)), the
+ IMMUTABLE `openwa_unaccent(text)` wrapper, a `GIN` trigram index on `openwa_unaccent(body)` and the
+ `idx_messages_created_at_id` b-tree on `("createdAt", "id")` that serves the candidate window (the
+ existing message indexes all lead with `sessionId`). Both are built **non-`CONCURRENTLY`**: plan a
+ maintenance window for a very large table.
+- **SQLite** creates the `messages_trgm` FTS5 trigram table, backfills it like `messages_fts` and
+ installs its own three sync triggers. A trigram index holds every three-character window of the
+ body, so it takes noticeably more space than the word index.
+
+Its `down` path drops what it created except the Postgres extensions, which other objects may use.
+
---
> See also: [06 - API Specification](./06-api-specification.md) (§6.4.12 Search),
diff --git a/openapi.json b/openapi.json
index 860ec7985..94f5f34c7 100644
--- a/openapi.json
+++ b/openapi.json
@@ -17823,6 +17823,19 @@
"type": "string"
}
},
+ {
+ "name": "match",
+ "required": false,
+ "in": "query",
+ "description": "word (default): whole words. contains: any part of a word, ignoring case and accents; ranks the 1000 most recently stored matches by match quality",
+ "schema": {
+ "enum": [
+ "word",
+ "contains"
+ ],
+ "type": "string"
+ }
+ },
{
"name": "sessionId",
"required": false,
@@ -17924,7 +17937,7 @@
}
},
"400": {
- "description": "Empty or whitespace-only \"q\", or one over 1000 characters or 32 words",
+ "description": "Empty or whitespace-only \"q\", or one over 1000 characters or 32 words; an unknown \"match\"; or a \"match=contains\" query whose terms are all shorter than 3 characters",
"content": {
"application/json": {
"schema": {
@@ -17954,7 +17967,7 @@
}
},
"501": {
- "description": "No search provider configured",
+ "description": "No search provider configured, or the built-in provider lacks the index the requested match mode needs (for \"match=contains\" on PostgreSQL: the pg_trgm and unaccent extensions)",
"content": {
"application/json": {
"schema": {
diff --git a/sdk/go/types_search.go b/sdk/go/types_search.go
index ddc4628c8..bf33be5de 100644
--- a/sdk/go/types_search.go
+++ b/sdk/go/types_search.go
@@ -3,9 +3,12 @@ package openwa
import "net/url"
// SearchQuery is the query for GET /search. Q is required; all else optional.
-// DateFrom/DateTo are epoch-ms.
+// DateFrom/DateTo are epoch-ms. Match is "word" (the server default: whole
+// words) or "contains" (any part of a word, ignoring case and accents; needs a
+// term of 3+ characters).
type SearchQuery struct {
Q string
+ Match *string
SessionID *string
ChatID *string
Direction *string
@@ -20,6 +23,7 @@ type SearchQuery struct {
func (q *SearchQuery) values() url.Values {
v := url.Values{}
v.Set("q", q.Q)
+ setStr(v, "match", q.Match)
setStr(v, "sessionId", q.SessionID)
setStr(v, "chatId", q.ChatID)
setStr(v, "direction", q.Direction)
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchMatch.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchMatch.java
new file mode 100644
index 000000000..6688533dd
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchMatch.java
@@ -0,0 +1,15 @@
+package com.rmyndharis.openwa.model;
+
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * How {@code GET /search} matches {@code q}. {@link #WORD} (the server default) matches whole words;
+ * {@link #CONTAINS} matches any part of a word, ignoring case and accents, and needs at least one
+ * term of 3+ characters. Wire values are lowercase.
+ */
+public enum SearchMatch {
+ @SerializedName("word")
+ WORD,
+ @SerializedName("contains")
+ CONTAINS
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchQuery.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchQuery.java
index 0be8470ec..6766a720d 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchQuery.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchQuery.java
@@ -10,6 +10,7 @@ package com.rmyndharis.openwa.model;
*/
public record SearchQuery(
String q,
+ SearchMatch match,
String sessionId,
String chatId,
MessageDirection direction,
@@ -25,6 +26,7 @@ public record SearchQuery(
public static final class Builder {
private String q;
+ private SearchMatch match;
private String sessionId;
private String chatId;
private MessageDirection direction;
@@ -41,6 +43,12 @@ public record SearchQuery(
return this;
}
+ /** Match mode; the server defaults to {@link SearchMatch#WORD} when omitted. */
+ public Builder match(SearchMatch v) {
+ this.match = v;
+ return this;
+ }
+
public Builder sessionId(String v) {
this.sessionId = v;
return this;
@@ -87,7 +95,7 @@ public record SearchQuery(
}
public SearchQuery build() {
- return new SearchQuery(q, sessionId, chatId, direction, type, from, dateFrom, dateTo, limit, offset);
+ return new SearchQuery(q, match, sessionId, chatId, direction, type, from, dateFrom, dateTo, limit, offset);
}
}
}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SearchResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SearchResourceTest.java
index 152691809..8bf5fdc25 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SearchResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SearchResourceTest.java
@@ -11,6 +11,7 @@ import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.MessageDirection;
import com.rmyndharis.openwa.model.SearchHit;
+import com.rmyndharis.openwa.model.SearchMatch;
import com.rmyndharis.openwa.model.SearchQuery;
import com.rmyndharis.openwa.model.SearchResults;
import com.rmyndharis.openwa.support.MockTransport;
@@ -48,6 +49,13 @@ class SearchResourceTest {
assertTrue(tx.lastRequest().url().contains("direction=incoming"));
}
+ @Test
+ void searchSerializesMatchAsLowercaseWireValue() {
+ tx.respond(200, RESULTS);
+ client.search.search(SearchQuery.builder().q("voic").match(SearchMatch.CONTAINS).build());
+ assertTrue(tx.lastRequest().url().contains("match=contains"));
+ }
+
@Test
void searchSerializesEpochMsDateBounds() {
tx.respond(200, RESULTS);
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index d5ad3705d..611bbd157 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -1430,10 +1430,18 @@ export interface SendProductRequest {
// ── Search ────────────────────────────────────────────────────────
+/**
+ * How `q` matches: `word` (the server default) matches whole words; `contains` matches any part of a
+ * word, ignoring case and accents, and needs at least one term of 3+ characters.
+ */
+export type SearchMatch = 'word' | 'contains';
+
/** Query parameters for `GET /search`. Only `q` is required; all filters are optional. */
export interface SearchParams {
/** Search term (required, non-empty — the server rejects empty/whitespace with 400). */
q: string;
+ /** Match mode; the server defaults to `word`. */
+ match?: SearchMatch;
/** Restrict to a single session. */
sessionId?: string;
/** Restrict to a single chat id. */
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index 736b25bab..ef68d2b38 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -539,4 +539,12 @@ describe('SearchResource — exact path and query forwarding', () => {
await c.search.search({ q: 'term', chatId: '[email protected]', direction: 'incoming' });
expect(t.lastCall!.url).toBe('http://x/api/search?q=term&chatId=628%40c.us&direction=incoming');
});
+
+ it('forwards the match mode', async () => {
+ const t = new MockTransport().on('GET', /\/search$/, {
+ body: { hits: [], total: 0, tookMs: 1, provider: 'builtin-fts' },
+ });
+ await client(t).search.search({ q: 'voic', match: 'contains' });
+ expect(t.lastCall!.url).toBe('http://x/api/search?q=voic&match=contains');
+ });
});
diff --git a/sdk/php/src/Resources/SearchResource.php b/sdk/php/src/Resources/SearchResource.php
index c6f34b868..c1b3684d5 100644
--- a/sdk/php/src/Resources/SearchResource.php
+++ b/sdk/php/src/Resources/SearchResource.php
@@ -30,8 +30,12 @@ class SearchResource
* into the query string). Numeric filters are passed through as-is; the
* gateway coerces and validates them server-side.
*
+ * `match` is `word` (the server default: whole words) or `contains` (any
+ * part of a word, ignoring case and accents; needs a term of 3+ characters).
+ *
* @param array{
* q:string,
+ * match?:'word'|'contains'|null,
* sessionId?:string|null,
* chatId?:string|null,
* direction?:string|null,
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index fc3c5a0b3..961adf5bf 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -1453,9 +1453,12 @@ class _SearchQueryRequired(TypedDict):
q: str
+# `match` is "word" (the server default: whole words) or "contains" (any part
+# of a word, ignoring case and accents; needs a term of 3+ characters).
_SearchQueryOptional = TypedDict(
"_SearchQueryOptional",
{
+ "match": Literal["word", "contains"],
"sessionId": str,
"chatId": Jid,
"direction": MessageDirection,
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index bed9deaf7..83d0833fd 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -1231,6 +1231,7 @@ class TestSearch:
})
make_client(backend).search.search({
"q": "invoice",
+ "match": "contains",
"sessionId": "s1",
"chatId": "[email protected]",
"direction": "incoming",
@@ -1244,6 +1245,7 @@ class TestSearch:
url = backend.last_call.url
assert url.startswith("http://localhost:2785/api/search?")
assert "q=invoice" in url
+ assert "match=contains" in url
assert "sessionId=s1" in url
assert "chatId=628123%40c.us" in url # @ percent-encoded in query
assert "direction=incoming" in url
diff --git a/src/core/agent-tools/agent-tools.module.ts b/src/core/agent-tools/agent-tools.module.ts
index 1343b96aa..61d7ece0f 100644
--- a/src/core/agent-tools/agent-tools.module.ts
+++ b/src/core/agent-tools/agent-tools.module.ts
@@ -14,6 +14,7 @@ import { GroupService } from '../../modules/group/group.service';
import { WebhookService } from '../../modules/webhook/webhook.service';
import { LabelService } from '../../modules/label/label.service';
import { AutomationRulesService } from '../../modules/automation/automation-rules.service';
+import { SearchService } from '../../modules/search/search.service';
import { allAgentTools } from './tools';
@Global()
@@ -30,6 +31,8 @@ import { allAgentTools } from './tools';
WebhookService,
LabelService,
AutomationRulesService,
+ // Optional: SEARCH_ENABLED=false leaves SearchModule (global, so no import here) out of the app.
+ { token: SearchService, optional: true },
],
useFactory: (
session: SessionService,
@@ -39,7 +42,11 @@ import { allAgentTools } from './tools';
webhook: WebhookService,
labels: LabelService,
automation: AutomationRulesService,
- ) => new ToolRegistryService(allAgentTools({ session, message, contact, group, webhook, labels, automation })),
+ search?: SearchService,
+ ) =>
+ new ToolRegistryService(
+ allAgentTools({ session, message, contact, group, webhook, labels, automation, search }),
+ ),
},
],
exports: [ToolRegistryService],
diff --git a/src/core/agent-tools/tool-registry.spec.ts b/src/core/agent-tools/tool-registry.spec.ts
index c3851f827..3ac7d23d5 100644
--- a/src/core/agent-tools/tool-registry.spec.ts
+++ b/src/core/agent-tools/tool-registry.spec.ts
@@ -52,6 +52,7 @@ describe('v1 tool surface snapshot', () => {
'MessageList',
'MessageHistory',
'MessageGetReactions',
+ 'MessageSearch',
'MessageSendText',
'MessageSendImage',
'MessageSendVideo',
@@ -96,6 +97,6 @@ describe('v1 tool surface snapshot', () => {
const actualNames = [...allAgentTools({} as never)].map(t => t.name).sort();
expect(actualNames).toEqual(expected);
- expect(expected).toHaveLength(51);
+ expect(expected).toHaveLength(52);
});
});
diff --git a/src/core/agent-tools/tools/index.ts b/src/core/agent-tools/tools/index.ts
index 66158e7d9..40236bea2 100644
--- a/src/core/agent-tools/tools/index.ts
+++ b/src/core/agent-tools/tools/index.ts
@@ -5,6 +5,7 @@ import type { GroupService } from '../../../modules/group/group.service';
import type { WebhookService } from '../../../modules/webhook/webhook.service';
import type { LabelService } from '../../../modules/label/label.service';
import type { AutomationRulesService } from '../../../modules/automation/automation-rules.service';
+import type { SearchService } from '../../../modules/search/search.service';
import type { AnyToolDescriptor } from '../tool-descriptor';
import { sessionTools } from './session.tools';
import { messageTools } from './message.tools';
@@ -13,6 +14,7 @@ import { groupTools } from './group.tools';
import { webhookTools } from './webhook.tools';
import { labelTools } from './label.tools';
import { automationTools } from './automation.tools';
+import { searchTools } from './search.tools';
/** The services each tool family needs. Stubs suffice where a spec only inspects declarations. */
export interface AgentToolDeps {
@@ -23,6 +25,8 @@ export interface AgentToolDeps {
webhook: WebhookService;
labels: LabelService;
automation: AutomationRulesService;
+ /** Absent when SEARCH_ENABLED=false omits SearchModule; MessageSearch then answers 501. */
+ search?: SearchService;
}
/**
@@ -42,5 +46,6 @@ export function allAgentTools(deps: AgentToolDeps): AnyToolDescriptor[] {
...webhookTools(deps.webhook),
...labelTools(deps.labels),
...automationTools(deps.automation),
+ ...searchTools(deps.search),
];
}
diff --git a/src/core/agent-tools/tools/search.tools.spec.ts b/src/core/agent-tools/tools/search.tools.spec.ts
new file mode 100644
index 000000000..2e7c71cb4
--- /dev/null
+++ b/src/core/agent-tools/tools/search.tools.spec.ts
@@ -0,0 +1,84 @@
+import { BadRequestException, ForbiddenException, NotImplementedException } from '@nestjs/common';
+import { ChatScopeService } from '../../../modules/auth/chat-scope.service';
+import type { AuthService } from '../../../modules/auth/auth.service';
+import type { SearchService } from '../../../modules/search/search.service';
+import { invokeTool } from '../tool-invoker';
+import { searchTools } from './search.tools';
+
+const CHAT = '[email protected]';
+const OTHER = '[email protected]';
+const results = { hits: [], total: 0, tookMs: 1, provider: 'builtin-fts' };
+
+function authFor(key: object): AuthService {
+ return {
+ validateApiKey: jest.fn().mockResolvedValue(key),
+ hasPermission: jest.fn().mockReturnValue(true),
+ } as unknown as AuthService;
+}
+
+describe('MessageSearch tool', () => {
+ const search = jest.fn().mockResolvedValue(results);
+ const tool = searchTools({ search } as unknown as SearchService)[0];
+ const call = (key: object, input: unknown) =>
+ invokeTool(tool, input, 'key', authFor(key), undefined, undefined, new ChatScopeService());
+
+ beforeEach(() => search.mockClear());
+
+ it('forwards the query with the key session scope and no chat scope for an unrestricted key', async () => {
+ const key = { id: 'k1', allowedSessions: ['s1'], allowedChats: null };
+ const input = { q: 'invoice', match: 'word', from: '628111000111', direction: 'incoming', dateFrom: 1, limit: 10 };
+
+ await expect(call(key, input)).resolves.toBe(results);
+
+ expect(search).toHaveBeenCalledWith(input, ['s1'], undefined);
+ });
+
+ it('searches every session with match=contains when the agent names neither', async () => {
+ await call({ id: 'k1', allowedSessions: null, allowedChats: null }, { q: 'invoice' });
+
+ expect(search).toHaveBeenCalledWith({ q: 'invoice', match: 'contains' }, undefined, undefined);
+ });
+
+ it('rejects an unknown match mode', async () => {
+ await expect(call({ id: 'k1', allowedSessions: null }, { q: 'invoice', match: 'fuzzy' })).rejects.toBeInstanceOf(
+ BadRequestException,
+ );
+ });
+
+ it('rejects a blank query before searching', async () => {
+ await expect(call({ id: 'k1', allowedSessions: null }, { q: ' ' })).rejects.toBeInstanceOf(BadRequestException);
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ describe('for a key restricted to selected chats', () => {
+ const key = { id: 'k2', allowedSessions: null, allowedChats: [CHAT] };
+
+ it('requires a chatId', async () => {
+ await expect(call(key, { q: 'invoice' })).rejects.toBeInstanceOf(ForbiddenException);
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ it('refuses a chat outside the allowlist', async () => {
+ await expect(call(key, { q: 'invoice', chatId: OTHER })).rejects.toBeInstanceOf(ForbiddenException);
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ it('passes the chat allowlist to the provider for an allowed chat', async () => {
+ await call(key, { q: 'invoice', chatId: CHAT });
+
+ expect(search).toHaveBeenCalledWith(
+ { q: 'invoice', match: 'contains', chatId: CHAT },
+ undefined,
+ expect.arrayContaining([CHAT]),
+ );
+ });
+ });
+
+ it('answers 501 when the search module is disabled', async () => {
+ const disabled = searchTools(undefined)[0];
+
+ await expect(
+ invokeTool(disabled, { q: 'invoice' }, 'key', authFor({ id: 'k1', allowedSessions: null })),
+ ).rejects.toBeInstanceOf(NotImplementedException);
+ });
+});
diff --git a/src/core/agent-tools/tools/search.tools.ts b/src/core/agent-tools/tools/search.tools.ts
new file mode 100644
index 000000000..2f3d54dd9
--- /dev/null
+++ b/src/core/agent-tools/tools/search.tools.ts
@@ -0,0 +1,61 @@
+import { NotImplementedException } from '@nestjs/common';
+import { z } from 'zod';
+import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';
+import { MessageDirection } from '../../../modules/message/entities/message.entity';
+import type { SearchService } from '../../../modules/search/search.service';
+import {
+ SEARCH_CONTAINS_WINDOW,
+ SEARCH_LIMIT_MAX,
+ SEARCH_MATCH_MODES,
+ SEARCH_OFFSET_MAX,
+ SEARCH_QUERY_MAX_LENGTH,
+} from '../../../modules/search/search.constants';
+import { chatIdSchema } from '../chat-id-schema';
+import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';
+
+/**
+ * Global message search for agents: the same SearchService, scopes and limits as `GET /api/search`.
+ *
+ * `search` is undefined when SEARCH_ENABLED=false leaves SearchModule out. The tool is still
+ * registered, so the published tool surface (and the counts the README states) does not depend on
+ * configuration; calling it answers 501, as the REST route answers 404 then.
+ */
+export function searchTools(search: SearchService | undefined): AnyToolDescriptor[] {
+ return [
+ defineTool({
+ name: 'MessageSearch',
+ // A key restricted to selected chats must name an allowed chat, as MessageList requires; the
+ // allowlist is then also handed to the provider, which narrows hits before limit/offset/total and
+ // is how a plugin provider knows to refuse a restricted key.
+ chatScope: ['chatId'],
+ description:
+ 'Search persisted messages across every session and chat the API key may read. Returns ranked hits with a <mark>-highlighted snippet, chatId, sender and timestamp; resolve names with SessionGetChats or ContactFindOne. ' +
+ `match=contains (the default) finds any part of a word, ignoring case and accents, and ranks the ${SEARCH_CONTAINS_WINDOW} most recently stored matches (whole words first, then newest), so total is at most ${SEARCH_CONTAINS_WINDOW}: narrow with more terms, chatId or dateTo to reach older ones. ` +
+ 'match=word finds whole words only. A key restricted to selected chats must pass chatId.',
+ tier: 'read',
+ requiredRole: ApiKeyRole.OPERATOR,
+ inputSchema: z.object({
+ q: z.string().trim().min(1).max(SEARCH_QUERY_MAX_LENGTH).describe('Search term'),
+ // Defaults to contains, unlike REST (word): an agent often knows only part of a word or types
+ // it without accents, and contains finds everything word finds.
+ match: z
+ .enum(SEARCH_MATCH_MODES)
+ .default('contains')
+ .describe('contains: any part of a word (default); word: whole words only'),
+ chatId: chatIdSchema.optional().describe('Restrict to a single chat JID'),
+ from: z.string().optional().describe('Filter by sender phone or JID'),
+ direction: z.enum(MessageDirection).optional(),
+ dateFrom: z.number().optional().describe('Epoch-ms lower bound (inclusive)'),
+ dateTo: z.number().optional().describe('Epoch-ms upper bound (inclusive)'),
+ limit: z.number().int().min(1).max(SEARCH_LIMIT_MAX).optional(),
+ offset: z.number().int().min(0).max(SEARCH_OFFSET_MAX).optional(),
+ }),
+ handler: async (input, apiKey, chatScope) => {
+ if (!search) throw new NotImplementedException('Search is disabled (SEARCH_ENABLED=false).');
+ // Both scopes come from the authenticated key, never the input, exactly as SearchController
+ // passes them: SearchService overwrites any caller-supplied scope at the provider boundary.
+ return search.search(input, apiKey.allowedSessions ?? undefined, await chatScope?.idsForFilter(apiKey));
+ },
+ }),
+ ];
+}
diff --git a/src/database/migrations/1792400000000-AddMessagesTrigramSearch.ts b/src/database/migrations/1792400000000-AddMessagesTrigramSearch.ts
new file mode 100644
index 000000000..76d8a3234
--- /dev/null
+++ b/src/database/migrations/1792400000000-AddMessagesTrigramSearch.ts
@@ -0,0 +1,123 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Adds the trigram index behind `GET /api/search?match=contains` (substring search, case- and
+ * accent-insensitive), next to the word index of 1782400000000-AddMessagesFts:
+ * - SQLite: an FTS5 external-content table with the trigram tokenizer (remove_diacritics), keyed on
+ * the implicit `rowid`, kept in sync by triggers and backfilled once, exactly like `messages_fts`.
+ * - Postgres: the pg_trgm and unaccent extensions, an IMMUTABLE `openwa_unaccent(text)` wrapper, a
+ * GIN trigram index on `openwa_unaccent(body)`, and a b-tree on `("createdAt", "id")`. A contains
+ * search ranks the most recently stored matches (SEARCH_CONTAINS_WINDOW); the existing message
+ * indexes all lead with `sessionId`, so without this one a common term would sort every match to
+ * find them. SQLite needs no counterpart: FTS5 walks its doclist in rowid (insertion) order.
+ *
+ * Never fails the boot over a missing capability. A SQLite build without FTS5 or older than 3.45 (the
+ * first with remove_diacritics for trigram) gets no schema, and a Postgres role that may not create
+ * the extensions gets the extension attempt rolled back to a savepoint and nothing else. In both cases
+ * the provider answers 501 for match=contains only; match=word is untouched. On Postgres the provider
+ * creates the function and indexes at a later boot once an operator has installed the extensions.
+ *
+ * Non-CONCURRENTLY on PG (one-time blocking build), as the word index. For very large `messages` tables,
+ * run the upgrade during a maintenance window.
+ *
+ * Mirrored by BuiltInFtsProvider.ensureTrigramSchema, which brings the same schema up under
+ * DATABASE_SYNCHRONIZE=true, where migrations never run. Kept self-contained rather than importing the
+ * provider's helpers, so a later change to the provider cannot rewrite what this migration did.
+ */
+export class AddMessagesTrigramSearch1792400000000 implements MigrationInterface {
+ name = 'AddMessagesTrigramSearch1792400000000';
+
+ async up(qr: QueryRunner): Promise<void> {
+ if (qr.dataSource.options.type === 'postgres') {
+ await this.upPostgres(qr);
+ return;
+ }
+ const [probe] = (await qr.query(
+ `SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled, sqlite_version() AS version`,
+ )) as Array<{ enabled: number; version: string }>;
+ const [major, minor] = String(probe?.version ?? '')
+ .split('.')
+ .map(Number);
+ if (!Number(probe?.enabled) || !(major > 3 || (major === 3 && minor >= 45))) return;
+
+ await qr.query(
+ `CREATE VIRTUAL TABLE IF NOT EXISTS "messages_trgm" USING fts5(body, content='messages', content_rowid='rowid', tokenize='trigram remove_diacritics 1')`,
+ );
+ await qr.query(
+ `INSERT INTO "messages_trgm"("rowid", "body") SELECT "rowid", "body" FROM "messages" WHERE "body" IS NOT NULL`,
+ );
+ await qr.query(`DROP TRIGGER IF EXISTS messages_trgm_ai`);
+ await qr.query(`CREATE TRIGGER messages_trgm_ai AFTER INSERT ON "messages" BEGIN
+ INSERT INTO "messages_trgm"("rowid", "body") VALUES (new."rowid", new."body");
+ END`);
+ await qr.query(`DROP TRIGGER IF EXISTS messages_trgm_ad`);
+ await qr.query(`CREATE TRIGGER messages_trgm_ad AFTER DELETE ON "messages" BEGIN
+ INSERT INTO "messages_trgm"("messages_trgm", "rowid", "body") VALUES ('delete', old."rowid", old."body");
+ END`);
+ await qr.query(`DROP TRIGGER IF EXISTS messages_trgm_au`);
+ // Same WHEN guard as messages_fts_au: acks, reactions and status updates do not touch the body, so
+ // they skip the delete+insert on the busiest message path.
+ await qr.query(`CREATE TRIGGER messages_trgm_au AFTER UPDATE ON "messages" WHEN OLD.body IS NOT NEW.body BEGIN
+ INSERT INTO "messages_trgm"("messages_trgm", "rowid", "body") VALUES ('delete', old."rowid", old."body");
+ INSERT INTO "messages_trgm"("rowid", "body") VALUES (new."rowid", new."body");
+ END`);
+ }
+
+ async down(qr: QueryRunner): Promise<void> {
+ if (qr.dataSource.options.type === 'postgres') {
+ // The extensions stay: other objects in the database may depend on them.
+ await qr.query(`DROP INDEX IF EXISTS "idx_messages_created_at_id"`);
+ await qr.query(`DROP INDEX IF EXISTS "idx_messages_body_trgm"`);
+ await qr.query(`DROP FUNCTION IF EXISTS openwa_unaccent(text)`);
+ return;
+ }
+ await qr.query(`DROP TRIGGER IF EXISTS messages_trgm_au`);
+ await qr.query(`DROP TRIGGER IF EXISTS messages_trgm_ad`);
+ await qr.query(`DROP TRIGGER IF EXISTS messages_trgm_ai`);
+ await qr.query(`DROP TABLE IF EXISTS "messages_trgm"`);
+ }
+
+ private async upPostgres(qr: QueryRunner): Promise<void> {
+ // Guards the index build against a role- or database-level statement_timeout, as 1782400000000 does.
+ await qr.query('SET LOCAL statement_timeout = 0');
+ if (!(await this.createExtensions(qr))) return;
+
+ const [schemas] = (await qr.query(
+ `SELECT (SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'pg_trgm') AS trgm,
+ (SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'unaccent') AS unaccent`,
+ )) as Array<{ trgm: string; unaccent: string }>;
+ const trgm = `"${schemas.trgm.replace(/"/g, '""')}"`;
+ const unaccent = `"${schemas.unaccent.replace(/"/g, '""')}"`;
+
+ // unaccent() is STABLE and Postgres indexes only IMMUTABLE expressions. Naming the dictionary and
+ // schema-qualifying both references pins what the wrapper calls whatever the caller's search_path,
+ // which is what makes declaring it IMMUTABLE safe.
+ await qr.query(
+ `CREATE OR REPLACE FUNCTION openwa_unaccent(text) RETURNS text LANGUAGE sql IMMUTABLE PARALLEL SAFE STRICT AS $$ SELECT ${unaccent}.unaccent('${unaccent.replace(/'/g, "''")}.unaccent'::regdictionary, $1) $$`,
+ );
+ await qr.query(
+ `CREATE INDEX IF NOT EXISTS "idx_messages_body_trgm" ON "messages" USING GIN (openwa_unaccent("body") ${trgm}.gin_trgm_ops)`,
+ );
+ await qr.query(`CREATE INDEX IF NOT EXISTS "idx_messages_created_at_id" ON "messages" ("createdAt", "id")`);
+ }
+
+ /**
+ * Both extensions ship with PostgreSQL's contrib package and are trusted from PostgreSQL 13, so a
+ * database owner can create them; managed Postgres may still refuse. A failed statement aborts the
+ * surrounding migration transaction, so the attempt runs inside a savepoint and a refusal rolls back
+ * to it, leaving the rest of the chain to run. Returns whether both are installed.
+ */
+ private async createExtensions(qr: QueryRunner): Promise<boolean> {
+ const inTransaction = qr.isTransactionActive;
+ if (inTransaction) await qr.query('SAVEPOINT trigram_extensions');
+ try {
+ await qr.query('CREATE EXTENSION IF NOT EXISTS pg_trgm');
+ await qr.query('CREATE EXTENSION IF NOT EXISTS unaccent');
+ if (inTransaction) await qr.query('RELEASE SAVEPOINT trigram_extensions');
+ return true;
+ } catch {
+ if (inTransaction) await qr.query('ROLLBACK TO SAVEPOINT trigram_extensions');
+ return false;
+ }
+ }
+}
diff --git a/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts
index 85a9f4189..bfaf599c2 100644
--- a/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts
+++ b/src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts
@@ -4,6 +4,7 @@ import 'reflect-metadata';
import { DataSource } from 'typeorm';
import { BuiltInFtsProvider } from '../../../modules/search/providers/builtin-fts.provider';
import { AddMessagesFts1782400000000 } from '../1782400000000-AddMessagesFts';
+import { AddMessagesTrigramSearch1792400000000 } from '../1792400000000-AddMessagesTrigramSearch';
/**
* Postgres runtime coverage for BuiltInFtsProvider. Companion to the SQLite spec
@@ -51,6 +52,9 @@ const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';
// Adds the STORED generated `body_ts` tsvector + the GIN index — the exact objects the provider
// relies on; running the migration (not hand-rolling DDL) is the point of this test.
await new AddMessagesFts1782400000000().up(ds.createQueryRunner());
+ // The rest of the search chain, so the boot self-heal tests below see what a migrations-based
+ // deployment has: with the trigram objects missing, the provider would rightly build them at boot.
+ await new AddMessagesTrigramSearch1792400000000().up(ds.createQueryRunner());
provider = new BuiltInFtsProvider(ds);
diff --git a/src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.pg.spec.ts b/src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.pg.spec.ts
new file mode 100644
index 000000000..b401f5ce4
--- /dev/null
+++ b/src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.pg.spec.ts
@@ -0,0 +1,156 @@
+/* istanbul ignore file -- PG-gated: only runs under DATABASE_TYPE=postgres (test-postgres CI job);
+ skipped in the default test job, so its lines would be unread and skew the global coverage gate. */
+import 'reflect-metadata';
+import { BadRequestException } from '@nestjs/common';
+import { DataSource } from 'typeorm';
+import { BuiltInFtsProvider } from '../../../modules/search/providers/builtin-fts.provider';
+import { AddMessagesFts1782400000000 } from '../1782400000000-AddMessagesFts';
+import { AddMessagesTrigramSearch1792400000000 } from '../1792400000000-AddMessagesTrigramSearch';
+
+/**
+ * Postgres runtime coverage for match=contains: the pg_trgm/unaccent schema the 1792400000000
+ * migration builds, queried through BuiltInFtsProvider. Companion to the SQLite spec
+ * (builtin-fts.provider.contains.spec.ts); asserts the same contract (substring, case- and
+ * accent-insensitive, every term required, short terms narrowing, literal wildcards, exact totals)
+ * plus what only Postgres has: word_similarity ranking and the GIN index actually answering the query.
+ *
+ * Gated and provisioned exactly like 1782400000000-AddMessagesFts.pg.spec.ts: skipped unless
+ * DATABASE_TYPE=postgres, connecting with DATABASE_HOST/PORT/USERNAME/PASSWORD/NAME. The role must be
+ * allowed to create the two extensions (the CI postgres:16 service's owner role is).
+ */
+const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';
+
+(POSTGRES_ENABLED ? describe : describe.skip)('AddMessagesTrigramSearch + match=contains (postgres)', () => {
+ let ds: DataSource;
+ let provider: BuiltInFtsProvider;
+
+ const insert = (id: string, sessionId: string, body: string, ts: number) =>
+ ds.query(
+ `INSERT INTO "messages" ("id","sessionId","chatId","from","to","body","type","direction","timestamp") ` +
+ `VALUES ($1,$2,$3,$4,'[email protected]',$5,'text','incoming',$6)`,
+ [id, sessionId, `${id}-chat`, `${id}-from`, body, ts],
+ );
+
+ beforeEach(async () => {
+ ds = new DataSource({
+ type: 'postgres',
+ host: process.env.DATABASE_HOST || 'localhost',
+ port: Number(process.env.DATABASE_PORT || 5432),
+ username: process.env.DATABASE_USERNAME || 'openwa',
+ password: process.env.DATABASE_PASSWORD || 'openwa',
+ database: process.env.DATABASE_NAME || 'openwa',
+ });
+ await ds.initialize();
+ await ds.query(`DROP TABLE IF EXISTS "messages" CASCADE`);
+ await ds.query(`DROP FUNCTION IF EXISTS openwa_unaccent(text)`);
+ await ds.query(
+ `CREATE TABLE "messages" (` +
+ `"id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, "waMessageId" varchar, ` +
+ `"chatId" varchar NOT NULL, "from" varchar NOT NULL, "to" varchar NOT NULL, "body" text, ` +
+ `"type" varchar NOT NULL DEFAULT 'text', "direction" varchar NOT NULL DEFAULT 'outgoing', ` +
+ `"timestamp" bigint, "status" varchar NOT NULL DEFAULT 'sent', ` +
+ `"createdAt" timestamp NOT NULL DEFAULT now())`,
+ );
+ await new AddMessagesFts1782400000000().up(ds.createQueryRunner());
+ await new AddMessagesTrigramSearch1792400000000().up(ds.createQueryRunner());
+ provider = new BuiltInFtsProvider(ds);
+
+ await insert('m1', 's1', 'Your invoice INV-2048 is ready for download', 10);
+ await insert('m2', 's1', 'Thanks, I will pay the invoice today', 20);
+ await insert('m3', 's2', 'Meeting moved to the Café Résumé at 10am', 30);
+ await insert('m4', 's1', 'Order shipped with a 10% discount, tracking id 42', 40);
+ });
+
+ afterEach(async () => {
+ if (ds && ds.isInitialized) {
+ await ds.query(`DROP TABLE IF EXISTS "messages" CASCADE`).catch(() => undefined);
+ await ds.query(`DROP FUNCTION IF EXISTS openwa_unaccent(text)`).catch(() => undefined);
+ await ds.destroy();
+ }
+ });
+
+ it('finds any part of a word, ignoring case and accents, and marks it', async () => {
+ const res = await provider.search({ q: 'voic', match: 'contains' });
+ expect(res.total).toBe(2);
+ expect(res.hits.map(h => h.snippet).sort()).toEqual([
+ 'Thanks, I will pay the in<mark>voic</mark>e today',
+ 'Your in<mark>voic</mark>e INV-2048 is ready for download',
+ ]);
+
+ for (const q of ['cafe', 'CAFÉ', 'resume']) {
+ expect((await provider.search({ q, match: 'contains' })).hits.map(h => h.messageId)).toEqual(['m3']);
+ }
+ });
+
+ it('requires every term, narrows with short ones, and rejects short terms alone', async () => {
+ expect((await provider.search({ q: 'invoice 2048', match: 'contains' })).hits.map(h => h.messageId)).toEqual([
+ 'm1',
+ ]);
+ expect((await provider.search({ q: 'invoice to', match: 'contains' })).hits.map(h => h.messageId)).toEqual(['m2']);
+ await expect(provider.search({ q: 'id to', match: 'contains' })).rejects.toBeInstanceOf(BadRequestException);
+ });
+
+ it('matches LIKE wildcards in a term literally', async () => {
+ expect((await provider.search({ q: '10%', match: 'contains' })).total).toBe(1);
+ expect((await provider.search({ q: 'invoice _', match: 'contains' })).total).toBe(0);
+ });
+
+ it('ranks whole words first, newest first within a score, and scores a scoped caller too', async () => {
+ await insert('m5', 's1', 'reinvoiced items are listed below', 50);
+ const res = await provider.search({ q: 'invoice', match: 'contains', sessionIds: ['s1'] });
+
+ expect(res.hits.map(h => [h.messageId, h.score])).toEqual([
+ ['m2', 3],
+ ['m1', 3],
+ ['m5', 1],
+ ]);
+ });
+
+ it('pages with the window total', async () => {
+ const page = await provider.search({ q: 'invoice', match: 'contains', limit: 1, offset: 1 });
+ expect(page.total).toBe(2);
+ expect(page.hits).toHaveLength(1);
+ });
+
+ // A four-row table is cheaper to scan than to look up, so the planner is told not to scan: what
+ // these prove is that the SQL the provider emits matches the indexed expressions and CAN use them.
+ // One query runner keeps SET LOCAL and EXPLAIN on the same connection and transaction.
+ const plan = async (settings: string[], sql: string, params: unknown[]): Promise<string> => {
+ const runner = ds.createQueryRunner();
+ await runner.startTransaction();
+ try {
+ for (const setting of settings) await runner.query(`SET LOCAL ${setting} = off`);
+ const rows = (await runner.query(`EXPLAIN ${sql}`, params)) as Array<{ 'QUERY PLAN': string }>;
+ return rows.map(r => r['QUERY PLAN']).join('\n');
+ } finally {
+ await runner.rollbackTransaction();
+ await runner.release();
+ }
+ };
+
+ it('answers the substring predicate from the GIN trigram index', async () => {
+ const sql = `SELECT 1 FROM messages m WHERE openwa_unaccent(m."body") ILIKE openwa_unaccent($1)`;
+ expect(await plan(['enable_seqscan'], sql, ['%voic%'])).toContain('idx_messages_body_trgm');
+ });
+
+ it('can fetch the most recently stored candidates by walking the recency index', async () => {
+ const sql =
+ `SELECT 1 FROM messages m WHERE openwa_unaccent(m."body") ILIKE openwa_unaccent($1) ` +
+ `ORDER BY m."createdAt" DESC, m."id" DESC LIMIT 1000`;
+ expect(await plan(['enable_seqscan', 'enable_bitmapscan'], sql, ['%voic%'])).toContain(
+ 'Index Scan Backward using idx_messages_created_at_id',
+ );
+ });
+
+ it('builds the function and both indexes at boot when only the extensions exist', async () => {
+ await new AddMessagesTrigramSearch1792400000000().down(ds.createQueryRunner());
+ const fresh = new BuiltInFtsProvider(ds);
+ await fresh.onModuleInit();
+
+ expect((await fresh.search({ q: 'voice', match: 'contains' })).total).toBe(2);
+ const indexes = await ds.query<Array<{ indexname: string }>>(
+ `SELECT indexname FROM pg_indexes WHERE tablename = 'messages' AND indexname IN ('idx_messages_body_trgm', 'idx_messages_created_at_id') ORDER BY indexname`,
+ );
+ expect(indexes.map(i => i.indexname)).toEqual(['idx_messages_body_trgm', 'idx_messages_created_at_id']);
+ });
+});
diff --git a/src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.spec.ts b/src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.spec.ts
new file mode 100644
index 000000000..c68c4d4e1
--- /dev/null
+++ b/src/database/migrations/__tests__/1792400000000-AddMessagesTrigramSearch.spec.ts
@@ -0,0 +1,120 @@
+import 'reflect-metadata';
+import { DataSource, QueryRunner } from 'typeorm';
+import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';
+import { Session } from '../../../modules/session/entities/session.entity';
+import { AddMessagesTrigramSearch1792400000000 } from '../1792400000000-AddMessagesTrigramSearch';
+
+/**
+ * SQLite in-memory coverage for the AddMessagesTrigramSearch migration, plus the capability gates of
+ * both dialects through stub query runners:
+ * - the FTS5 trigram table + 3 sync triggers are created, backfilled, and kept in sync;
+ * - re-running up() is a no-op and down() removes all four objects;
+ * - a SQLite build without FTS5, or older than 3.45, gets no schema and no error;
+ * - a Postgres role refused CREATE EXTENSION rolls back to the savepoint and stops there.
+ *
+ * The Postgres objects themselves are exercised in 1792400000000-AddMessagesTrigramSearch.pg.spec.ts.
+ */
+describe('AddMessagesTrigramSearch migration (sqlite)', () => {
+ let ds: DataSource;
+ let runner: QueryRunner;
+
+ const insert = (body: string | null) =>
+ ds.getRepository(Message).insert({
+ sessionId: 's1',
+ chatId: 'c1',
+ body: body as string,
+ type: 'text',
+ direction: MessageDirection.INCOMING,
+ timestamp: 1,
+ });
+ const matches = async (q: string): Promise<number> =>
+ (
+ (await runner.query(`SELECT count(*) AS n FROM messages_trgm WHERE messages_trgm MATCH ?`, [q])) as Array<{
+ n: number;
+ }>
+ )[0].n;
+ const objects = async (): Promise<string[]> =>
+ (
+ (await runner.query(
+ `SELECT name FROM sqlite_master WHERE name = 'messages_trgm' OR name LIKE 'messages_trgm\\_a_' ESCAPE '\\' ORDER BY name`,
+ )) as Array<{ name: string }>
+ ).map(r => r.name);
+
+ beforeEach(async () => {
+ ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Session, Message],
+ synchronize: true,
+ migrations: [],
+ });
+ await ds.initialize();
+ runner = ds.createQueryRunner();
+ });
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ it('creates the trigram table and triggers, backfilling the rows already stored', async () => {
+ await insert('Meeting at the Café');
+ await insert(null);
+ await new AddMessagesTrigramSearch1792400000000().up(runner);
+
+ expect(await objects()).toEqual(['messages_trgm', 'messages_trgm_ad', 'messages_trgm_ai', 'messages_trgm_au']);
+ expect(await matches('"cafe"')).toBe(1);
+
+ await insert('Your invoice is ready');
+ expect(await matches('"voic"')).toBe(1);
+ });
+
+ it('is idempotent on re-run and fully reversible', async () => {
+ await insert('Your invoice is ready');
+ const migration = new AddMessagesTrigramSearch1792400000000();
+ await migration.up(runner);
+ await migration.down(runner);
+ await migration.up(runner);
+ expect(await matches('"invo"')).toBe(1);
+
+ await migration.down(runner);
+ expect(await objects()).toEqual([]);
+ });
+
+ it.each([
+ ['a build without FTS5', { enabled: 0, version: '3.53.4' }],
+ ['SQLite older than 3.45', { enabled: 1, version: '3.44.2' }],
+ ])('creates nothing on %s', async (_label, probe) => {
+ const query = jest.fn().mockResolvedValue([probe]);
+ const stub = { dataSource: { options: { type: 'better-sqlite3' } }, query } as unknown as QueryRunner;
+
+ await new AddMessagesTrigramSearch1792400000000().up(stub);
+
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('AddMessagesTrigramSearch migration (postgres capability gate)', () => {
+ it('rolls back to the savepoint and creates nothing else when CREATE EXTENSION is refused', async () => {
+ const statements: string[] = [];
+ const query = jest.fn((sql: string) => {
+ statements.push(sql);
+ if (sql.startsWith('CREATE EXTENSION')) return Promise.reject(new Error('permission denied to create extension'));
+ return Promise.resolve([]);
+ });
+ const stub = {
+ dataSource: { options: { type: 'postgres' } },
+ isTransactionActive: true,
+ query,
+ } as unknown as QueryRunner;
+
+ await new AddMessagesTrigramSearch1792400000000().up(stub);
+
+ expect(statements).toEqual([
+ 'SET LOCAL statement_timeout = 0',
+ 'SAVEPOINT trigram_extensions',
+ 'CREATE EXTENSION IF NOT EXISTS pg_trgm',
+ 'ROLLBACK TO SAVEPOINT trigram_extensions',
+ ]);
+ });
+});
diff --git a/src/modules/search/dto/search-query.dto.spec.ts b/src/modules/search/dto/search-query.dto.spec.ts
index e5b548dd4..f7e859302 100644
--- a/src/modules/search/dto/search-query.dto.spec.ts
+++ b/src/modules/search/dto/search-query.dto.spec.ts
@@ -78,6 +78,12 @@ describe('SearchQueryDto', () => {
expect(validateSync(dto)).toHaveLength(0);
});
+ it('accepts both match modes and rejects any other value', () => {
+ expect(validateSync(fromQuery({ q: 'hello', match: 'word' }))).toHaveLength(0);
+ expect(validateSync(fromQuery({ q: 'hello', match: 'contains' }))).toHaveLength(0);
+ expect(validateSync(fromQuery({ q: 'hello', match: 'fuzzy' })).some(e => e.property === 'match')).toBe(true);
+ });
+
// @nestjs/swagger derives no bounds from @IsInt/@Min/@Max, so the decorator has to state them.
it('publishes limit and offset as bounded integers', () => {
const published = (key: string): unknown =>
diff --git a/src/modules/search/dto/search-query.dto.ts b/src/modules/search/dto/search-query.dto.ts
index 76b14c764..4f16a410b 100644
--- a/src/modules/search/dto/search-query.dto.ts
+++ b/src/modules/search/dto/search-query.dto.ts
@@ -1,10 +1,18 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
-import { IsString, IsNotEmpty, IsOptional, IsEnum, IsInt, IsNumber, Max, MaxLength, Min } from 'class-validator';
+import { IsString, IsNotEmpty, IsOptional, IsEnum, IsIn, IsInt, IsNumber, Max, MaxLength, Min } from 'class-validator';
import { Type } from 'class-transformer';
import { MessageDirection } from '../../message/entities/message.entity';
import type { MessageType } from '../../../engine/interfaces/whatsapp-engine.interface';
import { ToStrictNumber } from '../../../common/utils/strict-boolean';
-import { SEARCH_OFFSET_MAX, SEARCH_QUERY_MAX_LENGTH, SEARCH_TERMS_MAX } from '../search.constants';
+import {
+ SEARCH_CONTAINS_MIN_TERM_LENGTH,
+ SEARCH_CONTAINS_WINDOW,
+ SEARCH_MATCH_MODES,
+ SEARCH_OFFSET_MAX,
+ SEARCH_QUERY_MAX_LENGTH,
+ SEARCH_TERMS_MAX,
+} from '../search.constants';
+import type { SearchMatch } from '../search.types';
/**
* Request shape for GET /search. Numeric fields are coerced from query-string strings via
@@ -26,6 +34,20 @@ export class SearchQueryDto {
@MaxLength(SEARCH_QUERY_MAX_LENGTH)
q!: string;
+ @ApiPropertyOptional({
+ enum: SEARCH_MATCH_MODES,
+ default: 'word',
+ description:
+ '`word` (default) matches whole words. `contains` matches any part of a word, ignoring case and ' +
+ `accents (\`voic\` finds "Invoice", \`cafe\` finds "Café"); it needs at least one term of ` +
+ `${SEARCH_CONTAINS_MIN_TERM_LENGTH} or more characters, and on PostgreSQL the pg_trgm and unaccent extensions. ` +
+ `It ranks the ${SEARCH_CONTAINS_WINDOW} most recently stored matches by match quality, so \`total\` is at most ` +
+ `${SEARCH_CONTAINS_WINDOW}.`,
+ })
+ @IsOptional()
+ @IsIn(SEARCH_MATCH_MODES)
+ match?: SearchMatch;
+
@ApiPropertyOptional({ description: 'Restrict to a single session' })
@IsOptional()
@IsString()
diff --git a/src/modules/search/providers/builtin-fts.provider.contains.spec.ts b/src/modules/search/providers/builtin-fts.provider.contains.spec.ts
new file mode 100644
index 000000000..ba2ed6ba6
--- /dev/null
+++ b/src/modules/search/providers/builtin-fts.provider.contains.spec.ts
@@ -0,0 +1,218 @@
+import 'reflect-metadata';
+import { BadRequestException, NotImplementedException } from '@nestjs/common';
+import { DataSource } from 'typeorm';
+import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';
+import { Session } from '../../../modules/session/entities/session.entity';
+import { AddMessagesFts1782400000000 } from '../../../database/migrations/1782400000000-AddMessagesFts';
+import { AddMessagesTrigramSearch1792400000000 } from '../../../database/migrations/1792400000000-AddMessagesTrigramSearch';
+import { SEARCH_CONTAINS_WINDOW } from '../search.constants';
+import {
+ BuiltInFtsProvider,
+ postgresUnaccentFunctionDdl,
+ sqliteSupportsTrigramDiacritics,
+} from './builtin-fts.provider';
+
+/**
+ * SQLite runtime coverage for match=contains: the FTS5 trigram index the 1792400000000 migration
+ * builds, queried through BuiltInFtsProvider. Companion to builtin-fts.provider.spec.ts (match=word);
+ * the Postgres branch runs in 1792400000000-AddMessagesTrigramSearch.pg.spec.ts.
+ */
+const row = (sessionId: string, chatId: string, body: string, direction: MessageDirection, timestamp: number) => ({
+ sessionId,
+ chatId,
+ from: `${chatId}@c.us`,
+ body,
+ type: 'text',
+ direction,
+ timestamp,
+});
+
+async function boot(options: { trigramMigration: boolean }): Promise<DataSource> {
+ const ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Session, Message],
+ synchronize: true,
+ });
+ await ds.initialize();
+ await new AddMessagesFts1782400000000().up(ds.createQueryRunner());
+ if (options.trigramMigration) await new AddMessagesTrigramSearch1792400000000().up(ds.createQueryRunner());
+ await ds
+ .getRepository(Message)
+ .insert([
+ row('s1', 'c1', 'Your invoice INV-2048 is ready for download', MessageDirection.INCOMING, 10),
+ row('s1', 'c2', 'Thanks, I will pay the invoice today', MessageDirection.OUTGOING, 20),
+ row('s2', 'c3', 'Meeting moved to the Café Résumé at 10am', MessageDirection.INCOMING, 30),
+ row('s1', 'c4', 'Order shipped with a 10% discount, tracking id 42', MessageDirection.INCOMING, 40),
+ ]);
+ return ds;
+}
+
+describe('BuiltInFtsProvider match=contains (sqlite)', () => {
+ let ds: DataSource;
+ let provider: BuiltInFtsProvider;
+
+ beforeEach(async () => {
+ ds = await boot({ trigramMigration: true });
+ provider = new BuiltInFtsProvider(ds);
+ });
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ it('finds any part of a word and marks it in the snippet', async () => {
+ const res = await provider.search({ q: 'voic', match: 'contains' });
+
+ expect(res.total).toBe(2);
+ expect(res.hits.map(h => h.snippet).sort()).toEqual([
+ 'Thanks, I will pay the in<mark>voic</mark>e today',
+ 'Your in<mark>voic</mark>e INV-2048 is ready for download',
+ ]);
+ });
+
+ it('ignores case and accents in both the query and the body', async () => {
+ for (const q of ['cafe', 'CAFÉ', 'resume']) {
+ const res = await provider.search({ q, match: 'contains' });
+ expect(res.hits.map(h => h.chatId)).toEqual(['c3']);
+ }
+ });
+
+ it('requires every term, as match=word does', async () => {
+ const res = await provider.search({ q: 'invoice 2048', match: 'contains' });
+
+ expect(res.hits.map(h => h.chatId)).toEqual(['c1']);
+ expect(res.hits[0].snippet).toBe('Your <mark>invoice</mark> INV-<mark>2048</mark> is ready for download');
+ });
+
+ it('narrows with a term shorter than a trigram instead of dropping it', async () => {
+ expect((await provider.search({ q: 'invoice to', match: 'contains' })).hits.map(h => h.chatId)).toEqual(['c2']);
+ expect((await provider.search({ q: 'tracking id', match: 'contains' })).total).toBe(1);
+ });
+
+ it('rejects a query made only of terms shorter than a trigram', async () => {
+ await expect(provider.search({ q: 'id to', match: 'contains' })).rejects.toBeInstanceOf(BadRequestException);
+ });
+
+ it('matches a LIKE wildcard in a term literally', async () => {
+ expect((await provider.search({ q: '10%', match: 'contains' })).total).toBe(1);
+ expect((await provider.search({ q: 'invoice _', match: 'contains' })).total).toBe(0);
+ });
+
+ it('ranks whole words, then word starts, then the rest, newest first within a score', async () => {
+ await ds
+ .getRepository(Message)
+ .insert([
+ row('s1', 'c5', 'Reinvoice requested by finance', MessageDirection.INCOMING, 60),
+ row('s1', 'c6', 'Invoiced orders are listed below', MessageDirection.INCOMING, 50),
+ ]);
+
+ const res = await provider.search({ q: 'invoice', match: 'contains' });
+
+ expect(res.hits.map(h => [h.chatId, h.score])).toEqual([
+ ['c2', 3],
+ ['c1', 3],
+ ['c6', 2],
+ ['c5', 1],
+ ]);
+ });
+
+ it('pages the ranked window with a stable order and its total', async () => {
+ const all = await provider.search({ q: 'invoice', match: 'contains' });
+ const page1 = await provider.search({ q: 'invoice', match: 'contains', limit: 1 });
+ const page2 = await provider.search({ q: 'invoice', match: 'contains', limit: 1, offset: 1 });
+
+ expect(page1.total).toBe(2);
+ expect([...page1.hits, ...page2.hits].map(h => h.messageId)).toEqual(all.hits.map(h => h.messageId));
+ expect((await provider.search({ q: 'invoice', match: 'contains', offset: 2 })).hits).toEqual([]);
+ });
+
+ it('ranks only the most recently stored matches, so one search does bounded work', async () => {
+ const bulk = Array.from({ length: SEARCH_CONTAINS_WINDOW + 5 }, (_, i) =>
+ row('s1', 'c7', `Bulk invoice ${i}`, MessageDirection.INCOMING, 100 + i),
+ );
+ // In batches: TypeORM re-reads inserted rows with one OR term each, past SQLite's expression depth.
+ for (let i = 0; i < bulk.length; i += 200) await ds.getRepository(Message).insert(bulk.slice(i, i + 200));
+
+ const res = await provider.search({ q: 'invoice', match: 'contains', limit: 100, offset: 900 });
+
+ expect(res.total).toBe(SEARCH_CONTAINS_WINDOW);
+ expect(Math.min(...res.hits.map(h => h.timestamp))).toBe(100 + 5);
+
+ // The filters apply before the window, so a date bound reaches the matches older than it.
+ const older = await provider.search({ q: 'invoice', match: 'contains', dateTo: 99_000 });
+ expect(older.hits.map(h => h.chatId)).toEqual(['c2', 'c1']);
+ const narrower = await provider.search({ q: 'invoice 2048', match: 'contains' });
+ expect(narrower.hits.map(h => h.chatId)).toEqual(['c1']);
+ });
+
+ it('applies the structural filters and returns each hit its own score to a scoped caller', async () => {
+ const res = await provider.search({ q: 'meeting', match: 'contains', sessionIds: ['s2'] });
+ expect(res.hits.map(h => h.chatId)).toEqual(['c3']);
+ expect(res.hits[0].score).toBe(3);
+
+ const outgoing = await provider.search({ q: 'invoice', match: 'contains', direction: MessageDirection.OUTGOING });
+ expect(outgoing.hits.map(h => h.chatId)).toEqual(['c2']);
+ expect((await provider.search({ q: 'invoice', match: 'contains', chatIds: [] })).total).toBe(0);
+ });
+
+ it('leaves match=word unchanged: whole words only', async () => {
+ expect((await provider.search({ q: 'voic' })).total).toBe(0);
+ expect((await provider.search({ q: 'invoice', match: 'word' })).total).toBe(2);
+ });
+
+ it('keeps the trigram index in sync on update and delete', async () => {
+ const repo = ds.getRepository(Message);
+ const target = await repo.findOneByOrFail({ chatId: 'c2' });
+
+ await repo.update({ id: target.id }, { body: 'Thanks, I will pay the receipt today' });
+ expect((await provider.search({ q: 'receip', match: 'contains' })).hits.map(h => h.chatId)).toEqual(['c2']);
+ expect((await provider.search({ q: 'invoice', match: 'contains' })).total).toBe(1);
+
+ await repo.delete({ id: target.id });
+ expect((await provider.search({ q: 'receip', match: 'contains' })).total).toBe(0);
+ });
+});
+
+describe('BuiltInFtsProvider match=contains without the trigram index (sqlite)', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = await boot({ trigramMigration: false });
+ });
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ it('answers 501 for match=contains while match=word keeps working', async () => {
+ const provider = new BuiltInFtsProvider(ds);
+
+ await expect(provider.search({ q: 'voic', match: 'contains' })).rejects.toBeInstanceOf(NotImplementedException);
+ expect((await provider.search({ q: 'invoice' })).total).toBe(2);
+ });
+
+ it('builds and backfills the index at boot, as under DATABASE_SYNCHRONIZE=true', async () => {
+ const provider = new BuiltInFtsProvider(ds);
+ await provider.onModuleInit();
+
+ expect((await provider.search({ q: 'voic', match: 'contains' })).total).toBe(2);
+ await ds.getRepository(Message).insert(row('s1', 'c9', 'Invoice reminder', MessageDirection.INCOMING, 50));
+ expect((await provider.search({ q: 'voic', match: 'contains' })).total).toBe(3);
+ });
+});
+
+describe('trigram schema helpers', () => {
+ it('requires SQLite 3.45 for the trigram tokenizer with remove_diacritics', () => {
+ expect(sqliteSupportsTrigramDiacritics('3.44.2')).toBe(false);
+ expect(sqliteSupportsTrigramDiacritics('3.45.0')).toBe(true);
+ expect(sqliteSupportsTrigramDiacritics('3.53.4')).toBe(true);
+ expect(sqliteSupportsTrigramDiacritics('')).toBe(false);
+ });
+
+ it('schema-qualifies the unaccent wrapper, quoting the schema name', () => {
+ expect(postgresUnaccentFunctionDdl('public')).toContain(
+ `SELECT "public".unaccent('"public".unaccent'::regdictionary, $1)`,
+ );
+ expect(postgresUnaccentFunctionDdl(`we"ird's`)).toContain(`SELECT "we""ird's".unaccent('"we""ird''s".unaccent'`);
+ });
+});
diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.ts
index 27da680a4..acd5980ba 100644
--- a/src/modules/search/providers/builtin-fts.provider.ts
+++ b/src/modules/search/providers/builtin-fts.provider.ts
@@ -5,10 +5,94 @@ import { DataSource } from 'typeorm';
import type { MessageType } from '../../../engine/interfaces/whatsapp-engine.interface';
import { MessageDirection } from '../../message/entities/message.entity';
import type { SearchProvider, SearchQuery, SearchResults, SearchHit } from '../search.types';
-import { SEARCH_LIMIT_MAX } from '../search.constants';
+import { SEARCH_CONTAINS_MIN_TERM_LENGTH, SEARCH_CONTAINS_WINDOW, SEARCH_LIMIT_MAX } from '../search.constants';
+import { containsTerms, foldSearchText } from '../search-terms';
+import { containsSnippet } from '../search-snippet';
+import { containsScore } from '../search-score';
const MAX_SNIPPET_WORDS = 24;
+/**
+ * One SQLite FTS5 external-content index over `messages.body`, kept in sync by the `<table>_ai/_ad/_au`
+ * triggers ensureSqliteIndex creates. `tokenize` is the FTS5 tokenizer spec; absent means FTS5's
+ * default (unicode61), which is what the word index has always used.
+ */
+interface Fts5Index {
+ table: string;
+ tokenize?: string;
+}
+
+/** The match=word index (migration 1782400000000-AddMessagesFts). */
+const WORD_INDEX: Fts5Index = { table: 'messages_fts' };
+
+/**
+ * The match=contains index (migration 1792400000000-AddMessagesTrigramSearch). The trigram tokenizer
+ * indexes every three-character window of the body, so any substring of three or more characters is a
+ * lookup instead of a scan; remove_diacritics makes it accent-insensitive like unicode61.
+ */
+const TRIGRAM_INDEX: Fts5Index = { table: 'messages_trgm', tokenize: 'trigram remove_diacritics 1' };
+
+/**
+ * The contains candidate SELECT list. It carries no snippet or score column: searchContains computes
+ * both in the application (see containsSnippet and containsScore).
+ */
+const CONTAINS_COLUMNS = `m."id", m."waMessageId" AS wa_message_id, m."sessionId" AS session_id, m."chatId" AS chat_id, m."from" AS "from", m."body", m."timestamp", m."type", m."direction"`;
+
+/**
+ * What the Postgres catalog holds for contains search: the schema of each extension it needs (null when
+ * not installed), and whether the `openwa_unaccent` wrapper, the trigram index and the recency index
+ * exist.
+ */
+interface TrigramStateRow {
+ trgm: string | null;
+ unaccent: string | null;
+ fn: boolean;
+ idx: boolean;
+ recent: boolean;
+}
+
+/** Descending string order for the `id` tiebreak, as `ORDER BY "id" DESC` sorts a UUID column. */
+function compareDescending(a: string, b: string): number {
+ if (a === b) return 0;
+ return a < b ? 1 : -1;
+}
+
+/**
+ * The trigram tokenizer shipped in SQLite 3.34, but its remove_diacritics option only in 3.45; an older
+ * library rejects the whole CREATE VIRTUAL TABLE. better-sqlite3 bundles its own SQLite, so this only
+ * fails on a build linked against an old system library, where contains search then answers 501.
+ */
+export function sqliteSupportsTrigramDiacritics(version: string): boolean {
+ const [major, minor] = version.split('.').map(Number);
+ return major > 3 || (major === 3 && minor >= 45);
+}
+
+function quoteIdent(name: string): string {
+ return `"${name.replace(/"/g, '""')}"`;
+}
+
+/**
+ * `unaccent()` is STABLE (its result depends on a dictionary that could change), and Postgres only
+ * indexes IMMUTABLE expressions, so the trigram index is built on this wrapper. Naming the dictionary
+ * explicitly and schema-qualifying both references pins what the wrapper calls regardless of the
+ * caller's search_path, which is what makes declaring it IMMUTABLE safe. The schema is whatever the
+ * unaccent extension was installed into, read from the catalog.
+ */
+export function postgresUnaccentFunctionDdl(unaccentSchema: string): string {
+ const schema = quoteIdent(unaccentSchema);
+ return `CREATE OR REPLACE FUNCTION openwa_unaccent(text) RETURNS text LANGUAGE sql IMMUTABLE PARALLEL SAFE STRICT AS $$ SELECT ${schema}.unaccent('${schema.replace(/'/g, "''")}.unaccent'::regdictionary, $1) $$`;
+}
+
+/** A LIKE/ILIKE pattern that finds `term` anywhere, with its own `\`, `%` and `_` matched literally. */
+function likePattern(term: string): string {
+ return `%${term.replace(/[\\%_]/g, '\\$&')}%`;
+}
+
+/** Shorter than a trigram once folded, so no trigram index can look it up. */
+function isShortTerm(term: string): boolean {
+ return [...foldSearchText(term)].length < SEARCH_CONTAINS_MIN_TERM_LENGTH;
+}
+
/** Shape returned by the dialect-specific SELECT in buildSqlite / buildPostgres. */
interface FtsResultRow {
id: string;
@@ -34,6 +118,12 @@ type PlaceholderFn = () => string;
/**
* Built-in, DB-native full-text provider. Index sync is DB-level (generated tsvector / FTS5 triggers),
* so this class ONLY queries — it never writes the index. See migration 1782400000000-AddMessagesFts.
+ *
+ * Two match modes, each on its own index: `word` (the default) matches whole words through the word
+ * index above and ranks them in SQL; `contains` matches any substring of three or more characters,
+ * case- and accent-insensitively, through the trigram index of migration
+ * 1792400000000-AddMessagesTrigramSearch (an FTS5 trigram table on SQLite, a pg_trgm GIN index on
+ * Postgres), and ranks a bounded window of candidates in the application (see searchContains).
*/
@Injectable()
export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
@@ -68,6 +158,16 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
// Never fail boot over index creation: the route 501s cleanly via probeFts()/ensureFts() instead.
this.logger.error(`Failed to ensure FTS schema: ${e instanceof Error ? e.message : String(e)}`);
}
+ try {
+ this.trigramAvailable = await this.ensureTrigramSchema();
+ if (this.trigramAvailable) {
+ this.logger.log('Trigram index ready');
+ } else {
+ this.logger.warn('Trigram index unavailable; match=contains searches will return 501');
+ }
+ } catch (e) {
+ this.logger.error(`Failed to ensure trigram schema: ${e instanceof Error ? e.message : String(e)}`);
+ }
}
/**
@@ -167,16 +267,33 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
return true;
}
// SQLite: probe FTS5 first; skip leaving any schema if this build lacks it.
+ if (!(await this.sqliteHasFts5())) return false;
+ await this.ensureSqliteIndex(WORD_INDEX);
+ return true;
+ }
+
+ /** Whether this SQLite build was compiled with FTS5; neither index can exist without it. */
+ private async sqliteHasFts5(): Promise<boolean> {
const fts5: unknown[] = await this.dataSource.query(`SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled`);
- if (!Number((fts5 as Array<{ enabled: number }>)[0]?.enabled)) return false;
+ return Boolean(Number((fts5 as Array<{ enabled: number }>)[0]?.enabled));
+ }
+
+ /**
+ * Creates one FTS5 index over `messages.body` if missing, repairs its contents, and (re)creates its
+ * three sync triggers. Shared by the word and trigram indexes, which differ only in table name and
+ * tokenizer, so both get the same repair guarantees. Idempotent: on a healthy index every step is a
+ * no-op or a trigger replaced by an identical one.
+ */
+ private async ensureSqliteIndex({ table, tokenize }: Fts5Index): Promise<void> {
+ const docsize = `${table}_docsize`;
await this.dataSource.query(
- `CREATE VIRTUAL TABLE IF NOT EXISTS "messages_fts" USING fts5(body, content='messages', content_rowid='rowid')`,
+ `CREATE VIRTUAL TABLE IF NOT EXISTS "${table}" USING fts5(body, content='messages', content_rowid='rowid'${tokenize ? `, tokenize='${tokenize}'` : ''})`,
);
- // Backfill the rows this index does not hold. NOT an emptiness test: `messages_fts` is an FTS5
+ // Backfill the rows this index does not hold. NOT an emptiness test: the index is an FTS5
// external-content table, so `count(*)` on it scans `messages` and returns THAT table's row
// count, never the number of indexed documents — a "the index is empty" probe written that way
// is unsatisfiable, because a zero count means `messages` itself is empty. The indexed documents
- // live in the `messages_fts_docsize` shadow table, so completeness is a rowid-level anti-join.
+ // live in the `<table>_docsize` shadow table, so completeness is a rowid-level anti-join.
//
// It has to hold on a PARTIALLY populated index, not just an empty one: once a box has booted
// once without the backfill, its later writes are indexed by the triggers below while its older
@@ -193,48 +310,146 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
// such a rebuild, and any rebuild that renumbered a row leaves the old highest rowid behind. Drop
// the whole index then and let the gap repair below re-add every row.
const orphanRow: unknown[] = await this.dataSource.query(
- `SELECT EXISTS(SELECT 1 FROM "messages_fts_docsize" d
+ `SELECT EXISTS(SELECT 1 FROM "${docsize}" d
WHERE NOT EXISTS (SELECT 1 FROM "messages" m WHERE m."rowid" = d."rowid")) AS orphan`,
);
if (Number((orphanRow as Array<{ orphan: number }>)[0]?.orphan)) {
- this.logger.warn('FTS index holds rows the messages table no longer has; re-indexing every message');
- await this.dataSource.query(`INSERT INTO "messages_fts"("messages_fts") VALUES ('delete-all')`);
+ this.logger.warn(`${table} holds rows the messages table no longer has; re-indexing every message`);
+ await this.dataSource.query(`INSERT INTO "${table}"("${table}") VALUES ('delete-all')`);
}
const gapRow: unknown[] = await this.dataSource.query(
`SELECT EXISTS(SELECT 1 FROM "messages" m WHERE m."body" IS NOT NULL
- AND NOT EXISTS (SELECT 1 FROM "messages_fts_docsize" d WHERE d."rowid" = m."rowid")) AS missing`,
+ AND NOT EXISTS (SELECT 1 FROM "${docsize}" d WHERE d."rowid" = m."rowid")) AS missing`,
);
if (Number((gapRow as Array<{ missing: number }>)[0]?.missing)) {
// `body IS NOT NULL` mirrors the migration's own backfill exactly: a repair that indexed a NULL
// body as an empty document would leave the index disagreeing with the schema it repairs.
await this.dataSource.query(
- `INSERT INTO "messages_fts"("rowid", "body")
+ `INSERT INTO "${table}"("rowid", "body")
SELECT m."rowid", m."body" FROM "messages" m WHERE m."body" IS NOT NULL
- AND NOT EXISTS (SELECT 1 FROM "messages_fts_docsize" d WHERE d."rowid" = m."rowid")`,
+ AND NOT EXISTS (SELECT 1 FROM "${docsize}" d WHERE d."rowid" = m."rowid")`,
);
}
// The three sync triggers are CREATE-OR-REPLACE by name via DROP + CREATE; idempotent on re-run.
- await this.dataSource.query(`DROP TRIGGER IF EXISTS messages_fts_ai`);
- await this.dataSource.query(`CREATE TRIGGER messages_fts_ai AFTER INSERT ON "messages" BEGIN
- INSERT INTO "messages_fts"("rowid", "body") VALUES (new."rowid", new."body");
+ await this.dataSource.query(`DROP TRIGGER IF EXISTS ${table}_ai`);
+ await this.dataSource.query(`CREATE TRIGGER ${table}_ai AFTER INSERT ON "messages" BEGIN
+ INSERT INTO "${table}"("rowid", "body") VALUES (new."rowid", new."body");
END`);
- await this.dataSource.query(`DROP TRIGGER IF EXISTS messages_fts_ad`);
- await this.dataSource.query(`CREATE TRIGGER messages_fts_ad AFTER DELETE ON "messages" BEGIN
- INSERT INTO "messages_fts"("messages_fts", "rowid", "body") VALUES ('delete', old."rowid", old."body");
+ await this.dataSource.query(`DROP TRIGGER IF EXISTS ${table}_ad`);
+ await this.dataSource.query(`CREATE TRIGGER ${table}_ad AFTER DELETE ON "messages" BEGIN
+ INSERT INTO "${table}"("${table}", "rowid", "body") VALUES ('delete', old."rowid", old."body");
END`);
- await this.dataSource.query(`DROP TRIGGER IF EXISTS messages_fts_au`);
+ await this.dataSource.query(`DROP TRIGGER IF EXISTS ${table}_au`);
// WHEN clause skips re-indexing on body-unchanged updates (acks/reactions/status) — mirrors the
// migration. NULL-safe via `IS NOT` so NULL↔non-NULL body transitions still fire.
await this.dataSource.query(
- `CREATE TRIGGER messages_fts_au AFTER UPDATE ON "messages" WHEN OLD.body IS NOT NEW.body BEGIN
- INSERT INTO "messages_fts"("messages_fts", "rowid", "body") VALUES ('delete', old."rowid", old."body");
- INSERT INTO "messages_fts"("rowid", "body") VALUES (new."rowid", new."body");
+ `CREATE TRIGGER ${table}_au AFTER UPDATE ON "messages" WHEN OLD.body IS NOT NEW.body BEGIN
+ INSERT INTO "${table}"("${table}", "rowid", "body") VALUES ('delete', old."rowid", old."body");
+ INSERT INTO "${table}"("rowid", "body") VALUES (new."rowid", new."body");
END`,
);
+ }
+
+ /**
+ * Brings up the match=contains index at boot, the way ensureFtsSchema does for the word index, and
+ * mirrors migration 1792400000000-AddMessagesTrigramSearch. Returns false, leaving no schema behind,
+ * when the database cannot hold the index: then only match=contains answers 501, while match=word
+ * keeps working.
+ */
+ private async ensureTrigramSchema(): Promise<boolean> {
+ if (this.dataSource.options.type === 'postgres') return this.ensurePostgresTrigramSchema();
+ if (!(await this.sqliteHasFts5())) return false;
+ const rows: Array<{ version: string }> = await this.dataSource.query(`SELECT sqlite_version() AS version`);
+ if (!sqliteSupportsTrigramDiacritics(rows[0]?.version ?? '')) return false;
+ await this.ensureSqliteIndex(TRIGRAM_INDEX);
return true;
}
+ /**
+ * Creates the wrapper function, the trigram index and the recency index when they are missing but
+ * both extensions are installed. It never runs CREATE EXTENSION: that needs a privilege managed
+ * Postgres often withholds, and the migration has already tried it inside a savepoint. An operator
+ * who installs the extensions later gets the indexes on the next boot. Like the word index, the
+ * builds are not CONCURRENTLY, so a large table is best upgraded in a maintenance window.
+ */
+ private async ensurePostgresTrigramSchema(): Promise<boolean> {
+ const [state] = await this.postgresTrigramState();
+ if (!state?.trgm || !state.unaccent) return false;
+ if (!state.fn) {
+ await this.dataSource.query(postgresUnaccentFunctionDdl(state.unaccent));
+ }
+ if (!state.idx) {
+ await this.dataSource.query(
+ `CREATE INDEX IF NOT EXISTS "idx_messages_body_trgm" ON "messages" USING GIN (openwa_unaccent("body") ${quoteIdent(state.trgm)}.gin_trgm_ops)`,
+ );
+ }
+ if (!state.recent) {
+ await this.dataSource.query(
+ `CREATE INDEX IF NOT EXISTS "idx_messages_created_at_id" ON "messages" ("createdAt", "id")`,
+ );
+ }
+ return true;
+ }
+
+ /**
+ * One catalog read of everything contains search needs on Postgres. The function and the indexes
+ * are looked up through the session search_path, the same resolution the runtime queries use (see
+ * the to_regclass note in probeFts).
+ */
+ private postgresTrigramState(): Promise<TrigramStateRow[]> {
+ const indexExists = (name: string) =>
+ `EXISTS (SELECT 1 FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid WHERE i.indrelid = to_regclass('messages') AND c.relname = '${name}')`;
+ return this.dataSource.query<TrigramStateRow[]>(
+ `SELECT (SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'pg_trgm') AS trgm,
+ (SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'unaccent') AS unaccent,
+ to_regprocedure('openwa_unaccent(text)') IS NOT NULL AS fn,
+ ${indexExists('idx_messages_body_trgm')} AS idx,
+ ${indexExists('idx_messages_created_at_id')} AS recent`,
+ );
+ }
+
+ /** Whether the match=contains index is usable; cached like ftsAvailable after the first probe. */
+ private trigramAvailable: boolean | null = null;
+
+ /**
+ * Probes the contains index once per instance, with the same fail-closed posture as probeFts: a
+ * Postgres probe error reports unavailable without caching, so a later call re-probes.
+ */
+ private async probeTrigram(): Promise<boolean> {
+ if (this.trigramAvailable !== null) return this.trigramAvailable;
+ if (this.dataSource.options.type === 'postgres') {
+ let state: TrigramStateRow | undefined;
+ try {
+ [state] = await this.postgresTrigramState();
+ } catch (e) {
+ this.logger.warn(
+ `Trigram probe failed; treating contains search as unavailable: ${e instanceof Error ? e.message : String(e)}`,
+ );
+ return false;
+ }
+ // The recency index only speeds up the candidate query; contains search is correct without it.
+ this.trigramAvailable = Boolean(state?.trgm && state.fn && state.idx);
+ } else {
+ const rows: unknown[] = await this.dataSource.query(
+ `SELECT name FROM sqlite_master WHERE type='table' AND name='${TRIGRAM_INDEX.table}'`,
+ );
+ this.trigramAvailable = Array.isArray(rows) && rows.length === 1;
+ }
+ return this.trigramAvailable;
+ }
+
+ /** Guards a match=contains search: a missing trigram index is a 501 that names the fix. */
+ private async ensureTrigram(): Promise<void> {
+ if (await this.probeTrigram()) return;
+ throw new NotImplementedException(
+ this.dataSource.options.type === 'postgres'
+ ? 'Contains search is unavailable: install the pg_trgm and unaccent extensions (CREATE EXTENSION pg_trgm; CREATE EXTENSION unaccent;) and restart.'
+ : 'Contains search is unavailable: this SQLite build has no FTS5 trigram tokenizer (SQLite 3.45+ is required).',
+ );
+ }
+
async search(query: SearchQuery): Promise<SearchResults> {
+ if (query.match === 'contains') return this.searchContains(query);
await this.ensureFts();
const start = Date.now();
const isPostgres = this.dataSource.options.type === 'postgres';
@@ -266,6 +481,56 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
return { hits, total, tookMs: Date.now() - start, provider: this.id };
}
+ /**
+ * match=contains, in two phases (docs/26, "Match modes"):
+ *
+ * 1. The database returns at most SEARCH_CONTAINS_WINDOW candidates: the most recently stored
+ * messages that contain every term, found through the trigram index, newest first. Both
+ * dialects answer that order from an index and stop at the window, so the work is bounded
+ * however many messages match.
+ * 2. The application ranks the candidates with containsScore (whole word, then word start, then
+ * inside a word), newest first within a score and `id` last for a total order, and pages them in
+ * memory.
+ *
+ * Ranking every match in SQL instead (bm25 / word_similarity) costs time in proportion to the
+ * matches: about 100 ms on SQLite and 1.6 s on Postgres for a term found in 200k of 1M messages, and
+ * on SQLite that time blocks the event loop every session shares. With the window the same search
+ * takes about 2 ms on SQLite and 10 to 20 ms on Postgres. The price is that relevance only orders
+ * the window: `total` is the window's size at most, and older matches are reached by narrowing the
+ * query (more terms, chatId, dateTo), since the filters apply before the window. Scoring one row at
+ * a time also means a score never reflects messages outside the caller's scope, so unlike bm25 it
+ * is never withheld.
+ */
+ private async searchContains(query: SearchQuery): Promise<SearchResults> {
+ const terms = BuiltInFtsProvider.containsTermsOf(query.q);
+ await this.ensureTrigram();
+ const start = Date.now();
+ const limit = Math.max(1, Math.min(query.limit ?? 50, SEARCH_LIMIT_MAX));
+ const offset = Math.max(0, query.offset ?? 0);
+
+ const { sql, params } =
+ this.dataSource.options.type === 'postgres'
+ ? this.buildPostgresCandidates(query, terms)
+ : this.buildSqliteCandidates(query, terms);
+ const rows = await this.dataSource.query<FtsResultRow[]>(sql, params);
+
+ const ranked = rows
+ .map(row => ({ row, score: containsScore(row.body ?? '', terms) }))
+ .sort(
+ (a, b) =>
+ b.score - a.score ||
+ Number(b.row.timestamp ?? 0) - Number(a.row.timestamp ?? 0) ||
+ compareDescending(a.row.id, b.row.id),
+ );
+ const hits: SearchHit[] = ranked.slice(offset, offset + limit).map(({ row, score }) => ({
+ ...this.mapRow(row),
+ snippet: containsSnippet(row.body ?? '', terms, MAX_SNIPPET_WORDS),
+ score,
+ }));
+
+ return { hits, total: ranked.length, tookMs: Date.now() - start, provider: this.id };
+ }
+
async health(): Promise<{ ok: boolean; detail?: string }> {
// Reflects FTS availability (not just raw connectivity): a non-FTS5 build reports unhealthy here
// for callers of health(). DB errors still map to { ok: false }.
@@ -321,6 +586,23 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
return tokens.map(tok => `"${tok.replace(/"/g, '""')}"`).join(' ');
}
+ /**
+ * The whitespace-separated terms of a contains query, repeats folded away (`Invoice invoice` is one
+ * term). Every term must appear in the body, as with match=word. A trigram index cannot answer a term
+ * shorter than three characters (FTS5 returns nothing for it, pg_trgm scans every row), so such terms
+ * only narrow the rows a longer term already found, and a query made of short terms alone is a 400
+ * rather than a full-table scan.
+ */
+ private static containsTermsOf(q: string): string[] {
+ const terms = containsTerms(q);
+ if (!terms.some(term => !isShortTerm(term))) {
+ throw new BadRequestException(
+ `A contains search needs at least one term of ${SEARCH_CONTAINS_MIN_TERM_LENGTH} or more characters.`,
+ );
+ }
+ return terms;
+ }
+
// --- SQLite FTS5 -----------------------------------------------------------
// SQL appearance order: MATCH term -> filters -> LIMIT -> OFFSET. Params pushed in that order.
// Both dialects tiebreak on `m."id"`: neither `rank`/`score` nor the whole-second `timestamp` is
@@ -368,6 +650,50 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
return { sql, params };
}
+ // --- SQLite FTS5 trigram candidates (match=contains) -----------------------
+ // SQL appearance order: MATCH term -> short-term LIKEs -> filters -> LIMIT. The trigram tokenizer
+ // folds case and, with remove_diacritics, accents, so `cafe` finds `Café` and `voic` finds
+ // `Invoice`. A term under three characters cannot be looked up in it and is checked with LIKE on the
+ // rows the MATCH kept; SQLite's LIKE folds ASCII case only, which covers the ids and abbreviations
+ // such terms usually are (`id`, `pm`, `v2`). FTS5 answers `ORDER BY rowid DESC` from its own doclist
+ // order, so the LIMIT stops the walk at the window instead of sorting every match; rowid is the
+ // insertion order, so these are the most recently stored matches.
+ private buildSqliteCandidates(q: SearchQuery, terms: string[]) {
+ const ph = BuiltInFtsProvider.sqlitePlaceholder;
+ const params: unknown[] = [];
+ const where = [`${TRIGRAM_INDEX.table} MATCH ${ph()}`];
+ params.push(BuiltInFtsProvider.toFts5Query(terms.filter(term => !isShortTerm(term)).join(' ')));
+ for (const term of terms.filter(isShortTerm)) {
+ where.push(`m."body" LIKE ${ph()} ESCAPE '\\'`);
+ params.push(likePattern(term));
+ }
+ this.applyFilters(where, params, q, 'm.', ph);
+ const sql = `SELECT ${CONTAINS_COLUMNS} FROM ${TRIGRAM_INDEX.table} JOIN messages m ON m."rowid" = ${TRIGRAM_INDEX.table}."rowid" WHERE ${where.join(' AND ')} ORDER BY ${TRIGRAM_INDEX.table}."rowid" DESC LIMIT ${ph()}`;
+ params.push(SEARCH_CONTAINS_WINDOW);
+ return { sql, params };
+ }
+
+ // --- Postgres pg_trgm candidates (match=contains) --------------------------
+ // SQL appearance order: one ILIKE per term -> filters -> LIMIT. Each ILIKE compares
+ // openwa_unaccent(body), the exact expression the GIN trigram index holds; ILIKE folds case and
+ // openwa_unaccent folds accents, matching the SQLite trigram tokenizer, and each term has its `%`,
+ // `_` and `\` escaped so it matches literally. The most recently stored first, as on SQLite:
+ // idx_messages_created_at_id lets the planner walk them backward and stop at the window when a term
+ // is common, while for a rare one it reads the few matches from the GIN index and sorts them.
+ private buildPostgresCandidates(q: SearchQuery, terms: string[]) {
+ const ph = this.pgPlaceholder();
+ const params: unknown[] = [];
+ const where = terms.map(term => {
+ const placeholder = ph();
+ params.push(likePattern(term));
+ return `openwa_unaccent(m."body") ILIKE openwa_unaccent(${placeholder})`;
+ });
+ this.applyFilters(where, params, q, 'm.', ph);
+ const sql = `SELECT ${CONTAINS_COLUMNS} FROM messages m WHERE ${where.join(' AND ')} ORDER BY m."createdAt" DESC, m."id" DESC LIMIT ${ph()}`;
+ params.push(SEARCH_CONTAINS_WINDOW);
+ return { sql, params };
+ }
+
/** Emits dialect-correct placeholders. For PG, MUST be called in SQL-appearance order. */
private applyFilters(where: string[], params: unknown[], q: SearchQuery, prefix: string, ph: PlaceholderFn): void {
if (q.sessionIds && q.sessionIds.length) {
diff --git a/src/modules/search/search-score.spec.ts b/src/modules/search/search-score.spec.ts
new file mode 100644
index 000000000..e813a588e
--- /dev/null
+++ b/src/modules/search/search-score.spec.ts
@@ -0,0 +1,27 @@
+import { containsScore } from './search-score';
+
+describe('containsScore', () => {
+ it('scores a whole word above a word start above a match inside a word', () => {
+ expect(containsScore('Please pay the invoice today', ['invoice'])).toBe(3);
+ expect(containsScore('Invoiced orders are listed below', ['invoice'])).toBe(2);
+ expect(containsScore('Reinvoice requested', ['invoice'])).toBe(1);
+ });
+
+ it('keeps the best occurrence of a term', () => {
+ expect(containsScore('reinvoice, then invoice', ['invoice'])).toBe(3);
+ });
+
+ it('ignores case and accents, and treats punctuation as a word boundary', () => {
+ expect(containsScore('Meeting at the CAFÉ.', ['cafe'])).toBe(3);
+ expect(containsScore('INV-2048 is ready', ['2048'])).toBe(3);
+ });
+
+ it('adds the scores of all terms', () => {
+ expect(containsScore('Your invoice INV-2048 is ready', ['invoice', '2048'])).toBe(6);
+ expect(containsScore('Thanks, I will pay the invoice today', ['invoice', 'to'])).toBe(5);
+ });
+
+ it('scores 0 for a term the body does not contain', () => {
+ expect(containsScore('Order shipped', ['invoice'])).toBe(0);
+ });
+});
diff --git a/src/modules/search/search-score.ts b/src/modules/search/search-score.ts
new file mode 100644
index 000000000..32b4793ae
--- /dev/null
+++ b/src/modules/search/search-score.ts
@@ -0,0 +1,34 @@
+import { foldSearchText } from './search-terms';
+
+/**
+ * Relevance of a match=contains candidate, computed in the application so both dialects rank alike
+ * (see BuiltInFtsProvider.searchContains for why ranking left the database).
+ *
+ * Each term scores by its best occurrence in the body, compared folded (case and accents dropped):
+ * - 3 as a whole word (`invoice` in "pay the invoice today"),
+ * - 2 at the start of a word (`invoice` in "invoiced"),
+ * - 1 inside a word (`voic` in "invoice"),
+ * - 0 when the folded body does not contain it (a short term SQLite's ASCII-only LIKE matched).
+ * The score is the sum over the terms, so a message matching more terms as words ranks higher. It
+ * reads only the one body, never statistics of other messages, so it reveals nothing outside the
+ * caller's scope.
+ */
+export function containsScore(body: string, terms: string[]): number {
+ const folded = foldSearchText(body);
+ let score = 0;
+ for (const term of terms.map(foldSearchText)) {
+ let best = 0;
+ for (let at = folded.indexOf(term); at !== -1 && best < 3; at = folded.indexOf(term, at + 1)) {
+ const startsWord = !isWordChar(folded[at - 1]);
+ const endsWord = !isWordChar(folded[at + term.length]);
+ best = Math.max(best, startsWord && endsWord ? 3 : startsWord ? 2 : 1);
+ }
+ score += best;
+ }
+ return score;
+}
+
+/** A letter or a digit in any script; anything else (space, punctuation, start or end) bounds a word. */
+function isWordChar(char: string | undefined): boolean {
+ return char !== undefined && /[\p{L}\p{N}]/u.test(char);
+}
diff --git a/src/modules/search/search-snippet.spec.ts b/src/modules/search/search-snippet.spec.ts
new file mode 100644
index 000000000..61abf910d
--- /dev/null
+++ b/src/modules/search/search-snippet.spec.ts
@@ -0,0 +1,58 @@
+import { containsSnippet } from './search-snippet';
+import { containsTerms, foldSearchText } from './search-terms';
+
+describe('foldSearchText', () => {
+ it('drops accents and lowers case, as the contains indexes compare text', () => {
+ expect(foldSearchText('Meeting at the CAFÉ')).toBe('meeting at the cafe');
+ expect(foldSearchText('Ação')).toBe('acao');
+ });
+});
+
+describe('containsTerms', () => {
+ it('splits on whitespace and keeps each term as written', () => {
+ expect(containsTerms(' invoice INV-2048 ')).toEqual(['invoice', 'INV-2048']);
+ });
+
+ it('drops a term that folds to one already seen', () => {
+ expect(containsTerms('Café cafe CAFE meeting')).toEqual(['Café', 'meeting']);
+ });
+});
+
+describe('containsSnippet', () => {
+ it('marks a substring match ignoring case and accents, keeping the original text', () => {
+ expect(containsSnippet('Meeting at the Café Résumé', ['cafe'], 24)).toBe('Meeting at the <mark>Café</mark> Résumé');
+ expect(containsSnippet('Your INVOICE is ready', ['voic'], 24)).toBe('Your IN<mark>VOIC</mark>E is ready');
+ });
+
+ it('marks every occurrence of every term and merges overlapping ones', () => {
+ expect(containsSnippet('invoice and invoice', ['invo', 'voice'], 24)).toBe(
+ '<mark>invoice</mark> and <mark>invoice</mark>',
+ );
+ });
+
+ it('maps matches back through a body written with combining accents', () => {
+ const decomposed = 'café'.normalize('NFD');
+ expect(containsSnippet(`meet at the ${decomposed}`, ['cafe'], 24)).toBe(`meet at the <mark>${decomposed}</mark>`);
+ });
+
+ it('opens the window a few words before a late match and marks where it cut', () => {
+ const words = Array.from({ length: 40 }, (_, i) => `w${i}`);
+ words[30] = 'invoice';
+ const snippet = containsSnippet(words.join(' '), ['invoice'], 10);
+ expect(snippet).toBe('…w22 w23 w24 w25 w26 w27 w28 w29 <mark>invoice</mark> w31…');
+ });
+
+ it('keeps the match inside a window smaller than the usual context', () => {
+ const words = Array.from({ length: 30 }, (_, i) => `w${i}`);
+ words[29] = 'invoice';
+ expect(containsSnippet(words.join(' '), ['invoice'], 5)).toBe('…w25 w26 w27 w28 <mark>invoice</mark>');
+ });
+
+ it('falls back to the start of the body when no term is found in it', () => {
+ expect(containsSnippet('one two three', ['zzz'], 2)).toBe('one two…');
+ });
+
+ it('returns an empty snippet for an empty body', () => {
+ expect(containsSnippet(' ', ['invoice'], 24)).toBe('');
+ });
+});
diff --git a/src/modules/search/search-snippet.ts b/src/modules/search/search-snippet.ts
new file mode 100644
index 000000000..883f5064a
--- /dev/null
+++ b/src/modules/search/search-snippet.ts
@@ -0,0 +1,95 @@
+import { foldSearchText } from './search-terms';
+
+/**
+ * Snippets for match=contains hits, built in the application rather than the database so both
+ * dialects return the same text: FTS5's snippet() counts its window in trigrams on a trigram index,
+ * and Postgres has no headline function for a substring match.
+ *
+ * The output follows the SearchHit.snippet contract of match=word: a window of the body, `…` where it
+ * was cut, every match inside it wrapped in `<mark>`/`</mark>`, and the body text itself NOT
+ * HTML-escaped (render it as text, never as HTML).
+ */
+
+/** Words shown before the first match, so a match late in a long message keeps some context. */
+const WORDS_BEFORE_MATCH = 8;
+
+/** A folded copy of a text, with the original start and end offset of each folded UTF-16 unit. */
+interface FoldedText {
+ folded: string;
+ starts: number[];
+ ends: number[];
+}
+
+/**
+ * Folding can change a text's length: a body that spells `é` as `e` followed by a combining accent
+ * loses that accent unit. Matches are therefore found in the folded copy and mapped back through
+ * per-unit offsets, rather than assuming positions line up.
+ */
+function foldWithOffsets(text: string): FoldedText {
+ let folded = '';
+ const starts: number[] = [];
+ const ends: number[] = [];
+ let offset = 0;
+ for (const char of text) {
+ const mapped = foldSearchText(char);
+ // A combining mark folds to nothing; it belongs to the letter before it, so a match ending on that
+ // letter also covers the mark instead of leaving a dangling accent outside </mark>.
+ if (!mapped && ends.length) ends[ends.length - 1] = offset + char.length;
+ for (let i = 0; i < mapped.length; i++) {
+ starts.push(offset);
+ ends.push(offset + char.length);
+ }
+ folded += mapped;
+ offset += char.length;
+ }
+ return { folded, starts, ends };
+}
+
+/** Every occurrence of every term in `body`, as sorted, merged [start, end) offsets into the original. */
+function matchRanges(body: string, terms: string[]): Array<[number, number]> {
+ const { folded, starts, ends } = foldWithOffsets(body);
+ const ranges: Array<[number, number]> = [];
+ for (const term of terms.map(foldSearchText).filter(Boolean)) {
+ for (let at = folded.indexOf(term); at !== -1; at = folded.indexOf(term, at + term.length)) {
+ ranges.push([starts[at], ends[at + term.length - 1]]);
+ }
+ }
+ ranges.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
+ const merged: Array<[number, number]> = [];
+ for (const [start, end] of ranges) {
+ const last = merged[merged.length - 1];
+ if (last && start <= last[1]) last[1] = Math.max(last[1], end);
+ else merged.push([start, end]);
+ }
+ return merged;
+}
+
+/**
+ * Up to `maxWords` words of `body`, starting a few words before the first match (or at the start when
+ * none is found, e.g. a short term LIKE matched on SQLite's ASCII-only case folding), with every match
+ * in the window marked.
+ */
+export function containsSnippet(body: string, terms: string[], maxWords: number): string {
+ const words = [...body.matchAll(/\S+/g)];
+ if (words.length === 0) return '';
+ const ranges = matchRanges(body, terms);
+ const firstHit = ranges.length ? words.findIndex(w => (w.index ?? 0) + w[0].length > ranges[0][0]) : 0;
+ // Never more context than the window can hold next to the match itself.
+ const before = Math.min(WORDS_BEFORE_MATCH, maxWords - 1);
+ const from = Math.max(0, Math.min(firstHit - before, words.length - maxWords));
+ const to = Math.min(words.length, from + maxWords);
+ const sliceStart = words[from].index ?? 0;
+ const sliceEnd = (words[to - 1].index ?? 0) + words[to - 1][0].length;
+
+ let snippet = from > 0 ? '…' : '';
+ let cursor = sliceStart;
+ for (const [start, end] of ranges) {
+ if (end <= sliceStart || start >= sliceEnd) continue;
+ const markStart = Math.max(start, sliceStart);
+ const markEnd = Math.min(end, sliceEnd);
+ snippet += `${body.slice(cursor, markStart)}<mark>${body.slice(markStart, markEnd)}</mark>`;
+ cursor = markEnd;
+ }
+ snippet += body.slice(cursor, sliceEnd);
+ return to < words.length ? `${snippet}…` : snippet;
+}
diff --git a/src/modules/search/search-terms.ts b/src/modules/search/search-terms.ts
index 9cd07cf62..f21997b88 100644
--- a/src/modules/search/search-terms.ts
+++ b/src/modules/search/search-terms.ts
@@ -56,6 +56,29 @@ function wordsOf(word: string): number {
* symbol or emoji that stands apart counts as a word of its own. A whitespace-separated word said again
* is run once and counts once, and a word with no letter, digit or symbol counts as one.
*/
+/**
+ * Folds text the way the match=contains indexes compare it: accents dropped (NFD, then every combining
+ * mark removed, as remove_diacritics and unaccent do for Latin text) and case lowered. Used to compare
+ * terms and to place highlights, never to build SQL, which leaves folding to the database.
+ */
+export function foldSearchText(text: string): string {
+ return text.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
+}
+
+/**
+ * The whitespace-separated terms of a match=contains query, each kept as written, with a term that
+ * folds to one already seen dropped (`Café cafe` is one term): it would add nothing to an AND but
+ * one more predicate per matching row.
+ */
+export function containsTerms(q: string): string[] {
+ const terms = new Map<string, string>();
+ for (const term of q.trim().split(/\s+/)) {
+ const folded = foldSearchText(term);
+ if (folded && !terms.has(folded)) terms.set(folded, term);
+ }
+ return [...terms.values()];
+}
+
export function searchTermCount(q: string): number {
let count = 0;
for (const word of new Set(q.trim().split(/\s+/))) {
diff --git a/src/modules/search/search.constants.ts b/src/modules/search/search.constants.ts
index 00b9accff..1dbe9e86c 100644
--- a/src/modules/search/search.constants.ts
+++ b/src/modules/search/search.constants.ts
@@ -1,4 +1,5 @@
import { resolveNonNegativeIntEnv } from '../../config/configuration';
+import type { SearchMatch } from './search.types';
/**
* Host-side /search pagination bounds. Applied in SearchService BEFORE delegating to any provider,
@@ -29,3 +30,22 @@ export const SEARCH_QUERY_MAX_LENGTH = 1000;
* provider collapses repeats.
*/
export const SEARCH_TERMS_MAX = 32;
+
+/** Every accepted `match` value, for the DTO, the OpenAPI enum and the MCP tool schema alike. */
+export const SEARCH_MATCH_MODES = ['word', 'contains'] as const satisfies readonly SearchMatch[];
+
+/**
+ * Shortest term a match=contains search can look up in a trigram index: a trigram is three characters,
+ * so a shorter term has none (SQLite's trigram table returns nothing for it, pg_trgm scans every row).
+ * A query needs at least one term this long; shorter ones only narrow what it found.
+ */
+export const SEARCH_CONTAINS_MIN_TERM_LENGTH = 3;
+
+/**
+ * How many candidates a match=contains search ranks: the most recently stored matches, fetched from
+ * the index in recency order so the database stops at this many however many messages match, then
+ * ranked in the application. It bounds the work of one search (ranking every match in SQL took about
+ * 100 ms on SQLite and 1.6 s on Postgres for 200k matches) and is therefore also the most `total` can
+ * report in this mode. Fixed rather than env-driven, like SEARCH_OFFSET_MAX.
+ */
+export const SEARCH_CONTAINS_WINDOW = 1000;
diff --git a/src/modules/search/search.controller.ts b/src/modules/search/search.controller.ts
index 95cea2c76..115ffa762 100644
--- a/src/modules/search/search.controller.ts
+++ b/src/modules/search/search.controller.ts
@@ -6,7 +6,7 @@ import { ChatScopeService } from '../auth/chat-scope.service';
import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';
import { SearchService } from './search.service';
import { SearchQueryDto } from './dto/search-query.dto';
-import { SEARCH_OFFSET_MAX } from './search.constants';
+import { SEARCH_CONTAINS_WINDOW, SEARCH_MATCH_MODES, SEARCH_OFFSET_MAX } from './search.constants';
import type { SearchResults } from './search.types';
@ApiTags('search')
@@ -24,10 +24,17 @@ export class SearchController {
@ApiResponse({ status: 200, description: 'Search results from the active provider', type: SearchResultsResponseDto })
@ApiResponse({
status: 400,
- description: 'Empty or whitespace-only "q", or one over 1000 characters or 32 words',
+ description:
+ 'Empty or whitespace-only "q", or one over 1000 characters or 32 words; an unknown "match"; or a ' +
+ '"match=contains" query whose terms are all shorter than 3 characters',
})
@ApiResponse({ status: 403, description: 'Chat scope denied or chat-restricted search uses a plugin provider' })
- @ApiResponse({ status: 501, description: 'No search provider configured' })
+ @ApiResponse({
+ status: 501,
+ description:
+ 'No search provider configured, or the built-in provider lacks the index the requested match mode needs ' +
+ '(for "match=contains" on PostgreSQL: the pg_trgm and unaccent extensions)',
+ })
@ApiResponse({
status: 502,
description:
@@ -45,6 +52,14 @@ export class SearchController {
required: true,
description: 'Search term (required, non-empty, at most 1000 characters and 32 words)',
})
+ @ApiQuery({
+ name: 'match',
+ required: false,
+ enum: SEARCH_MATCH_MODES,
+ description:
+ 'word (default): whole words. contains: any part of a word, ignoring case and accents; ranks the ' +
+ `${SEARCH_CONTAINS_WINDOW} most recently stored matches by match quality`,
+ })
@ApiQuery({ name: 'sessionId', required: false, description: 'Restrict to a single session' })
@ApiQuery({ name: 'chatId', required: false, description: 'Restrict to a single chat id' })
@ApiQuery({ name: 'direction', required: false, description: 'incoming | outgoing' })
diff --git a/src/modules/search/search.module.ts b/src/modules/search/search.module.ts
index 8c38316a3..7fcbea5ce 100644
--- a/src/modules/search/search.module.ts
+++ b/src/modules/search/search.module.ts
@@ -1,4 +1,4 @@
-import { Module } from '@nestjs/common';
+import { Global, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { SearchController } from './search.controller';
import { SearchService } from './search.service';
@@ -18,6 +18,10 @@ import { PLUGIN_SEARCH_REGISTRY_PORT } from '../../core/plugins/plugin-host-port
* The module is imported by AppModule only when `SEARCH_ENABLED !== 'false'`. Plugin providers
* register themselves through the same registry; in `auto` mode the most recently registered plugin
* supersedes builtin (no health gating).
+ *
+ * Global and exporting SearchService so the agent-tool registry (MessageSearch) can inject it as an
+ * optional dependency: importing this module there would load search even when SEARCH_ENABLED=false
+ * asks for it to be absent.
*/
export function bootstrapSearchProviders(
registry: SearchProviderRegistry,
@@ -37,6 +41,7 @@ export function bootstrapSearchProviders(
return registry;
}
+@Global()
@Module({
imports: [ConfigModule],
controllers: [SearchController],
@@ -55,5 +60,6 @@ export function bootstrapSearchProviders(
// An alias, not a factory, so lifecycle hooks are not dispatched twice on the same instance.
{ provide: PLUGIN_SEARCH_REGISTRY_PORT, useExisting: SearchProviderRegistry },
],
+ exports: [SearchService],
})
export class SearchModule {}
diff --git a/src/modules/search/search.types.ts b/src/modules/search/search.types.ts
index 1a43c7b6d..ba94a722f 100644
--- a/src/modules/search/search.types.ts
+++ b/src/modules/search/search.types.ts
@@ -18,8 +18,17 @@ export interface SearchHealth {
detail?: string;
}
+/**
+ * How `q` matches a message body. `word` matches whole words (the built-in provider's original
+ * behavior); `contains` matches any substring of three or more characters, ignoring case and accents.
+ * A plugin provider receives the field and may treat it as its backend allows.
+ */
+export type SearchMatch = 'word' | 'contains';
+
export interface SearchQuery {
q: string;
+ /** Absent means `word`, so callers that predate the field keep their results. */
+ match?: SearchMatch;
/** Scoped by SearchService from the caller's API-key allowedSessions (not user-supplied). */
sessionIds?: string[];
/** Host-set, lid-expanded chat scope: undefined is unrestricted, [] denies every chat. */