Skip to content

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

docs(integrations): fix setup doc drift (#190)

Rufusd2d4bf39f5c2
diff --git a/.env.example b/.env.example
index 0dcb0627..0eecfe56 100644
--- a/.env.example
+++ b/.env.example
@@ -206,13 +206,18 @@ EMAIL_POLL_INTERVAL_SECONDS=60
# Manage access via the /people UI; no env-var allowlists.
# Telegram integration (optional)
-TELEGRAM_BOT_TOKEN= # from @BotFather — see docs/telegram_setup.md
-TELEGRAM_WEBHOOK_SECRET= # any random string; set when registering the webhook
+# Setup: docs/telegram_setup.md
+TELEGRAM_BOT_TOKEN= # from @BotFather
+# Must equal the secret_token passed to setWebhook, or every update is rejected
+# with 401. 1-256 chars of A-Z a-z 0-9 _ - (e.g. `openssl rand -hex 32`).
+TELEGRAM_WEBHOOK_SECRET=
# Discord integration (optional)
# Setup: create an application at https://discord.com/developers/applications
# Enable the "Message Content" privileged intent. Invite with bot + applications.commands scopes.
-# Run: make discord (in a second shell alongside make dev)
+# Setting DISCORD_BOT_TOKEN starts the bot inside the API — `make dev` brings it
+# up, no separate process. Don't also run `make discord` while the API has the
+# token: two gateway connections on one token answer every message twice.
# Bot token from the Discord Developer Portal → Bot tab
DISCORD_BOT_TOKEN=
# Application ID (General Information tab)
diff --git a/CLAUDE.md b/CLAUDE.md
index d9bc280b..07769da5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -144,7 +144,7 @@ and deploy configuration for a specific environment are kept outside this repo.
## Environment Variables
-See `.env.example`. Required: `ANTHROPIC_API_KEY`. Optional integrations: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN`, `EMAIL_ADDRESS`, `EMAIL_PASSWORD`, `EMAIL_IMAP_HOST`, `EMAIL_SMTP_HOST`.
+See `.env.example`. Required: `ANTHROPIC_API_KEY`, `EXEC_EMAIL_ADDRESS` (no default). Optional integrations: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN`, `TELEGRAM_BOT_TOKEN` + `TELEGRAM_WEBHOOK_SECRET` (`docs/telegram_setup.md`), `DISCORD_BOT_TOKEN` + `DISCORD_APP_ID`, `GOOGLE_CHAT_PROJECT_NUMBER` + one of `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` / `_EMAIL` (`docs/google_chat_setup.md`). Email has no IMAP/SMTP settings: the poller (`integrations/email_poller.py`) reads and sends through the Gmail tools of the Google Workspace MCP (`GOOGLE_OAUTH_CLIENT_ID` / `GOOGLE_OAUTH_CLIENT_SECRET`), signed in as `EXEC_EMAIL_ADDRESS`.
## Testing
diff --git a/README.md b/README.md
index 49f717da..9c389ac6 100644
--- a/README.md
+++ b/README.md
@@ -174,7 +174,7 @@ make dev
The bot is embedded in the API process (alongside the email poller, scheduler, and resumer) so it shares the same SQLite database and ChromaDB vector store under `/data` in production. Skip the token to disable.
-For iterating on bot-only code without restarting the API, `make discord` runs the bot as a standalone process against the same local DB.
+For iterating on bot-only code without restarting the API, `make discord` runs the bot as a standalone process against the same local DB. Use it **instead of** the embedded bot, not alongside it: stop the API, or start it without `DISCORD_BOT_TOKEN`, first — two processes on one token each open a gateway connection and every message gets answered twice.
Users can DM the bot, `@mention` it in a channel (replies in a thread), or use `/ask` and `/today` slash commands. Slash commands sync to `DISCORD_GUILD_IDS` instantly on startup; leave blank for global registration (up to 1-hour propagation delay).
@@ -212,7 +212,7 @@ The built-in knowledge base is **trusted by default** — the Executive can use
|-----------|-----------|
| **Web UI** | `http://localhost:3000` |
| **Slack** | Mention `@OpenExecutive` or DM the app |
-| **Email** | CC or email the configured address (IMAP/SMTP poller) |
+| **Email** | CC or email the configured address (Gmail poller via the Google Workspace MCP) |
| **Telegram** | Message the configured bot |
| **Google Chat** | Mention the app in a space |
| **Discord** | DM the bot, `@mention` it in a channel, or use `/ask` / `/today` slash commands |
diff --git a/docs/architecture.md b/docs/architecture.md
index 4bec3f5c..857b9778 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -506,23 +506,26 @@ Polls the configured Gmail inbox via Gmail MCP OAuth every `EMAIL_POLL_INTERVAL_
Required env var: `EXEC_EMAIL_ADDRESS`
Optional: `EMAIL_POLL_INTERVAL_SECONDS`
-**Access control**: roster-driven. A sender's address must match the `email` field of a non-archived Person row to receive a response; unknown senders are silently dropped and marked read. Manage via the /people UI.
+**Access control**: inbound is **not** roster-gated. Mail from a sender who isn't on the People roster still reaches the Executive — prefixed with a `[POLICY]` notice and audited as `integration_inbound` with `outcome=accepted_non_roster` — so it can be triaged, logged, or raised as an alert. What it cannot do is auto-reply: the outbound Gmail gate (`orchestrator.mcp_gateway._check_gmail_recipients`) refuses any send whose recipient isn't a non-archived Person's `email`. Self-sent mail and automated senders (noreply, mailer-daemon, postmaster) are skipped before routing. Manage the roster via the /people UI.
### Telegram Bot
`integrations/telegram_bot.py`
-Webhook-based bot registered via FastAPI (`POST /webhook/telegram`). Validates incoming requests against `TELEGRAM_WEBHOOK_SECRET` using HMAC. Splits long responses at paragraph boundaries to stay within Telegram's 4096-char limit.
+Webhook-based bot registered via FastAPI (`POST /webhook/telegram`). When `TELEGRAM_WEBHOOK_SECRET` is set, rejects (401) any request whose `X-Telegram-Bot-Api-Secret-Token` header doesn't match it (constant-time comparison). Splits long responses at paragraph boundaries to stay within Telegram's 4096-char limit.
Required env vars: `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`
**Access control**: roster-driven. A sender's chat_id must match the `telegram_chat_id` field of a non-archived Person row to receive a response.
-Setup: register the webhook once with Telegram after the API is deployed:
+Setup: register the webhook once with Telegram after the API is deployed, passing the same secret as `secret_token` — without it Telegram sends no header and every update gets a 401:
```bash
curl -F "url=https://your-api-host/webhook/telegram" \
- "https://api.telegram.org/bot<TOKEN>/setWebhook"
+ -F "secret_token=$TELEGRAM_WEBHOOK_SECRET" \
+ "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook"
```
+See [docs/telegram_setup.md](telegram_setup.md) for full setup instructions.
+
### Google Chat
`integrations/google_chat.py`
@@ -531,10 +534,9 @@ Webhook-based integration registered via FastAPI (`POST /webhook/google-chat`).
Three auth modes (selected by which env vars are set):
1. **Key file** (`GOOGLE_CHAT_SERVICE_ACCOUNT_FILE`) — standard SA JSON key; blocked by some org policies
2. **Impersonation** (`GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL`, no key file) — uses ADC to impersonate the SA
-3. **ADC direct** — neither var set; ambient credential must already be the Chat bot SA
+3. **ADC direct** — neither var set; ambient credential must already be the Chat bot SA. `_build_credentials` supports this, but the webhook currently rejects it: it returns 503 unless one of the two vars above is set.
-Required env var: `GOOGLE_CHAT_PROJECT_NUMBER`
-Optional: `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE`, `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL`
+Required env vars: `GOOGLE_CHAT_PROJECT_NUMBER`, plus one of `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` / `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL`
See [docs/google_chat_setup.md](google_chat_setup.md) for full setup instructions.
@@ -558,13 +560,13 @@ All settings via environment variables (`.env` file in `packages/core/`).
| `SCHEDULER_POLL_INTERVAL_SECONDS` | No | `30` | Scheduler poll frequency |
| `SLACK_BOT_TOKEN` | No | — | Slack bot OAuth token |
| `SLACK_APP_TOKEN` | No | — | Slack socket mode token |
-| `EXEC_EMAIL_ADDRESS` | No | — | Executive Gmail address (Gmail MCP OAuth) |
+| `EXEC_EMAIL_ADDRESS` | Yes | — | Executive Gmail address (Gmail MCP OAuth) |
| `EMAIL_POLL_INTERVAL_SECONDS` | No | `60` | Email poll frequency |
| `TELEGRAM_BOT_TOKEN` | No | — | Telegram bot token |
-| `TELEGRAM_WEBHOOK_SECRET` | No | — | HMAC secret for webhook validation |
+| `TELEGRAM_WEBHOOK_SECRET` | No | — | Must match the `secret_token` given to `setWebhook`; checked against `X-Telegram-Bot-Api-Secret-Token` |
| `GOOGLE_CHAT_PROJECT_NUMBER` | No | — | GCP project number |
-| `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` | No | — | Path to SA JSON key |
-| `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL` | No | — | SA email for ADC impersonation |
+| `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` | No | — | Path to SA JSON key (Google Chat needs this or `_EMAIL`) |
+| `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL` | No | — | SA email for ADC impersonation (Google Chat needs this or `_FILE`) |
| `GOOGLE_OAUTH_CLIENT_ID` | No | — | Google OAuth client ID (Gmail MCP) |
| `GOOGLE_OAUTH_CLIENT_SECRET` | No | — | Google OAuth client secret (Gmail MCP) |
| `MCP_ENABLED` | No | `false` | Enable MCP tool gateway |
diff --git a/docs/google_chat_setup.md b/docs/google_chat_setup.md
index d6fc11b9..85879fd6 100644
--- a/docs/google_chat_setup.md
+++ b/docs/google_chat_setup.md
@@ -67,7 +67,11 @@ No key file is downloaded. Your user credential impersonates the service account
#### Option C — ADC direct *(for GCP-hosted deployments only)*
-If the server runs on **Cloud Run, GCE, or GKE**, attach the `open-executive-chat` service account to the compute resource. Set `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL` to that SA's email address — the code will use the metadata server's credential directly (no key file, no personal ADC login).
+If the server runs on **Cloud Run, GCE, or GKE**, attach the `open-executive-chat` service account to the compute resource. No key file and no personal ADC login are involved.
+
+1. Grant the service account the **Service Account Token Creator** role *on itself* (**IAM & Admin → Service Accounts** → `open-executive-chat` → **Permissions** → **Grant Access**, principal = the SA's own email). With `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL` set, the code impersonates that SA using the metadata server's credential, and Google requires this grant even when an SA impersonates itself. On GCE, the VM's access scopes must also allow `cloud-platform`.
+
+2. Set `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL` to that SA's email address. This is **required**: the webhook returns `503 Google Chat integration not configured` unless `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` or `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL` is set.
```
GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL=open-executive-chat@YOUR_PROJECT_ID.iam.gserviceaccount.com
@@ -104,7 +108,7 @@ GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL=open-executive-chat@YOUR_PROJECT_ID.iam.gservi
## Step 4 — Set Environment Variables
-`GOOGLE_CHAT_PROJECT_NUMBER` is always required. The auth var depends on which option you chose in Step 2b:
+`GOOGLE_CHAT_PROJECT_NUMBER` is always required, plus one auth var — which one depends on the option you chose in Step 2b. With neither auth var set, the webhook returns `503`.
```bash
# Always required
@@ -116,7 +120,8 @@ GOOGLE_CHAT_SERVICE_ACCOUNT_FILE=/absolute/path/to/google_chat_service_account.j
# Option B (impersonation — org policy blocks key creation)
GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL=open-executive-chat@YOUR_PROJECT_ID.iam.gserviceaccount.com
-# Option C (GCP-hosted) — no additional vars needed
+# Option C (GCP-hosted) — same var as Option B, set to the SA attached to the compute resource
+GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL=open-executive-chat@YOUR_PROJECT_ID.iam.gserviceaccount.com
```
---
@@ -151,7 +156,7 @@ The webhook endpoint is now active at `POST /webhook/google-chat`. Google Chat w
| Symptom | Cause | Fix |
|---|---|---|
-| `503 Google Chat integration not configured` | Env vars missing or server not restarted | Add vars to `.env` and restart |
+| `503 Google Chat integration not configured` | `GOOGLE_CHAT_PROJECT_NUMBER` or both auth vars missing, or server not restarted | Set the project number plus `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` or `_EMAIL`, and restart |
| `401 Invalid JWT` | Wrong project number | Use the **numeric** Project Number, not the string Project ID |
| No reply, no error in Chat | Handler exception | Check server logs for `Google Chat: handler error` — usually an `ANTHROPIC_API_KEY` issue |
| Bot added to space but never responds | Webhook URL unreachable | Verify the URL is publicly accessible; for local dev, check ngrok is still running |
diff --git a/docs/telegram_setup.md b/docs/telegram_setup.md
new file mode 100644
index 00000000..4b9ef6ec
--- /dev/null
+++ b/docs/telegram_setup.md
@@ -0,0 +1,102 @@
+# Telegram Integration Setup
+
+The Open Executive Telegram bot receives messages via a webhook (`POST /webhook/telegram`) and replies through the Telegram Bot API. The integration is already implemented — you just need a bot token, a webhook secret, and a publicly reachable API.
+
+---
+
+## Step 1 — Create the Bot
+
+1. In Telegram, open a chat with [@BotFather](https://t.me/BotFather).
+2. Send `/newbot` and follow the prompts (display name, then a username ending in `bot`).
+3. BotFather replies with a token like `123456789:AA...`. This is your `TELEGRAM_BOT_TOKEN` — treat it as a secret.
+
+---
+
+## Step 2 — Generate a Webhook Secret
+
+Telegram echoes a secret of your choosing back in the `X-Telegram-Bot-Api-Secret-Token` header of every webhook request. The API compares that header against `TELEGRAM_WEBHOOK_SECRET` and rejects mismatches with `401`.
+
+Telegram only accepts 1–256 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. A hex string fits:
+
+```bash
+openssl rand -hex 32
+```
+
+---
+
+## Step 3 — Set Environment Variables
+
+```bash
+TELEGRAM_BOT_TOKEN=123456789:AA... # from Step 1
+TELEGRAM_WEBHOOK_SECRET=<value from Step 2>
+```
+
+Restart the API so it picks them up (`make dev` locally). Without `TELEGRAM_BOT_TOKEN` the webhook answers `503 Telegram integration not configured`.
+
+If `TELEGRAM_WEBHOOK_SECRET` is left unset, the header check is skipped and anyone who finds the URL can post fake updates to it. Always set it for a public deployment.
+
+---
+
+## Step 4 — Expose the Webhook
+
+Telegram must reach `https://<your-api-host>/webhook/telegram` over HTTPS. The route is exempt from the `BACKEND_SHARED_SECRET` gate (see [auth.md](auth.md)) — the webhook secret is its authentication.
+
+For **local development**, expose your server with [ngrok](https://ngrok.com):
+
+```bash
+ngrok http 8000
+# Use the HTTPS forwarding URL, e.g. https://abc123.ngrok-free.app/webhook/telegram
+```
+
+---
+
+## Step 5 — Register the Webhook
+
+Pass the **same** secret as `secret_token`. Omitting it registers a webhook that sends no header, and every update is rejected with `401`.
+
+```bash
+curl -F "url=https://<your-api-host>/webhook/telegram" \
+ -F "secret_token=$TELEGRAM_WEBHOOK_SECRET" \
+ "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook"
+```
+
+Expected response: `{"ok":true,"result":true,"description":"Webhook was set"}`.
+
+Re-run this command whenever the host URL or the secret changes. Verify the registration with:
+
+```bash
+curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getWebhookInfo"
+```
+
+`last_error_message` in that response shows the most recent delivery failure (e.g. `Wrong response from the webhook: 401 Unauthorized`).
+
+---
+
+## Step 6 — Grant Access
+
+Access is roster-driven. The bot only answers a chat whose ID matches the `telegram_chat_id` of a non-archived Person — add or edit the Person in the **/people** UI. Messages from any other chat are dropped without a reply.
+
+To find a chat ID, message the bot once and check the API logs for:
+
+```
+Telegram: rejected message from chat_id=<id> (not in People roster)
+```
+
+The same rejection is recorded in the audit log as an `integration_inbound` event with `outcome=rejected_unknown_sender`.
+
+---
+
+## Step 7 — Test
+
+Send the bot a direct message. It should reply within a few seconds. `/start`, `/help` and `/ask` prefixes are stripped before the text reaches the Executive; photos and documents are passed along as attachments.
+
+---
+
+## Troubleshooting
+
+| Symptom | Cause | Fix |
+|---|---|---|
+| `getWebhookInfo` shows `401 Unauthorized` | `secret_token` missing from `setWebhook`, or it differs from `TELEGRAM_WEBHOOK_SECRET` | Re-run Step 5 with the current secret |
+| `503 Telegram integration not configured` | `TELEGRAM_BOT_TOKEN` unset or API not restarted | Set the var and restart |
+| No reply, `rejected message from chat_id=…` in logs | Chat not on the People roster | Add the chat ID to a Person in /people (Step 6) |
+| No reply, nothing in logs | Webhook URL unreachable | Check `getWebhookInfo`; for local dev, confirm ngrok is still running and re-register if its URL changed |
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 674b3aa4..9e50b638 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -3623,8 +3623,10 @@ integrations:
TELEGRAM_ALLOWED_CHAT_IDS / DISCORD_ALLOWED_USER_IDS) have been
removed; access is managed entirely via the /people UI.
email_poller: |
- IMAP poll loop in openexecutive.integrations.email_poller — runs
- as an asyncio task in the FastAPI lifespan. Strips Reply-To
+ Gmail poll loop in openexecutive.integrations.email_poller — reads
+ and marks mail through the Google Workspace MCP's Gmail tools (no
+ IMAP/SMTP), and runs as an asyncio task in the FastAPI lifespan,
+ started only once the MCP gateway is up. Strips Reply-To
headers to defend against redirect attacks; filters auto-replies
(mailer-daemon, noreply senders) and self-sent messages. INBOUND
is NOT roster-gated — see ``channel_access`` for the split. When
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index 52d63664..41a39fb1 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`) — IMAP poll loop; strips Reply-To, filters auto-replies. 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.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). 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### 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, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\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 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`. 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**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 — 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.",
+ "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. 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.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). 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### 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, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\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 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`. 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**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 — 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.",
"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 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",
- "generated_at": "2026-09-23T16:11:27Z"
+ "generated_at": "2026-09-23T22:46:42Z"
}
diff --git a/packages/core/openexecutive/audit/logger.py b/packages/core/openexecutive/audit/logger.py
index 92aedd22..db1cf791 100644
--- a/packages/core/openexecutive/audit/logger.py
+++ b/packages/core/openexecutive/audit/logger.py
@@ -87,7 +87,7 @@ class AuditEvent:
@contextmanager
def _get_conn(db_path: Path) -> Generator[sqlite3.Connection, None, None]:
# 5s busy_timeout + WAL so concurrent writers (FastAPI worker, scheduler
- # task, IMAP poller thread, Slack/Telegram webhook threads) don't hit
+ # task, email poller task, Slack/Telegram webhook threads) don't hit
# "database is locked". Audit writes swallow exceptions, so silent loss
# under contention would be undetectable.
conn = sqlite3.connect(str(db_path), timeout=5.0)
diff --git a/packages/core/openexecutive/integrations/discord_bot.py b/packages/core/openexecutive/integrations/discord_bot.py
index 3bed319c..6699d010 100644
--- a/packages/core/openexecutive/integrations/discord_bot.py
+++ b/packages/core/openexecutive/integrations/discord_bot.py
@@ -4,7 +4,9 @@ Mirrors the structure of slack_bot.py. In production the bot is embedded in
the FastAPI lifespan (api/main.py) so it shares the same /data volume as the
API. `run_discord_bot()` / `python -m openexecutive.integrations.discord_bot`
is a standalone dev entry point — useful for iterating on bot-only changes
-without restarting the API. Both rely on `create_discord_bot()` returning a
+without restarting the API. Run it only while the API is stopped or has no
+DISCORD_BOT_TOKEN: the lifespan starts its own bot whenever the token is set,
+and two gateway connections on one token reply to every message twice. Both rely on `create_discord_bot()` returning a
`commands.Bot` whose `.start()` / `.close()` work in any event loop.
Supported interactions:
diff --git a/packages/core/openexecutive/integrations/email_poller.py b/packages/core/openexecutive/integrations/email_poller.py
index 4e714aa5..09cf57ae 100644
--- a/packages/core/openexecutive/integrations/email_poller.py
+++ b/packages/core/openexecutive/integrations/email_poller.py
@@ -463,7 +463,7 @@ async def _handle_email(
subject = subject_line[len("subject:"):].strip()[:160] if subject_line else ""
# Deterministic per-thread session id so every audit row from this inbound
# (chat_turn, specialist_consult, tool_invocation) shares a grouping key
- # with the integration_inbound row. Falls back to from_addr when the IMAP
+ # with the integration_inbound row. Falls back to from_addr when the Gmail
# message exposes no thread header.
session_id = f"email:{thread_id or from_addr}"
audit_log(
diff --git a/packages/core/openexecutive/people/store.py b/packages/core/openexecutive/people/store.py
index 81605cda..fb44cd59 100644
--- a/packages/core/openexecutive/people/store.py
+++ b/packages/core/openexecutive/people/store.py
@@ -357,7 +357,7 @@ def find_person_by_telegram_chat_id(telegram_chat_id: str, db_path: Path | None
def find_person_by_email(email: str, db_path: Path | None = None) -> Person | None:
"""Return the first non-archived Person with this email address, or None.
- Case-insensitive match — IMAP `From:` headers come back with the
+ Case-insensitive match — email `From:` headers come back with the
sender's chosen capitalization, which isn't necessarily what was
stored on the Person row.
"""
diff --git a/scripts/mint-google-token.py b/scripts/mint-google-token.py
index 3b93fe57..5d5752a2 100644
--- a/scripts/mint-google-token.py
+++ b/scripts/mint-google-token.py
@@ -4,8 +4,8 @@
workspace-mcp has no `auth` subcommand: the OAuth flow fires on the first
authenticated tool call. This spawns the server over stdio and triggers that
call so your browser opens for consent; the refresh-token credential is written
-to WORKSPACE_MCP_CREDENTIALS_DIR. Copy that file onto the API volume afterward
-(scripts/seed-google-workspace.sh).
+to WORKSPACE_MCP_CREDENTIALS_DIR. Copy that file onto the API volume afterward,
+into /data/google_credentials/ (see "Google Workspace credentials" in docs/deployment.md).
Run in a shell where the OAuth client is exported: