Skip to content

feat(platform): index inbound email bodies for chat retrieval - #3530

Merged
yannickmonney merged 6 commits into
mainfrom
feat/index-inbound-email-bodies
Sep 27, 2026
Merged

yannickmonney merged 6 commits into
mainfrom
feat/index-inbound-email-bodies

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

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

  1. rag_fetch versus citing the conversation: both, on one row. A body hit comes back as a conversation row. It cites its conversation by subject, carries the matched passage (wrapped as untrusted mail) and a msg: ref that rag_fetch reads 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.
  2. Inbound only: yes. Only direction = inbound and channel = email messages 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 with isCustomer: true) is never indexed. API-mirrored conversations (channel: api) stay out too.

What changed

  • Refs: lib/knowledge/message-ref.ts gains an encoder and parser (msg:<message id>), the LIKE pattern, and the one definition of which messages the corpus holds (isIndexedMessage).

  • Ingest: addMessageToConversation queues rag.index_message in 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):

    • reads an HTML body down to text with lib/knowledge/html-to-text.ts;
    • heads its chunks with the subject and sender;
    • stamps the conversation id;
    • runs the secret scan and the PII policy over the chunk header (subject and sender) and the stored name as well as the body — prepareDocument now does this for every lane: mask masks both, block refuses when either matches;
    • ends quietly on refusals no retry changes, such as no embedding model.

    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 in filterRetrievableRagFileIds becomes 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 MCP get_knowledge door, 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_search maps a body hit to conversation (a conversation narrow searches bodies alone, and runs no search at all for a role that cannot read the inbox). rag_fetch reads an email ref under the inbox's role. The fetch result is not kind: document, so no source card offers a file preview. The timeline shows the subject, never a raw msg: 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).

    • deleteConversation queues knowledge.release_refs for its bodies in its own transaction.
    • The retention window queues the same release in the transaction that deletes the conversations, so an unreachable knowledge database never holds the window back, and a body a late job indexed is released too.
    • A spam verdict (PATCH or bulk) releases the conversation's bodies — liveness reads a spam conversation's messages as dead — and lifting it queues them for indexing again.
    • The corpus reconcile walks message refs apart from blob refs, from a random pivot. msg: sorts before s3:, so a shared bounded walk would have starved the blob refs.
  • Docs and registers: the chat docs line (EN/DE/FR), manual boxes CHAT-F49 and CHAT-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

  • Unit: the whole server and pii projects pass (830 files, 77,598 tests), and the 35 chat UI files (461 tests) passed on the rebased tree. New suites cover:
    • the ref and body helpers and the pure gate decision;
    • the gate's plumbing and the index job;
    • ingest and delete enqueueing, release and reconcile, and the retention purge;
    • corpus, fetch, search and document-text scoping;
    • dedup, the executor, the tool descriptions, the timeline label and the source cards.
  • Real Postgres, in-repo: a new backend:integration lane, 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 with checkFiles, checkDocuments, checkProviderCredentials, checkKnowledge (its file PII block/mask probes included), checkCorpusScopeReconcile, checkCorpusPurgeConsistency, checkIndexingReleaseRace, checkEmbeddingCredentialRefusal, checkChat, checkRetentionAuditTrail and checkConversationRouting: 96/96 checks passed.
  • Gates: oxlint (type-aware) and a type-check scoped to the changed files and their imports are clean. Knip for the platform workspace reports nothing new (its one finding, oidcOrganizationClaims in auth/oidc.ts, predates this). Opengrep: 0 findings. lint:manual, check-guide on chat.md and the docs suite pass.
  • Not run here: the whole-platform suite and a workspace-wide tsc (CI runs them), the full backend: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

  • Emailed attachments are not conversation-stamped in 0.5. indexUploadedFile never passes conversation_id (0.4's indexFileBlob did), nor feat(platform): give an emailed attachment its mail's context #3014's mail-context title. So chat labels an attachment hit document and does not wrap it (fix(platform): treat email content as untrusted #3082 regressed in the port), and the mail-attachment narrow can never match. This is a separate fix.
  • Other doors: email bodies reach only the chat tools. Serving them over MCP or to sandbox agents needs mail wrapping at those doors first.
  • No backfill: mail stored before this change, or before an embedding model was configured, is not indexed; it is still found by the conversation leg's keyword walk. A mailbox connected after this change indexes the history its first sync imports (one job per email, bounded by the queue's batch and the embedding limiter).
  • Pre-existing blob reconcile walk: it restarts at its keyset head every run (500 refs per org), so refs behind a long run of live ones are never reconciled. Left unchanged.

Closes #3015

yannickmonney and others added 6 commits September 27, 2026 17:20
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.
@yannickmonney
yannickmonney merged commit 164577e into main Sep 27, 2026
57 checks passed
@yannickmonney
yannickmonney deleted the feat/index-inbound-email-bodies branch September 27, 2026 21:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: an email's body is searchable nowhere

1 participant