From adeaa384dbea5e130c4e6c06977683f3e3a24eb7 Mon Sep 17 00:00:00 2001 From: larryro <371767072@qq.com> Date: Thu, 20 Aug 2026 18:44:18 +0800 Subject: [PATCH] feat(platform): split chat rag_search into search and list actions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Browse questions were stuffed into the search query, where they match nothing by construction: "list all in-review tasks" tokenises to words no task title contains, so the model reworded and re-searched its way through the whole tool budget. The verb is now explicit — a required action enum, because inferring "list" from an empty query is the omission-becomes-another-operation trap. - action="search" keeps today's fan-out byte-identical (including the tasks/projects listing fallback); an optional kind narrows it to one leg, and a residue detector (en/de/fr, punctuation-aware, reusing the search stopwords) steers pure listing utterances to the list verb — any surviving noun honours the search. - action="list" browses ONE kind through the kind's existing reader with the text predicate off, behind the same role gate and scope as its search leg: tasks/projects via the listing path (which now honours numItems and returns its real cursor), conversations via a predicate-off branch (privacy predicate untouched, hasMore proven by overfetching one), documents via listForAgent, entities via their paginated queries. Task lists require a status or projectId slice; kind="web-page" is refused with a steer to the site catalog. - The envelope always carries hasMore and a kind-tagged continueCursor only when the next call can redeem it — no totalCount, and a cross-kind or hallucinated cursor is refused before touching an index. An exact repeat of a call within one turn is answered with "use the previous result"; paging is keyed apart by its cursor. - Missing action stays cheap: a query alone runs as the search it always meant, a kind alone as the list it can only mean — only the verbless empty call costs a correction round. - rag_fetch on a project ref opts into the same listing, fixing its never-true truncated flag (the fallback pinned its own 15-row cap while the flag compared against 25). - The timeline labels a list step "Listing tasks" (en/de/fr) instead of interpolating an empty query, and the chat basics docs gain the browse story in all three locales (plus the stale "knowledge base" label quote corrected to the shipped "workspace" wording). Wire cost, measured: the rag_search definition grows 2,069 to 3,804 chars (~+460 tokens per request); a board question drops from an 8-leg fan-out with embedding and rerank to one Convex query. --- docs/de/platform/chat/basics.md | 14 +- docs/en/platform/chat/basics.md | 14 +- docs/fr/platform/chat/basics.md | 14 +- .../chat/components/message-parts.tsx | 9 +- .../chat/components/thought-timeline.tsx | 9 +- .../chat/utils/activity-label.test.ts | 84 + .../app/features/chat/utils/activity-label.ts | 40 + services/platform/convex/_generated/api.d.ts | 2 + .../convex/chat/assistant_tools.test.ts | 533 +++++- .../platform/convex/chat/assistant_tools.ts | 1451 +++++++++++++---- .../conversations/search_for_chat.test.ts | 61 + .../convex/conversations/search_for_chat.ts | 57 +- services/platform/convex/lib/search/index.ts | 2 + .../convex/lib/search/listing_intent.test.ts | 64 + .../convex/lib/search/listing_intent.ts | 294 ++++ .../platform/convex/lib/search/relevance.ts | 6 +- .../convex/tasks/search_for_chat.test.ts | 202 +++ .../platform/convex/tasks/search_for_chat.ts | 130 +- services/platform/lib/chat/index.ts | 6 + services/platform/lib/chat/tools.test.ts | 50 + services/platform/lib/chat/tools.ts | 158 +- services/platform/messages/de.yml | 10 + services/platform/messages/en.yml | 10 + services/platform/messages/fr.yml | 10 + 24 files changed, 2761 insertions(+), 469 deletions(-) create mode 100644 services/platform/app/features/chat/utils/activity-label.test.ts create mode 100644 services/platform/convex/lib/search/listing_intent.test.ts create mode 100644 services/platform/convex/lib/search/listing_intent.ts diff --git a/docs/de/platform/chat/basics.md b/docs/de/platform/chat/basics.md index 456d0e216c..0dc68266b9 100644 --- a/docs/de/platform/chat/basics.md +++ b/docs/de/platform/chat/basics.md @@ -57,14 +57,16 @@ Wächst das Gespräch über das Kontextfenster des Modells hinaus, fallen die ä Der Assistent trägt genau drei Tools, alle drei reiner Lese-Abruf — das ist die Grenze, die Chat ein Gespräch bleiben lässt statt einer Werkbank. -| Tool | Was es erreicht | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `rag_search` | Das Wissen der Organisation und ihre Arbeit: Dokumente, Wissenseinträge, gecrawlte Website-Seiten, Produkte, Kontakte, Aufgaben und Projekte | -| `rag_fetch` | Das Detail hinter einer Referenz — ein Dokument über seine Datei-ID, eine gecrawlte Seite über ihre URL, eine Aufgabe über die Referenz aus einer Suche | -| `web_fetch` | Eine öffentliche Webseite, live geholt — der Schritt über das Org-Wissen hinaus; bereits gecrawlte Inhalte liefert `rag_fetch` | +| Tool | Was es erreicht | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `rag_search` | Das Wissen der Organisation und ihre Arbeit: Dokumente, Wissenseinträge, gecrawlte Website-Seiten, Produkte, Kontakte, Websites, Aufgaben und Projekte — und die Konversationen des Posteingangs | +| `rag_fetch` | Das Detail hinter einer Referenz — ein Dokument über seine Datei-ID, eine gecrawlte Seite über ihre URL, eine Aufgabe über die Referenz aus einer Suche | +| `web_fetch` | Eine öffentliche Webseite, live geholt — der Schritt über das Org-Wissen hinaus; bereits gecrawlte Inhalte liefert `rag_fetch` | Nach dem Board zu fragen — etwa was in einem Projekt offen ist — ist eine Suche, kein separates Feature. Dieselbe `rag_search` liest die Aufgaben und Projekte, die du sehen darfst, auf deinen eigenen Zugriff gefiltert, und der Assistent antwortet daraus, statt einen externen Tracker vorzuschlagen. Ein Aufgaben-Treffer bringt Titel, Status und Projekt mit; `rag_fetch` auf seine Referenz ergänzt die vollständige Beschreibung, Kommentare, Teilaufgaben und Blocker. +Durchblättern ist dasselbe Tool mit seinem zweiten Verb. „Liste die Aufgaben in Review" oder „zeig unsere Kontakte" lässt `rag_search` explizit auflisten statt Text zu matchen: eine Art pro Aufruf, das aktuelle Board ohne archivierte Zeilen, höchstens zwanzig Zeilen pro Seite. Der Assistent erfährt, wenn eine Seite nicht die ganze Menge ist — er holt dann die nächste Seite oder sagt, welchen Ausschnitt er gesehen hat, statt zwanzig Zeilen als alles auszugeben. + Eine Suche ist ehrlich darüber, was sie abgedeckt hat: Das Ergebnis benennt jede durchsuchte Quelle und sagt, welche nicht verfügbar waren — eine Organisation ohne konfiguriertes Embedding-Modell bekommt zum Beispiel „Dokumente und gecrawlte Seiten sind noch nicht durchsuchbar" statt einer stumm leeren Liste, und der Assistent gibt das weiter, statt darum herumzuraten. Mehr gibt es bewusst nicht — kein Code-Ausführen, kein Datei-Schreiben, keine Connectors, keine Sub-Agents. Diese Fähigkeiten leben auf Aufgaben und in Automatisierungen, wo es Verantwortliche, einen Prüfschritt und ein Audit-Protokoll gibt, das ihnen gewachsen ist. @@ -78,7 +80,7 @@ Bitte den Assistenten um eine Präsentation, ein übersetztes Dokument oder ein Die Antwort streamt herein, während sie entsteht. Darüber hält der Denkverlauf fest, was der Assistent getan hat, in Reihenfolge: - Eine einklappbare Zeile **„Hat _n_ s nachgedacht"** trägt das Nachdenken des Modells — ein Klick klappt die Prosa auf. -- Jeder Tool-Aufruf ist eine Schrittzeile — _Durchsucht die Wissensdatenbank nach "…"_, _Liest example.com_ — mit einem Spinner, solange er läuft, und einer Warnung samt Grund, wenn er scheitert. Die Schritte bleiben sichtbar, wenn das Nachdenken eingeklappt ist; sie sind das Protokoll dessen, wonach der Assistent gegriffen hat. +- Jeder Tool-Aufruf ist eine Schrittzeile — _Durchsucht den Workspace nach "…"_, _Listet Aufgaben auf_, _Liest example.com_ — mit einem Spinner, solange er läuft, und einer Warnung samt Grund, wenn er scheitert. Die Schritte bleiben sichtbar, wenn das Nachdenken eingeklappt ist; sie sind das Protokoll dessen, wonach der Assistent gegriffen hat. Unter der Antwort listet **Quellen** die Seiten und Dokumente, die der Assistent tatsächlich geladen hat — abgeleitet aus den Tool-Ergebnissen, nicht aus der Prosa, sodass eine Quellenkarte nie eine Lektüre behauptet, die nicht stattgefunden hat. Web-Quellen öffnen in einem neuen Tab. diff --git a/docs/en/platform/chat/basics.md b/docs/en/platform/chat/basics.md index b387215d7a..5dc74782f5 100644 --- a/docs/en/platform/chat/basics.md +++ b/docs/en/platform/chat/basics.md @@ -57,14 +57,16 @@ When the conversation outgrows the model's context window, the oldest messages a The assistant carries exactly three tools, all read-only retrieval — this is the boundary that keeps chat a conversation rather than a workbench. -| Tool | What it reaches | -| ------------ | --------------------------------------------------------------------------------------------------------------------------------------- | -| `rag_search` | The organisation's knowledge and its work: documents, knowledge entries, crawled website pages, products, contacts, tasks, and projects | -| `rag_fetch` | The full detail behind a ref — a document by its file id, a crawled page by its URL, or a task by the ref a search returned | -| `web_fetch` | A public web page, fetched live — the step beyond the organisation's knowledge; content already crawled is served by `rag_fetch` | +| Tool | What it reaches | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `rag_search` | The organisation's knowledge and its work: documents, knowledge entries, crawled website pages, products, contacts, websites, tasks and projects, and the inbox's conversations | +| `rag_fetch` | The full detail behind a ref — a document by its file id, a crawled page by its URL, or a task by the ref a search returned | +| `web_fetch` | A public web page, fetched live — the step beyond the organisation's knowledge; content already crawled is served by `rag_fetch` | Asking about the board is a search, not a different feature. "What's open on the launch project?" reaches the same `rag_search` — it reads the tasks and projects you can see, filtered to your own access, and the assistant answers from them instead of suggesting an external tracker. A task result carries its title, status and project; `rag_fetch` on its ref adds the full description, comments, subtasks and blockers. +Browsing is the same tool with its second verb. "List the tasks in review" or "show our contacts" runs `rag_search` as an explicit listing rather than a text match: one kind per call, the current board without archived rows, and a page of at most twenty at a time. The assistant is told when a page is not the whole set, so it fetches the next page or says which part it saw — it never presents twenty rows as everything. + A search is honest about what it covered: the result names every source it searched and says which were unavailable — an organisation without an embedding model configured, for example, gets "documents and crawled pages can't be searched yet" rather than a silent empty list, and the assistant relays that instead of guessing around it. There is deliberately nothing else — no code execution, no file writing, no connectors, no sub-agents. Those capabilities live on tasks and inside automations, where there is an owner, a review step, and an audit trail sized for them. @@ -78,7 +80,7 @@ Ask the assistant for a presentation, a translated document, or any other artifa The reply streams in as it is generated. Above it, the thought timeline records what the assistant did, in order: - A collapsible **"Thought for _n_ s"** line carries the model's reasoning — click to expand the prose. -- Each tool call is a step row — _Searching knowledge base for "…"_, _Reading example.com_ — with a spinner while it runs and a warning with the reason when it fails. The steps stay visible when the reasoning is collapsed; they are the record of what the assistant reached for. +- Each tool call is a step row — _Searching the workspace for "…"_, _Listing tasks_, _Reading example.com_ — with a spinner while it runs and a warning with the reason when it fails. The steps stay visible when the reasoning is collapsed; they are the record of what the assistant reached for. Below the answer, **Sources** lists the pages and documents the assistant actually loaded — derived from the tool results, not from the prose, so a source card never claims reading that did not happen. Web sources open in a new tab. diff --git a/docs/fr/platform/chat/basics.md b/docs/fr/platform/chat/basics.md index 72ee2d4f4b..76711d71dc 100644 --- a/docs/fr/platform/chat/basics.md +++ b/docs/fr/platform/chat/basics.md @@ -57,14 +57,16 @@ Quand la conversation dépasse la fenêtre de contexte du modèle, les messages L’assistant porte exactement trois outils, tous tournés vers la récupération et tous en lecture seule — c’est la frontière qui fait du chat une conversation plutôt qu’un établi. -| Outil | Ce qu’il atteint | -| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `rag_search` | Les connaissances de l’organisation et son travail : documents, entrées de connaissances, pages de sites web explorés, produits, contacts, tâches et projets | -| `rag_fetch` | Le détail derrière une référence — un document par son identifiant de fichier, une page explorée par son URL, une tâche par la référence issue d’une recherche | -| `web_fetch` | Une page web publique, récupérée en direct — l’étape au-delà des connaissances de l’organisation ; le contenu déjà exploré passe par `rag_fetch` | +| Outil | Ce qu’il atteint | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `rag_search` | Les connaissances de l’organisation et son travail : documents, entrées de connaissances, pages de sites web explorés, produits, contacts, sites web, tâches et projets — et les conversations de la boîte de réception | +| `rag_fetch` | Le détail derrière une référence — un document par son identifiant de fichier, une page explorée par son URL, une tâche par la référence issue d’une recherche | +| `web_fetch` | Une page web publique, récupérée en direct — l’étape au-delà des connaissances de l’organisation ; le contenu déjà exploré passe par `rag_fetch` | Interroger le tableau — ce qui est ouvert sur un projet, par exemple — relève de la recherche, pas d’une autre fonctionnalité. La même `rag_search` lit les tâches et les projets que tu peux voir, filtrés selon ton propre accès, et l’assistant répond à partir de là plutôt que de proposer un outil externe. Un résultat de tâche porte son titre, son statut et son projet ; `rag_fetch` sur sa référence ajoute la description complète, les commentaires, les sous-tâches et les bloqueurs. +Parcourir, c’est le même outil avec son second verbe. « Liste les tâches en revue » ou « montre nos contacts » fait tourner `rag_search` en listage explicite plutôt qu’en correspondance de texte : une seule sorte par appel, le tableau courant sans les lignes archivées, au plus vingt lignes par page. L’assistant sait quand une page n’est pas l’ensemble complet — il va chercher la page suivante ou dit quelle partie il a vue, au lieu de présenter vingt lignes comme le tout. + Une recherche est honnête sur ce qu’elle a couvert : le résultat nomme chaque source interrogée et dit lesquelles étaient indisponibles — une organisation sans modèle d’embedding configuré reçoit par exemple « les documents et les pages explorées ne peuvent pas encore être cherchés » plutôt qu’une liste vide et muette, et l’assistant relaie ce constat au lieu de deviner autour. Il n’y a délibérément rien d’autre — pas d’exécution de code, pas d’écriture de fichiers, pas de connectors, pas de sous-agents. Ces capacités vivent sur les tâches et dans les automatisations, là où existent un responsable, une étape de relecture et une piste d’audit à leur mesure. @@ -78,7 +80,7 @@ Demande à l’assistant une présentation, un document traduit ou n’importe q La réponse arrive en streaming à mesure qu’elle se génère. Au-dessus d’elle, le déroulé de réflexion consigne ce que l’assistant a fait, dans l’ordre : - Une ligne repliable **« A réfléchi pendant _n_ s »** porte le raisonnement du modèle — clique pour déplier la prose. -- Chaque appel d’outil est une ligne d’étape — _Recherche dans la base de connaissances pour « … »_, _Lecture de example.com_ — avec un indicateur d’activité pendant qu’il tourne et, quand il échoue, un avertissement qui en donne la raison. Les étapes restent visibles quand le raisonnement est replié ; elles sont la trace de ce que l’assistant est allé chercher. +- Chaque appel d’outil est une ligne d’étape — _Recherche de « … » dans l’espace de travail_, _Liste des tâches_, _Lecture de example.com_ — avec un indicateur d’activité pendant qu’il tourne et, quand il échoue, un avertissement qui en donne la raison. Les étapes restent visibles quand le raisonnement est replié ; elles sont la trace de ce que l’assistant est allé chercher. Sous la réponse, **Sources** liste les pages et les documents que l’assistant a réellement chargés — la liste dérive des résultats d’outils, pas de la prose, si bien qu’une carte de source ne revendique jamais une lecture qui n’a pas eu lieu. Les sources web s’ouvrent dans un nouvel onglet. diff --git a/services/platform/app/features/chat/components/message-parts.tsx b/services/platform/app/features/chat/components/message-parts.tsx index 25c148fc73..5416b10960 100644 --- a/services/platform/app/features/chat/components/message-parts.tsx +++ b/services/platform/app/features/chat/components/message-parts.tsx @@ -47,9 +47,16 @@ function isImageAttachment( } /** What a tool was asked, for the chip's detail: the retrieval tools carry - * exactly one human-meaningful argument each. */ + * exactly one human-meaningful argument each — except a list call, whose + * load-bearing facts are its filters. */ function toolCallDetail(input: unknown): string | undefined { if (!isRecord(input)) return undefined; + if (input.action === 'list') { + const kind = typeof input.kind === 'string' ? input.kind : undefined; + const status = typeof input.status === 'string' ? input.status : undefined; + if (kind === undefined) return undefined; + return status === undefined ? kind : `${kind} · ${status}`; + } for (const key of ['query', 'ref', 'url'] as const) { const value = input[key]; if (typeof value === 'string' && value.length > 0) return value; diff --git a/services/platform/app/features/chat/components/thought-timeline.tsx b/services/platform/app/features/chat/components/thought-timeline.tsx index da683d20b9..83661318b5 100644 --- a/services/platform/app/features/chat/components/thought-timeline.tsx +++ b/services/platform/app/features/chat/components/thought-timeline.tsx @@ -60,9 +60,16 @@ const TOOL_ICONS: Record> = { }; /** What a tool was asked, for the step's detail: the retrieval tools carry - * exactly one human-meaningful argument each. */ + * exactly one human-meaningful argument each — except a list call, whose + * load-bearing facts are its filters. */ function toolCallDetail(input: unknown): string | undefined { if (!isRecord(input)) return undefined; + if (input.action === 'list') { + const kind = typeof input.kind === 'string' ? input.kind : undefined; + const status = typeof input.status === 'string' ? input.status : undefined; + if (kind === undefined) return undefined; + return status === undefined ? kind : `${kind} · ${status}`; + } for (const key of ['query', 'ref', 'url'] as const) { const value = input[key]; if (typeof value === 'string' && value.length > 0) return value; diff --git a/services/platform/app/features/chat/utils/activity-label.test.ts b/services/platform/app/features/chat/utils/activity-label.test.ts new file mode 100644 index 0000000000..ad6f4820db --- /dev/null +++ b/services/platform/app/features/chat/utils/activity-label.test.ts @@ -0,0 +1,84 @@ +import type { TFunction } from 'i18next'; +import { describe, expect, it } from 'vitest'; + +import { ragSearchListingKind, stepActivityLabel } from './activity-label'; + +/** A translator that renders the key and its params, so an assertion reads + * the exact call instead of a locale string. */ +function fakeT(): TFunction { + const impl = (key: string, params?: Record) => + params === undefined ? key : `${key} ${JSON.stringify(params)}`; + return impl as TFunction; +} + +describe('stepActivityLabel — rag_search', () => { + const t = fakeT(); + + it('labels a list call by its kind, never with empty quotes', () => { + const label = stepActivityLabel(t, { + tool: 'rag_search', + input: { action: 'list', kind: 'task', status: 'in_review' }, + }); + expect(label).toBe('thinking.listing.tasks'); + expect(label).not.toContain('""'); + }); + + it('reads a queryless kind-only call as the list the executor runs', () => { + expect( + stepActivityLabel(t, { + tool: 'rag_search', + input: { kind: 'contact' }, + }), + ).toBe('thinking.listing.contacts'); + }); + + it('falls back to the generic listing label on an unknown kind', () => { + expect( + stepActivityLabel(t, { + tool: 'rag_search', + input: { action: 'list', kind: 'mystery' }, + }), + ).toBe('thinking.listing.generic'); + expect( + stepActivityLabel(t, { + tool: 'rag_search', + input: { action: 'list' }, + }), + ).toBe('thinking.listing.generic'); + }); + + it('keeps every historical query row rendering as a search', () => { + expect( + stepActivityLabel(t, { + tool: 'rag_search', + detail: 'refunds', + input: { query: 'refunds' }, + }), + ).toBe('thinking.searchingKnowledgeBase {"query":"refunds"}'); + // A row with no input at all (the oldest shape) still renders. + expect( + stepActivityLabel(t, { tool: 'rag_search', detail: 'refunds' }), + ).toBe('thinking.searchingKnowledgeBase {"query":"refunds"}'); + }); + + it('a kind-narrowed search stays a search label', () => { + expect( + stepActivityLabel(t, { + tool: 'rag_search', + detail: 'ada', + input: { action: 'search', query: 'ada', kind: 'contact' }, + }), + ).toBe('thinking.searchingKnowledgeBase {"query":"ada"}'); + }); +}); + +describe('ragSearchListingKind', () => { + it('never reads a query-bearing call as a list', () => { + expect(ragSearchListingKind({ query: 'open tasks' })).toBeUndefined(); + expect( + ragSearchListingKind({ action: 'search', query: 'x', kind: 'task' }), + ).toBeUndefined(); + expect(ragSearchListingKind(undefined)).toBeUndefined(); + expect(ragSearchListingKind('list')).toBeUndefined(); + }); +}); diff --git a/services/platform/app/features/chat/utils/activity-label.ts b/services/platform/app/features/chat/utils/activity-label.ts index 98cde0c56f..e6e7a89653 100644 --- a/services/platform/app/features/chat/utils/activity-label.ts +++ b/services/platform/app/features/chat/utils/activity-label.ts @@ -9,6 +9,8 @@ import type { TFunction } from 'i18next'; +import { isRecord } from '@/lib/utils/type-utils'; + /** The hostname of a URL, when it parses — shared by the "Reading {hostname}" * step titles and the web source cards' muted detail. */ export function hostnameOf(url: string): string | undefined { @@ -26,6 +28,40 @@ export interface StepActivity { readonly detail?: string; /** The fetched document's filename, when the result named one. */ readonly resultName?: string; + /** The raw call arguments, for the labels one argument cannot carry — + * a rag_search list call has no query, only filters. */ + readonly input?: unknown; +} + +/** Label key per listed kind — literal strings, so the i18n usage scan sees + * every key. Anything unknown (or a kind added later) falls back to the + * generic line rather than an empty-quotes search label. */ +const LISTING_LABEL_KEYS: Record = { + task: 'thinking.listing.tasks', + project: 'thinking.listing.projects', + contact: 'thinking.listing.contacts', + product: 'thinking.listing.products', + document: 'thinking.listing.documents', + website: 'thinking.listing.websites', + 'knowledge-entry': 'thinking.listing.knowledgeEntries', + conversation: 'thinking.listing.conversations', +}; + +/** + * The kind a rag_search call is LISTING, when it is one. An explicit + * `action: 'list'` decides; a call with a kind and no query is the same + * intent (the executor runs it as a list). Every historical `{query}` row + * stays a search — this is what keeps old transcripts rendering. + */ +export function ragSearchListingKind(input: unknown): string | undefined { + if (!isRecord(input)) return undefined; + const kind = typeof input.kind === 'string' ? input.kind : undefined; + if (input.action === 'list') return kind ?? 'generic'; + const query = typeof input.query === 'string' ? input.query.trim() : ''; + if (input.action === undefined && query === '' && kind !== undefined) { + return kind; + } + return undefined; } /** @@ -35,6 +71,10 @@ export interface StepActivity { */ export function stepActivityLabel(t: TFunction, step: StepActivity): string { if (step.tool === 'rag_search') { + const listedKind = ragSearchListingKind(step.input); + if (listedKind !== undefined) { + return t(LISTING_LABEL_KEYS[listedKind] ?? 'thinking.listing.generic'); + } return t('thinking.searchingKnowledgeBase', { query: step.detail ?? '' }); } if ( diff --git a/services/platform/convex/_generated/api.d.ts b/services/platform/convex/_generated/api.d.ts index e95c3ec7a4..30de4d8028 100644 --- a/services/platform/convex/_generated/api.d.ts +++ b/services/platform/convex/_generated/api.d.ts @@ -605,6 +605,7 @@ import type * as lib_rls_wrappers_with_organization_rls from "../lib/rls/wrapper import type * as lib_rls_wrappers_with_resource_rls from "../lib/rls/wrappers/with_resource_rls.js"; import type * as lib_safe_path_segment from "../lib/safe_path_segment.js"; import type * as lib_search_index from "../lib/search/index.js"; +import type * as lib_search_listing_intent from "../lib/search/listing_intent.js"; import type * as lib_search_relevance from "../lib/search/relevance.js"; import type * as lib_search_run_entity_search from "../lib/search/run_entity_search.js"; import type * as lib_search_scoped_substring_search from "../lib/search/scoped_substring_search.js"; @@ -1567,6 +1568,7 @@ declare const fullApi: ApiFromModules<{ "lib/rls/wrappers/with_resource_rls": typeof lib_rls_wrappers_with_resource_rls; "lib/safe_path_segment": typeof lib_safe_path_segment; "lib/search/index": typeof lib_search_index; + "lib/search/listing_intent": typeof lib_search_listing_intent; "lib/search/relevance": typeof lib_search_relevance; "lib/search/run_entity_search": typeof lib_search_run_entity_search; "lib/search/scoped_substring_search": typeof lib_search_scoped_substring_search; diff --git a/services/platform/convex/chat/assistant_tools.test.ts b/services/platform/convex/chat/assistant_tools.test.ts index 617db86109..0e62875edf 100644 --- a/services/platform/convex/chat/assistant_tools.test.ts +++ b/services/platform/convex/chat/assistant_tools.test.ts @@ -14,6 +14,7 @@ import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { CHAT_ASSISTANT_SLUG, RAG_SEARCH_ENTITY_LIMIT, + RAG_SEARCH_MAX_LIMIT, RAG_SEARCH_MIN_SIMILARITY, } from '../../lib/chat'; import { SafeFetchError } from '../lib/http/safe_fetch'; @@ -111,6 +112,7 @@ const TASK_BY_ID_FN = 'tasks/internal_queries:getTaskByIdInternal'; const TASK_CONTEXT_FN = 'tasks/internal_queries:getTaskContextForAgent'; const CONVERSATIONS_SEARCH_FN = 'conversations/search_for_chat:searchConversationsForChat'; +const DOCUMENTS_LIST_FN = 'documents/internal_queries:listForAgent'; const WHO = { organizationId: 'org_1', userId: 'user_1' }; @@ -143,6 +145,13 @@ function createCtx( continueCursor: '', }), [CONVERSATIONS_SEARCH_FN]: () => ({ conversations: [], truncated: false }), + [DOCUMENTS_LIST_FN]: () => ({ + documents: [], + totalCount: 0, + hasMore: false, + cursor: null, + warning: null, + }), [TASK_BY_ID_FN]: () => null, [TASK_CONTEXT_FN]: () => null, [DOCUMENT_ROW_FN]: () => null, @@ -1157,7 +1166,7 @@ describe('rag_search work legs', () => { await executor.execute({ id: 'c1', name: 'rag_search', - input: { query: 'what is open', status: 'open' }, + input: { query: 'zebra payments', status: 'open' }, }); const call = runQuery.mock.calls.find( ([ref]) => fnName(ref) === TASKS_SEARCH_FN, @@ -1694,7 +1703,10 @@ describe('rag_search reports a listing as a listing', () => { const result = (await executor.execute({ id: 'c1', name: 'rag_search', - input: { query: 'are there any open tasks' }, + // A residue noun keeps this a SEARCH; the words then match nothing and + // the reader falls back to its listing. (Pure listing language would + // now be steered to action "list" before any leg runs.) + input: { query: 'billing cadence tasks' }, })) as Record; // The model must not read a list as "these matched your words". expect((result.sources as Record).tasks).toContain( @@ -1727,7 +1739,7 @@ describe('rag_search reports a listing as a listing', () => { const result = (await executor.execute({ id: 'c1', name: 'rag_search', - input: { query: 'are there any open tasks' }, + input: { query: 'billing cadence tasks' }, })) as Record; const tasks = (result.sources as Record).tasks; expect(tasks).toContain('listed'); @@ -1786,3 +1798,518 @@ describe('rag_search reports a listing as a listing', () => { expect(rows[1].data).toMatchObject({ unassigned: true }); }); }); + +describe('rag_search action contract', () => { + beforeEach(() => vi.clearAllMocks()); + + it('treats a query with no action as the search it always meant', async () => { + searchKnowledgeMock.mockResolvedValueOnce({ hits: [], diagnostics: {} }); + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { query: 'zebra payments' }, + })) as Record; + expect(result.status).toBe('ok'); + expect(searchKnowledgeMock).toHaveBeenCalled(); + }); + + it('treats a kind with no action and no query as the list it can only mean', async () => { + const { ctx, runQuery } = createCtx(); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { kind: 'contact' }, + })) as Record; + expect(result.status).toBe('ok'); + expect(result.action).toBe('list'); + const call = runQuery.mock.calls.find( + ([ref]) => fnName(ref) === CONTACTS_FN, + ); + expect(call?.[1]).not.toHaveProperty('searchTerm'); + }); + + it('refuses a verbless empty call with both example calls', async () => { + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: {}, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect(result.message).toContain('"action":"search"'); + expect(result.message).toContain('"action":"list"'); + expect(searchKnowledgeMock).not.toHaveBeenCalled(); + }); + + it('points an empty search that already names a status at the list call', async () => { + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'search', query: ' ', status: 'in_review' }, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect(result.message).toContain( + '{"action":"list","kind":"task","status":"in_review"}', + ); + }); + + it('steers a stuffed listing utterance to the list call it means', async () => { + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'search', query: 'list all in-review tasks' }, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect(result.message).toContain( + '{"action":"list","kind":"task","status":"in_review"}', + ); + expect(searchKnowledgeMock).not.toHaveBeenCalled(); + }); + + it('honors a search for one named item even when a status word appears', async () => { + searchKnowledgeMock.mockResolvedValueOnce({ hits: [], diagnostics: {} }); + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'search', query: 'show me the login review task' }, + })) as Record; + expect(result.status).toBe('ok'); + expect(searchKnowledgeMock).toHaveBeenCalled(); + }); + + it('ignores a cursor on search instead of failing the call', async () => { + searchKnowledgeMock.mockResolvedValueOnce({ hits: [], diagnostics: {} }); + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'search', query: 'zebra', cursor: 'task:task_9' }, + })) as Record; + expect(result.status).toBe('ok'); + }); + + it('refuses the second identical call of a turn and lets paging through', async () => { + const { ctx } = createCtx({ + reads: { + [TASKS_SEARCH_FN]: () => ({ + page: [], + isDone: false, + continueCursor: 'task_9', + listed: true, + }), + }, + }); + const executor = await makeExecutor(ctx); + const first = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'task', status: 'open' }, + })) as Record; + expect(first.status).toBe('ok'); + + const repeat = (await executor.execute({ + id: 'c2', + name: 'rag_search', + input: { action: 'list', kind: 'task', status: 'open' }, + })) as Record; + expect(repeat.status).toBe('invalid_args'); + expect(repeat.message).toContain('already ran this turn'); + + // A different cursor is a different page, never a repetition. + const nextPage = (await executor.execute({ + id: 'c3', + name: 'rag_search', + input: { + action: 'list', + kind: 'task', + status: 'open', + cursor: 'task:task_9', + }, + })) as Record; + expect(nextPage.status).toBe('ok'); + }); + + it('keeps giving the corrective message when a rejected call is repeated', async () => { + const executor = await makeExecutor(createCtx().ctx); + const call = { action: 'list', kind: 'task' }; + const first = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: call, + })) as Record; + const second = (await executor.execute({ + id: 'c2', + name: 'rag_search', + input: call, + })) as Record; + // A failure never registers in the repeat guard — the model must keep + // seeing what to fix, not a dead end. + expect(first.message).toBe(second.message); + expect(second.message).not.toContain('already ran this turn'); + }); +}); + +describe('rag_search list action', () => { + beforeEach(() => vi.clearAllMocks()); + + it('requires a kind, naming the listable ones', async () => { + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list' }, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect(result.message).toContain('"task"'); + expect(result.message).toContain('"contact"'); + expect(result.message).not.toContain('"web-page"'); + }); + + it('refuses to list crawled pages, steering to the site catalog', async () => { + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'web-page' }, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect(result.message).toContain('"kind":"website"'); + }); + + it('refuses a list that smuggles a query, showing the corrected call', async () => { + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'task', status: 'open', query: 'stuff' }, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect(result.message).toContain( + '{"action":"list","kind":"task","status":"open"}', + ); + }); + + it('refuses a whole-workspace task dump and an unknown list status', async () => { + const executor = await makeExecutor(createCtx().ctx); + const noSlice = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'task' }, + })) as Record; + expect(noSlice.status).toBe('invalid_args'); + expect(noSlice.message).toContain('"status"'); + expect(noSlice.message).toContain('"projectId"'); + + // A search drops an unknown status; a listing of one must not silently + // become a listing of everything. + const badStatus = (await executor.execute({ + id: 'c2', + name: 'rag_search', + input: { action: 'list', kind: 'task', status: 'nonsense' }, + })) as Record; + expect(badStatus.status).toBe('invalid_args'); + expect(badStatus.message).toContain('in_review'); + }); + + it('lists tasks by status through the reader, text off and archived out', async () => { + const { ctx, runQuery } = createCtx({ + reads: { + [TASKS_SEARCH_FN]: () => ({ + // A title that does NOT contain the word "review" — a list is a + // board slice, never a text match. + page: [ + { _id: 'task_1', title: 'Verify billing', status: 'in_review' }, + ], + isDone: true, + continueCursor: 'task_1', + listed: true, + }), + }, + }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'task', status: 'in_review' }, + })) as Record; + + expect(result.status).toBe('ok'); + expect(result.action).toBe('list'); + expect(result.kind).toBe('task'); + expect(result.hasMore).toBe(false); + expect(result).not.toHaveProperty('continueCursor'); + const rows = result.results as Array>; + expect(rows[0]?.title).toBe('Verify billing'); + expect(rows[0]?.ref).toBe('task:task_1'); + expect((result.sources as Record).tasks).toBe('listed'); + + const call = runQuery.mock.calls.find( + ([ref]) => fnName(ref) === TASKS_SEARCH_FN, + )?.[1] as Record; + expect(call).toMatchObject({ + term: '', + list: true, + excludeArchived: true, + status: 'in_review', + }); + expect((call.paginationOpts as Record).numItems).toBe( + RAG_SEARCH_MAX_LIMIT, + ); + }); + + it('reports an unfinished walk as hasMore with a redeemable tagged cursor', async () => { + const { ctx, runQuery } = createCtx({ + reads: { + [TASKS_SEARCH_FN]: () => ({ + page: [{ _id: 'task_1', title: 'Verify billing', status: 'todo' }], + isDone: false, + continueCursor: 'task_9', + listed: true, + }), + }, + }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'task', status: 'open' }, + })) as Record; + expect(result.hasMore).toBe(true); + expect(result.continueCursor).toBe('task:task_9'); + expect(result).not.toHaveProperty('totalCount'); + expect(result.message).toContain('one page'); + + // The tagged cursor redeems: the tag comes off before the reader sees it. + await executor.execute({ + id: 'c2', + name: 'rag_search', + input: { + action: 'list', + kind: 'task', + status: 'open', + cursor: 'task:task_9', + }, + }); + const second = runQuery.mock.calls.findLast( + ([ref]) => fnName(ref) === TASKS_SEARCH_FN, + )?.[1] as Record; + expect((second.paginationOpts as Record).cursor).toBe( + 'task_9', + ); + }); + + it('refuses a cursor from another kind before touching the index', async () => { + const { ctx, runQuery } = createCtx(); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { + action: 'list', + kind: 'task', + status: 'open', + cursor: 'contact:xyz', + }, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect( + runQuery.mock.calls.some(([ref]) => fnName(ref) === TASKS_SEARCH_FN), + ).toBe(false); + }); + + it('refuses a projectId outside the readable set, uniformly', async () => { + const executor = await makeExecutor(createCtx().ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'task', projectId: 'project_foreign' }, + })) as Record; + expect(result.status).toBe('invalid_args'); + expect(result.message).toContain('No readable project'); + }); + + it('lists contacts with the term off and marks a non-active row', async () => { + const { ctx, runQuery } = createCtx({ + reads: { + [CONTACTS_FN]: () => ({ + page: [ + { name: 'Ada Acme', email: 'ada@acme.com' }, + { name: 'Gone Corp', lifecycleStatus: 'expired' }, + ], + isDone: true, + continueCursor: 'contact_2', + }), + }, + }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'contact' }, + })) as Record; + + const rows = result.results as Array>; + expect(rows).toHaveLength(2); + expect(rows[0]?.data).not.toHaveProperty('lifecycleStatus'); + // A trashed row must not read as the current address book. + expect(rows[1]?.data).toMatchObject({ lifecycleStatus: 'expired' }); + + const call = runQuery.mock.calls.find( + ([ref]) => fnName(ref) === CONTACTS_FN, + )?.[1] as Record; + expect(call).not.toHaveProperty('searchTerm'); + expect((call.paginationOpts as Record).numItems).toBe( + RAG_SEARCH_MAX_LIMIT, + ); + }); + + it('lists websites without paging, saying the list does not page', async () => { + const summaries = Array.from({ length: 25 }, (_, i) => ({ + domain: `site-${i}.example`, + title: `Site ${i}`, + pageCount: i, + })); + const { ctx } = createCtx({ reads: { [WEBSITES_FN]: () => summaries } }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'website' }, + })) as Record; + + const rows = result.results as Array>; + expect(rows).toHaveLength(RAG_SEARCH_MAX_LIMIT); + expect(rows[1]?.data).toMatchObject({ pageCount: 1 }); + expect(result.hasMore).toBe(true); + expect(result).not.toHaveProperty('continueCursor'); + }); + + it('overfetches conversations so a full page never claims completeness', async () => { + const inbox = Array.from({ length: 21 }, (_, i) => ({ + _id: `conv_${i}`, + subject: `Ticket ${i}`, + })); + const { ctx, runQuery } = createCtx({ + reads: { + [CONVERSATIONS_SEARCH_FN]: () => ({ + conversations: inbox, + truncated: false, + }), + }, + }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'conversation' }, + })) as Record; + + expect((result.results as unknown[]).length).toBe(RAG_SEARCH_MAX_LIMIT); + expect(result.hasMore).toBe(true); + expect(result).not.toHaveProperty('continueCursor'); + expect(result.message).toContain('does not page'); + expect((result.sources as Record).conversations).toContain( + 'recent only', + ); + + const call = runQuery.mock.calls.find( + ([ref]) => fnName(ref) === CONVERSATIONS_SEARCH_FN, + )?.[1] as Record; + expect(call).toMatchObject({ term: '', list: true, limit: 21 }); + }); + + it('lists hub documents through listForAgent, relaying its warning', async () => { + const { ctx, runQuery } = createCtx({ + reads: { + [DOCUMENTS_LIST_FN]: () => ({ + documents: [ + { + fileId: 'file_9', + title: 'Q3 report.pdf', + extension: 'pdf', + folderPath: '/reports', + teamId: null, + createdAt: 1_700_000_000_000, + sizeBytes: 1024, + }, + ], + totalCount: null, + hasMore: true, + cursor: 20, + warning: 'Scan limit reached: results may be incomplete.', + }), + }, + }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'document' }, + })) as Record; + + const rows = result.results as Array>; + expect(rows[0]?.ref).toBe('file_9'); + expect(rows[0]?.data).toMatchObject({ folderPath: '/reports' }); + expect(result.hasMore).toBe(true); + expect(result.continueCursor).toBe('document:20'); + expect(result).not.toHaveProperty('totalCount'); + expect(result.message).toContain('Scan limit reached'); + expect((result.sources as Record).documents).toContain( + 'hub and team files', + ); + + const call = runQuery.mock.calls.find( + ([ref]) => fnName(ref) === DOCUMENTS_LIST_FN, + )?.[1] as Record; + expect(call).toMatchObject({ organizationId: 'org_1', userId: 'user_1' }); + }); + + it('answers a denied subject with unavailable, not an empty page', async () => { + const { ctx, runQuery } = createCtx({ + access: (subject) => ({ + allowed: subject !== 'contacts', + role: 'member', + }), + }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'list', kind: 'contact' }, + })) as Record; + expect(result.status).toBe('unavailable'); + expect( + runQuery.mock.calls.some(([ref]) => fnName(ref) === CONTACTS_FN), + ).toBe(false); + }); + + it('narrows a search to one kind when the model names it', async () => { + const { ctx, runQuery } = createCtx({ + reads: { + [CONTACTS_FN]: () => ({ + page: [{ name: 'Ada Acme' }], + isDone: true, + }), + }, + }); + const executor = await makeExecutor(ctx); + const result = (await executor.execute({ + id: 'c1', + name: 'rag_search', + input: { action: 'search', query: 'ada', kind: 'contact' }, + })) as Record; + + expect(result.status).toBe('ok'); + expect(result.sources).toEqual({ contacts: 'searched' }); + // The other legs never ran — no corpus call, no task read. + expect(searchKnowledgeMock).not.toHaveBeenCalled(); + expect( + runQuery.mock.calls.some(([ref]) => fnName(ref) === TASKS_SEARCH_FN), + ).toBe(false); + }); +}); diff --git a/services/platform/convex/chat/assistant_tools.ts b/services/platform/convex/chat/assistant_tools.ts index 45e2acf5a4..e07c54ba5c 100644 --- a/services/platform/convex/chat/assistant_tools.ts +++ b/services/platform/convex/chat/assistant_tools.ts @@ -27,12 +27,15 @@ import { RAG_SEARCH_DEFAULT_LIMIT, RAG_SEARCH_ENTITY_LIMIT, + RAG_SEARCH_KINDS, RAG_SEARCH_MAX_LIMIT, RAG_SEARCH_MIN_SIMILARITY, + RAG_SEARCH_STATUS_VALUES, CHAT_TOOL_NAMES, CHAT_WIRE_TOOLS, CHAT_ASSISTANT_SLUG, type ChatToolExecutor, + type RagSearchKind, type ToolCallRequest, } from '../../lib/chat'; import { htmlTitle, htmlToText } from '../../lib/knowledge/html-to-text'; @@ -53,6 +56,7 @@ import { searchKnowledge } from '../knowledge/search'; import { orgSlugFromId } from '../lib/helpers/org_slug'; import { SafeFetchError, isPrivateIp, safeFetch } from '../lib/http/safe_fetch'; import type { AgentReadSubject } from '../lib/rls/helpers/agent_read_access'; +import { detectListingIntent } from '../lib/search'; import { toId } from '../lib/type_cast_helpers'; import { wrapUntrusted } from '../lib/untrusted_content'; @@ -135,31 +139,260 @@ function archiveFlags(args: { }; } -/** Task statuses `rag_search` accepts, plus the `open` shorthand. Mirrors the - * enum in `RAG_SEARCH_SCHEMA`; a value outside it is dropped rather than - * refused, so a model guessing never fails the whole search. */ -const WORK_STATUS_VALUES = [ - 'open', - 'backlog', - 'todo', - 'in_progress', - 'in_review', - 'done', - 'cancelled', -] as const; - -/** Derived from the list, so the two cannot drift apart. */ -type WorkStatusFilter = (typeof WORK_STATUS_VALUES)[number]; +// ------------------------------------------------------------- result rows + +/** One `rag_search` result row — the SAME shape for a search hit and a + * listed row, so the model never learns two vocabularies. */ +interface SearchResultEntry { + readonly kind: RagSearchKind; + readonly title: string; + /** What `rag_fetch` accepts: a document file id, a page URL, or a work + * ref. Entity rows carry their content inline instead. */ + readonly ref?: string; + readonly url?: string; + readonly snippet?: string; + /** Char position of the match within the ref's full text — a rag_fetch + * starting offset that lands on the match instead of the start. */ + readonly offset?: number; + /** Retrieval ranking (reranker score when one ran, else the fusion + * score). Orders hits within ONE response only — the fusion score is a + * reciprocal-rank value, not a similarity, so its absolute magnitude + * means nothing across searches. Absent on listed rows: a listing is + * ordered by recency, not relevance. */ + readonly score?: number; + readonly data?: Record; +} + +// The search legs and the list action build their rows through ONE mapper +// per kind, so the two surfaces can never disagree about what a row says. + +function taskResultEntry( + task: Doc<'tasks'>, + archivedProjectIds: ReadonlySet, +): SearchResultEntry { + return { + kind: 'task', + title: task.title, + // A fetchable ref, unlike contacts/products — the depth path for work + // is `rag_fetch`, not a tool of its own. + ref: `${WORK_REF_PREFIX.task}${String(task._id)}`, + ...(task.description + ? { snippet: clip(task.description, SNIPPET_CHARS) } + : {}), + data: { + status: task.status, + ...(task.priority ? { priority: task.priority } : {}), + ...(task.assigneeType ? { assigneeType: task.assigneeType } : {}), + ...(task.projectId ? { projectId: String(task.projectId) } : {}), + ...(task.dueDate ? { dueDate: task.dueDate } : {}), + ...archiveFlags({ + archivedAt: task.archivedAt, + projectId: task.projectId != null ? String(task.projectId) : null, + archivedProjectIds, + }), + }, + }; +} + +function projectResultEntry( + project: Doc<'projects'>, + archivedProjectIds: ReadonlySet, +): SearchResultEntry { + return { + kind: 'project', + title: project.name, + ref: `${WORK_REF_PREFIX.project}${String(project._id)}`, + ...(project.description + ? { snippet: clip(project.description, SNIPPET_CHARS) } + : {}), + data: { + ...(project.key ? { key: project.key } : {}), + // The denormalized rollups (`projects/schema.ts`) — a project has + // no status of its own, and "how much is still open" is what a + // question about a project usually means. Undefined reads as 0. + openTasks: project.openTaskCount ?? 0, + doneTasks: project.doneTaskCount ?? 0, + // `projectArchived` would be redundant here: this row is the + // project, so its own `archived` says it. + ...archiveFlags({ + archivedAt: project.archivedAt, + archivedProjectIds, + }), + }, + }; +} + +function contactResultEntry(contact: { + name?: string; + email?: string; + phone?: string; + tags?: string[]; + lifecycleStatus?: string; +}): SearchResultEntry { + return { + kind: 'contact', + title: contact.name ?? 'Unnamed contact', + data: { + ...(contact.email ? { email: contact.email } : {}), + ...(contact.phone ? { phone: contact.phone } : {}), + ...(contact.tags && contact.tags.length > 0 + ? { tags: contact.tags } + : {}), + // A non-active row must say so, or a trashed contact reads as the + // current address book. + ...(contact.lifecycleStatus && contact.lifecycleStatus !== 'active' + ? { lifecycleStatus: contact.lifecycleStatus } + : {}), + }, + }; +} + +function productResultEntry(product: { + name?: string; + category?: string; + price?: number; + stock?: number; + status?: string; +}): SearchResultEntry { + return { + kind: 'product', + title: product.name ?? 'Unnamed product', + data: { + ...(product.category ? { category: product.category } : {}), + ...(product.price !== undefined ? { price: product.price } : {}), + ...(product.stock !== undefined ? { stock: product.stock } : {}), + // Draft and archived SKUs are real rows but not current inventory. + ...(product.status && product.status !== 'active' + ? { status: product.status } + : {}), + }, + }; +} + +function knowledgeEntryResultEntry(entry: { + topic: string; + content: string; +}): SearchResultEntry { + return { + kind: 'knowledge-entry', + title: entry.topic, + snippet: clip(entry.content, SNIPPET_CHARS * 2), + }; +} + +function websiteResultEntry(site: { + domain: string; + title?: string; + description?: string; +}): SearchResultEntry { + return { + kind: 'website', + title: site.title ?? site.domain, + url: `https://${site.domain}`, + ...(site.description + ? { snippet: clip(site.description, SNIPPET_CHARS) } + : {}), + }; +} + +function conversationResultEntry(conversation: { + subject?: string; + status?: string; + channel?: string; + lastMessageAt?: number; + assigneeUserId?: string; + assigneeTeamId?: string; +}): SearchResultEntry { + return { + kind: 'conversation', + title: conversation.subject ?? 'Conversation', + data: { + ...(conversation.status ? { status: conversation.status } : {}), + ...(conversation.channel ? { channel: conversation.channel } : {}), + ...(conversation.assigneeUserId + ? { assigneeUserId: conversation.assigneeUserId } + : {}), + ...(conversation.assigneeTeamId + ? { assigneeTeamId: conversation.assigneeTeamId } + : {}), + ...(conversation.assigneeUserId || conversation.assigneeTeamId + ? {} + : // Unassigned is a real state an admin acts on, not missing data. + { unassigned: true }), + ...(conversation.lastMessageAt + ? { lastMessageAt: conversation.lastMessageAt } + : {}), + }, + }; +} + +/** Task statuses `rag_search` accepts, plus the `open` shorthand — the SAME + * array the schema enum is built from (`lib/chat/tools.ts`), so the two + * cannot drift. On a search an unknown value is dropped rather than refused, + * so a model guessing never fails the whole fan-out; an explicit LISTING of + * one status is different — there a typo silently listing everything would + * be wrong, so the list path refuses it instead. */ +type WorkStatusFilter = (typeof RAG_SEARCH_STATUS_VALUES)[number]; /** A type PREDICATE rather than a cast: narrowing an unknown tool argument by * assertion is exactly what `no-unsafe-type-assertion` exists to stop. */ function isWorkStatus(value: unknown): value is WorkStatusFilter { return ( typeof value === 'string' && - (WORK_STATUS_VALUES as readonly string[]).includes(value) + (RAG_SEARCH_STATUS_VALUES as readonly string[]).includes(value) + ); +} + +/** Same shape for the result-kind argument. */ +function isRagSearchKind(value: unknown): value is RagSearchKind { + return ( + typeof value === 'string' && + (RAG_SEARCH_KINDS as readonly string[]).includes(value) ); } +/** Copyable next-call examples for `invalid_args` messages. A correction the + * model can paste beats prose describing one — the message IS the retry. */ +const EXAMPLE_SEARCH_CALL = '{"action":"search","query":"refund policy"}'; +const EXAMPLE_LIST_CALL = '{"action":"list","kind":"task","status":"open"}'; + +/** The kinds `action: 'list'` accepts — every result kind except `web-page`, + * which has no bounded org-wide catalog (pages live under their domain; the + * site inventory is `kind: 'website'`). */ +const LISTABLE_KINDS = RAG_SEARCH_KINDS.filter((kind) => kind !== 'web-page'); + +/** The `sources` key a one-kind list reports under — the same vocabulary the + * search legs use, so a list result reads like a one-leg search result. */ +const LIST_SOURCE_KEYS: Record = { + document: 'documents', + 'web-page': 'webPages', + 'knowledge-entry': 'knowledgeEntries', + contact: 'contacts', + product: 'products', + website: 'websites', + task: 'tasks', + project: 'projects', + conversation: 'conversations', +}; + +/** The role-matrix subject each kind's listing answers to — identical to the + * subject its search leg checks, because a list is not an ACL widening. */ +const LIST_READ_SUBJECTS: Record = { + document: 'documents', + 'web-page': 'websites', + 'knowledge-entry': 'documents', + contact: 'contacts', + product: 'products', + website: 'websites', + task: 'tasks', + project: 'projects', + conversation: 'conversations', +}; + +const LIST_PAGE_MESSAGE = + 'This is one page, not the whole set. Pass "continueCursor" back as ' + + '"cursor" for the next page, or say you only saw this page.'; + /** * What the model is told when the corpora cannot be searched. * @@ -338,53 +571,153 @@ export function createChatToolExecutor( // ------------------------------------------------------------- rag_search - interface SearchResultEntry { - readonly kind: - | 'document' - | 'web-page' - | 'knowledge-entry' - | 'product' - | 'contact' - | 'website' - | 'task' - | 'project' - | 'conversation'; - readonly title: string; - /** What `rag_fetch` accepts: a document file id or a page URL. Entity - * rows carry their content inline instead. */ - readonly ref?: string; - readonly url?: string; - readonly snippet?: string; - /** Char position of the match within the ref's full text — a rag_fetch - * starting offset that lands on the match instead of the start. */ - readonly offset?: number; - /** Retrieval ranking (reranker score when one ran, else the fusion - * score). Orders hits within ONE response only — the fusion score is a - * reciprocal-rank value, not a similarity, so its absolute magnitude - * means nothing across searches. */ - readonly score?: number; - readonly data?: Record; + /** One rag_search call per shape per turn. The tools are read-only, so an + * exact repeat can only re-buy the same rows; the second call gets a steer + * instead. Keyed on the RESOLVED call — cursor included, so paging is + * never mistaken for repetition — and only OK results register, so a + * rejected call keeps earning its corrective message. */ + const seenRagSearchCalls = new Set(); + + interface RagSearchOk extends Record { + status: 'ok'; } + type RagSearchOutcome = RagSearchOk | ToolFailure; const ragSearch = async (args: Record): Promise => { const query = typeof args.query === 'string' ? args.query.trim() : ''; - if (query === '') { + const kindRaw = args.kind; + const statusRaw = args.status; + const projectId = + typeof args.projectId === 'string' && args.projectId.trim() !== '' + ? args.projectId.trim() + : undefined; + const cursorRaw = + typeof args.cursor === 'string' && args.cursor.trim() !== '' + ? args.cursor.trim() + : undefined; + + // The verb. The schema requires it, but an omission must not tax the + // model with a correction round when the meaning is unambiguous: a query + // has always meant a search, and a kind with no query can only mean a + // list. What is NEVER inferred is a list from an empty query — that + // omission-becomes-another-operation trap is why the verb exists. + let action: 'search' | 'list'; + if (args.action === 'search' || args.action === 'list') { + action = args.action; + } else if (args.action === undefined && query !== '') { + action = 'search'; + } else if (args.action === undefined && isRagSearchKind(kindRaw)) { + action = 'list'; + } else { const result = invalidArgs( - 'rag_search needs a non-empty "query" string.', + 'rag_search needs "action": "search" (with a "query") or "list" ' + + `(with a "kind"). Examples: ${EXAMPLE_SEARCH_CALL} · ` + + `${EXAMPLE_LIST_CALL}. Retry once.`, ); await recordDispatch('rag_search', result.status, result.message); return result; } + + const callKey = JSON.stringify({ + action, + kind: isRagSearchKind(kindRaw) ? kindRaw : null, + status: typeof statusRaw === 'string' ? statusRaw : null, + projectId: projectId ?? null, + cursor: cursorRaw ?? null, + query: query + .toLowerCase() + .split(/[^\p{L}\p{N}]+/u) + .filter(Boolean) + .sort(), + }); + if (seenRagSearchCalls.has(callKey)) { + const result = invalidArgs( + 'This exact rag_search call already ran this turn — use that ' + + 'result instead of repeating it.', + ); + await recordDispatch('rag_search', result.status, result.message); + return result; + } + + const result = + action === 'list' + ? await ragSearchList({ + kindRaw, + query, + statusRaw, + projectId, + cursorRaw, + limitRaw: args.limit, + }) + : await ragSearchSearch({ + query, + kindRaw, + statusRaw, + limitRaw: args.limit, + }); + if (result.status === 'ok') { + seenRagSearchCalls.add(callKey); + await recordDispatch('rag_search', 'ok'); + } else { + await recordDispatch('rag_search', result.status, result.message); + } + return result; + }; + + // ---------------------------------------------------- rag_search · search + + const ragSearchSearch = async (call: { + query: string; + kindRaw: unknown; + statusRaw: unknown; + limitRaw: unknown; + }): Promise => { + const { query } = call; + if (query === '') { + const hint = isWorkStatus(call.statusRaw) + ? 'To browse the board, call ' + + `{"action":"list","kind":"task","status":"${call.statusRaw}"}.` + : 'Pass "query" with distinctive keywords — or browse a kind with ' + + `${EXAMPLE_LIST_CALL}.`; + return invalidArgs( + `action "search" needs a non-empty "query". ${hint} Retry once.`, + ); + } + // A query that is PURE listing language matches nothing by construction + // — steer it to the verb it meant instead of running legs that can only + // fail. Any surviving noun honors the search (see `listing_intent.ts`). + const stuffed = detectListingIntent(query); + if (stuffed !== undefined) { + const corrected = JSON.stringify({ + action: 'list', + kind: stuffed.kind, + ...(stuffed.status !== undefined ? { status: stuffed.status } : {}), + }); + return invalidArgs( + 'query_looks_like_list: that query only names a kind and a state. ' + + `Browse it instead: ${corrected}. Retry once.`, + ); + } + const limit = - typeof args.limit === 'number' && args.limit > 0 - ? Math.min(Math.floor(args.limit), RAG_SEARCH_MAX_LIMIT) + typeof call.limitRaw === 'number' && call.limitRaw > 0 + ? Math.min(Math.floor(call.limitRaw), RAG_SEARCH_MAX_LIMIT) : RAG_SEARCH_DEFAULT_LIMIT; // Only the tasks leg reads this; an unknown value is dropped rather than // refused, so a model guessing a status never fails the whole search. - const statusFilter = isWorkStatus(args.status) ? args.status : undefined; + const statusFilter = isWorkStatus(call.statusRaw) + ? call.statusRaw + : undefined; + // An optional narrow: a known kind runs that leg alone (documents and + // pages are one corpus leg, split by `corpus`). An unknown kind is + // dropped like an unknown status — the full fan-out still answers. + const kindFilter = isRagSearchKind(call.kindRaw) ? call.kindRaw : undefined; + const runLeg = (...kinds: RagSearchKind[]): boolean => + kindFilter === undefined || kinds.includes(kindFilter); const slug = await orgSlug(); - /** Per-source outcome, so an empty answer is attributable. */ + /** Per-source outcome, so an empty answer is attributable. Narrowed + * searches report only the legs they ran. */ const sources: Record = {}; const results: SearchResultEntry[] = []; @@ -411,67 +744,90 @@ export function createChatToolExecutor( // to, projects they can read, and the org hub — never the whole org. // The similarity floor drops weak dense neighbours BEFORE they reach the // model; keyword (BM25) hits are never floored. - if (documentsAllowed) { - try { - const docAccess = await knowledgeAccess(); - const archivedForDocs = new Set(docAccess.archivedProjectIds ?? []); - const knowledge = await searchKnowledge(ctx, { - organizationId: who.organizationId, - orgSlug: slug, - query, - corpus: 'all', - limit, - minSimilarity: RAG_SEARCH_MIN_SIMILARITY, - access: docAccess, - }); - for (const hit of knowledge.hits) { - const score = hit.rerankScore ?? hit.fusedScore; - // A document has no archive state of its own — only its project - // does, so `projectArchived` is the only flag it can carry. It is - // still returned and still citable; the label is the context. - const flags = archiveFlags({ - projectId: hit.source.projectId, - archivedProjectIds: archivedForDocs, - }); - results.push({ - kind: hit.corpus === 'documents' ? 'document' : 'web-page', - title: hit.source.title ?? hit.source.ref, - ref: hit.source.ref, - ...(hit.source.url ? { url: hit.source.url } : {}), - snippet: clip(hit.text, SNIPPET_CHARS), - ...(hit.offset !== undefined ? { offset: hit.offset } : {}), - score: Math.round(score * 1000) / 1000, - ...(flags.projectArchived ? { data: flags } : {}), + if (runLeg('document', 'web-page')) { + // One corpus leg serves both kinds; a narrow selects within it. + const corpus = + kindFilter === 'document' + ? ('documents' as const) + : kindFilter === 'web-page' + ? ('web' as const) + : ('all' as const); + if (documentsAllowed) { + try { + const docAccess = await knowledgeAccess(); + const archivedForDocs = new Set(docAccess.archivedProjectIds ?? []); + const knowledge = await searchKnowledge(ctx, { + organizationId: who.organizationId, + orgSlug: slug, + query, + corpus, + limit, + minSimilarity: RAG_SEARCH_MIN_SIMILARITY, + access: docAccess, }); + for (const hit of knowledge.hits) { + const score = hit.rerankScore ?? hit.fusedScore; + // A document has no archive state of its own — only its project + // does, so `projectArchived` is the only flag it can carry. It is + // still returned and still citable; the label is the context. + const flags = archiveFlags({ + projectId: hit.source.projectId, + archivedProjectIds: archivedForDocs, + }); + results.push({ + kind: hit.corpus === 'documents' ? 'document' : 'web-page', + title: hit.source.title ?? hit.source.ref, + ref: hit.source.ref, + ...(hit.source.url ? { url: hit.source.url } : {}), + snippet: clip(hit.text, SNIPPET_CHARS), + ...(hit.offset !== undefined ? { offset: hit.offset } : {}), + score: Math.round(score * 1000) / 1000, + ...(flags.projectArchived ? { data: flags } : {}), + }); + } + if (runLeg('document')) { + sources.documents = knowledge.hits.some( + (h) => h.corpus === 'documents', + ) + ? 'searched' + : 'searched (no matches — the document index may also still be empty)'; + } + if (runLeg('web-page')) { + sources.webPages = knowledge.hits.some((h) => h.corpus === 'web') + ? 'searched' + : 'searched (no matches — no crawled pages may be indexed yet)'; + } + } catch (error) { + // Two audiences, two messages — conflating them is what made this + // outage invisible for hours. + // + // The OPERATOR needs the real error and needs it in the logs. Before + // this, "said out loud" meant only to the model, so nothing reached + // anyone who could fix it: no log line, no badge, no alert, while the + // tool still returned `status: 'ok'` because the other legs are plain + // Convex reads that succeed. + console.warn( + `[chat] knowledge search unavailable for organization ${who.organizationId}: ${describeError(error)}`, + ); + // The MODEL gets a stable sentence that names the remedy and leaks no + // internals. Relaying `Error.message` verbatim is how configuration + // prose ended up quoted to an end user, who read it as a product + // fault. + if (runLeg('document')) { + sources.documents = KNOWLEDGE_UNAVAILABLE_FOR_MODEL; + } + if (runLeg('web-page')) { + sources.webPages = KNOWLEDGE_UNAVAILABLE_FOR_MODEL; + } + } + } else { + if (runLeg('document')) { + sources.documents = 'access denied for your role'; + } + if (runLeg('web-page')) { + sources.webPages = 'access denied for your role'; } - sources.documents = knowledge.hits.some((h) => h.corpus === 'documents') - ? 'searched' - : 'searched (no matches — the document index may also still be empty)'; - sources.webPages = knowledge.hits.some((h) => h.corpus === 'web') - ? 'searched' - : 'searched (no matches — no crawled pages may be indexed yet)'; - } catch (error) { - // Two audiences, two messages — conflating them is what made this - // outage invisible for hours. - // - // The OPERATOR needs the real error and needs it in the logs. Before - // this, "said out loud" meant only to the model, so nothing reached - // anyone who could fix it: no log line, no badge, no alert, while the - // tool still returned `status: 'ok'` because the other legs are plain - // Convex reads that succeed. - console.warn( - `[chat] knowledge search unavailable for organization ${who.organizationId}: ${describeError(error)}`, - ); - // The MODEL gets a stable sentence that names the remedy and leaks no - // internals. Relaying `Error.message` verbatim is how configuration - // prose ended up quoted to an end user, who read it as a product - // fault. - sources.documents = KNOWLEDGE_UNAVAILABLE_FOR_MODEL; - sources.webPages = sources.documents; } - } else { - sources.documents = 'access denied for your role'; - sources.webPages = sources.documents; } // Legs 2–5 are capped EACH — never by a global slice over the @@ -479,120 +835,99 @@ export function createChatToolExecutor( // contact or product match out of the results entirely. // Leg 2 — knowledge entries (Convex rows; lexical topic match). - if (documentsAllowed) { - const entries = await ctx.runQuery( - internal.knowledge_entries.internal_queries.listEntriesForAgent, - { - organizationId: who.organizationId, - topic: query, - paginationOpts: { - numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), - cursor: null, + if (runLeg('knowledge-entry')) { + if (documentsAllowed) { + const entries = await ctx.runQuery( + internal.knowledge_entries.internal_queries.listEntriesForAgent, + { + organizationId: who.organizationId, + topic: query, + paginationOpts: { + numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), + cursor: null, + }, }, - }, - ); - for (const entry of entries.page) { - results.push({ - kind: 'knowledge-entry', - title: entry.topic, - snippet: clip(entry.content, SNIPPET_CHARS * 2), - }); + ); + for (const entry of entries.page) { + results.push(knowledgeEntryResultEntry(entry)); + } + sources.knowledgeEntries = + entries.page.length > 0 ? 'searched' : 'searched (no matches)'; + } else { + sources.knowledgeEntries = 'access denied for your role'; } - sources.knowledgeEntries = - entries.page.length > 0 ? 'searched' : 'searched (no matches)'; - } else { - sources.knowledgeEntries = 'access denied for your role'; } // Leg 3 — contacts (lexical). - if (contactsAllowed) { - const contacts = await ctx.runQuery( - internal.contacts.internal_queries.queryContacts, - { - organizationId: who.organizationId, - searchTerm: query, - paginationOpts: { - numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), - cursor: null, - }, - }, - ); - for (const contact of contacts.page) { - results.push({ - kind: 'contact', - title: contact.name ?? 'Unnamed contact', - data: { - ...(contact.email ? { email: contact.email } : {}), - ...(contact.phone ? { phone: contact.phone } : {}), - ...(contact.tags && contact.tags.length > 0 - ? { tags: contact.tags } - : {}), + if (runLeg('contact')) { + if (contactsAllowed) { + const contacts = await ctx.runQuery( + internal.contacts.internal_queries.queryContacts, + { + organizationId: who.organizationId, + searchTerm: query, + paginationOpts: { + numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), + cursor: null, + }, }, - }); + ); + for (const contact of contacts.page) { + results.push(contactResultEntry(contact)); + } + sources.contacts = + contacts.page.length > 0 ? 'searched' : 'searched (no matches)'; + } else { + sources.contacts = 'access denied for your role'; } - sources.contacts = - contacts.page.length > 0 ? 'searched' : 'searched (no matches)'; - } else { - sources.contacts = 'access denied for your role'; } // Leg 4 — products (lexical). - if (productsAllowed) { - const products = await ctx.runQuery( - internal.products.internal_queries.queryProducts, - { - organizationId: who.organizationId, - searchTerm: query, - paginationOpts: { - numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), - cursor: null, - }, - }, - ); - for (const product of products.page) { - results.push({ - kind: 'product', - title: product.name ?? 'Unnamed product', - data: { - ...(product.category ? { category: product.category } : {}), - ...(product.price !== undefined ? { price: product.price } : {}), - ...(product.stock !== undefined ? { stock: product.stock } : {}), + if (runLeg('product')) { + if (productsAllowed) { + const products = await ctx.runQuery( + internal.products.internal_queries.queryProducts, + { + organizationId: who.organizationId, + searchTerm: query, + paginationOpts: { + numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), + cursor: null, + }, }, - }); + ); + for (const product of products.page) { + results.push(productResultEntry(product)); + } + sources.products = + products.page.length > 0 ? 'searched' : 'searched (no matches)'; + } else { + sources.products = 'access denied for your role'; } - sources.products = - products.page.length > 0 ? 'searched' : 'searched (no matches)'; - } else { - sources.products = 'access denied for your role'; } // Leg 5 — registered websites (domain metadata; pages are leg 1). - if (websitesAllowed) { - const websites = await ctx.runQuery( - internal.websites.internal_queries.listWebsiteSummaries, - { organizationId: who.organizationId }, - ); - const needle = query.toLowerCase(); - const matches = websites.filter( - (site) => - site.domain.toLowerCase().includes(needle) || - (site.title ?? '').toLowerCase().includes(needle) || - (site.description ?? '').toLowerCase().includes(needle), - ); - for (const site of matches.slice(0, RAG_SEARCH_ENTITY_LIMIT)) { - results.push({ - kind: 'website', - title: site.title ?? site.domain, - url: `https://${site.domain}`, - ...(site.description - ? { snippet: clip(site.description, SNIPPET_CHARS) } - : {}), - }); + if (runLeg('website')) { + if (websitesAllowed) { + const websites = await ctx.runQuery( + internal.websites.internal_queries.listWebsiteSummaries, + { organizationId: who.organizationId }, + ); + const needle = query.toLowerCase(); + const matches = websites.filter( + (site) => + site.domain.toLowerCase().includes(needle) || + (site.title ?? '').toLowerCase().includes(needle) || + (site.description ?? '').toLowerCase().includes(needle), + ); + for (const site of matches.slice(0, RAG_SEARCH_ENTITY_LIMIT)) { + results.push(websiteResultEntry(site)); + } + sources.websites = + matches.length > 0 ? 'searched' : 'searched (no matches)'; + } else { + sources.websites = 'access denied for your role'; } - sources.websites = - matches.length > 0 ? 'searched' : 'searched (no matches)'; - } else { - sources.websites = 'access denied for your role'; } // Legs 6–7 — the organization's work. Scoped by the readable project set @@ -601,111 +936,76 @@ export function createChatToolExecutor( // RLS-bypassing query — the shape legs 3–4 safely use — would hand every // project's work to any member, because those tables are org-scope-only and // work is not. - if (tasksAllowed || projectsAllowed) { - const access = await knowledgeAccess(); - const projectIds = [...access.projectIds]; - const archivedProjectIds = new Set(access.archivedProjectIds ?? []); + if (runLeg('task', 'project')) { + if (tasksAllowed || projectsAllowed) { + const access = await knowledgeAccess(); + const projectIds = [...access.projectIds]; + const archivedProjectIds = new Set(access.archivedProjectIds ?? []); - // Leg 6 — tasks (question-aware; open/status filter). - if (tasksAllowed) { - const tasks = await ctx.runQuery( - internal.tasks.search_for_chat.searchTasksForChat, - { - organizationId: who.organizationId, - projectIds, - term: query, - ...(statusFilter !== undefined ? { status: statusFilter } : {}), - paginationOpts: { - numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), - cursor: null, - }, - }, - ); - for (const task of tasks.page) { - results.push({ - kind: 'task', - title: task.title, - // A fetchable ref, unlike contacts/products — the depth path for - // work is `rag_fetch`, not a tool of its own. - ref: `${WORK_REF_PREFIX.task}${String(task._id)}`, - ...(task.description - ? { snippet: clip(task.description, SNIPPET_CHARS) } - : {}), - data: { - status: task.status, - ...(task.priority ? { priority: task.priority } : {}), - ...(task.assigneeType ? { assigneeType: task.assigneeType } : {}), - ...(task.projectId ? { projectId: String(task.projectId) } : {}), - ...(task.dueDate ? { dueDate: task.dueDate } : {}), - ...archiveFlags({ - archivedAt: task.archivedAt, - projectId: - task.projectId != null ? String(task.projectId) : null, - archivedProjectIds, - }), - }, - }); + // Leg 6 — tasks (question-aware; open/status filter). + if (runLeg('task')) { + if (tasksAllowed) { + const tasks = await ctx.runQuery( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: who.organizationId, + projectIds, + term: query, + ...(statusFilter !== undefined ? { status: statusFilter } : {}), + paginationOpts: { + numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), + cursor: null, + }, + }, + ); + for (const task of tasks.page) { + results.push(taskResultEntry(task, archivedProjectIds)); + } + sources.tasks = + tasks.page.length === 0 + ? 'searched (no matches)' + : tasks.listed + ? listedSource('tasks', tasks.isDone) + : 'searched'; + } else { + sources.tasks = 'access denied for your role'; + } } - sources.tasks = - tasks.page.length === 0 - ? 'searched (no matches)' - : tasks.listed - ? listedSource('tasks', tasks.isDone) - : 'searched'; - } else { - sources.tasks = 'access denied for your role'; - } - // Leg 7 — projects. - if (projectsAllowed) { - const projects = await ctx.runQuery( - internal.tasks.search_for_chat.searchProjectsForChat, - { - organizationId: who.organizationId, - projectIds, - term: query, - paginationOpts: { - numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), - cursor: null, - }, - }, - ); - for (const project of projects.page) { - results.push({ - kind: 'project', - title: project.name, - ref: `${WORK_REF_PREFIX.project}${String(project._id)}`, - ...(project.description - ? { snippet: clip(project.description, SNIPPET_CHARS) } - : {}), - data: { - ...(project.key ? { key: project.key } : {}), - // The denormalized rollups (`projects/schema.ts`) — a project has - // no status of its own, and "how much is still open" is what a - // question about a project usually means. Undefined reads as 0. - openTasks: project.openTaskCount ?? 0, - doneTasks: project.doneTaskCount ?? 0, - // `projectArchived` would be redundant here: this row is the - // project, so its own `archived` says it. - ...archiveFlags({ - archivedAt: project.archivedAt, - archivedProjectIds, - }), - }, - }); + // Leg 7 — projects. + if (runLeg('project')) { + if (projectsAllowed) { + const projects = await ctx.runQuery( + internal.tasks.search_for_chat.searchProjectsForChat, + { + organizationId: who.organizationId, + projectIds, + term: query, + paginationOpts: { + numItems: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), + cursor: null, + }, + }, + ); + for (const project of projects.page) { + results.push(projectResultEntry(project, archivedProjectIds)); + } + sources.projects = + projects.page.length === 0 + ? 'searched (no matches)' + : projects.listed + ? listedSource('projects', projects.isDone) + : 'searched'; + } else { + sources.projects = 'access denied for your role'; + } } - sources.projects = - projects.page.length === 0 - ? 'searched (no matches)' - : projects.listed - ? listedSource('projects', projects.isDone) - : 'searched'; } else { - sources.projects = 'access denied for your role'; + if (runLeg('task')) sources.tasks = 'access denied for your role'; + if (runLeg('project')) { + sources.projects = 'access denied for your role'; + } } - } else { - sources.tasks = 'access denied for your role'; - sources.projects = sources.tasks; } // Leg 8 — conversations. The narrowest leg by far: assignment privacy is @@ -714,54 +1014,35 @@ export function createChatToolExecutor( // given an `isAdmin` flag to trust, and it is not handed organizationId // alone the way legs 3–4 safely are — those tables are org-scope-only and // an inbox is not. - if (conversationsAllowed) { - const found = await ctx.runQuery( - internal.conversations.search_for_chat.searchConversationsForChat, - { - organizationId: who.organizationId, - userId: who.userId, - term: query, - limit: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), - }, - ); - for (const conversation of found.conversations) { - results.push({ - kind: 'conversation', - title: conversation.subject ?? 'Conversation', - data: { - ...(conversation.status ? { status: conversation.status } : {}), - ...(conversation.channel ? { channel: conversation.channel } : {}), - ...(conversation.assigneeUserId - ? { assigneeUserId: conversation.assigneeUserId } - : {}), - ...(conversation.assigneeTeamId - ? { assigneeTeamId: conversation.assigneeTeamId } - : {}), - ...(conversation.assigneeUserId || conversation.assigneeTeamId - ? {} - : // Unassigned is a real state an admin acts on, not missing data. - { unassigned: true }), - ...(conversation.lastMessageAt - ? { lastMessageAt: conversation.lastMessageAt } - : {}), + if (runLeg('conversation')) { + if (conversationsAllowed) { + const found = await ctx.runQuery( + internal.conversations.search_for_chat.searchConversationsForChat, + { + organizationId: who.organizationId, + userId: who.userId, + term: query, + limit: Math.min(limit, RAG_SEARCH_ENTITY_LIMIT), }, - }); + ); + for (const conversation of found.conversations) { + results.push(conversationResultEntry(conversation)); + } + // A bounded scan that filled up must say so — otherwise "no matches" + // reads as "the inbox holds nothing", which is a different claim. + sources.conversations = + found.conversations.length > 0 + ? found.truncated + ? 'searched (recent conversations only)' + : 'searched' + : found.truncated + ? 'searched (no matches among recent conversations)' + : 'searched (no matches)'; + } else { + sources.conversations = 'access denied for your role'; } - // A bounded scan that filled up must say so — otherwise "no matches" - // reads as "the inbox holds nothing", which is a different claim. - sources.conversations = - found.conversations.length > 0 - ? found.truncated - ? 'searched (recent conversations only)' - : 'searched' - : found.truncated - ? 'searched (no matches among recent conversations)' - : 'searched (no matches)'; - } else { - sources.conversations = 'access denied for your role'; } - await recordDispatch('rag_search', 'ok'); // Every leg is already capped; no global slice. An empty answer says // what to do INSTEAD of searching again — the result payload is the // steer, not a system rule. @@ -773,7 +1054,8 @@ export function createChatToolExecutor( ? { message: 'No matches in the organization’s knowledge. Do not re-run ' + - 'reworded variants of this query. Answer from what you ' + + 'reworded variants of this query. Browse a catalog with ' + + 'action "list" when you meant one, answer from what you ' + 'already have — or, when a public page’s URL is known, read ' + 'it with web_fetch.', } @@ -782,6 +1064,473 @@ export function createChatToolExecutor( }; }; + // ------------------------------------------------------ rag_search · list + + /** + * `action: 'list'` — one kind, no text predicate, honest paging. + * + * Every backend is the kind's EXISTING reader with its words turned off, + * behind the same role gate and the same scope its search leg uses: a list + * is a browse, never an ACL widening. The envelope always carries + * `hasMore`, and `continueCursor` only when a next call can redeem it — + * never an empty string, and never for the recency-bounded kinds + * (conversations, websites), which say "narrow, not page" instead. + */ + const ragSearchList = async (call: { + kindRaw: unknown; + query: string; + statusRaw: unknown; + projectId: string | undefined; + cursorRaw: string | undefined; + limitRaw: unknown; + }): Promise => { + if (!isRagSearchKind(call.kindRaw)) { + return invalidArgs( + 'action "list" needs "kind": one of ' + + `${LISTABLE_KINDS.map((kind) => `"${kind}"`).join(', ')}. ` + + `Example: ${EXAMPLE_LIST_CALL}.`, + ); + } + const kind = call.kindRaw; + if (kind === 'web-page') { + // `source-cards.tsx` keys web sources off a top-level `kind: + // 'web-page'` in rag_fetch results — this refusal also keeps a list + // envelope from ever colliding with that renderer. + return invalidArgs( + 'Crawled pages cannot be listed. Browse the site catalog with ' + + '{"action":"list","kind":"website"}, or search the pages with ' + + 'action "search".', + ); + } + if (call.query !== '') { + const corrected = JSON.stringify({ + action: 'list', + kind, + ...(isWorkStatus(call.statusRaw) ? { status: call.statusRaw } : {}), + ...(call.projectId !== undefined ? { projectId: call.projectId } : {}), + }); + return invalidArgs( + 'action "list" takes filters, not a "query". Drop the query and ' + + `re-call: ${corrected}. For a text match, use action "search".`, + ); + } + + // A list is a page the model reads in full — the max IS the default. + const limit = + typeof call.limitRaw === 'number' && call.limitRaw > 0 + ? Math.min(Math.floor(call.limitRaw), RAG_SEARCH_MAX_LIMIT) + : RAG_SEARCH_MAX_LIMIT; + + // Cursors are kind-tagged on the way out, so a stale or cross-kind value + // is caught HERE instead of walking an index for a row that was never in + // this list. + let cursor: string | null = null; + if (call.cursorRaw !== undefined) { + if (kind === 'conversation' || kind === 'website') { + return invalidArgs( + `A ${kind} list does not page — re-call without "cursor" and ` + + 'narrow instead.', + ); + } + const prefix = `${kind}:`; + const rest = call.cursorRaw.startsWith(prefix) + ? call.cursorRaw.slice(prefix.length) + : ''; + if (rest === '') { + return invalidArgs( + `That "cursor" is not from a ${kind} list. Pass the ` + + '"continueCursor" the previous page of this list returned, or ' + + 'omit it for the first page.', + ); + } + cursor = rest; + } + + const subject = LIST_READ_SUBJECTS[kind]; + if (!(await readAllowed(subject))) { + return { + status: 'unavailable', + message: `Your role does not permit reading ${subject} in this organization.`, + }; + } + + /** The standard honesty note; kinds with their own story pass a note. */ + const standardNote = (page: { + count: number; + hasMore: boolean; + pageable: boolean; + }): string | undefined => { + if (page.hasMore && page.pageable) { + return page.count === 0 + ? 'This page is empty but the walk is unfinished — pass ' + + '"continueCursor" back as "cursor" to continue, or narrow ' + + 'the filters.' + : LIST_PAGE_MESSAGE; + } + if (!page.hasMore && cursor !== null && page.count === 0) { + return ( + 'The list ended or changed since that cursor was issued — ' + + 're-call without "cursor" for a fresh first page.' + ); + } + return undefined; + }; + + const envelope = (page: { + results: SearchResultEntry[]; + hasMore: boolean; + continueCursor?: string; + source: string; + note?: string; + }): RagSearchOk => ({ + status: 'ok', + action: 'list', + kind, + results: page.results, + hasMore: page.hasMore, + ...(page.continueCursor !== undefined && page.continueCursor !== '' + ? { continueCursor: `${kind}:${page.continueCursor}` } + : {}), + ...(page.note !== undefined ? { message: page.note } : {}), + sources: { [LIST_SOURCE_KEYS[kind]]: page.source }, + }); + + if (kind === 'task') { + if (call.statusRaw !== undefined && !isWorkStatus(call.statusRaw)) { + // A search drops an unknown status; an explicit LISTING of one must + // not silently list everything instead. + return invalidArgs( + `Unknown "status" ${JSON.stringify(call.statusRaw)}. One of: ` + + `${RAG_SEARCH_STATUS_VALUES.join(', ')}.`, + ); + } + const status = isWorkStatus(call.statusRaw) ? call.statusRaw : undefined; + if (status === undefined && call.projectId === undefined) { + return invalidArgs( + 'Listing every task in the workspace is refused — slice the ' + + `board: pass "status" (e.g. ${EXAMPLE_LIST_CALL}) or ` + + '"projectId" (an id from a project row\'s data).', + ); + } + const access = await knowledgeAccess(); + if ( + call.projectId !== undefined && + !access.projectIds.includes(call.projectId) + ) { + return invalidArgs( + 'No readable project with that "projectId" in this organization. ' + + 'Use the "data"."projectId" a previous task or project row ' + + 'carried.', + ); + } + const archivedProjectIds = new Set(access.archivedProjectIds ?? []); + let tasks; + try { + tasks = await ctx.runQuery( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: who.organizationId, + projectIds: [...access.projectIds], + term: '', + list: true, + excludeArchived: true, + ...(status !== undefined ? { status } : {}), + ...(call.projectId !== undefined + ? { projectId: toId<'projects'>(call.projectId) } + : {}), + paginationOpts: { numItems: limit, cursor }, + }, + ); + } catch { + // A malformed projectId fails the reader's arg validation — the + // remedy is the same uniform message as an unreadable one. + return invalidArgs( + 'No readable project with that "projectId" in this organization. ' + + 'Use the "data"."projectId" a previous task or project row ' + + 'carried.', + ); + } + const hasMore = !tasks.isDone; + const results = tasks.page.map((task) => + taskResultEntry(task, archivedProjectIds), + ); + return envelope({ + results, + hasMore, + ...(hasMore ? { continueCursor: tasks.continueCursor } : {}), + source: hasMore ? 'listed (more — pass continueCursor)' : 'listed', + ...(() => { + const note = standardNote({ + count: results.length, + hasMore, + pageable: true, + }); + return note !== undefined ? { note } : {}; + })(), + }); + } + + if (kind === 'project') { + const access = await knowledgeAccess(); + const archivedProjectIds = new Set(access.archivedProjectIds ?? []); + const projects = await ctx.runQuery( + internal.tasks.search_for_chat.searchProjectsForChat, + { + organizationId: who.organizationId, + projectIds: [...access.projectIds], + term: '', + list: true, + excludeArchived: true, + paginationOpts: { numItems: limit, cursor }, + }, + ); + const hasMore = !projects.isDone; + const results = projects.page.map((project) => + projectResultEntry(project, archivedProjectIds), + ); + return envelope({ + results, + hasMore, + ...(hasMore ? { continueCursor: projects.continueCursor } : {}), + source: hasMore ? 'listed (more — pass continueCursor)' : 'listed', + ...(() => { + const note = standardNote({ + count: results.length, + hasMore, + pageable: true, + }); + return note !== undefined ? { note } : {}; + })(), + }); + } + + if (kind === 'knowledge-entry') { + const entries = await ctx.runQuery( + internal.knowledge_entries.internal_queries.listEntriesForAgent, + { + organizationId: who.organizationId, + paginationOpts: { numItems: limit, cursor }, + }, + ); + const hasMore = !entries.isDone; + const results = entries.page.map((entry) => + knowledgeEntryResultEntry(entry), + ); + return envelope({ + results, + hasMore, + ...(hasMore ? { continueCursor: entries.continueCursor } : {}), + source: hasMore ? 'listed (more — pass continueCursor)' : 'listed', + ...(() => { + const note = standardNote({ + count: results.length, + hasMore, + pageable: true, + }); + return note !== undefined ? { note } : {}; + })(), + }); + } + + if (kind === 'contact') { + const contacts = await ctx.runQuery( + internal.contacts.internal_queries.queryContacts, + { + organizationId: who.organizationId, + paginationOpts: { numItems: limit, cursor }, + }, + ); + const hasMore = !contacts.isDone; + const results = contacts.page.map((contact) => + contactResultEntry(contact), + ); + return envelope({ + results, + hasMore, + ...(hasMore ? { continueCursor: contacts.continueCursor } : {}), + source: hasMore ? 'listed (more — pass continueCursor)' : 'listed', + ...(() => { + const note = standardNote({ + count: results.length, + hasMore, + pageable: true, + }); + return note !== undefined ? { note } : {}; + })(), + }); + } + + if (kind === 'product') { + const products = await ctx.runQuery( + internal.products.internal_queries.queryProducts, + { + organizationId: who.organizationId, + paginationOpts: { numItems: limit, cursor }, + }, + ); + const hasMore = !products.isDone; + const results = products.page.map((product) => + productResultEntry(product), + ); + return envelope({ + results, + hasMore, + ...(hasMore ? { continueCursor: products.continueCursor } : {}), + source: hasMore ? 'listed (more — pass continueCursor)' : 'listed', + ...(() => { + const note = standardNote({ + count: results.length, + hasMore, + pageable: true, + }); + return note !== undefined ? { note } : {}; + })(), + }); + } + + if (kind === 'website') { + const websites = await ctx.runQuery( + internal.websites.internal_queries.listWebsiteSummaries, + { organizationId: who.organizationId }, + ); + const pageRows = websites.slice(0, limit); + const hasMore = websites.length > pageRows.length; + const results = pageRows.map((site) => ({ + ...websiteResultEntry(site), + // The catalog answer "how big is each site?" — search rows skip it. + ...(site.pageCount !== undefined + ? { data: { pageCount: site.pageCount } } + : {}), + })); + return envelope({ + results, + hasMore, + source: hasMore ? 'listed (first sites only)' : 'listed', + ...(hasMore + ? { + note: + `Only the first ${pageRows.length} sites are shown and ` + + 'this list does not page — search for a specific site ' + + 'instead.', + } + : {}), + }); + } + + if (kind === 'conversation') { + // Overfetch by one: the reader's `truncated` only reports a scan-cap + // stop, so a full page from a bigger inbox would otherwise read as + // complete (the limit-break leaves it false). + const found = await ctx.runQuery( + internal.conversations.search_for_chat.searchConversationsForChat, + { + organizationId: who.organizationId, + userId: who.userId, + term: '', + list: true, + limit: limit + 1, + }, + ); + const overfetched = found.conversations.length > limit; + const rows = overfetched + ? found.conversations.slice(0, limit) + : found.conversations; + const hasMore = overfetched || found.truncated; + const results = rows.map((conversation) => + conversationResultEntry(conversation), + ); + return envelope({ + results, + hasMore, + source: hasMore + ? 'listed (recent only — narrowing, not paging)' + : 'listed', + ...(hasMore + ? { + note: + 'Recent conversations only — this list does not page. ' + + 'Narrow by asking about a person, a topic, or a timeframe.', + } + : {}), + }); + } + + // kind === 'document' — the hub listing, not the RAG chunk index: the + // same reader the sandbox lane's document_find uses, scoped to the turn + // user's teams (and one readable project when named). + const offset = cursor !== null ? Number.parseInt(cursor, 10) : 0; + if ( + cursor !== null && + (!Number.isInteger(offset) || offset < 0 || String(offset) !== cursor) + ) { + return invalidArgs( + 'That "cursor" is not from a document list. Pass the ' + + '"continueCursor" the previous page returned, or omit it.', + ); + } + if (call.projectId !== undefined) { + const access = await knowledgeAccess(); + if (!access.projectIds.includes(call.projectId)) { + return invalidArgs( + 'No readable project with that "projectId" in this organization. ' + + 'Use the "data"."projectId" a previous task or project row ' + + 'carried.', + ); + } + } + const found = await ctx.runQuery( + internal.documents.internal_queries.listForAgent, + { + organizationId: who.organizationId, + userId: who.userId, + limit, + ...(offset > 0 ? { cursor: offset } : {}), + ...(call.projectId !== undefined ? { projectId: call.projectId } : {}), + }, + ); + const hasMore = found.hasMore; + const results = found.documents.map( + (doc): SearchResultEntry => ({ + kind: 'document', + title: doc.title, + ref: doc.fileId, + data: { + ...(doc.extension !== null ? { extension: doc.extension } : {}), + ...(doc.folderPath !== null ? { folderPath: doc.folderPath } : {}), + createdAt: doc.createdAt, + }, + }), + ); + // Hub and team files are the whole catalog only for project-less asks — + // project files stay behind their "projectId", and the source line says + // so rather than presenting the hub as everything. + const scopeLabel = + call.projectId !== undefined + ? 'project files' + : 'hub and team files — project files need "projectId"'; + const warningNote = found.warning !== null ? found.warning : undefined; + const pagingNote = standardNote({ + count: results.length, + hasMore, + pageable: true, + }); + const note = + warningNote !== undefined && pagingNote !== undefined + ? `${pagingNote} ${warningNote}` + : (pagingNote ?? warningNote); + return envelope({ + results, + hasMore, + ...(hasMore && found.cursor !== null + ? { continueCursor: String(found.cursor) } + : {}), + source: hasMore + ? `listed (${scopeLabel}; more pages)` + : `listed (${scopeLabel})`, + ...(note !== undefined ? { note } : {}), + }); + }; + // -------------------------------------------------------------- rag_fetch const ragFetch = async (args: Record): Promise => { @@ -936,6 +1685,10 @@ export function createChatToolExecutor( projectIds: [...access.projectIds], projectId: toId<'projects'>(projectId), term: '', + // An explicit listing, so the page size is honoured (the old + // fallback pinned its own cap and `truncated` could never be + // true). Archived tasks stay included and labelled, as before. + list: true, paginationOpts: { numItems: PROJECT_TASKS_LIMIT, cursor: null }, }, ); @@ -962,7 +1715,7 @@ export function createChatToolExecutor( })), // A capped list must say it is capped, or "that is all of them" is a // claim the tool never made. - truncated: tasks.page.length >= PROJECT_TASKS_LIMIT, + truncated: !tasks.isDone, }; } diff --git a/services/platform/convex/conversations/search_for_chat.test.ts b/services/platform/convex/conversations/search_for_chat.test.ts index f9fd74a5fe..c06c0b25ef 100644 --- a/services/platform/convex/conversations/search_for_chat.test.ts +++ b/services/platform/convex/conversations/search_for_chat.test.ts @@ -256,3 +256,64 @@ describe('searchConversationsForChat — the assignment is returned', () => { expect(pool?.assigneeTeamId).toBeUndefined(); }); }); + +describe('searchConversationsForChat — explicit list mode', () => { + let t: T; + + beforeEach(async () => { + t = convexTest(schema, modules); + await seedWorld(t); + }); + + async function listFor(userId: string, limit = 10) { + return t.query( + internal.conversations.search_for_chat.searchConversationsForChat, + { organizationId: ORG, userId, term: '', list: true, limit }, + ); + } + + it('lists without any words — the text predicate is off', async () => { + const result = await listFor(ADMIN); + expect(result.conversations.map((c) => c.subject ?? '').sort()).toEqual([ + 'Refund owned by a person', + 'Refund pool unassigned', + 'Refund queued to team X', + ]); + expect(result.truncated).toBe(false); + }); + + // Turning the words off must not turn the privacy off: the listing passes + // exactly the same assignment predicate as the search. + it('shows a plain member nothing, listed or searched', async () => { + const result = await listFor(PLAIN_MEMBER); + expect(result.conversations).toEqual([]); + }); + + it('shows a team member their team queue only', async () => { + const result = await listFor(TEAM_MEMBER); + expect(result.conversations.map((c) => c.subject ?? '')).toEqual([ + 'Refund queued to team X', + ]); + }); + + it('honours the limit, newest first', async () => { + const result = await listFor(ADMIN, 2); + expect(result.conversations.map((c) => c.subject ?? '')).toEqual([ + 'Refund pool unassigned', + 'Refund queued to team X', + ]); + // The limit-break is NOT the scan cap: truncated stays false, which is + // why the caller overfetches by one to detect a fuller inbox. + expect(result.truncated).toBe(false); + }); + + // Search behavior is untouched: term '' without the flag still matches + // nothing, because an empty token list passes no row in 'any' mode. + it('keeps the searchless empty result without the flag', async () => { + const result = await t.query( + internal.conversations.search_for_chat.searchConversationsForChat, + { organizationId: ORG, userId: ADMIN, term: '', limit: 10 }, + ); + expect(result.conversations).toEqual([]); + }); +}); diff --git a/services/platform/convex/conversations/search_for_chat.ts b/services/platform/convex/conversations/search_for_chat.ts index 4d2f6d0969..033d01a875 100644 --- a/services/platform/convex/conversations/search_for_chat.ts +++ b/services/platform/convex/conversations/search_for_chat.ts @@ -82,6 +82,12 @@ export const searchConversationsForChat = internalQuery({ /** The turn user. Authority is derived from this, never passed in. */ userId: v.string(), term: v.string(), + /** Explicit listing — the chat tool's `action: 'list'`. Skips the + * subject/contact text match and returns the most recent readable + * conversations; the privacy predicate and {@link SCAN_CAP} stay exactly + * as they are. There is still no cursor: the walk is recency-bounded, + * so a caller wanting more must narrow, not page. */ + list: v.optional(v.boolean()), limit: v.number(), }, returns: v.object({ @@ -122,10 +128,11 @@ export const searchConversationsForChat = internalQuery({ return teamIds.has(teamId); }; + const listing = args.list === true; const term = args.term.trim(); const lower = term.toLowerCase(); const contactIds = - term === '' + listing || term === '' ? new Set() : await matchingContactIds(ctx, { organizationId: args.organizationId, @@ -147,28 +154,32 @@ export const searchConversationsForChat = internalQuery({ } scanned += 1; - const bySubject = - conversation.subject !== undefined && - rowMatches( - conversation, - // A one-field strategy: `subject` is the only prose a conversation - // row carries. Declared inline rather than exported, because nothing - // else searches this table. - { - table: 'conversations', - orgIndex: 'by_organizationId', - textFields: ['subject'], - idFields: [], - engine: 'scan', - }, - lower, - term, - 'any', - ); - const byContact = - conversation.contactId !== undefined && - contactIds.has(String(conversation.contactId)); - if (!bySubject && !byContact) continue; + // A listing has no words to match: every scanned row goes straight to + // the assignment decision below. + if (!listing) { + const bySubject = + conversation.subject !== undefined && + rowMatches( + conversation, + // A one-field strategy: `subject` is the only prose a conversation + // row carries. Declared inline rather than exported, because + // nothing else searches this table. + { + table: 'conversations', + orgIndex: 'by_organizationId', + textFields: ['subject'], + idFields: [], + engine: 'scan', + }, + lower, + term, + 'any', + ); + const byContact = + conversation.contactId !== undefined && + contactIds.has(String(conversation.contactId)); + if (!bySubject && !byContact) continue; + } // The scope decision comes AFTER the text match so an unreadable row // never costs a team lookup it cannot benefit from. diff --git a/services/platform/convex/lib/search/index.ts b/services/platform/convex/lib/search/index.ts index 44cd8c4b15..e0ff9da630 100644 --- a/services/platform/convex/lib/search/index.ts +++ b/services/platform/convex/lib/search/index.ts @@ -7,12 +7,14 @@ export { } from './scoped_substring_search'; export { runEntitySearch } from './run_entity_search'; export { + STOPWORDS, isActiveRow, type MatchMode, queryTokens, rowMatches, scoreAndSort, } from './relevance'; +export { detectListingIntent, type ListingIntent } from './listing_intent'; // Per-entity strategies. export { contactsSearchStrategy } from './strategies/contacts'; diff --git a/services/platform/convex/lib/search/listing_intent.test.ts b/services/platform/convex/lib/search/listing_intent.test.ts new file mode 100644 index 0000000000..dab6941b41 --- /dev/null +++ b/services/platform/convex/lib/search/listing_intent.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vitest'; + +import { detectListingIntent } from './listing_intent'; + +/** + * The contract, table-first: a stuffed listing steers to `list` with the + * kind/status it names; anything with a surviving noun stays a search. The + * named utterances come from the design review and must never regress. + */ + +describe('detectListingIntent — fires on pure listing language', () => { + const listings: Array<[string, { kind: string; status?: string }]> = [ + ['list all in-review tasks', { kind: 'task', status: 'in_review' }], + ['welche Tasks sind in Review', { kind: 'task', status: 'in_review' }], + ['montre les tâches en revue', { kind: 'task', status: 'in_review' }], + ['list open tasks', { kind: 'task', status: 'open' }], + ['show our contacts', { kind: 'contact' }], + ['list our customers', { kind: 'contact' }], + ['zeige alle offenen Aufgaben', { kind: 'task', status: 'open' }], + ['liste des projets', { kind: 'project' }], + ['show all documents', { kind: 'document' }], + // A bare state question is a task list with that status. + ['what is open?', { kind: 'task', status: 'open' }], + ['was steht im backlog?', { kind: 'task', status: 'backlog' }], + ]; + + it.each(listings)('%s → list', (utterance, expected) => { + expect(detectListingIntent(utterance)).toEqual(expected); + }); +}); + +describe('detectListingIntent — honors a search whenever a noun survives', () => { + const searches = [ + "what's our refund policy", + 'show me the login review task', + 'do we have anything about GDPR?', + 'refund policy', + 'login', + 'tasks about onboarding', + 'which tasks mention the Bergmann account?', + 'list crawled pages of the marketing site', // "crawled"/"marketing" survive + ]; + + it.each(searches)('%s → search', (utterance) => { + expect(detectListingIntent(utterance)).toBeUndefined(); + }); + + it('never proposes the unlistable web-page kind', () => { + // Pure page-listing language strips clean, but the steer must not point + // at a kind the executor refuses — the search (and its listing fallback) + // is the better outcome. + expect(detectListingIntent('list all pages')).toBeUndefined(); + }); + + it('needs two signals, not one', () => { + expect(detectListingIntent('tasks')).toBeUndefined(); + expect(detectListingIntent('open')).toBeUndefined(); + }); + + it('is calm about empty and whitespace queries', () => { + expect(detectListingIntent('')).toBeUndefined(); + expect(detectListingIntent(' ')).toBeUndefined(); + }); +}); diff --git a/services/platform/convex/lib/search/listing_intent.ts b/services/platform/convex/lib/search/listing_intent.ts new file mode 100644 index 0000000000..5e0b0a253c --- /dev/null +++ b/services/platform/convex/lib/search/listing_intent.ts @@ -0,0 +1,294 @@ +/** + * Listing-intent residue detector for chat `rag_search`. + * + * A search whose query is PURE browsing language — "list all in-review + * tasks" — matches nothing by construction (no task title contains the word + * "tasks"), so the executor steers it to `action: 'list'` instead of running + * legs that can only fail. The steer must never fire on a real information + * need, so the rule is conservative in one direction: + * + * strip function words, listing verbs, kind nouns, and status words; if + * ANY token survives, the query names a thing and the search is honored. + * Only an empty residue with at least two listing signals (and an + * inferrable kind) reads as a stuffed listing. + * + * False negatives are safe — the search still runs, and the tasks/projects + * legs fall back to their own bounded listing when nothing matches. False + * positives are the failure mode this shape exists to avoid. + * + * en/de/fr, mirroring {@link STOPWORDS}: a browse question arrives in the + * reader's language. The detector splits on punctuation (unlike search + * tokenization, which is whitespace-only) so "in-review" reads as the status + * it names. + */ + +import type { RagSearchKind, RagSearchStatus } from '../../../lib/chat/tools'; +import { STOPWORDS } from './relevance'; + +export interface ListingIntent { + readonly kind: RagSearchKind; + readonly status?: RagSearchStatus; +} + +/** Browsing markers: list verbs, quantifiers, and the interrogatives that + * open a board question. Some double as search stopwords ("all", "welche"); + * they are classified as signals FIRST so they count toward the threshold. */ +const LIST_SIGNALS: ReadonlySet = new Set([ + // en — interrogatives included: "what is open?" carries its browse intent + // in the question word, and the residue guard keeps "what's our refund + // policy" a search regardless. + 'list', + 'lists', + 'listing', + 'show', + 'display', + 'browse', + 'enumerate', + 'view', + 'overview', + 'all', + 'every', + 'everything', + 'current', + 'currently', + 'what', + 'which', + // de + 'zeige', + 'zeig', + 'zeigen', + 'anzeigen', + 'auflisten', + 'liste', + 'listen', + 'übersicht', + 'alle', + 'welche', + 'welcher', + 'welches', + 'was', + 'aktuelle', + 'aktuellen', + // fr + 'lister', + 'listes', + 'montre', + 'montrer', + 'montrez', + 'affiche', + 'afficher', + 'affichez', + 'aperçu', + 'tous', + 'toutes', + 'quel', + 'quels', + 'quelle', + 'quelles', + 'actuels', + 'actuelles', +]); + +/** Kind nouns → the `kind` a listing of them means. Plurals and the de/fr + * words a browse question would use. `web-page` nouns are mapped so they + * strip as signals, but the detector never PROPOSES that kind — pages have + * no listable catalog, and a steer must not point at a refusal. */ +const KIND_NOUNS: ReadonlyMap = new Map([ + ['task', 'task'], + ['tasks', 'task'], + ['ticket', 'task'], + ['tickets', 'task'], + ['aufgabe', 'task'], + ['aufgaben', 'task'], + ['tâche', 'task'], + ['tâches', 'task'], + ['project', 'project'], + ['projects', 'project'], + ['projekt', 'project'], + ['projekte', 'project'], + ['projekten', 'project'], + ['projet', 'project'], + ['projets', 'project'], + ['contact', 'contact'], + ['contacts', 'contact'], + ['kontakt', 'contact'], + ['kontakte', 'contact'], + ['kontakten', 'contact'], + ['customer', 'contact'], + ['customers', 'contact'], + ['kunde', 'contact'], + ['kunden', 'contact'], + ['client', 'contact'], + ['clients', 'contact'], + ['product', 'product'], + ['products', 'product'], + ['produkt', 'product'], + ['produkte', 'product'], + ['produkten', 'product'], + ['produit', 'product'], + ['produits', 'product'], + ['document', 'document'], + ['documents', 'document'], + ['dokument', 'document'], + ['dokumente', 'document'], + ['dokumenten', 'document'], + ['file', 'document'], + ['files', 'document'], + ['datei', 'document'], + ['dateien', 'document'], + ['fichier', 'document'], + ['fichiers', 'document'], + ['website', 'website'], + ['websites', 'website'], + ['webseite', 'website'], + ['webseiten', 'website'], + ['site', 'website'], + ['sites', 'website'], + ['domain', 'website'], + ['domains', 'website'], + ['conversation', 'conversation'], + ['conversations', 'conversation'], + ['unterhaltung', 'conversation'], + ['unterhaltungen', 'conversation'], + ['gespräch', 'conversation'], + ['gespräche', 'conversation'], + ['inbox', 'conversation'], + ['email', 'conversation'], + ['emails', 'conversation'], + ['mail', 'conversation'], + ['mails', 'conversation'], + ['entry', 'knowledge-entry'], + ['entries', 'knowledge-entry'], + ['eintrag', 'knowledge-entry'], + ['einträge', 'knowledge-entry'], + ['entrée', 'knowledge-entry'], + ['entrées', 'knowledge-entry'], + ['note', 'knowledge-entry'], + ['notes', 'knowledge-entry'], + ['notizen', 'knowledge-entry'], + ['knowledge', 'knowledge-entry'], + ['page', 'web-page'], + ['pages', 'web-page'], + ['seite', 'web-page'], + ['seiten', 'web-page'], +]); + +/** Board-state words → the `status` filter they name. Only what a column is + * CALLED — never generic adjectives, which belong to the residue. */ +const STATUS_WORDS: ReadonlyMap = new Map([ + ['open', 'open'], + ['offen', 'open'], + ['offene', 'open'], + ['offenen', 'open'], + ['outstanding', 'open'], + ['unerledigt', 'open'], + ['ouvert', 'open'], + ['ouverts', 'open'], + ['ouverte', 'open'], + ['ouvertes', 'open'], + ['backlog', 'backlog'], + ['todo', 'todo'], + ['todos', 'todo'], + ['progress', 'in_progress'], + ['ongoing', 'in_progress'], + ['wip', 'in_progress'], + ['bearbeitung', 'in_progress'], + ['laufende', 'in_progress'], + ['laufenden', 'in_progress'], + ['cours', 'in_progress'], + ['review', 'in_review'], + ['reviews', 'in_review'], + ['prüfung', 'in_review'], + ['überprüfung', 'in_review'], + ['revue', 'in_review'], + ['done', 'done'], + ['erledigt', 'done'], + ['erledigte', 'done'], + ['erledigten', 'done'], + ['fertig', 'done'], + ['abgeschlossen', 'done'], + ['abgeschlossene', 'done'], + ['completed', 'done'], + ['finished', 'done'], + ['terminé', 'done'], + ['terminés', 'done'], + ['terminée', 'done'], + ['terminées', 'done'], + ['fini', 'done'], + ['finis', 'done'], + ['cancelled', 'cancelled'], + ['canceled', 'cancelled'], + ['abgebrochen', 'cancelled'], + ['storniert', 'cancelled'], + ['annulé', 'cancelled'], + ['annulés', 'cancelled'], + ['annulée', 'cancelled'], + ['annulées', 'cancelled'], +]); + +/** Function words the shared search stopword list happens not to carry but a + * browse sentence uses. Detector-only on purpose: adding them to + * {@link STOPWORDS} would change what SEARCH drops, and this module must + * never move search behavior. */ +const DETECTOR_FUNCTION_WORDS: ReadonlySet = new Set([ + 'please', + 'bitte', + 'mir', + 'uns', + 'steht', + 'stehen', + 'moi', + 'nous', + 'que', + 's', +]); + +/** + * Whether a search query is a stuffed listing, and the list call it means. + * `undefined` honors the search — the only wrong answer here is steering a + * real information need away from retrieval. + */ +export function detectListingIntent(query: string): ListingIntent | undefined { + const tokens = query + .toLowerCase() + .split(/[^\p{L}\p{N}]+/u) + .filter((token) => token.length > 0); + if (tokens.length === 0) return undefined; + + let signals = 0; + let kind: RagSearchKind | undefined; + let status: RagSearchStatus | undefined; + for (const token of tokens) { + if (LIST_SIGNALS.has(token)) { + signals += 1; + continue; + } + const kindHit = KIND_NOUNS.get(token); + if (kindHit !== undefined) { + signals += 1; + kind ??= kindHit; + continue; + } + const statusHit = STATUS_WORDS.get(token); + if (statusHit !== undefined) { + signals += 1; + status ??= statusHit; + continue; + } + if ( + STOPWORDS.has(token) || + DETECTOR_FUNCTION_WORDS.has(token) || + token.length <= 1 + ) { + continue; + } + // A surviving noun means the query names a thing: honor the search. + return undefined; + } + + if (signals < 2) return undefined; + // A bare state question ("what is open?") is a task list with that status. + const inferred = kind ?? (status !== undefined ? 'task' : undefined); + if (inferred === undefined || inferred === 'web-page') return undefined; + return { kind: inferred, ...(status !== undefined ? { status } : {}) }; +} diff --git a/services/platform/convex/lib/search/relevance.ts b/services/platform/convex/lib/search/relevance.ts index 346bc398e6..6b17119154 100644 --- a/services/platform/convex/lib/search/relevance.ts +++ b/services/platform/convex/lib/search/relevance.ts @@ -44,8 +44,12 @@ export type MatchMode = 'all' | 'any'; * * Deliberately NO domain vocabulary: "open", "done", "review" and the like * carry real meaning on a task board and must stay searchable. + * + * Exported for the listing-intent detector (`listing_intent.ts`), which asks + * the inverse question — "is there anything here BUT function words?" — and + * must agree with search about what a function word is. */ -const STOPWORDS: ReadonlySet = new Set([ +export const STOPWORDS: ReadonlySet = new Set([ // en 'a', 'about', diff --git a/services/platform/convex/tasks/search_for_chat.test.ts b/services/platform/convex/tasks/search_for_chat.test.ts index 970d2afb7d..149197cc99 100644 --- a/services/platform/convex/tasks/search_for_chat.test.ts +++ b/services/platform/convex/tasks/search_for_chat.test.ts @@ -646,3 +646,205 @@ describe('a listing bounds what it examines, not just what it keeps', () => { expect(result.isDone).toBe(true); }); }); + +describe('explicit list mode — the chat list action backend', () => { + const LIST_ORG = 'org_task_list'; + let t: T; + let project: Id<'projects'>; + + beforeEach(async () => { + t = convexTest(schema, modules); + project = await t.run(async (ctx) => { + const id = await ctx.db.insert('projects', { + organizationId: LIST_ORG, + name: 'Board project', + createdBy: 'user_1', + createdAt: 0, + updatedAt: 0, + }); + // Five live tasks and one archived — updated newest-first is t5..t1. + for (let i = 1; i <= 5; i += 1) { + await ctx.db.insert('tasks', { + organizationId: LIST_ORG, + title: `Board task ${i}`, + status: 'todo', + rank: String(i), + projectId: id, + createdBy: 'user_1', + createdByType: 'user', + createdAt: i, + updatedAt: i * 1_000, + }); + } + await ctx.db.insert('tasks', { + organizationId: LIST_ORG, + title: 'Archived board task', + status: 'todo', + rank: 'z', + projectId: id, + createdBy: 'user_1', + createdByType: 'user', + createdAt: 9, + updatedAt: 9_000, + archivedAt: 1_700_000_000_000, + }); + return id; + }); + }); + + it('honours the requested page size and returns a redeemable cursor', async () => { + const first = await t.query( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: LIST_ORG, + projectIds: [String(project)], + term: '', + list: true, + status: 'open', + paginationOpts: { numItems: 2, cursor: null }, + }, + ); + expect(first.listed).toBe(true); + expect(first.page).toHaveLength(2); + expect(first.isDone).toBe(false); + expect(first.continueCursor).not.toBe(''); + + const second = await t.query( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: LIST_ORG, + projectIds: [String(project)], + term: '', + list: true, + status: 'open', + paginationOpts: { numItems: 2, cursor: first.continueCursor }, + }, + ); + // The next page carries DIFFERENT rows — the cursor really resumed. + const firstIds = new Set(first.page.map((task) => String(task._id))); + expect(second.page.length).toBeGreaterThan(0); + for (const task of second.page) { + expect(firstIds.has(String(task._id))).toBe(false); + } + }); + + it('excludes archived rows only when asked — the current board reading', async () => { + const listed = await t.query( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: LIST_ORG, + projectIds: [String(project)], + term: '', + list: true, + excludeArchived: true, + status: 'open', + paginationOpts: { numItems: 20, cursor: null }, + }, + ); + expect( + listed.page.some((task) => task.title === 'Archived board task'), + ).toBe(false); + + // Without the flag the archive policy stays: returned, not filtered. + const unfiltered = await t.query( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: LIST_ORG, + projectIds: [String(project)], + term: '', + list: true, + status: 'open', + paginationOpts: { numItems: 20, cursor: null }, + }, + ); + expect( + unfiltered.page.some((task) => task.title === 'Archived board task'), + ).toBe(true); + }); + + it('narrows a projectId list to that project alone', async () => { + const other = await t.run(async (ctx) => + ctx.db.insert('projects', { + organizationId: LIST_ORG, + name: 'Other project', + createdBy: 'user_1', + createdAt: 0, + updatedAt: 0, + }), + ); + await t.run(async (ctx) => { + await ctx.db.insert('tasks', { + organizationId: LIST_ORG, + title: 'Other project task', + status: 'todo', + rank: 'y', + projectId: other, + createdBy: 'user_1', + createdByType: 'user', + createdAt: 8, + updatedAt: 8_000, + }); + }); + const narrowed = await t.query( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: LIST_ORG, + projectIds: [String(project), String(other)], + term: '', + list: true, + projectId: project, + paginationOpts: { numItems: 20, cursor: null }, + }, + ); + expect(narrowed.page.length).toBeGreaterThan(0); + expect( + narrowed.page.every((task) => String(task.projectId) === String(project)), + ).toBe(true); + }); + + it('lists projects the same way, with archived excluded on request', async () => { + const retired = await t.run(async (ctx) => + ctx.db.insert('projects', { + organizationId: LIST_ORG, + name: 'Retired board project', + createdBy: 'user_1', + createdAt: 0, + updatedAt: 0, + archivedAt: 1_700_000_000_000, + }), + ); + const listed = await t.query( + internal.tasks.search_for_chat.searchProjectsForChat, + { + organizationId: LIST_ORG, + projectIds: [String(project), String(retired)], + term: '', + list: true, + excludeArchived: true, + paginationOpts: { numItems: 20, cursor: null }, + }, + ); + expect(listed.listed).toBe(true); + expect(listed.page.map((row) => row.name)).toEqual(['Board project']); + }); + + // The implicit fallback (no `list` flag) must stay byte-identical: its own + // fixed cap, no cursor — asserted by the "newest 15" suite above. This + // pins the boundary from the other side: the flag is what opts in. + it('keeps the fallback cap when the flag is absent', async () => { + const fallback = await t.query( + internal.tasks.search_for_chat.searchTasksForChat, + { + organizationId: LIST_ORG, + projectIds: [String(project)], + term: 'zebra nonsense words', + paginationOpts: { numItems: 2, cursor: null }, + }, + ); + expect(fallback.listed).toBe(true); + // numItems 2 is IGNORED by the fallback (its cap is LIST_CAP) — all six + // readable tasks fit under 15 and come back despite the tiny page ask. + expect(fallback.page.length).toBeGreaterThan(2); + expect(fallback.continueCursor).toBe(''); + }); +}); diff --git a/services/platform/convex/tasks/search_for_chat.ts b/services/platform/convex/tasks/search_for_chat.ts index 5a6b088d07..f7758f3366 100644 --- a/services/platform/convex/tasks/search_for_chat.ts +++ b/services/platform/convex/tasks/search_for_chat.ts @@ -106,10 +106,11 @@ async function listTasksInScope( ctx: QueryCtx, args: { organizationId: string; - readable: ReadonlySet; - status?: 'open' | Doc<'tasks'>['status']; + numItems: number; + cursor: string | null; + allowed: (task: Doc<'tasks'>) => boolean; }, -): Promise<{ rows: Doc<'tasks'>[]; complete: boolean }> { +): Promise<{ rows: Doc<'tasks'>[]; complete: boolean; cursor: string }> { const listed = await paginateWithFilter( ctx.db .query('tasks') @@ -118,9 +119,9 @@ async function listTasksInScope( ) .order('desc'), { - numItems: LIST_CAP, - cursor: null, - filter: (task) => taskAllowed(task, args.readable, args.status), + numItems: args.numItems, + cursor: args.cursor, + filter: args.allowed, }, ); const rows = [...listed.page]; @@ -129,7 +130,9 @@ async function listTasksInScope( ? a.rank.localeCompare(b.rank) : a.status.localeCompare(b.status), ); - return { rows, complete: listed.isDone }; + // The resume cursor comes from the WALK (index order), never from the + // sorted display copy — sorting is per-page presentation only. + return { rows, complete: listed.isDone, cursor: listed.continueCursor }; } export const searchTasksForChat = internalQuery({ @@ -142,8 +145,19 @@ export const searchTasksForChat = internalQuery({ /** `open` = not done/cancelled. Any concrete status filters exactly. */ status: v.optional(v.union(v.literal('open'), taskStatusValidator)), /** One project, for "which tasks are in this project?". Narrows BOTH the - * search and the listing; still subject to `projectIds`. */ + * search and the listing; still subject to `projectIds`. Asking for one + * project excludes project-less org-level work — that is what the + * narrowing means. */ projectId: v.optional(v.id('projects')), + /** Explicit listing — the chat tool's `action: 'list'` backend. Skips the + * text match entirely, honours `paginationOpts` (page size AND resume + * cursor), and returns a redeemable `continueCursor`. Absent keeps the + * search-with-fallback behavior byte-identical, including the fallback's + * fixed `LIST_CAP` page. */ + list: v.optional(v.boolean()), + /** Hide archived rows — a listing reads as the CURRENT board. Absent + * keeps the return-and-label policy the module header documents. */ + excludeArchived: v.optional(v.boolean()), paginationOpts: cursorPaginationOptsValidator, }, handler: async (ctx, args) => { @@ -154,20 +168,43 @@ export const searchTasksForChat = internalQuery({ new Set(args.projectIds.filter((id) => id === String(args.projectId))) : new Set(args.projectIds); const status = args.status; + const allowed = (task: Doc<'tasks'>): boolean => { + if (args.excludeArchived === true && task.archivedAt !== undefined) { + return false; + } + return taskAllowed(task, readable, status); + }; + + if (args.list === true) { + const listing = await listTasksInScope(ctx, { + organizationId: args.organizationId, + numItems: args.paginationOpts.numItems, + cursor: args.paginationOpts.cursor, + allowed, + }); + return { + page: listing.rows, + isDone: listing.complete, + continueCursor: listing.cursor, + listed: true, + }; + } + const found = await runEntitySearch(ctx, tasksSearchStrategy, { organizationId: args.organizationId, term: args.term, paginationOpts: args.paginationOpts, matchMode: 'any', - accessFilter: (task: Doc<'tasks'>) => taskAllowed(task, readable, status), + accessFilter: allowed, }); if (found.page.length > 0) return { ...found, listed: false }; // Nothing matched the words. Answer the question the words were describing. const listing = await listTasksInScope(ctx, { organizationId: args.organizationId, - readable, - ...(status !== undefined ? { status } : {}), + numItems: LIST_CAP, + cursor: null, + allowed, }); return { page: listing.rows, @@ -186,39 +223,68 @@ export const searchProjectsForChat = internalQuery({ * so visibility is decided by the caller, not re-derived here. */ projectIds: v.array(v.string()), term: v.string(), + /** Explicit listing, exactly as on `searchTasksForChat`: no text match, + * `paginationOpts` honoured, redeemable cursor. */ + list: v.optional(v.boolean()), + /** Hide archived projects — a listing reads as the current portfolio. */ + excludeArchived: v.optional(v.boolean()), paginationOpts: cursorPaginationOptsValidator, }, handler: async (ctx, args) => { const readable = new Set(args.projectIds); + const allowed = (project: Doc<'projects'>): boolean => { + if (args.excludeArchived === true && project.archivedAt !== undefined) { + return false; + } + return readable.has(String(project._id)); + }; + // "Are there any archived projects?" names no project, so nothing matches + // and whichever project has the word in its DESCRIPTION wins by accident. + // List instead — the readable set is already the answer's scope. Newest + // first, for the reason `listTasksInScope` gives: the cap decides the + // answer, and the org index would have kept the least recently touched + // projects in scope. + const listProjects = async ( + numItems: number, + cursor: string | null, + ): Promise<{ + page: Doc<'projects'>[]; + isDone: boolean; + continueCursor: string; + }> => + paginateWithFilter( + ctx.db + .query('projects') + .withIndex('by_organization_updatedAt', (q) => + q.eq('organizationId', args.organizationId), + ) + .order('desc'), + { numItems, cursor, filter: allowed }, + ); + + if (args.list === true) { + const listed = await listProjects( + args.paginationOpts.numItems, + args.paginationOpts.cursor, + ); + return { + page: listed.page, + isDone: listed.isDone, + continueCursor: listed.continueCursor, + listed: true, + }; + } + const found = await runEntitySearch(ctx, projectsSearchStrategy, { organizationId: args.organizationId, term: args.term, paginationOpts: args.paginationOpts, matchMode: 'any', - accessFilter: (project: Doc<'projects'>) => - readable.has(String(project._id)), + accessFilter: allowed, }); if (found.page.length > 0) return { ...found, listed: false }; - // "Are there any archived projects?" names no project, so nothing matches - // and whichever project has the word in its DESCRIPTION wins by accident. - // List instead — the readable set is already the answer's scope. Newest - // first, for the reason `listTasksInScope` gives: the cap decides the - // answer, and the org index would have kept the least recently touched - // projects in scope. - const listed = await paginateWithFilter( - ctx.db - .query('projects') - .withIndex('by_organization_updatedAt', (q) => - q.eq('organizationId', args.organizationId), - ) - .order('desc'), - { - numItems: LIST_CAP, - cursor: null, - filter: (project) => readable.has(String(project._id)), - }, - ); + const listed = await listProjects(LIST_CAP, null); return { page: listed.page, isDone: listed.isDone, diff --git a/services/platform/lib/chat/index.ts b/services/platform/lib/chat/index.ts index 06995f9873..160232391b 100644 --- a/services/platform/lib/chat/index.ts +++ b/services/platform/lib/chat/index.ts @@ -119,9 +119,12 @@ export { CHAT_TOOL_NAMES, CHAT_WIRE_TOOLS, PAUSING_CHAT_TOOLS, + RAG_SEARCH_ACTIONS, RAG_SEARCH_DEFAULT_LIMIT, RAG_SEARCH_ENTITY_LIMIT, + RAG_SEARCH_KINDS, RAG_SEARCH_MAX_LIMIT, + RAG_SEARCH_STATUS_VALUES, isAwaitingAnswerResult, RAG_SEARCH_MIN_SIMILARITY, isChatToolName, @@ -129,6 +132,9 @@ export { type AwaitingAnswerResult, type ChatToolExecutor, type ChatToolName, + type RagSearchAction, + type RagSearchKind, + type RagSearchStatus, type ToolCallRequest, type WireTool, } from './tools'; diff --git a/services/platform/lib/chat/tools.test.ts b/services/platform/lib/chat/tools.test.ts index 0de16cebfb..45a03cb4f6 100644 --- a/services/platform/lib/chat/tools.test.ts +++ b/services/platform/lib/chat/tools.test.ts @@ -17,10 +17,13 @@ import { CHAT_TOOL_DOCS, CHAT_TOOL_NAMES, CHAT_WIRE_TOOLS, + RAG_SEARCH_ACTIONS, RAG_SEARCH_DEFAULT_LIMIT, RAG_SEARCH_ENTITY_LIMIT, + RAG_SEARCH_KINDS, RAG_SEARCH_MAX_LIMIT, RAG_SEARCH_MIN_SIMILARITY, + RAG_SEARCH_STATUS_VALUES, isAwaitingAnswerResult, isPausingChatTool, } from './tools'; @@ -120,6 +123,53 @@ describe('CHAT_WIRE_TOOLS — the model-facing contract', () => { ); }); + // The verb is the contract's spine: an omission must never silently become + // a different operation, so `action` is the ONLY schema-required field and + // both enums are closed. The schema, the executor, and this test all read + // the same exported arrays, so none of the three can drift. + it('rag_search requires the action verb and closes its enums', () => { + const schema = wireSchema('rag_search'); + expect(at(schema, 'required')).toEqual(['action']); + expect(at(schema, 'additionalProperties')).toBe(false); + expect(at(schema, 'properties', 'action', 'enum')).toEqual([ + ...RAG_SEARCH_ACTIONS, + ]); + expect(at(schema, 'properties', 'kind', 'enum')).toEqual([ + ...RAG_SEARCH_KINDS, + ]); + expect(at(schema, 'properties', 'status', 'enum')).toEqual([ + ...RAG_SEARCH_STATUS_VALUES, + ]); + }); + + it('rag_search splits search from list and stays honest about paging', () => { + const text = wireDescription('rag_search'); + expect(text).toContain('action="search"'); + expect(text).toContain('action="list"'); + expect(text).toMatch(/browses ONE kind/); + // The two first-call traps: a named item is not a list, and a bare state + // question is not a search. + expect(text).toMatch(/named item is a search/i); + expect(text).toMatch(/task dump\s+is refused/i); + // Paging honesty rides the description, like rag_fetch's nextOffset rule. + expect(text).toContain('hasMore'); + expect(text).toContain('continueCursor'); + expect(text).toMatch(/never present one page/i); + // Empty searches steer to the list verb, not to rewording. + expect(text).toMatch(/switch to action="list"/i); + }); + + // The description dropped its offset parenthetical because rag_fetch's own + // `offset` field carries the fact at the moment it matters — this pins the + // dependency so a rewrite there cannot orphan the contract. + it('rag_fetch still explains the offset a rag_search hit carries', () => { + const offsetDescription = String( + at(wireSchema('rag_fetch'), 'properties', 'offset', 'description'), + ); + expect(offsetDescription).toMatch(/rag_search hit.s\s+"offset"/i); + expect(offsetDescription).toMatch(/land on the match/i); + }); + it('rag_fetch accepts a task ref and says what it returns', () => { const text = wireDescription('rag_fetch'); expect(text).toMatch(/task ref/i); diff --git a/services/platform/lib/chat/tools.ts b/services/platform/lib/chat/tools.ts index b484871d96..a35624e672 100644 --- a/services/platform/lib/chat/tools.ts +++ b/services/platform/lib/chat/tools.ts @@ -148,9 +148,50 @@ function object( }; } -/** How many results one `rag_search` may return. */ +/** How many results one `rag_search` may return. Doubles as the `list` + * action's default page size: a list is a page the model reads in full, so + * the default IS the ceiling. */ export const RAG_SEARCH_MAX_LIMIT = 20; export const RAG_SEARCH_DEFAULT_LIMIT = 8; + +/** The two verbs `rag_search` accepts. An explicit verb, because inferring + * "list" from an empty query is the classic tool-design trap: models omit + * optional fields, and an omission must never silently become a different + * operation. One array feeds the schema, the executor, and the tests, so the + * three cannot drift. */ +export const RAG_SEARCH_ACTIONS = ['search', 'list'] as const; +export type RagSearchAction = (typeof RAG_SEARCH_ACTIONS)[number]; + +/** The nine result kinds `rag_search` returns — and the browse targets the + * `list` action accepts (all but `web-page`, which has no bounded catalog; + * the executor refuses it with a steer). Singular, because one list call + * browses ONE backend — this is not a type-tag array over a shared index. */ +export const RAG_SEARCH_KINDS = [ + 'document', + 'web-page', + 'knowledge-entry', + 'product', + 'contact', + 'website', + 'task', + 'project', + 'conversation', +] as const; +export type RagSearchKind = (typeof RAG_SEARCH_KINDS)[number]; + +/** Task statuses the tool accepts, `open` shorthand included. The executor + * and the schema both read THIS list — previously the executor kept a + * hand-written mirror, which nothing tested. */ +export const RAG_SEARCH_STATUS_VALUES = [ + 'open', + 'backlog', + 'todo', + 'in_progress', + 'in_review', + 'done', + 'cancelled', +] as const; +export type RagSearchStatus = (typeof RAG_SEARCH_STATUS_VALUES)[number]; /** Dense-leg similarity floor: cosine hits under this read as noise and are * dropped before fusion. BM25 (keyword) hits are never floored — an exact * term match stays a result even when the embedding disagrees. */ @@ -163,37 +204,65 @@ export const RAG_SEARCH_ENTITY_LIMIT = 5; const RAG_SEARCH_SCHEMA = object( { + action: { + type: 'string', + enum: [...RAG_SEARCH_ACTIONS], + description: + 'What to do: "search" retrieves by meaning or leftover keywords; ' + + '"list" browses one kind with filters and no text match. Always ' + + 'pass it.', + }, query: { type: 'string', description: - "The user's question, in the words they used. Do not re-search " + - 'reworded variants of a query that already came back empty.', + 'The information need for action="search": a short question or noun ' + + 'phrase with distinctive terms. Omit for action="list". Do not ' + + 're-search reworded variants of a query that already came back empty.', + }, + kind: { + type: 'string', + enum: [...RAG_SEARCH_KINDS], + description: + 'Which result kind to browse — required for action="list" (one kind ' + + 'per call). On action="search" it narrows the search to that kind ' + + 'alone; omit it to search everything. kind="web-page" cannot be ' + + 'listed — search it, or list kind="website".', + }, + status: { + type: 'string', + enum: [...RAG_SEARCH_STATUS_VALUES], + description: + 'Filter TASK results by status. "open" means not done and not ' + + 'cancelled — use it for "open", "outstanding" or "current" work. ' + + '"in_review" is the "In review" / "In Prüfung" / "En revue" column. ' + + 'Listing tasks requires this or "projectId". Omit it when the ' + + 'question does not name a state. Ignored by every other kind of ' + + 'result.', + }, + projectId: { + type: 'string', + description: + 'Filter tasks or documents to one project. Only an id already seen ' + + 'in a result row (e.g. "data"."projectId") — never invent one; if ' + + 'you only hold a project name, find the project first.', }, limit: { type: 'integer', minimum: 1, maximum: RAG_SEARCH_MAX_LIMIT, - description: `How many results to return (default ${RAG_SEARCH_DEFAULT_LIMIT}).`, + description: + `How many results to return (search default ${RAG_SEARCH_DEFAULT_LIMIT}; ` + + `list default and maximum ${RAG_SEARCH_MAX_LIMIT}).`, }, - status: { + cursor: { type: 'string', - enum: [ - 'open', - 'backlog', - 'todo', - 'in_progress', - 'in_review', - 'done', - 'cancelled', - ], description: - 'Filter TASK results by status. "open" means not done and not ' + - 'cancelled — use it for "open", "outstanding" or "current" work. ' + - 'Omit it when the question does not name a state. Ignored by every ' + - 'other kind of result.', + 'The "continueCursor" a previous list result reported — continues ' + + 'that same list on its next page. Only for action="list"; ignored ' + + 'on search.', }, }, - ['query'], + ['action'], ); const RAG_FETCH_SCHEMA = object( @@ -347,27 +416,34 @@ const ASK_QUESTION_SCHEMA = object( * {@link CHAT_TOOL_DOCS} instead, so the two surfaces never compete. */ const CHAT_TOOL_DESCRIPTIONS: Record = { rag_search: - "Search the organization's own knowledge AND its work: uploaded " + + "Search or list the organization's own knowledge AND its work: uploaded " + 'documents, knowledge entries, crawled website pages, products, ' + - 'contacts, plus its tasks and projects. This is how you answer ' + - 'questions about the board — what is open, what someone is working on, ' + - 'what a project contains. Never suggest an external task tracker; this ' + - 'organization runs its work here. Call it when the answer needs the ' + - "organization's own material and the conversation does not already " + - 'contain it — not for general knowledge, definitions, or reasoning ' + - 'about what the user wrote. Pass "status" to filter tasks ("open" means ' + - 'not done and not cancelled). A question about the board needs no ' + - 'matching words: when nothing matches the wording, the tasks and projects ' + - 'sources LIST what is in scope instead, and say so — so ask "open tasks" ' + - 'once and read the list rather than rewording the query. Results come ' + - 'back ranked; "score" orders ' + - 'hits within one response only. Document, web-page and task rows carry ' + - 'a "ref" for rag_fetch (documents and pages also carry the match\'s ' + - 'character "offset"); contact, product, knowledge-entry, website and ' + - 'project rows carry their content inline and cannot be fetched. Ignore ' + - 'rows that do not answer the question. When a search comes back empty ' + - 'or unhelpful, do not re-run reworded variants — answer from what you ' + - "have, or use web_fetch when a public page's URL is known.", + 'contacts, websites, tasks and projects, and inbox conversations. Two ' + + 'actions. action="search" retrieves by meaning or keywords: pass ' + + '"query" as a short information need — a question or noun phrase with ' + + 'distinctive terms ("refund policy", "login review task") — never the ' + + 'user\'s whole message; put board state in "status", not in the query. ' + + 'action="list" browses ONE kind with filters and no text match — use it ' + + 'when the user asks to see, list, or browse a set of things ("list the ' + + 'tasks in review", "show our contacts"): pass "kind", and for ' + + 'kind="task" also "status" or "projectId" (a whole-workspace task dump ' + + 'is refused). One named item is a search, not a list; a bare state ' + + 'question ("what is open?") is a task list with that "status". This is ' + + 'how you answer questions about the board — what is open, who is ' + + 'working on what, what a project contains; never suggest an external ' + + 'task tracker. It is not for general knowledge, definitions, or ' + + 'reasoning about what the user wrote — call it only when the answer ' + + "needs the organization's material and the conversation does not " + + 'already contain it. "score" orders hits within one response only. ' + + 'Document, web-page and task rows carry a "ref" for rag_fetch; contact, ' + + 'product, knowledge-entry, website and project rows carry their content ' + + 'inline and cannot be fetched. Never present one page of a list as the ' + + 'whole set: when "hasMore" is true, pass the "continueCursor" back as ' + + '"cursor", or say which part you saw. Ignore rows that do not answer ' + + 'the question. When a search comes back empty or unhelpful, do not ' + + 're-run reworded variants — switch to action="list" for browse ' + + 'questions, answer from what you have, or use web_fetch when a public ' + + "page's URL is known.", rag_fetch: 'Load the full detail behind a "ref": a document file id (from a ' + 'rag_search hit or the attached-documents list), a crawled website page ' + @@ -448,8 +524,8 @@ export const CHAT_TOOL_DOCS: readonly ToolDoc[] = [ { id: 'rag_search', description: - "search the organization's knowledge and work (documents, entries, " + - 'crawled pages, products, contacts, tasks, projects)', + "search or list the organization's knowledge and work (documents, " + + 'entries, pages, products, contacts, tasks, projects)', }, { id: 'rag_fetch', diff --git a/services/platform/messages/de.yml b/services/platform/messages/de.yml index fb0f05bc53..a129df75f5 100644 --- a/services/platform/messages/de.yml +++ b/services/platform/messages/de.yml @@ -1398,6 +1398,16 @@ chat: searchingKnowledgeBase: Durchsucht den Workspace nach "{query}" readingDocument: Liest {name} readingTask: Liest Aufgabe {name} + listing: + generic: Listet den Workspace auf + tasks: Listet Aufgaben auf + projects: Listet Projekte auf + contacts: Listet Kontakte auf + products: Listet Produkte auf + documents: Listet Dokumente auf + websites: Listet Websites auf + knowledgeEntries: Listet Wissenseinträge auf + conversations: Listet Konversationen auf seconds: '{seconds}s' summaryReasoningOnly: Hat den Gedankengang gezeigt sources: diff --git a/services/platform/messages/en.yml b/services/platform/messages/en.yml index 753572e13a..55d00ae5b7 100644 --- a/services/platform/messages/en.yml +++ b/services/platform/messages/en.yml @@ -1355,6 +1355,16 @@ chat: searchingKnowledgeBase: Searching the workspace for "{query}" readingDocument: Reading {name} readingTask: Reading task {name} + listing: + generic: Listing the workspace + tasks: Listing tasks + projects: Listing projects + contacts: Listing contacts + products: Listing products + documents: Listing documents + websites: Listing websites + knowledgeEntries: Listing knowledge entries + conversations: Listing conversations seconds: '{seconds}s' summaryReasoningOnly: Showed its reasoning sources: diff --git a/services/platform/messages/fr.yml b/services/platform/messages/fr.yml index ce99b748b8..ad2d40b3b1 100644 --- a/services/platform/messages/fr.yml +++ b/services/platform/messages/fr.yml @@ -1406,6 +1406,16 @@ chat: searchingKnowledgeBase: Recherche de "{query}" dans l'espace de travail readingDocument: Lecture de {name} readingTask: Lecture de la tâche {name} + listing: + generic: Liste de l'espace de travail + tasks: Liste des tâches + projects: Liste des projets + contacts: Liste des contacts + products: Liste des produits + documents: Liste des documents + websites: Liste des sites web + knowledgeEntries: Liste des entrées de connaissances + conversations: Liste des conversations seconds: '{seconds}s' summaryReasoningOnly: A montré son raisonnement sources: