Repository navigation
feat(platform): index inbound email bodies for chat retrieval - #3530
Merged
Merged
Conversation
An email's body reached no index: the covering note that explains an attachment (the role an applicant names, the order a complaint is about) was invisible to every retrieval leg. Inbound email bodies now index under a message ref and answer the chat assistant, behind the same assignment privacy as an emailed attachment. - lib/knowledge/message-ref.ts: encoder and parser (`msg:<message id>`), the LIKE pattern, and the one definition of what the corpus holds: inbound `email` messages (`isIndexedMessage`). - Ingest: `addMessageToConversation` queues `rag.index_message` in the insert's own transaction for a non-empty inbound email; the job reads an HTML body down to text (html-to-text), heads its chunks with subject and sender, stamps the conversation id, runs the secret scan and PII policy, and ends quietly on refusals no retry changes. Its own queue, so a mailbox backlog never stands in front of an upload. - Gate: the `msg:` deny becomes a branch decided by the message's conversation (`conversationAssignmentAllows`, a live lifecycle, not spam), resolved with the attachments' conversations in one read, and only for a door that asks (`includeConversationMessages`: the chat tools). The corpus pre-filter excludes message rows for every other door, so the sandbox bridge, the MCP door and REST never see a body they do not wrap. - Chat: a body hit is a `conversation` row citing its conversation, its passage wrapped as mail; `rag_fetch` reads the whole body under the inbox role. The timeline never shows a raw `msg:` id, and no source card offers a file preview for one. - Dedup: an email body never clones another row's chunks and nothing clones from one (the header names a correspondent another reader may not see). - Cascade: liveness is the inbound message row; `deleteConversation` queues the release of its bodies, the retention window releases them before it purges (a failed release keeps the conversation), and the corpus reconcile walks message refs apart from blob refs from a random pivot. - Real-Postgres proof: the `checkInboundEmailBodies` integration lane. - Docs (EN/DE/FR), manual boxes CHAT-F49/CHAT-B16, the automation register and the knowledge ledger's stale PENDING notes (queue-on-bind landed in #3225). Refs #3015
prepareDocument ran the organization's PII policy over the body alone, then prepended the header (title or filename) to every chunk unscrubbed. An email body's header names its sender, so under a mask policy the address was still embedded, stored in chunk_content, keyword-indexed and kept as documents.filename; under block, PII in the header never refused the document. The header and the stored name now go through the same decision as the text, for every lane: mask masks both, block refuses when either matches. A header the policy rewrote joins the content hash, so a policy switched on re-indexes a body it found nothing in; an untouched header leaves every stored hash where it was.
A chat caller who reads the inbox asked the corpus for email bodies, and the SQL pre-filter admitted every body org-wide in the same candidate pool as the documents; assignment privacy was decided only afterwards by the admission re-check. In a shared inbox, where an unassigned conversation is admin triage, a member's query filled each leg's pool with bodies the re-check then refused, and a document they could read ranked just behind them never came back. The documents reader now searches bodies as a partition of their own, each leg with its own candidate pool, and merges the two lists by the leg's score without cutting either: a refused body can only displace another body. A conversation narrow searches bodies alone (onlyEmailBodies), and one the role cannot read runs no embedding and no query at all.
Which email bodies the corpus holds, and how each lane lets them go: - Only mail a connector delivered indexes (connector_name). A member logging a message by hand may say isCustomer and bring its own from and subject, and must never index as a customer's mail. - A spam verdict releases a conversation's bodies (liveness reads a spam conversation's messages as dead) and lifting it queues them for indexing again, from the PATCH door and the bulk verb alike. Mail that lands on a conversation already marked spam is never queued, and the indexer skips it, so junk is never sent to the embedding provider. - The retention window queues the release in the transaction that deletes the conversations, as deleteConversation does, instead of releasing synchronously and stranding the conversation when the knowledge database cannot be reached. The job runs after the commit, so a body a late job indexed is released too. - The indexer's secret scan reads the chunk header with the body, and a test proves the organization's PII policy reaches it. The reads live in domains/conversations/message-corpus.ts; the integration lane now proves the PII mask on the header, chunks and stored name, and the spam release and re-index, on real Postgres.
Inbound email indexing waits for the organization's embedding limiter beside file batches in arrival order: its own pg-boss queue keeps a mailbox backlog out of rag.index_file, not out of the limiter. The data-residency page (EN/DE/FR) now names it among the work sharing maxConcurrentRequests, and the enqueue and queue comments say where the order holds and why email gets no lower limiter priority. The knowledge ledger says a mailbox connected after this change indexes the history its first sync imports, and records the connector marker, the spam release and the queued retention release; CHAT-B16 and the automation register follow.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
An inbound email's body now reaches the knowledge corpus. The chat assistant can find the covering note that explains an attachment (the role an applicant names, the order a complaint is about), under the same assignment privacy an emailed attachment has.
The two open questions
rag_fetchversus citing the conversation: both, on one row. A body hit comes back as aconversationrow. It cites its conversation by subject, carries the matched passage (wrapped as untrusted mail) and amsg:ref thatrag_fetchreads the whole email by, behind the same gate. Conversation rows today carry no body and no ref, and a long email spans chunks, so citing alone would leave the rest unreadable. Fetching adds no admission surface.direction = inboundandchannel = emailmessages a connector delivered (connector_name) are indexed. Outbound mail is our own text (mostly acknowledgement) and member-authored, and the member erasure lane reaches no conversation; for the same reason a message a member logs by hand (POST /conversations/:id/messages, even withisCustomer: true) is never indexed. API-mirrored conversations (channel: api) stay out too.What changed
Refs:
lib/knowledge/message-ref.tsgains an encoder and parser (msg:<message id>), theLIKEpattern, and the one definition of which messages the corpus holds (isIndexedMessage).Ingest:
addMessageToConversationqueuesrag.index_messagein the insert's own transaction for a non-empty inbound email a connector delivered, unless its conversation is already marked spam. The job (domains/knowledge/message-index.ts):lib/knowledge/html-to-text.ts;prepareDocumentnow does this for every lane:maskmasks both,blockrefuses when either matches;It has its own queue, so a mailbox backlog never stands in front of an upload in
rag.index_file; past the queues, both wait for the organization's embedding limiter in arrival order (the data-residency docs now say so).Gate: the
msg:deny infilterRetrievableRagFileIdsbecomes a branch decided by the message's conversation:conversationAssignmentAllows, a live lifecycle, and not spam. It is resolved together with the attachments' conversations in one read. It admits only for a door that asks (includeConversationMessages), and only the chat tools ask. The corpus pre-filter excludes message rows for every other door (REST, the MCPget_knowledgedoor, the sandbox bridge, org-wide callers), since none of them wraps mail as untrusted. For the door that asks, bodies are searched as a partition with a candidate pool of their own and merged by the leg's score, so bodies a member may not read (an unassigned inbox is admin triage) never push a document out of the page.Chat:
rag_searchmaps a body hit toconversation(aconversationnarrow searches bodies alone, and runs no search at all for a role that cannot read the inbox).rag_fetchreads an email ref under the inbox's role. The fetch result is notkind: document, so no source card offers a file preview. The timeline shows the subject, never a rawmsg:id. The tool descriptions tell the model all of this.Dedup: an email body never clones another row's chunks, and nothing clones from one. A clone copies the source's header, and a body's header names a correspondent that the reader of the copy may have no right to see.
Delete and erasure cascade: liveness is the inbound message row (
assessMessageRefLiveness).deleteConversationqueuesknowledge.release_refsfor its bodies in its own transaction.msg:sorts befores3:, so a shared bounded walk would have starved the blob refs.Docs and registers: the chat docs line (EN/DE/FR), manual boxes
CHAT-F49andCHAT-B16, the automation register, a conversations README pointer, and the knowledge ledger's stale PENDING notes (queue-on-bind landed in fix(platform): close conversation send, dedupe and scoping gaps #3225).How I verified it
serverandpiiprojects pass (830 files, 77,598 tests), and the 35 chat UI files (461 tests) passed on the rebased tree. New suites cover:backend:integrationlane,checkInboundEmailBodies(domains/knowledge/message-index.integration.ts). It covers mailbox ingest → one job (the reply is never queued) → the live worker indexes the body with its conversation stamped → found by the admin, refused to a plain member, to a door that did not ask, and to an org-wide caller → a mask PII policy keeps the sender's address out of the header, the chunks and the stored name → a spam verdict releases the rows and lifting it indexes them again → delete releases its corpus rows. After the review fixes it ran on a throwaway ParadeDB (tale-db image) with a throwaway MinIO, together withcheckFiles,checkDocuments,checkProviderCredentials,checkKnowledge(its file PII block/mask probes included),checkCorpusScopeReconcile,checkCorpusPurgeConsistency,checkIndexingReleaseRace,checkEmbeddingCredentialRefusal,checkChat,checkRetentionAuditTrailandcheckConversationRouting: 96/96 checks passed.oidcOrganizationClaimsinauth/oidc.ts, predates this). Opengrep: 0 findings.lint:manual,check-guideonchat.mdand the docs suite pass.tsc(CI runs them), the fullbackend:integration(needs S3), and the chat UI in a browser (no running stack; the docs line and the manual boxes are grounded in code and tests).Worth a look, not in this PR
indexUploadedFilenever passesconversation_id(0.4'sindexFileBlobdid), nor feat(platform): give an emailed attachment its mail's context #3014's mail-context title. So chat labels an attachment hitdocumentand does not wrap it (fix(platform): treat email content as untrusted #3082 regressed in the port), and themail-attachmentnarrow can never match. This is a separate fix.Closes #3015