Skip to content

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

Start the Slack Socket Mode listener from the FastAPI lifespan

Rufus3f2c091c4f78
diff --git a/.env.example b/.env.example
index 84dbbcca..cbef709a 100644
--- a/.env.example
+++ b/.env.example
@@ -162,7 +162,10 @@ WEB_SEARCH_MAX_USES=5
# WEB_SEARCH_ALLOWED_DOMAINS=
# WEB_SEARCH_BLOCKED_DOMAINS=
-# Slack integration (optional)
+# Slack integration (optional). Setting BOTH tokens starts the Socket Mode
+# listener as part of the API's own startup — `make dev` brings Slack up with
+# the rest of the app, no separate process. Leave either unset to disable
+# inbound Slack (outbound sends only need SLACK_BOT_TOKEN).
SLACK_BOT_TOKEN=xoxb-your-bot-token
SLACK_APP_TOKEN=xapp-your-app-token
diff --git a/docs/architecture.md b/docs/architecture.md
index 21ba58d6..4bec3f5c 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -494,7 +494,7 @@ data: {"type": "error", "message": "..."}
### Slack Bot
`integrations/slack_bot.py`
-Slack Bolt app in socket mode. Listens for `@OpenExecutive` mentions and direct messages. Calls `Executive.chat()` synchronously via `asyncio.run()`. Runs as a separate process alongside FastAPI.
+Async Bolt app in socket mode, embedded in the FastAPI lifespan (no separate process). Listens for `@OpenExecutive` mentions and direct messages, and awaits `Executive.chat()` on the application event loop. Started when both tokens are set: the lifespan connects the Socket Mode handler as a background task and closes it on shutdown.
Required env vars: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN`
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index 91e34f8e..6e3b2de8 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -144,6 +144,11 @@ _UNAUTHENTICATED_PATHS: frozenset[str] = frozenset(
)
+# How long the lifespan waits for the Slack socket to cancel its pending
+# connect and close cleanly before abandoning it. Named so tests can shrink it.
+SLACK_SHUTDOWN_TIMEOUT_S = 10.0
+
+
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
from openexecutive.alerts.store import initialize_db as initialize_alerts_db
@@ -392,6 +397,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
catalog_refresh_task = asyncio.create_task(run_catalog_refresher(settings))
discord_bot: Any = None
discord_bot_task: asyncio.Task[None] | None = None
+ slack_handler: Any = None
+ slack_connect_task: asyncio.Task[None] | None = None
if settings.mcp_enabled:
from openexecutive.orchestrator.mcp_gateway import MCPGateway, set_active_gateway
@@ -459,6 +466,60 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
discord_bot = None
discord_bot_task = None
+ # Slack Socket Mode listener. Embedded for the same reason as Discord
+ # above: the bot reads the same SQLite + ChromaDB under /data, and that
+ # volume attaches to a single instance. Before this, `make dev` started
+ # only uvicorn + the UI, so Slack silently never listened unless someone
+ # ran `python -m openexecutive.integrations.slack_bot` by hand (#131).
+ #
+ # Requires BOTH tokens: the bot token authenticates the Web API calls,
+ # the app-level token opens the Socket Mode connection.
+ if settings.slack_bot_token and settings.slack_app_token:
+ _slack_log = logging.getLogger("openexecutive")
+ try:
+ # Imported inside the try, not above it: slack_bolt is itself
+ # imported lazily inside create_slack_app, so a missing dependency
+ # surfaces from the await rather than from this line — but keeping
+ # the import here means a future third-party import added to
+ # slack_bot.py degrades to "continue without Slack" instead of
+ # failing the whole boot.
+ from openexecutive.integrations.slack_bot import create_slack_app
+
+ _, slack_handler = await create_slack_app()
+
+ # connect_async() does NOT fail fast: on a bad app token or an
+ # unreachable Slack it retries internally and never returns, so
+ # awaiting it here would hang boot forever. Run it as a
+ # background task, like the Discord bot above. Unlike Discord's
+ # callback this one also logs on success: "listener connected"
+ # is the operator's confirmation that `make dev` really did
+ # bring Slack up, which is the whole point of #131.
+ slack_connect_task = asyncio.create_task(
+ slack_handler.connect_async()
+ )
+
+ def _on_slack_connect_done(task: asyncio.Task[None]) -> None:
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ _slack_log.error(
+ "Slack socket mode connect failed", exc_info=exc
+ )
+ else:
+ _slack_log.info("Slack socket mode listener connected")
+
+ slack_connect_task.add_done_callback(_on_slack_connect_done)
+ except Exception:
+ # Covers a missing slack_bolt, a malformed token, and any
+ # failure building the app. Nothing to release here: the
+ # handler is only bound by the tuple unpack above, so it is
+ # still None on this path. A connect_async() that fails later
+ # lands in the task and is released by the shutdown block.
+ _slack_log.exception(
+ "Failed to start Slack bot; continuing without it"
+ )
+
# Run the MCP Streamable-HTTP session manager for the life of the app.
# Mounting the sub-app does NOT run its lifespan, so without this every
# /mcp request 500s. The session manager was created when create_app()
@@ -496,6 +557,41 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
):
await discord_bot_task
+ # Close the Slack socket before tearing down the gateway/poller/scheduler
+ # that its handlers call into. Cancelling the pending connect and closing
+ # the client are bounded together under ONE deadline — the same shape as
+ # the Discord shutdown above — so neither step can hang the lifespan.
+ if slack_handler is not None or slack_connect_task is not None:
+ async def _shutdown_slack() -> None:
+ if slack_connect_task is not None and not slack_connect_task.done():
+ slack_connect_task.cancel()
+ # asyncio.wait(), not `suppress(CancelledError): await task`.
+ # wait_for enforces its deadline BY cancelling us, so
+ # suppressing CancelledError here would swallow that signal
+ # and the 10s bound would never fire. wait() reports the
+ # task's outcome without re-raising it, and still propagates
+ # a cancellation aimed at this coroutine.
+ await asyncio.wait([slack_connect_task])
+ if slack_handler is not None:
+ # close_async() disconnects and shuts down the client's
+ # monitor, message processor and worker pool. CancelledError
+ # is not an Exception subclass, so this suppress() does not
+ # swallow the deadline either.
+ with contextlib.suppress(Exception):
+ await slack_handler.close_async()
+
+ try:
+ await asyncio.wait_for(
+ _shutdown_slack(), timeout=SLACK_SHUTDOWN_TIMEOUT_S
+ )
+ except TimeoutError:
+ logging.getLogger("openexecutive").warning(
+ "Slack shutdown exceeded %.0fs; abandoning the socket",
+ SLACK_SHUTDOWN_TIMEOUT_S,
+ )
+ if slack_connect_task is not None and not slack_connect_task.done():
+ slack_connect_task.cancel()
+
if email_poller_task is not None:
email_poller_task.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 5933bc77..d70ff18d 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -902,8 +902,11 @@ peer_memory:
``HONCHO_ENABLED`` env var. When false, every entry point
short-circuits with ``outcome=disabled`` and the rest of OE
behaves identically to its pre-Honcho posture. Per-loop client
- cache keyed by ``asyncio.AbstractEventLoop`` so Slack's per-turn
- ``asyncio.run`` doesn't bind a stale client.
+ cache keyed by ``asyncio.AbstractEventLoop`` so a caller that
+ spins up its own loop doesn't bind a stale client. (Slack was the
+ original motivation; it now awaits on the app loop like every
+ other adapter, but the cache still guards tests and the
+ standalone entrypoints.)
surfaces:
prefetch: |
``prefetch(query, *, person_id, session_id=None, reasoning_level="low")``
@@ -2689,8 +2692,18 @@ integrations:
block. The outbound gate at ``mcp_gateway._check_gmail_recipients``
is the actual security boundary against auto-replying to spam.
slack: |
- openexecutive.integrations.slack_bot — Bolt socket-mode adapter
- (token-gated). Responds to (a) ``@mention`` events, (b) DMs, and
+ openexecutive.integrations.slack_bot — async Bolt socket-mode
+ adapter (``AsyncApp`` + ``AsyncSocketModeHandler``) embedded in the
+ FastAPI lifespan (no separate process), started when both
+ ``SLACK_BOT_TOKEN`` and ``SLACK_APP_TOKEN`` are set. The lifespan
+ runs ``connect_async()`` as a background task and ``close_async()``
+ on shutdown — ``connect_async()`` retries internally and never
+ returns on a bad app token, so awaiting it would hang boot, and
+ ``start_async()`` (sleep-forever) must never be used there.
+ Handlers await on the application event loop, which is what keeps
+ the uvicorn-bound MCP gateway, the shared AsyncAnthropic client and
+ the SSE queues off a foreign loop. Responds to (a) ``@mention``
+ events, (b) DMs, and
(c) thread continuations: any non-mention message in a thread the
bot has previously replied in is treated as a continuation and run
through the shared ``response_gate`` (see `response_gate:` below).
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index a48ca524..489e0cd2 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`) — Bolt socket-mode; responds to `@mention`s, DMs, and thread continuations.\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.\n- **Email** (`integrations.email_poller`) — IMAP poll loop; strips Reply-To, filters auto-replies.\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### 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. 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. 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 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.",
+ "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.\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.\n- **Email** (`integrations.email_poller`) — IMAP poll loop; strips Reply-To, filters auto-replies.\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### 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. 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. 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 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.",
"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-16T12:39:20.262413+00:00"
+ "generated_at": "2026-09-17T20:54:50.688172+00:00"
}
diff --git a/packages/core/openexecutive/integrations/slack_bot.py b/packages/core/openexecutive/integrations/slack_bot.py
index 4c4d00f0..aa46d79f 100644
--- a/packages/core/openexecutive/integrations/slack_bot.py
+++ b/packages/core/openexecutive/integrations/slack_bot.py
@@ -17,6 +17,13 @@ logger = logging.getLogger(__name__)
# without thread auto-continuation.
_bot_user_id: str | None = None
+# Preserves the concurrency ceiling the sync adapter had. That ceiling was
+# Bolt's own listener_executor — ThreadPoolExecutor(max_workers=5)
+# (slack_bolt/app/app.py) — which ran the handler bodies. The socket client's
+# `concurrency=10` pool only did dispatch+ack, which returns immediately, so
+# 5 (not 10) was the real cap on concurrent executive.chat() calls.
+_MAX_CONCURRENT_HANDLERS = 5
+
def _replies_contain_bot_message(messages: list[dict], bot_user_id: str | None) -> bool:
"""True iff any message in the thread was posted by this bot.
@@ -80,9 +87,23 @@ def _replies_to_gate_history(
return out
-def create_slack_app():
- from slack_bolt import App
- from slack_bolt.adapter.socket_mode import SocketModeHandler
+async def create_slack_app():
+ """Build the async Bolt app and its Socket Mode handler.
+
+ Async Bolt (not the sync ``App``) so every handler awaits on the caller's
+ event loop. That matters because the app is started from the FastAPI
+ lifespan: the MCP gateway's anyio task group and stdio subprocess, the
+ shared ``AsyncAnthropic`` client and the SSE subscriber queues are all
+ bound to the uvicorn loop, and driving them from a throwaway
+ ``asyncio.run`` loop on a Bolt worker thread would corrupt or hang them.
+ Every other inbound adapter (discord, telegram, google_chat) already
+ awaits on the request loop; this brings Slack in line.
+
+ Imports stay deferred inside the factory so the module imports cleanly
+ where slack_bolt is absent — the helper unit tests rely on that.
+ """
+ from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler
+ from slack_bolt.async_app import AsyncApp
from openexecutive.config import get_settings
@@ -93,7 +114,7 @@ def create_slack_app():
"SLACK_BOT_TOKEN and SLACK_APP_TOKEN must be set to run the Slack bot"
)
- app = App(token=settings.slack_bot_token)
+ app = AsyncApp(token=settings.slack_bot_token)
# Resolve and cache the bot's own user_id once at startup. Failure
# here disables thread auto-continuation but does NOT prevent the
@@ -101,7 +122,7 @@ def create_slack_app():
# depend on this value.
global _bot_user_id
try:
- auth = app.client.auth_test()
+ auth = await app.client.auth_test()
_bot_user_id = str(auth.get("user_id") or "") or None
logger.info("Slack bot_user_id resolved to %s", _bot_user_id)
except Exception:
@@ -111,11 +132,18 @@ def create_slack_app():
)
_bot_user_id = None
+ # The async client ensure_future()s every inbound envelope with no cap,
+ # so without this a burst of Slack traffic fans out into unbounded
+ # concurrent executive.chat() calls. The sync adapter was bounded (see
+ # _MAX_CONCURRENT_HANDLERS); keep it bounded.
+ # Created here (not at module scope) so it binds to the loop that runs it.
+ inflight = asyncio.Semaphore(_MAX_CONCURRENT_HANDLERS)
+
def _clean_message(text: str) -> str:
text = re.sub(r"<@\w+>", "", text)
return text.strip()
- def _handle_message_sync(
+ async def _handle_message(
event: dict, say, client=None, mode: str = "mention"
) -> None:
"""Process one inbound Slack message.
@@ -153,14 +181,23 @@ def create_slack_app():
thread_replies: list[dict] | None = None
if is_threaded_reply:
try:
- # 5s timeout: this call sits on the user-facing TTFB path
- # (sync handler runs before executive.chat). Default urllib
- # timeout is ~30s; a Slack API hang would freeze a Bolt
- # worker for that long.
- replies_resp = client.conversations_replies(
- channel=event.get("channel", ""),
- ts=str(thread_ts),
- limit=200,
+ # 5s bound: this call sits on the user-facing TTFB path (it
+ # runs before executive.chat). Enforced with wait_for, not the
+ # `timeout=` kwarg — AsyncWebClient has no such parameter, so
+ # that value was silently forwarded as a query string and the
+ # real ceiling stayed the client default of 30s. A timeout is
+ # caught below and degrades to thread_replies=None — which
+ # for mode="thread_continuation" trips the bot-presence guard
+ # and drops the message. That is the intended trade: a slow
+ # Slack API should cost one missed continuation, not a stalled
+ # event loop. Mentions and DMs are unaffected (they do not
+ # depend on thread_replies to decide whether to reply).
+ replies_resp = await asyncio.wait_for(
+ client.conversations_replies(
+ channel=event.get("channel", ""),
+ ts=str(thread_ts),
+ limit=200,
+ ),
timeout=5,
)
thread_replies = replies_resp.get("messages", []) or []
@@ -184,8 +221,13 @@ def create_slack_app():
):
return
+ # Audit writes go off-loop too: log_event opens SQLite with a 5s
+ # busy timeout, and the scheduler, resumer and email poller all write
+ # the same DB — under contention an inline call would stall the whole
+ # application event loop for that long.
from openexecutive.audit import log_event as audit_log
- audit_log(
+ await asyncio.to_thread(
+ audit_log,
"integration_inbound",
f"Inbound slack from user={slack_user_id} channel={event.get('channel', '')}: {cleaned[:160]}",
actor="slack",
@@ -206,10 +248,13 @@ def create_slack_app():
# without a matching slack_user_id on a non-archived Person row.
from openexecutive.people.store import find_person_by_slack_id
sender_person = (
- find_person_by_slack_id(slack_user_id) if slack_user_id else None
+ await asyncio.to_thread(find_person_by_slack_id, slack_user_id)
+ if slack_user_id
+ else None
)
if sender_person is None:
- audit_log(
+ await asyncio.to_thread(
+ audit_log,
"integration_inbound",
f"Rejected: slack user={slack_user_id} not in People roster",
actor="slack",
@@ -230,22 +275,22 @@ def create_slack_app():
from openexecutive.workflows.inbound_resolver import resolve_inbound_message
from openexecutive.workflows.resumer import apply_resolution
- person = find_person_by_slack_id(slack_user_id)
+ person = await asyncio.to_thread(
+ find_person_by_slack_id, slack_user_id
+ )
if person is not None and person.id is not None:
- resolution = asyncio.run(
- resolve_inbound_message(
- channel="slack",
- channel_ref=slack_user_id,
- from_person_id=person.id,
- text=cleaned,
- message_id=str(event.get("ts") or ""),
- in_reply_to=str(thread_ts or ""),
- )
+ resolution = await resolve_inbound_message(
+ channel="slack",
+ channel_ref=slack_user_id,
+ from_person_id=person.id,
+ text=cleaned,
+ message_id=str(event.get("ts") or ""),
+ in_reply_to=str(thread_ts or ""),
)
if resolution is not None and resolution.run_id:
- success = asyncio.run(apply_resolution(resolution.run_id, resolution))
+ success = await apply_resolution(resolution.run_id, resolution)
if success:
- say(
+ await say(
text="Got it — your response has been recorded.",
thread_ts=thread_ts,
)
@@ -269,14 +314,12 @@ def create_slack_app():
or getattr(sender_person, "name", None)
or slack_user_id
)
- decision = asyncio.run(
- should_respond(
- user_text=cleaned,
- author_display_name=speaker_label,
- history=gate_history,
- bot_display_name="Open Executive",
- channel="slack",
- )
+ decision = await should_respond(
+ user_text=cleaned,
+ author_display_name=speaker_label,
+ history=gate_history,
+ bot_display_name="Open Executive",
+ channel="slack",
)
if not decision.allow:
logger.info(
@@ -285,7 +328,8 @@ def create_slack_app():
session_id,
decision.reason,
)
- audit_log(
+ await asyncio.to_thread(
+ audit_log,
"integration_inbound",
f"Skipped: response gate (reason={decision.reason})",
actor="slack",
@@ -327,7 +371,7 @@ def create_slack_app():
from openexecutive.orchestrator.mcp_gateway import get_active_gateway
from openexecutive.orchestrator.session import Session
- profile = load_or_create_profile()
+ profile = await asyncio.to_thread(load_or_create_profile)
session = Session(
session_id=session_id,
company_profile=profile if not profile.is_empty() else None,
@@ -355,12 +399,22 @@ def create_slack_app():
if _bot_user_id and uid == _bot_user_id:
continue
seen.add(uid)
- other = find_person_by_slack_id(uid)
+ other = await asyncio.to_thread(find_person_by_slack_id, uid)
if other and other.id is not None:
co_present_person_ids.append(other.id)
- retrieved_context = retrieve(query=cleaned)
- episodic_context = format_for_prompt()
+ # Offloaded for the same reason api/routes/chat.py offloads them:
+ # both are blocking (ChromaDB query + embedding, SQLite read) and
+ # the handler now awaits on the application event loop, so running
+ # them inline would stall every other request. `get_store()` hands
+ # over the warm ChromaDB client the lifespan built, instead of
+ # constructing a fresh PersistentClient on every message.
+ from openexecutive.mcp_server.server import get_store
+
+ retrieved_context, episodic_context = await asyncio.gather(
+ asyncio.to_thread(retrieve, query=cleaned, store=get_store()),
+ asyncio.to_thread(format_for_prompt),
+ )
# On the 1:1 DM path, hydrate with the context of any recent
# outbound DM oe sent this user, so a reply oe solicited from
@@ -373,42 +427,42 @@ def create_slack_app():
hydrate_user_message,
)
- chat_user_message = hydrate_user_message(
+ chat_user_message = await asyncio.to_thread(
+ hydrate_user_message,
channel="slack_dm",
channel_ref=str(slack_user_id),
user_message=cleaned,
)
executive = Executive(mcp_gateway=get_active_gateway())
- response = asyncio.run(
- executive.chat(
- user_message=chat_user_message,
- session=session,
- retrieved_context=retrieved_context,
- episodic_context=episodic_context,
- person_id=person_id,
- co_present_person_ids=co_present_person_ids or None,
- )
+ response = await executive.chat(
+ user_message=chat_user_message,
+ session=session,
+ retrieved_context=retrieved_context,
+ episodic_context=episodic_context,
+ person_id=person_id,
+ co_present_person_ids=co_present_person_ids or None,
)
- say(text=response, thread_ts=thread_ts)
+ await say(text=response, thread_ts=thread_ts)
except Exception as e:
logger.error(f"Slack handler error: {e}", exc_info=True)
- say(
+ await say(
text="I encountered an error processing your request. Please try again.",
thread_ts=thread_ts,
)
@app.event("app_mention")
- def handle_mention(event: dict, say, client) -> None:
- # Bolt auto-injects `client` (a WebClient) when listed in the
+ async def handle_mention(event: dict, say, client) -> None:
+ # Bolt auto-injects `client` (an AsyncWebClient) when listed in the
# signature; we pass it through so the multi-peer thread-member
# fetch can call conversations.replies without a separate import.
- _handle_message_sync(event, say, client=client, mode="mention")
+ async with inflight:
+ await _handle_message(event, say, client=client, mode="mention")
@app.event("message")
- def handle_message(event: dict, say, client) -> None:
+ async def handle_message(event: dict, say, client) -> None:
# Slack delivers BOTH a generic `message` event AND `app_mention`
# when the bot is mentioned in a channel/thread. Filter early so
# only one handler fires.
@@ -417,13 +471,14 @@ def create_slack_app():
channel_type = event.get("channel_type")
if channel_type == "im":
- _handle_message_sync(event, say, client=client, mode="dm")
+ async with inflight:
+ await _handle_message(event, say, client=client, mode="dm")
return
# If the bot is @-mentioned, `app_mention` will handle it. Skip
# here to avoid double-firing. When _bot_user_id failed to resolve
# at startup this filter is a no-op, but the bot-presence guard
- # inside _handle_message_sync (see "Bot-presence guard for
+ # inside _handle_message (see "Bot-presence guard for
# thread_continuation mode") still catches the second invocation
# because the bot has not yet engaged in any thread.
text = event.get("text", "")
@@ -432,25 +487,38 @@ def create_slack_app():
# Auto-continuation only fires inside a thread the bot has
# previously engaged in. The "has the bot replied here?" check
- # happens inside _handle_message_sync where conversations_replies
+ # happens inside _handle_message where conversations_replies
# is already being fetched; we only filter the cheap signals here.
thread_ts = event.get("thread_ts")
if not thread_ts or str(thread_ts) == str(event.get("ts") or ""):
return # not a threaded reply (thread starters go through app_mention)
- _handle_message_sync(event, say, client=client, mode="thread_continuation")
+ async with inflight:
+ await _handle_message(
+ event, say, client=client, mode="thread_continuation"
+ )
+
+ handler = AsyncSocketModeHandler(app, settings.slack_app_token)
+ return app, handler
+
- return app, SocketModeHandler
+async def _run_slack_bot_async() -> None:
+ _, handler = await create_slack_app()
+ logger.info("Starting Slack bot in socket mode...")
+ # start_async() == connect_async() + sleep(inf): correct for a standalone
+ # process, but never call it from the FastAPI lifespan — it would never
+ # return. The lifespan uses connect_async()/close_async() instead.
+ await handler.start_async()
def run_slack_bot() -> None:
- app, SocketModeHandler = create_slack_app()
- from openexecutive.config import get_settings
+ """Standalone entrypoint: ``python -m openexecutive.integrations.slack_bot``.
- settings = get_settings()
- handler = SocketModeHandler(app, settings.slack_app_token)
- logger.info("Starting Slack bot in socket mode...")
- handler.start()
+ Still supported for running the bot in isolation. Normal operation now
+ starts the listener from the FastAPI lifespan instead (see api/main.py),
+ so ``make dev`` brings Slack up with the rest of the app.
+ """
+ asyncio.run(_run_slack_bot_async())
if __name__ == "__main__":
diff --git a/packages/core/tests/unit/test_slack_handler_async.py b/packages/core/tests/unit/test_slack_handler_async.py
new file mode 100644
index 00000000..aea33b2f
--- /dev/null
+++ b/packages/core/tests/unit/test_slack_handler_async.py
@@ -0,0 +1,226 @@
+"""Invariants of the async Bolt conversion (#131).
+
+`slack_bot.py` used to be a synchronous Bolt app whose listeners ran on a
+10-worker thread pool and drove async code with `asyncio.run()` once per
+message. It is now an `AsyncApp` whose listeners await on the application
+event loop, because the lifespan starts it in-process and the MCP gateway,
+the shared Anthropic client and the SSE queues are all bound to that loop.
+
+That conversion has three failure modes these tests pin down:
+ 1. a call that became a coroutine but is not awaited — the bot silently
+ stops replying;
+ 2. blocking SQLite/ChromaDB work left inline — it now stalls the whole API,
+ not just one Bolt worker;
+ 3. unbounded concurrency — the async client fans out every envelope.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager, suppress
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from openexecutive.integrations import slack_bot
+
+MENTION_EVENT = {
+ "text": "<@UBOT> where are we on hiring?",
+ "user": "U123",
+ "channel": "C1",
+ "ts": "1700000000.0",
+}
+
+
[email protected](autouse=True)
+def slack_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Tokens for the factory's guard, and no network for its auth_test().
+
+ `create_slack_app()` resolves the bot's own user_id via `auth_test()` at
+ construction; stub it so these tests never touch slack.com.
+ """
+ from openexecutive.config import get_settings
+
+ stub = get_settings().model_copy(
+ update={"slack_bot_token": "xoxb-test", "slack_app_token": "xapp-test"}
+ )
+ monkeypatch.setattr("openexecutive.config.get_settings", lambda: stub)
+ monkeypatch.setattr(
+ "slack_sdk.web.async_client.AsyncWebClient.auth_test",
+ AsyncMock(return_value={"user_id": "UBOT"}),
+ )
+ # create_slack_app() assigns the module global; restore it so these tests
+ # cannot leak a resolved id into any other Slack test.
+ monkeypatch.setattr(slack_bot, "_bot_user_id", None)
+
+
+def _person() -> MagicMock:
+ p = MagicMock()
+ p.id = 7
+ p.display_name = "Alex"
+ return p
+
+
+class _Harness:
+ """Patches every out-of-process dependency of the Slack handler."""
+
+ def __init__(self) -> None:
+ self.say = AsyncMock()
+ self.client = MagicMock()
+ self.client.conversations_replies = AsyncMock(return_value={"messages": []})
+ self.retrieve_threads: list[str] = []
+ self.chat = AsyncMock(return_value="the reply")
+
+ def _record_retrieve(self, *_: Any, **kwargs: Any) -> str:
+ self.retrieve_threads.append(threading.current_thread().name)
+ self.store_arg = kwargs.get("store")
+ return "ctx"
+
+ def __enter__(self) -> _Harness:
+ exec_patch = patch("openexecutive.orchestrator.executive.Executive")
+ self._patches = [
+ patch.object(slack_bot, "_bot_user_id", "UBOT"),
+ patch("openexecutive.people.store.find_person_by_slack_id",
+ return_value=_person()),
+ patch("openexecutive.audit.log_event"),
+ patch("openexecutive.knowledge.retriever.retrieve",
+ side_effect=self._record_retrieve),
+ patch("openexecutive.memory.episodic.format_for_prompt",
+ return_value="epi"),
+ patch("openexecutive.onboarding.profile_builder.load_or_create_profile"),
+ patch("openexecutive.alerts.pipeline.schedule_evaluation"),
+ patch("openexecutive.mcp_server.server.get_store",
+ return_value="WARM_STORE"),
+ patch("openexecutive.workflows.inbound_resolver.resolve_inbound_message",
+ new=AsyncMock(return_value=None)),
+ exec_patch,
+ ]
+ for p in self._patches:
+ started = p.start()
+ if p is exec_patch:
+ started.return_value.chat = self.chat
+ return self
+
+ def __exit__(self, *_: Any) -> None:
+ for p in reversed(self._patches):
+ p.stop()
+
+
+@asynccontextmanager
+async def _listeners() -> AsyncIterator[dict[str, Any]]:
+ """Build the real async Bolt app and hand back its event listeners.
+
+ Closes the socket-mode client on the way out so the suite does not leak
+ an aiohttp session per test.
+ """
+ app, handler = await slack_bot.create_slack_app()
+ try:
+ yield {
+ listener.ack_function.__name__: listener.ack_function
+ for listener in app._async_listeners
+ }
+ finally:
+ with suppress(Exception):
+ await handler.close_async()
+ session = getattr(app.client, "session", None)
+ if session is not None and not session.closed:
+ await session.close()
+
+
+async def test_mention_replies_with_no_unawaited_coroutine() -> None:
+ """The whole handler path runs and replies exactly once.
+
+ The real guard against the classic sync->async miss is `AsyncMock`, which
+ distinguishes *called* from *awaited*: a coroutine that is created but
+ never awaited leaves `assert_awaited_once()` failing. (Promoting
+ RuntimeWarning to an error does NOT catch it — "coroutine was never
+ awaited" is raised from `__del__` during GC, where Python prints
+ "Exception ignored in" rather than failing the test.)
+
+ These tests call the listener directly, so Bolt's middleware and kwarg
+ injection are not exercised; `test_slack_lifespan.py` covers the wiring.
+ """
+ async with _listeners() as listeners:
+ with _Harness() as h:
+ await listeners["handle_mention"](
+ event=dict(MENTION_EVENT), say=h.say, client=h.client
+ )
+
+ h.chat.assert_awaited_once()
+ assert h.say.await_count == 1
+ assert h.say.await_args.kwargs["text"] == "the reply"
+
+
+async def test_blocking_retrieval_runs_off_the_event_loop() -> None:
+ """ChromaDB retrieval must not run inline on the application loop.
+
+ `retrieve()` embeds the query on CPU and can take seconds; inline it would
+ stall every other request in the process (`/chat`, `/health`, the
+ scheduler, the Discord bot). api/routes/chat.py offloads the same call.
+ """
+ main_thread = threading.current_thread().name
+ async with _listeners() as listeners:
+ with _Harness() as h:
+ await listeners["handle_mention"](
+ event=dict(MENTION_EVENT), say=h.say, client=h.client
+ )
+
+ assert h.retrieve_threads, "retrieve() was never called"
+ assert main_thread not in h.retrieve_threads, (
+ "retrieve() ran on the event-loop thread — it must be offloaded "
+ f"(threads seen: {h.retrieve_threads})"
+ )
+
+
+async def test_retrieval_reuses_the_warm_store() -> None:
+ """Passing the lifespan's store avoids building a ChromaDB client per message."""
+ async with _listeners() as listeners:
+ with _Harness() as h:
+ await listeners["handle_mention"](
+ event=dict(MENTION_EVENT), say=h.say, client=h.client
+ )
+
+ assert h.store_arg == "WARM_STORE"
+
+
+async def test_inbound_handling_is_concurrency_bounded() -> None:
+ """The async client caps nothing; the adapter must cap itself.
+
+ The sync adapter was bounded by Bolt's listener_executor
+ (ThreadPoolExecutor(max_workers=5)), so a burst of Slack traffic could
+ never fan out into more than 5 concurrent `executive.chat()` calls. The
+ async client caps nothing, so the adapter has to cap itself.
+ """
+ peak = 0
+ current = 0
+
+ async def _slow_chat(**_: Any) -> str:
+ nonlocal peak, current
+ current += 1
+ peak = max(peak, current)
+ await asyncio.sleep(0.05)
+ current -= 1
+ return "the reply"
+
+ async with _listeners() as listeners:
+ with _Harness() as h:
+ h.chat.side_effect = _slow_chat
+ await asyncio.gather(*(
+ listeners["handle_mention"](
+ event=dict(MENTION_EVENT), say=h.say, client=h.client
+ )
+ for _ in range(25)
+ ))
+
+ assert h.say.await_count == 25, "some messages were dropped"
+ assert peak <= slack_bot._MAX_CONCURRENT_HANDLERS, (
+ f"{peak} handlers ran concurrently, bound is "
+ f"{slack_bot._MAX_CONCURRENT_HANDLERS}"
+ )
diff --git a/packages/core/tests/unit/test_slack_lifespan.py b/packages/core/tests/unit/test_slack_lifespan.py
new file mode 100644
index 00000000..d6b093cb
--- /dev/null
+++ b/packages/core/tests/unit/test_slack_lifespan.py
@@ -0,0 +1,244 @@
+"""The Slack Socket Mode listener starts and stops with the FastAPI app.
+
+Regression cover for #131: `run_slack_bot()` existed but nothing in the
+application lifecycle ever called it, so `make dev` brought up uvicorn and the
+UI while Slack silently never listened.
+
+These tests drive the real `create_app()` lifespan through `TestClient` as a
+context manager (entering it is what runs startup/shutdown) and assert on a
+faked `create_slack_app`, so no Slack credentials or network are involved.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from contextlib import suppress
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastapi.testclient import TestClient
+
+from openexecutive.api.main import create_app
+
+
+def fake_handler() -> MagicMock:
+ """Stand-in for `AsyncSocketModeHandler`."""
+ handler = MagicMock()
+ handler.connect_async = AsyncMock()
+ handler.close_async = AsyncMock()
+ return handler
+
+
+def _settings_with_slack(monkeypatch: pytest.MonkeyPatch, **overrides: Any) -> None:
+ """Make `get_settings()` inside the lifespan report the given Slack tokens.
+
+ A real `Settings` copy, not a mock — the lifespan reads dozens of other
+ fields off it, and every one of them must keep its true value.
+ """
+ from openexecutive.config import get_settings
+
+ stub = get_settings().model_copy(
+ update={
+ "slack_bot_token": overrides.get("slack_bot_token", "xoxb-test"),
+ "slack_app_token": overrides.get("slack_app_token", "xapp-test"),
+ }
+ )
+ monkeypatch.setattr("openexecutive.config.get_settings", lambda: stub)
+
+
+def test_lifespan_connects_and_closes_slack_socket(
+ monkeypatch: pytest.MonkeyPatch, fake_handler: MagicMock
+) -> None:
+ """With both tokens set, startup connects the socket and shutdown closes it."""
+ _settings_with_slack(monkeypatch)
+ create = AsyncMock(return_value=(MagicMock(), fake_handler))
+ monkeypatch.setattr(
+ "openexecutive.integrations.slack_bot.create_slack_app", create
+ )
+
+ with TestClient(create_app()) as client:
+ # Startup has run by the time the context manager yields.
+ create.assert_awaited_once()
+ # Called, not yet necessarily awaited: create_task() records the call
+ # synchronously when it evaluates its argument.
+ fake_handler.connect_async.assert_called_once()
+ fake_handler.close_async.assert_not_awaited()
+ assert client.get("/health").status_code == 200
+
+ # Exiting the context manager runs shutdown. By now the background connect
+ # task has actually been driven, so assert it was *awaited*, not just called.
+ fake_handler.connect_async.assert_awaited_once()
+ fake_handler.close_async.assert_awaited_once()
+
+
+ ("bot_token", "app_token"),
+ [(None, "xapp-test"), ("xoxb-test", None), (None, None)],
+)
+def test_lifespan_skips_slack_without_both_tokens(
+ monkeypatch: pytest.MonkeyPatch,
+ fake_handler: MagicMock,
+ bot_token: str | None,
+ app_token: str | None,
+) -> None:
+ """Socket Mode needs both tokens — a partial config must not half-start it.
+
+ This is also what keeps every other full-app test isolated: conftest never
+ sets the Slack tokens, so the block stays inert.
+ """
+ _settings_with_slack(monkeypatch, slack_bot_token=bot_token, slack_app_token=app_token)
+ create = AsyncMock(return_value=(MagicMock(), fake_handler))
+ monkeypatch.setattr(
+ "openexecutive.integrations.slack_bot.create_slack_app", create
+ )
+
+ with TestClient(create_app()):
+ pass
+
+ create.assert_not_awaited()
+ fake_handler.connect_async.assert_not_awaited()
+ fake_handler.close_async.assert_not_awaited()
+
+
+def test_slack_connect_failure_does_not_block_startup(
+ monkeypatch: pytest.MonkeyPatch, fake_handler: MagicMock
+) -> None:
+ """A bad token must degrade to "no Slack", never take the whole app down."""
+ _settings_with_slack(monkeypatch)
+ fake_handler.connect_async = AsyncMock(side_effect=RuntimeError("invalid auth"))
+ monkeypatch.setattr(
+ "openexecutive.integrations.slack_bot.create_slack_app",
+ AsyncMock(return_value=(MagicMock(), fake_handler)),
+ )
+
+ with TestClient(create_app()) as client:
+ assert client.get("/health").status_code == 200
+
+ # The handler object still exists, so shutdown must still release it —
+ # a half-open socket-mode client left unclosed keeps aiohttp resources
+ # alive and hangs the process.
+ fake_handler.close_async.assert_awaited_once()
+
+
+def test_slack_connect_that_never_returns_does_not_block_startup(
+ monkeypatch: pytest.MonkeyPatch, fake_handler: MagicMock
+) -> None:
+ """The real hazard: `connect_async()` does not fail fast.
+
+ On a bad app token or an unreachable Slack it retries internally and never
+ returns. Awaiting it in the lifespan hung boot forever (observed: startup
+ never completed, process had to be killed). It must run as a background
+ task instead, so startup finishes and shutdown cancels it.
+ """
+ _settings_with_slack(monkeypatch)
+ never_returns = asyncio.Event() # never set
+
+ async def _hang() -> None:
+ await never_returns.wait()
+
+ fake_handler.connect_async = AsyncMock(side_effect=_hang)
+ monkeypatch.setattr(
+ "openexecutive.integrations.slack_bot.create_slack_app",
+ AsyncMock(return_value=(MagicMock(), fake_handler)),
+ )
+
+ # Run the whole lifespan on a worker thread so a regression FAILS this
+ # test instead of hanging the suite forever (there is no pytest-timeout
+ # plugin here, and a blocked startup never reaches an assert).
+ done = threading.Event()
+ box: dict[str, Any] = {}
+
+ def _run() -> None:
+ try:
+ with TestClient(create_app()) as client:
+ box["status"] = client.get("/health").status_code
+ except BaseException as exc: # noqa: BLE001 - reported below
+ box["error"] = exc
+ finally:
+ done.set()
+
+ worker = threading.Thread(target=_run, daemon=True)
+ worker.start()
+ finished = done.wait(timeout=60)
+
+ assert finished, "startup blocked on Slack connect — lifespan awaited it directly"
+ assert "error" not in box, f"lifespan raised: {box.get('error')!r}"
+ assert box["status"] == 200
+
+ # Shutdown cancels the still-pending connect and closes the handler.
+ fake_handler.close_async.assert_awaited_once()
+
+
+def test_slack_close_failure_does_not_break_shutdown(
+ monkeypatch: pytest.MonkeyPatch, fake_handler: MagicMock
+) -> None:
+ """A stalled disconnect is logged, not propagated out of the lifespan."""
+ _settings_with_slack(monkeypatch)
+ fake_handler.close_async = AsyncMock(side_effect=RuntimeError("socket gone"))
+ monkeypatch.setattr(
+ "openexecutive.integrations.slack_bot.create_slack_app",
+ AsyncMock(return_value=(MagicMock(), fake_handler)),
+ )
+
+ with TestClient(create_app()):
+ pass # exiting must not raise
+
+ fake_handler.close_async.assert_awaited_once()
+
+
+def test_shutdown_is_bounded_even_if_the_socket_refuses_to_die(
+ monkeypatch: pytest.MonkeyPatch, fake_handler: MagicMock
+) -> None:
+ """Shutdown must honour its deadline, not hang, on a wedged socket.
+
+ Regression guard. The first version of this teardown did
+ ``with suppress(CancelledError, Exception): await slack_connect_task`` —
+ but `asyncio.wait_for` enforces its deadline BY cancelling the coroutine,
+ so that suppress() swallowed the deadline and the lifespan hung forever.
+ Here the connect task ignores cancellation and close_async() never
+ returns; shutdown must still finish, on the timeout path.
+ """
+ _settings_with_slack(monkeypatch)
+ monkeypatch.setattr("openexecutive.api.main.SLACK_SHUTDOWN_TIMEOUT_S", 0.5)
+
+ async def _ignores_cancellation() -> None:
+ # Swallows cancellation for well past the deadline, then exits. Short
+ # sleeps, not one long one: a swallowed cancel would otherwise leave
+ # the task parked in the next sleep forever, and an immortal task
+ # wedges the event loop's own teardown rather than testing shutdown.
+ for _ in range(60):
+ with suppress(asyncio.CancelledError):
+ await asyncio.sleep(0.05)
+
+ async def _never_returns() -> None:
+ await asyncio.sleep(3600)
+
+ fake_handler.connect_async = AsyncMock(side_effect=_ignores_cancellation)
+ fake_handler.close_async = AsyncMock(side_effect=_never_returns)
+ monkeypatch.setattr(
+ "openexecutive.integrations.slack_bot.create_slack_app",
+ AsyncMock(return_value=(MagicMock(), fake_handler)),
+ )
+
+ done = threading.Event()
+ box: dict[str, Any] = {}
+
+ def _run() -> None:
+ try:
+ with TestClient(create_app()) as client:
+ box["status"] = client.get("/health").status_code
+ except BaseException as exc: # noqa: BLE001 - reported below
+ box["error"] = exc
+ finally:
+ done.set()
+
+ threading.Thread(target=_run, daemon=True).start()
+
+ assert done.wait(timeout=30), (
+ "lifespan hung on shutdown — the wait_for deadline was swallowed"
+ )
+ assert "error" not in box, f"lifespan raised: {box.get('error')!r}"
+ assert box["status"] == 200