Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

fix(integrations): put an email that got no reply in Needs you (#479)

Rufus4b6ede6bd942
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index a8c982ff..177fd7ba 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -87,6 +87,7 @@ system:
- Voice follows the account. Text written as a person leaves only from that person's own Gmail (always as a draft first, sent only when they send it in Gmail or tap Send on its card); the Executive's own mailbox and bots always sign as the Executive.
- The model cannot reach a delegated mailbox. delegation.gmail.DelegateGmail talks to the Gmail REST API directly and is never registered with the MCP gateway, so only typed handlers (ghostwrite_email, the voice learner) call it, and its credential never lives in WORKSPACE_MCP_CREDENTIALS_DIR. Every google_workspace__* call through the gateway acts as the Executive's own account (mcp_gateway._check_acting_account refuses any other user_google_email).
- A teammate's own mail with the Executive is private to them. Every mailbox call the model makes through the MCP gateway (call_tool, a script's calls, a workflow step run from chat) passes through orchestrator.teammate_mail.guard_call_tool. Searches exclude every other teammate's address unless the reader is on the message too, except on a background run (Gmail query -from/-to/-cc OR'd with the reader's from/to/cc, headers forced on; Outlook lists always select the parties) and are filtered entry by entry; any other call naming a message or thread must use an id a filtered search returned to the same reader in this conversation (Session.mail_ids_seen, keyed by reader) or the inbound email the turn answers (email_poller seeds it); an Outlook call acting on a message (forward, reply, attachment) first reads its parties and is refused when it is another teammate's; a conversation where a non-principal teammate was shown their own mail is marked mail-private (session_store.mark_mail_private); Gmail thread/batch/search/attachment results are redacted in the audit log; reads are filtered message by message (a message naming another teammate is left out unless the reader is in its From / To / Cc); a Gmail reply with quote_original into a thread holding such a message is refused; Outlook search tools are refused. The reader is the principal or a teammate on a verified surface, or the teammate whose own email the turn answers when Gmail authenticated its From (Session.email_sender_authenticated); anyone else sees no teammate's mail. A background run the model drives (schedule_followup, reflection) reads as the principal; a workflow step outside any session reads as nobody (filters on, id gate off). Outlook mail rules / mailbox settings that forward or name another teammate are refused. The first turn that shows a non-principal teammate their own mail also marks that turn's remaining audit rows (its answer included) private to them. Internal callers (poller, brief) are unaffected. Fails closed when the roster can't be read.
+ - An email from the team or the principal that got no reply becomes a Needs you card, with no model in the loop. The MCP gateway marks on the conversation who each accepted send reached (Session.mail_sent_to for Gmail send_gmail_message to/cc and Outlook send-mail recipients; Session.mail_replied_ids for the message an Outlook reply-mail-message / reply-all-mail-message answered). After the turn, email_poller._note_reply_outcome checks the sender's addresses and the message id; with no reply it files integrations.unanswered_mail's card (source unanswered_email, high, private:principal, routed to the principal), one per thread with repeats folded into its occurrence count, resolved by a later turn that replies. Only mail Gmail proved is the principal's (Session.email_authenticated) carries its subject and what the Executive wrote; a teammate's card names who is waiting, never their subject or text; mail only claiming a team address says it could not be proven. A plain-text Error tool result is not counted as a send. Contacts and senders off the team are skipped. Why — Needs you shows alerts only, alerts depended on the model calling create_alert, and turns that ended without a send (a refused tool, an answer only written) left the sender waiting while only the brief, which reads the inbound log, said so.
- A teammate's own conversations with the Executive are private to them too. Every audit row of a turn a non-principal team member speaks on a verified surface, or by email Gmail authenticated as theirs, carries private_to_person (people_tools.teammate_turn_owner via audit_row_owner; the pre-bind rows via rows_for_person in audit_rows_on_senders_turn, the web chat route and the email poller). An unproven sender keeps the ordinary rule so a forged From can't hide a turn from the principal. The /audit read routes give the principal every row, a team member's own (their turns, Act as me, history notes) as an action only (api.routes.audit._redact: rebuilt summary naming the tool and whose conversation, safe details only, no full payload, left out of text search), and anyone else (once a principal exists) only their own rows in full (api.routes.audit._view, AuditLogger only_owned / all_owners); /audit/usage is unchanged. A teammate's web chat or DM (not a channel or group session, chat._shared_space) opens for its owner alone, the principal included (chat._session_access). A message the Executive sends to someone else on a teammate's turn is linked without its originating session, so the recipient's reply is not hydrated with an excerpt of the teammate's chat (schedule_tools._record_outbound_context).
- The Executive never offers to loop in, DM, or notify the human it is currently talking to. Each chat turn carries a <current_speaker> hint in the user turn (resolved from the caller's person_id, principal-flagged) and the persona "Choosing Who to Tell" rule forbids routing to anyone already in the room — so the principal reading a brief is never told the Executive will "loop Jordan in."
- Specialists run in parallel via route_parallel() for cross-domain questions.
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index 1ea6e241..86339560 100644
--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json
+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json
@@ -1,7 +1,7 @@
{
"section_id": "integrations",
"title": "Integrations",
- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. Responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it. It does look its sender up on People by the Google account email on the signed event, but hands that entry only to the department gate (`Session.gate_sender_person_id`): the principal's own sends and edits go, a teammate's meet their department's authority, and anyone else's wait for approval. It is never `caller_person_id`, so it grants nothing else.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The poller handles one message at a time, so each Executive turn on an email has a deadline, `EMAIL_TURN_TIMEOUT_S` (300 s): past it the turn is cut off, an `integration_inbound` row with outcome `turn_timeout` records it, and the message is marked read and not run again (it may already have replied). A message whose handling keeps raising is given up after three tries in a run and marked read, rather than retried every poll. Each gateway call it makes is bounded by `MCP_TOOL_TIMEOUT_S` (see Lifecycle). The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\n **Other mail sources** (`integrations.mail_sources`). Mail read from anywhere but the Executive's own mailbox (a hosted inbound address, a relay) follows the same rules through a vendor-neutral hook. Nothing is registered by default and the hook has no settings: a deployment registers a `MailSource` (its loop, an `enabled` check, and how to replay a held message), the lifespan starts the enabled ones, and each message goes to `handle_inbound` as an `InboundMail`: the parsed message, the address it came to, `prove_sender` (DMARC, or SPF and DKIM aligned, as the source can tell), `send_answer`, an optional attachment reader and what a held message keeps. `handle_inbound` runs the poller's own handling (`email_poller._handle_mail`): sender resolution, private-to-principal rows, the teammate's own rows only when proven, untrusted-content wrapping, the principal's proven mail, the forwarded-by-principal framing, hydration and the turn deadline. Because a source mails the answer itself (with the AI line, and an `integration_outbound` row) rather than the model calling a send tool, three things differ: a stranger is held for the principal silently, with no acknowledgement and no turn, and replayed through the source that read it (`replay_held_mail` dispatches on the payload's `mail_source`); a contact's mail, and mail claiming a teammate that nothing proves, is answered to the principal and never to the sender; and roster-request and fact confirmations are answered only from the mailbox they were sent from. A source must be registered to be handled, it does nothing while the Executive is paused (`handle_inbound` returns `PAUSED` and the source keeps the message), a stranger the request queue won't take is logged as not held, and a sender who is neither team nor contact by the time the turn runs gets no answer at all.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.session_title.generate_session_title` (the first words of the message if that fails), as a web chat's first turn does. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected. Once the guard allows a send, the handlers apply the recipient's own notification settings to the Executive's own (tagged) outreach: in their quiet hours, or when they chose *In my briefs*, the DM is stored and returned as `{\"status\":\"held\"}` rather than sent, and goes when quiet hours end or with their next brief (`outbound_guard.check_hold`; see Org).\n\n### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.",
+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. Responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it. It does look its sender up on People by the Google account email on the signed event, but hands that entry only to the department gate (`Session.gate_sender_person_id`): the principal's own sends and edits go, a teammate's meet their department's authority, and anyone else's wait for approval. It is never `caller_person_id`, so it grants nothing else.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The poller handles one message at a time, so each Executive turn on an email has a deadline, `EMAIL_TURN_TIMEOUT_S` (300 s): past it the turn is cut off, an `integration_inbound` row with outcome `turn_timeout` records it, and the message is marked read and not run again (it may already have replied). A message whose handling keeps raising is given up after three tries in a run and marked read, rather than retried every poll. Each gateway call it makes is bounded by `MCP_TOOL_TIMEOUT_S` (see Lifecycle). The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\n **An email that got no reply goes to Needs you.** Mail from the team or the principal is answered by the model calling the mailbox's send tool, so a turn can end with nothing sent (a tool refused, the answer only written). The gateway marks on the conversation who each accepted send reached (`Session.mail_sent_to`: Gmail `send_gmail_message` to/cc, Outlook `send-mail` recipients; `mail_replied_ids`: the message an Outlook `reply-mail-message` / `reply-all-mail-message` answered). After the turn the poller (`_note_reply_outcome`) checks the sender, by any of their addresses, or the message id; with no reply it files a card through `integrations.unanswered_mail` (source `unanswered_email`, high, tagged `private:principal` and routed to the principal, so only their own /today shows it), whatever the model did. Repeats in the thread fold into it (one card per thread, occurrence count), and a later turn that does reply resolves it. Only mail Gmail proved is the principal's (`Session.email_authenticated`) reads \"Your email got no reply\" with its subject and what the Executive wrote, which never reached them; a teammate's card names who is waiting and never their subject or text (their conversation is theirs alone); mail that only claims a teammate's or the principal's address says it could not be proven and carries nothing the sender wrote. A plain-text `Error …` tool result is not counted as a send. Contacts and senders off the team are not answered by design and keep their own paths. Why: the brief read the inbound log and said people were waiting while Needs you, which shows alerts only, stayed empty, since an alert depended on the model choosing `create_alert`.\n\n **Other mail sources** (`integrations.mail_sources`). Mail read from anywhere but the Executive's own mailbox (a hosted inbound address, a relay) follows the same rules through a vendor-neutral hook. Nothing is registered by default and the hook has no settings: a deployment registers a `MailSource` (its loop, an `enabled` check, and how to replay a held message), the lifespan starts the enabled ones, and each message goes to `handle_inbound` as an `InboundMail`: the parsed message, the address it came to, `prove_sender` (DMARC, or SPF and DKIM aligned, as the source can tell), `send_answer`, an optional attachment reader and what a held message keeps. `handle_inbound` runs the poller's own handling (`email_poller._handle_mail`): sender resolution, private-to-principal rows, the teammate's own rows only when proven, untrusted-content wrapping, the principal's proven mail, the forwarded-by-principal framing, hydration and the turn deadline. Because a source mails the answer itself (with the AI line, and an `integration_outbound` row) rather than the model calling a send tool, three things differ: a stranger is held for the principal silently, with no acknowledgement and no turn, and replayed through the source that read it (`replay_held_mail` dispatches on the payload's `mail_source`); a contact's mail, and mail claiming a teammate that nothing proves, is answered to the principal and never to the sender; and roster-request and fact confirmations are answered only from the mailbox they were sent from. A source must be registered to be handled, it does nothing while the Executive is paused (`handle_inbound` returns `PAUSED` and the source keeps the message), a stranger the request queue won't take is logged as not held, and a sender who is neither team nor contact by the time the turn runs gets no answer at all.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.session_title.generate_session_title` (the first words of the message if that fails), as a web chat's first turn does. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected. Once the guard allows a send, the handlers apply the recipient's own notification settings to the Executive's own (tagged) outreach: in their quiet hours, or when they chose *In my briefs*, the DM is stored and returned as `{\"status\":\"held\"}` rather than sent, and goes when quiet hours end or with their next brief (`outbound_guard.check_hold`; see Org).\n\n### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.",
"mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop\"]\n Hold[\"roster request<br/>(hold + fixed ack,<br/>ask the principal)\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n GW[\"Google Workspace<br/>(workspace-mcp child)\"]\n M365[\"Microsoft 365<br/>(ms-365-mcp-server child:<br/>Outlook + OneDrive)\"]\n WP[\"workspace providers<br/>(poller / alerts / booking)\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Hold\n Hold -- \"approved: replay\" --> Exec\n Hold -- \"contact / declined\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n MCP -- \"roster egress gate\" --> GW\n MCP -- \"roster egress gate\" --> M365\n WP -- \"EMAIL_PROVIDER / CALENDAR_PROVIDER\" --> MCP\n WP --> Exec\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n Own[(\"Principal's own Gmail<br/>(Act as me: REST, drafts only)\")]\n Exec -- \"ghostwrite_email\" --> Own\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Hold compute\n class Exec hot\n class Attach compute\n class MCP external\n class GW external\n class M365 external\n class WP compute\n class Guard compute\n class Out compute\n class Own external",
- "generated_at": "2026-10-14T14:19:00Z"
+ "generated_at": "2026-10-14T20:30:00Z"
}
diff --git a/packages/core/openexecutive/integrations/email_poller.py b/packages/core/openexecutive/integrations/email_poller.py
index 09c9d6d9..e647b2e9 100644
--- a/packages/core/openexecutive/integrations/email_poller.py
+++ b/packages/core/openexecutive/integrations/email_poller.py
@@ -1391,10 +1391,61 @@ async def _run_executive(
raise EmailTurnTimeout(timeout_s) from exc
raise
if source is None:
+ _note_reply_outcome(session, person, raw_email, message_id, thread_id, from_addr, response)
return None
return await _send_answer(source, response, answer_to, session_id or session.session_id)
+def _note_reply_outcome(
+ session: Any,
+ person: Any,
+ raw_email: str,
+ message_id: str,
+ thread_id: str,
+ from_addr: str,
+ response: Any,
+) -> None:
+ """After a mailbox email's turn: a card in Needs you when its sender, the
+ principal or a teammate, got no reply, and the thread's card resolved
+ when they did (``integrations.unanswered_mail``). Senders off the team
+ are not answered by design, and have their own paths (a roster request,
+ the contact notice). Never raises."""
+ from openexecutive.integrations import unanswered_mail
+
+ sender = from_addr.strip().lower()
+ if person is None or not sender:
+ return
+ thread_key = thread_id or sender
+ try:
+ addresses = {sender, *(a.strip().lower() for a in [person.email, *person.email_aliases] if a)}
+ if addresses & session.mail_sent_to or (message_id and message_id in session.mail_replied_ids):
+ unanswered_mail.close_card(thread_key)
+ return
+ # Only mail Gmail proved is the principal's carries its subject and
+ # what the Executive wrote: a forged From must not put the model's
+ # answer to it on Home as "your email". A teammate's card never
+ # carries either: their own conversation is theirs alone, and an
+ # unproven one's subject is whatever the sender typed.
+ from_principal = getattr(person, "is_principal", False) is True and session.email_authenticated
+ verified = from_principal or session.email_sender_authenticated is True
+ subject = ""
+ if from_principal:
+ header, _body, _attachments = _split_gmail_content(raw_email)
+ line = next((ln for ln in header if ln.lower().startswith("subject:")), "")
+ subject = line[len("subject:"):].strip()
+ unanswered_mail.file_card(
+ thread_key=thread_key,
+ message_id=message_id,
+ sender_name=str(getattr(person, "full_name", "") or from_addr),
+ from_principal=from_principal,
+ verified=verified,
+ subject=subject,
+ answer=response if from_principal and isinstance(response, str) else "",
+ )
+ except Exception:
+ logger.exception("email: could not note whether message=%s got its reply", message_id)
+
+
async def _send_answer(source: InboundMail, response: Any, to: str, session_id: str) -> str:
"""Mail a source's turn answer to ``to``, with the AI line, and audit it."""
from openexecutive.audit import log_event as audit_log
diff --git a/packages/core/openexecutive/integrations/unanswered_mail.py b/packages/core/openexecutive/integrations/unanswered_mail.py
new file mode 100644
index 00000000..f2c15a2a
--- /dev/null
+++ b/packages/core/openexecutive/integrations/unanswered_mail.py
@@ -0,0 +1,137 @@
+"""A card in Needs you when an email to the Executive got no reply.
+
+Mail from the team, or from the principal, reaches the Executive's mailbox
+and is answered by the model calling the mailbox's send tool. When the turn
+ends without that send (a tool refused, the model only wrote its answer, a
+reply that went to someone else), nobody heard: the sender waits, the
+morning brief and the Home header read the inbound row and say they are
+waiting, and Needs you, which shows alerts only, stays empty. Nothing raised
+one, since an alert depends on the model choosing ``create_alert``.
+
+:func:`file_card` files one card for the principal instead, whatever the
+model did; a repeat in the same thread folds into it (the occurrence count),
+and :func:`close_card` resolves it once a later turn does reply there.
+
+The card is private to the principal (``PRIVATE_ALERT_TAG``, routed to them):
+only their own /today shows it. On their own mail it carries what the
+Executive wrote, which never reached them, but only when the mailbox proved
+the mail is theirs. A teammate's card names only who is waiting: their own
+conversation with the Executive is theirs alone, and an unproven mail's
+text is whoever sent it. An unproven mail says so on its card.
+
+Never raises: a card left unfiled costs the card, never the email.
+"""
+from __future__ import annotations
+
+import logging
+
+logger = logging.getLogger(__name__)
+
+SOURCE = "unanswered_email"
+_ANSWER_MAX = 1500
+_SUBJECT_MAX = 120
+
+
+def _dedup_key(thread_key: str) -> str:
+ # The `private:` prefix keeps it apart from shared cards, as the
+ # pipeline's private alerts are (alerts.pipeline._make_private).
+ return f"private:{SOURCE}:{thread_key.strip().lower()}"
+
+
+def _principal_id() -> int | None:
+ from openexecutive.people.store import find_principal_person
+
+ principal = find_principal_person()
+ return principal.id if principal is not None else None
+
+
+def _one_line(text: str, limit: int) -> str:
+ flat = " ".join(str(text or "").split())
+ return flat if len(flat) <= limit else flat[: limit - 1].rstrip() + "…"
+
+
+def file_card(
+ *,
+ thread_key: str,
+ message_id: str,
+ sender_name: str,
+ from_principal: bool,
+ verified: bool = True,
+ subject: str = "",
+ answer: str = "",
+) -> int | None:
+ """File (or bump) the card for an email whose sender got no reply.
+
+ ``thread_key`` tells repeats apart (the mailbox thread id, else the
+ sender's address). ``from_principal`` only for mail proven to be the
+ principal's; ``subject`` and ``answer`` (what the Executive wrote) are
+ kept only then. ``verified`` False says the mail only claims to be from
+ ``sender_name``. Returns the card's id, or None when nothing was filed."""
+ from openexecutive.alerts import store
+ from openexecutive.alerts.models import PRIVATE_ALERT_TAG
+
+ topic = _one_line(subject, _SUBJECT_MAX)
+ about = f" about “{topic}”" if topic else ""
+ if from_principal:
+ headline = f"Your email got no reply{': ' + topic if topic else ''}"
+ written = answer.strip()
+ if len(written) > _ANSWER_MAX:
+ written = written[: _ANSWER_MAX - 1].rstrip() + "…"
+ body = (
+ f"The Executive worked on your email{about} but its reply never went out."
+ + (f" What it wrote:\n\n{written}" if written else "")
+ )
+ action = "Read what it wrote, or ask it again."
+ elif verified:
+ name = _one_line(sender_name, 80) or "A teammate"
+ headline = f"{name} is waiting on a reply"
+ body = (
+ f"{name} emailed the Executive and no reply went out. "
+ f"Reply to {name} yourself, or ask the Executive about it."
+ )
+ action = f"Reply to {name}."
+ else:
+ name = _one_line(sender_name, 80) or "someone on the team"
+ headline = f"An email from {name}'s address got no reply"
+ body = (
+ f"An email from {name}'s address reached the Executive and no reply went out. "
+ "The mailbox could not prove they sent it, so check with them before acting on it."
+ )
+ action = f"Check with {name}."
+ dedup_key = _dedup_key(thread_key)
+ try:
+ hit = store.coalesce_alert(
+ source=SOURCE, dedup_key=dedup_key, severity="high", body=body
+ )
+ if hit is not None:
+ return hit[0]
+ return store.insert_alert(
+ source=SOURCE,
+ external_id=f"message:{message_id}" if message_id else f"thread:{thread_key}",
+ severity="high",
+ headline=headline,
+ body=body,
+ suggested_action=action,
+ topic_tags=["email", PRIVATE_ALERT_TAG],
+ dedup_key=dedup_key,
+ routed_to_person_id=_principal_id(),
+ )
+ except Exception:
+ logger.exception("unanswered_mail: could not file the card for thread %s", thread_key)
+ return None
+
+
+def close_card(thread_key: str) -> None:
+ """Resolve the open card for a thread that has now had its reply."""
+ from openexecutive.alerts import store
+ from openexecutive.alerts.lifecycle import RESOLVED_STATUS
+
+ try:
+ with store._get_conn() as conn:
+ conn.execute(
+ "UPDATE alerts SET status = ? "
+ "WHERE source = ? AND dedup_key = ? AND status = 'unread'",
+ (RESOLVED_STATUS, SOURCE, _dedup_key(thread_key)),
+ )
+ except Exception:
+ logger.exception("unanswered_mail: could not close the card for thread %s", thread_key)
diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.py
index f71edaaa..649938eb 100644
--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py
+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py
@@ -2695,6 +2695,46 @@ def _record_m365_outbound_context(arguments: dict[str, Any]) -> None:
)
+# Outlook replies that answer one message by its id (a draft only waits).
+_M365_SENT_REPLY_TOOLS = frozenset({
+ "microsoft_365__reply_mail_message",
+ "microsoft_365__reply_all_mail_message",
+})
+
+
+def _note_mail_sent(tool_name: str, normalized: str, arguments: dict[str, Any]) -> None:
+ """Mark on the conversation (``Session.mail_sent_to`` /
+ ``mail_replied_ids``) who a send the mailbox accepted went to, so the
+ email poller can tell whether an inbound email got its reply
+ (``integrations.unanswered_mail``). Nothing without a live session, and
+ never raises: the send already happened."""
+ from openexecutive.orchestrator.schedule_tools import current_session
+
+ session = current_session.get()
+ if session is None:
+ return
+ try:
+ if tool_name == "google_workspace__send_gmail_message":
+ for field in _OUTBOUND_CONTEXT_RECIPIENT_FIELDS:
+ value = arguments.get(field)
+ items = value if isinstance(value, list) else [value]
+ for _name, addr in getaddresses([s for s in items if isinstance(s, str)]):
+ if addr.strip():
+ session.mail_sent_to.add(addr.strip().lower())
+ elif normalized == _M365_RECORD_SEND_TOOL:
+ message = _ci_get(_ci_get(arguments, "body"), "message")
+ for key in ("toRecipients", "ccRecipients"):
+ for addr in _m365_recipient_addresses(_ci_get(message, key)):
+ if addr.strip():
+ session.mail_sent_to.add(addr.strip().lower())
+ elif normalized in _M365_SENT_REPLY_TOOLS:
+ message_id = _ci_get(arguments, "messageId")
+ if isinstance(message_id, str) and message_id:
+ session.mail_replied_ids.add(message_id)
+ except Exception:
+ logger.exception("note_mail_sent: could not record the send (non-fatal)")
+
+
# extensible-mcp's refusal for a tool no search in this session has returned
# (DiscoveredToolsFilter, surfaced by its call_tool handler as "Error: ...").
_UNDISCOVERED_MARKER = "has not been discovered via search_tools"
@@ -3229,6 +3269,10 @@ class MCPGateway:
_record_email_outbound_context(arguments)
elif normalized == _M365_RECORD_SEND_TOOL and not _is_error_payload(result_text):
_record_m365_outbound_context(arguments)
+ # A plain-text "Error …" result (FastMCP, extensible-mcp) is no send
+ # either: marking it would hide the unanswered-email card.
+ if not _is_error_payload(result_text) and not result_text.lstrip().lower().startswith("error"):
+ _note_mail_sent(tool_name, normalized, arguments)
if attached_artifacts and not _is_error_payload(result_text):
from openexecutive.audit import log_event as audit_log
diff --git a/packages/core/openexecutive/orchestrator/session.py b/packages/core/openexecutive/orchestrator/session.py
index 9d5fb719..551cec1f 100644
--- a/packages/core/openexecutive/orchestrator/session.py
+++ b/packages/core/openexecutive/orchestrator/session.py
@@ -37,6 +37,13 @@ class Session:
# The model may reach the Executive's mailbox only by these
# (orchestrator.teammate_mail).
mail_ids_seen: set[str] = field(default_factory=set)
+ # Who this conversation's mail actually reached: the lowercased to/cc
+ # addresses of every send the mailbox accepted, and the message ids an
+ # Outlook reply answered. The email poller reads them after an inbound
+ # email's turn to tell whether its sender got a reply
+ # (integrations.unanswered_mail).
+ mail_sent_to: set[str] = field(default_factory=set)
+ mail_replied_ids: set[str] = field(default_factory=set)
# Which inbound channel this session arrived on ("slack", "discord",
# "telegram", "google_chat", "email"), and the address on it. Empty for
# web/CLI turns and runs nobody started from a channel. Used when a
diff --git a/packages/core/tests/unit/test_unanswered_mail.py b/packages/core/tests/unit/test_unanswered_mail.py
new file mode 100644
index 00000000..e7b0b452
--- /dev/null
+++ b/packages/core/tests/unit/test_unanswered_mail.py
@@ -0,0 +1,200 @@
+"""An email to the Executive that got no reply becomes a card in Needs you.
+
+Observed: a teammate emailed the Executive three times in one thread and a
+forward from the principal went unanswered twice. Every turn ended without
+the mailbox's send tool succeeding, and none called ``create_alert``, so the
+brief (which reads the inbound log) said they were waiting while Home's
+Needs you (alerts only) said "Nothing waiting on you".
+
+These cover the three pieces: the gateway marking who a send reached, the
+poller's check after the turn, and the card itself.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from openexecutive.alerts import store as alert_store
+from openexecutive.alerts.models import is_private_alert
+from openexecutive.integrations import email_poller, unanswered_mail
+from openexecutive.orchestrator import mcp_gateway
+from openexecutive.orchestrator.schedule_tools import current_session
+from openexecutive.orchestrator.session import Session
+from openexecutive.people import store as people_store
+
+RAW = "Subject: Re: Ocean Breeze LP\nFrom: [email protected]\n\nWas it bought?"
+
+
[email protected](autouse=True)
+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ db_path = tmp_path / "alerts.db"
+ alert_store.initialize_db(db_path)
+ people_store.initialize_db(db_path)
+ monkeypatch.setattr(alert_store, "DB_PATH", db_path)
+ monkeypatch.setattr(people_store, "DB_PATH", db_path)
+ return db_path
+
+
+def people(db: Path) -> SimpleNamespace:
+ principal_id = people_store.upsert_person(
+ full_name="John Principal", email="[email protected]", is_principal=True
+ )
+ teammate_id = people_store.upsert_person(full_name="Ann Teammate", email="[email protected]")
+ return SimpleNamespace(
+ principal_id=principal_id,
+ principal=people_store.get_person(principal_id),
+ teammate=people_store.get_person(teammate_id),
+ )
+
+
+def _cards(status: str = "unread") -> list[Any]:
+ return [a for a in alert_store.list_alerts(status=status) if a.source == unanswered_mail.SOURCE]
+
+
+def _note(session: Session, person: Any, *, message_id: str = "m1", answer: str = "My answer") -> None:
+ email_poller._note_reply_outcome(
+ session, person, RAW, message_id, "t1", person.email, answer,
+ )
+
+
+def _proven(**kw: Any) -> Session:
+ s = Session(**kw)
+ s.email_sender_authenticated = True
+ return s
+
+
+class TestTheCard:
+ def test_a_teammate_with_no_reply_gets_a_private_card_for_the_principal(
+ self, people: SimpleNamespace
+ ) -> None:
+ _note(_proven(), people.teammate)
+
+ [card] = _cards()
+ assert card.headline == "Ann Teammate is waiting on a reply"
+ assert is_private_alert(card)
+ assert card.routed_to_person_id == people.principal_id
+ # Their conversation is theirs: neither what they asked nor what the
+ # Executive wrote reaches the principal.
+ assert "Ocean Breeze" not in card.body
+ assert "My answer" not in card.body
+
+ def test_a_repeat_in_the_thread_folds_into_one_card(self, people: SimpleNamespace) -> None:
+ _note(_proven(), people.teammate, message_id="m1")
+ _note(_proven(), people.teammate, message_id="m2")
+ _note(_proven(), people.teammate, message_id="m3")
+
+ [card] = _cards()
+ assert card.occurrence_count == 3
+
+ def test_the_principals_proven_mail_carries_what_the_executive_wrote(
+ self, people: SimpleNamespace
+ ) -> None:
+ session = Session()
+ session.email_authenticated = True
+ _note(session, people.principal, answer="Brennan replied on Oct 9.")
+
+ [card] = _cards()
+ assert card.headline == "Your email got no reply: Re: Ocean Breeze LP"
+ assert "Brennan replied on Oct 9." in card.body
+
+ def test_mail_only_claiming_the_principal_never_reads_as_theirs(
+ self, people: SimpleNamespace
+ ) -> None:
+ _note(Session(), people.principal, answer="Click https://evil.example now")
+
+ [card] = _cards()
+ assert card.headline == "An email from John Principal's address got no reply"
+ assert "evil" not in card.body
+ assert "Ocean Breeze" not in card.headline + card.body
+
+ def test_an_unproven_teammate_mail_says_so(self, people: SimpleNamespace) -> None:
+ _note(Session(), people.teammate)
+
+ [card] = _cards()
+ assert card.headline == "An email from Ann Teammate's address got no reply"
+ assert "could not prove" in card.body
+
+
+class TestAReply:
+ def test_a_reply_to_the_sender_files_nothing(self, people: SimpleNamespace) -> None:
+ session = Session()
+ session.mail_sent_to.add("[email protected]")
+ _note(session, people.teammate)
+
+ assert _cards() == []
+
+ def test_a_later_reply_resolves_the_card(self, people: SimpleNamespace) -> None:
+ _note(_proven(), people.teammate, message_id="m1")
+ answered = _proven()
+ answered.mail_sent_to.add("[email protected]")
+ _note(answered, people.teammate, message_id="m2")
+
+ assert _cards() == []
+ assert len(_cards("resolved")) == 1
+
+ def test_an_outlook_reply_by_message_id_counts(self, people: SimpleNamespace) -> None:
+ session = Session()
+ session.mail_replied_ids.add("m1")
+ _note(session, people.teammate, message_id="m1")
+
+ assert _cards() == []
+
+ def test_a_sender_off_the_team_is_left_to_its_own_paths(self, people: SimpleNamespace) -> None:
+ email_poller._note_reply_outcome(Session(), None, RAW, "m1", "t1", "[email protected]", "hi")
+
+ assert _cards() == []
+
+
+class TestTheGatewayMarksWhoASendReached:
+ @pytest.fixture()
+ def session(self) -> Any:
+ s = Session()
+ token = current_session.set(s)
+ yield s
+ current_session.reset(token)
+
+ def test_gmail_to_and_cc(self, session: Session) -> None:
+ mcp_gateway._note_mail_sent(
+ "google_workspace__send_gmail_message",
+ "google_workspace__send_gmail_message",
+ {"to": "Ann <[email protected]>", "cc": ["[email protected]"], "body": "x"},
+ )
+ assert session.mail_sent_to == {"[email protected]", "[email protected]"}
+
+ def test_outlook_send_and_reply(self, session: Session) -> None:
+ mcp_gateway._note_mail_sent(
+ "microsoft_365__send-mail",
+ "microsoft_365__send_mail",
+ {"body": {"Message": {"toRecipients": [{"emailAddress": {"address": "[email protected]"}}]}}},
+ )
+ mcp_gateway._note_mail_sent(
+ "microsoft_365__reply-mail-message",
+ "microsoft_365__reply_mail_message",
+ {"messageId": "AAMk1", "body": {"Comment": "hi"}},
+ )
+ assert session.mail_sent_to == {"[email protected]"}
+ assert session.mail_replied_ids == {"AAMk1"}
+
+ def test_a_draft_marks_nothing(self, session: Session) -> None:
+ mcp_gateway._note_mail_sent(
+ "google_workspace__draft_gmail_message",
+ "google_workspace__draft_gmail_message",
+ {"to": "[email protected]"},
+ )
+ assert session.mail_sent_to == set()
+
+ def test_no_session_is_a_no_op(self) -> None:
+ token = current_session.set(None)
+ try:
+ mcp_gateway._note_mail_sent(
+ "google_workspace__send_gmail_message",
+ "google_workspace__send_gmail_message",
+ {"to": "[email protected]"},
+ )
+ finally:
+ current_session.reset(token)
+