Skip to content

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

fix(integrations): give email turns, gateway calls and the chat stream deadlines (#463)

Rufusa7ef7a920a0f
diff --git a/.env.example b/.env.example
index 6e32cb0b..25da91a1 100644
--- a/.env.example
+++ b/.env.example
@@ -172,6 +172,13 @@ LOCAL_INCLUDE_USAGE_ACCOUNTING=false
# Extra allowance added on top when a message opts in to Committee review, so
# 360s in total at the defaults.
# COMMITTEE_EXTRA_TIMEOUT_S=60
+# How often a streaming /chat turn sends an SSE keepalive comment while nothing
+# else is going out, so a browser or proxy doesn't drop it during a slow tool
+# call. 0 turns it off.
+# CHAT_STREAM_KEEPALIVE_S=15
+# Ceiling on one call through the MCP gateway (Gmail, Calendar, Drive, Outlook,
+# OneDrive). A call past it is abandoned and reported as not answered.
+# MCP_TOOL_TIMEOUT_S=120
# Per-call ceiling for the onboarding interview. Kept separate from the chat
# ceiling: the wizard retries twice, so a 300s value here would mean a 10-minute
# hang before the user sees a timeout.
@@ -258,6 +265,9 @@ [email protected]
# AI_DISCLOSURE_APPROVED_SENDS=false
# How often the email poller checks for new messages (seconds, default 60)
EMAIL_POLL_INTERVAL_SECONDS=60
+# Whole-turn ceiling for the Executive's answer to one inbound email (seconds).
+# A message that runs past it is marked read and not tried again.
+# EMAIL_TURN_TIMEOUT_S=300
# Channel access (Email/Telegram/Discord) is roster-driven: only senders
# whose channel ID matches a non-archived Person row receive a response.
# Manage access via the /people UI; no env-var allowlists.
diff --git a/docs/architecture.md b/docs/architecture.md
index 20373a3a..478e3071 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -577,6 +577,9 @@ All settings via environment variables (`.env` file in `packages/core/`).
| `SLACK_SIGNING_SECRET` | No | — | Slack signing secret: hear Slack over HTTP at `/webhook/slack` instead of socket mode |
| `EXEC_EMAIL_ADDRESS` | Yes | — | Executive Gmail address (Gmail MCP OAuth) |
| `EMAIL_POLL_INTERVAL_SECONDS` | No | `60` | Email poll frequency |
+| `EMAIL_TURN_TIMEOUT_S` | No | `300` | Ceiling on the Executive's answer to one inbound email; past it the message is marked read and skipped |
+| `MCP_TOOL_TIMEOUT_S` | No | `120` | Ceiling on one MCP gateway call (Gmail, Calendar, Drive, Outlook, OneDrive) |
+| `CHAT_STREAM_KEEPALIVE_S` | No | `15` | Interval of the SSE keepalive comment on a quiet chat stream; 0 turns it off |
| `TELEGRAM_BOT_TOKEN` | No | — | Telegram bot token |
| `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 |
diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.py
index aa702127..5a2ad7f6 100644
--- a/packages/core/openexecutive/api/routes/chat.py
+++ b/packages/core/openexecutive/api/routes/chat.py
@@ -283,7 +283,11 @@ class _StreamStep(NamedTuple):
"""One step of the SSE driver loop.
Exactly one of these is true: `item` holds a produced value, or `exhausted`
- / `stopped` / `timed_out` says why nothing was produced.
+ / `stopped` / `timed_out` / `idle` says why nothing was produced.
+
+ `idle` means the keepalive interval passed with the step still running:
+ `pending` is that step, still in flight, for the caller to send a
+ keepalive and hand back to the next call. The caller owns cancelling it.
"""
item: Any = None
@@ -291,6 +295,15 @@ class _StreamStep(NamedTuple):
exhausted: bool = False
stopped: bool = False
timed_out: bool = False
+ idle: bool = False
+ pending: asyncio.Task[Any] | None = None
+
+
+# What the SSE stream sends while a turn is quiet: a comment line, which every
+# SSE reader (the web chat's included, which reads only `data:` lines) skips.
+# It keeps a browser or a proxy from dropping the connection as idle during a
+# slow tool call or specialist round.
+_SSE_KEEPALIVE = ": keepalive\n\n"
async def _cancel_stream_step(anext_task: asyncio.Task[Any], turn_id: str) -> None:
@@ -329,9 +342,17 @@ async def _next_stream_step(
stop_waiter: asyncio.Task[bool] | None,
remaining: float,
turn_id: str,
+ *,
+ keepalive_s: float = 0.0,
+ pending: asyncio.Task[Any] | None = None,
) -> _StreamStep:
"""Advance `stream` one step, racing the stop switch and the deadline.
+ With `keepalive_s`, it also returns `idle` once that long passes with the
+ step still running and the deadline not yet reached, leaving the step in
+ flight (`pending`); the caller sends a keepalive and passes it back as
+ `pending` to go on waiting on the same step.
+
Extracted from the driver loop because the ordering here is load-bearing in
several ways and is much easier to reason about — and to test — on its own.
@@ -348,13 +369,19 @@ async def _next_stream_step(
# and like it this COPIES the current context, so the `set_turn` /
# `set_session` bindings made in `event_generator` are inherited by every
# step. See that function's comment for why that matters.
- anext_task: asyncio.Task[Any] = asyncio.ensure_future(stream.__anext__())
+ anext_task: asyncio.Task[Any] = (
+ pending if pending is not None else asyncio.ensure_future(stream.__anext__())
+ )
+ # Whether the step is handed back still running (`idle`), the one exit
+ # that does not cancel it.
+ keep = False
+ wait_s = min(remaining, keepalive_s) if keepalive_s > 0 else remaining
try:
waiters: set[asyncio.Future[Any]] = {anext_task}
if stop_waiter is not None:
waiters.add(stop_waiter)
await asyncio.wait(
- waiters, timeout=remaining, return_when=asyncio.FIRST_COMPLETED
+ waiters, timeout=wait_s, return_when=asyncio.FIRST_COMPLETED
)
if anext_task.done():
@@ -370,11 +397,15 @@ async def _next_stream_step(
if stop_waiter is not None and stop_waiter.done():
return _StreamStep(stopped=True)
+ if wait_s < remaining:
+ keep = True
+ return _StreamStep(idle=True, pending=anext_task)
return _StreamStep(timed_out=True)
finally:
- # Every exit: stop, deadline, AND an outer cancellation from a client
- # disconnect. Never leave the step running.
- await _cancel_stream_step(anext_task, turn_id)
+ # Every exit but `idle`: stop, deadline, AND an outer cancellation
+ # from a client disconnect. Never leave the step running unowned.
+ if not keep:
+ await _cancel_stream_step(anext_task, turn_id)
def _request_stop(client_turn_id: str, owner: str) -> str | None:
@@ -1388,6 +1419,9 @@ async def _run_chat_turn(
if stop_event is not None
else None
)
+ # A step left running across a keepalive (`_StreamStep.idle`).
+ # Every way out of the loop below cancels it in its `finally`.
+ pending: asyncio.Task[Any] | None = None
try:
while True:
if stop_event is not None and stop_event.is_set():
@@ -1416,8 +1450,15 @@ async def _run_chat_turn(
break
step = await _next_stream_step(
- stream, stop_waiter, remaining, turn_id
+ stream, stop_waiter, remaining, turn_id,
+ keepalive_s=settings.chat_stream_keepalive_s,
+ pending=pending,
)
+ pending = step.pending
+
+ if step.idle:
+ yield _SSE_KEEPALIVE
+ continue
if step.exhausted:
break
@@ -1465,6 +1506,10 @@ async def _run_chat_turn(
)
break
finally:
+ if pending is not None:
+ # Before the stream's `aclose` below, which raises on a
+ # generator whose step is still running.
+ await _cancel_stream_step(pending, turn_id)
if stop_waiter is not None:
# Otherwise: "Task was destroyed but it is pending".
stop_waiter.cancel()
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 9c9b5ce2..e7f85156 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -7415,6 +7415,34 @@ integrations:
The old env-var allowlists (EMAIL_ALLOWED_SENDERS /
TELEGRAM_ALLOWED_CHAT_IDS / DISCORD_ALLOWED_USER_IDS) have been
removed; access is managed entirely via the /people UI.
+ mcp_tool_timeout: |
+ Every call through MCPGateway to the extensible-mcp child (call_tool,
+ search_tools, load_mcp_server and the M365 gate lookups in
+ _fetch_m365_json) goes through mcp_gateway._session_call, which bounds
+ it with MCP_TOOL_TIMEOUT_S (120 s) and raises GatewayCallTimeout (a
+ TimeoutError) past it. MCPGateway.call_tool turns that into an error
+ payload ({"error": "... did not answer within N s. It may still have
+ run ...", "timed_out": true}) and skips everything after the call: no
+ outbound linkage, artifact row or grant-health reading for a call that
+ may not have happened. Gate lookups read a timeout as a failed lookup
+ (None), which the gates refuse on. Why: a hung workspace server held
+ whatever awaited it for good: the serial email poller, a brief, a chat
+ turn until its whole-turn deadline. The server is not told to cancel,
+ so a send that timed out may still go: the roster acknowledgement
+ (roster_intake.send_email_ack) raises AckUncertain on a timed_out
+ payload and keeps its claim (roster_ack_uncertain row) so no second
+ acknowledgement follows, and a turn cut off with MCP calls in flight
+ writes a CANCELLED tool_invocation row for each (Executive agent loop).
+ chat_stream_keepalive: |
+ The /chat SSE body sends ": keepalive\n\n" (an SSE comment, skipped by
+ every reader; the UI reads only data: lines) when CHAT_STREAM_KEEPALIVE_S
+ (15 s, 0 = off) passes with the Executive's step still running.
+ _next_stream_step waits min(remaining, keepalive) and returns idle with
+ the step still in flight (pending); the loop yields the comment and
+ passes pending back, so nothing restarts. Every other exit cancels the
+ step, and the loop's finally cancels a pending one before the stream's
+ aclose. The whole-turn deadline is unchanged. Why: browsers and proxies
+ drop an idle stream well inside CHAT_STREAM_TIMEOUT_S.
email_poller: |
MCP poll loop in openexecutive.integrations.email_poller — runs
as an asyncio task in the FastAPI lifespan, started by
@@ -7446,6 +7474,16 @@ integrations:
block. The outbound gate at ``mcp_gateway._check_gmail_recipients`` /
``_check_m365_recipients`` is the actual security boundary against
auto-replying to spam.
+ Deadlines: the loop is serial (one message at a time), so the
+ Executive turn on each email runs under asyncio.timeout
+ (EMAIL_TURN_TIMEOUT_S, 300 s). Past it the turn is cancelled
+ (EmailTurnTimeout; a TimeoutError raised inside the turn is not
+ mistaken for it), an integration_inbound row with outcome turn_timeout
+ is written (private when the mail is), and the message is marked read
+ and not run again, since the turn may already have replied. A message
+ whose handling raises is retried on the next polls up to _MAX_ATTEMPTS
+ (3) per run, then given up and marked read. Every gateway call it makes
+ is bounded by MCP_TOOL_TIMEOUT_S (see mcp_tool_timeout).
Mail from one of the principal's CONTACTS gets a contact [POLICY]
notice instead (`_contact_notice`): it names them (name, role /
company), says not to reply unless the principal asks, and asks for
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index b72d1730..b99f9149 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
"mermaid": null,
- "generated_at": "2026-10-13T22:40:00Z"
+ "generated_at": "2026-10-14T06:00:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index 13a05685..5cd5d2c3 100644
--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json
+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json
@@ -1,7 +1,7 @@
{
"section_id": "integrations",
"title": "Integrations",
- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. Responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it. It does look its sender up on People by the Google account email on the signed event, but hands that entry only to the department gate (`Session.gate_sender_person_id`): the principal's own sends and edits go, a teammate's meet their department's authority, and anyone else's wait for approval. It is never `caller_person_id`, so it grants nothing else.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.session_title.generate_session_title` (the first words of the message if that fails), as a web chat's first turn does. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected. Once the guard allows a send, the handlers apply the recipient's own notification settings to the Executive's own (tagged) outreach: in their quiet hours, or when they chose *In my briefs*, the DM is stored and returned as `{\"status\":\"held\"}` rather than sent, and goes when quiet hours end or with their next brief (`outbound_guard.check_hold`; see Org).\n\n### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.",
+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. Responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it. It does look its sender up on People by the Google account email on the signed event, but hands that entry only to the department gate (`Session.gate_sender_person_id`): the principal's own sends and edits go, a teammate's meet their department's authority, and anyone else's wait for approval. It is never `caller_person_id`, so it grants nothing else.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The poller handles one message at a time, so each Executive turn on an email has a deadline, `EMAIL_TURN_TIMEOUT_S` (300 s): past it the turn is cut off, an `integration_inbound` row with outcome `turn_timeout` records it, and the message is marked read and not run again (it may already have replied). A message whose handling keeps raising is given up after three tries in a run and marked read, rather than retried every poll. Each gateway call it makes is bounded by `MCP_TOOL_TIMEOUT_S` (see Lifecycle). The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from a teammate other than the principal is read the same way, before its inbound audit row is written: authenticated, the whole handling of it is theirs alone in the audit log (`rows_for_person`, see Audit) and the turn reads their own mail as them (`Session.email_sender_authenticated`); unauthenticated, it keeps the ordinary rule. Mail from anyone else costs no second read and is never authenticated. `fact_tools._gate` admits an email turn only from the principal's **primary** address, exactly (no alias, no company-domain rule), authenticated, and not private to the principal (mail they forwarded stays refused, as do contacts, teammates and unknown senders).\n- **The hold.** The tool returns `awaiting_confirmation` (no action chip, and the model is told to say nothing has changed). `request_confirmation` stores the change with the SHA-256 of a fresh one-time token (`FC-` + 20 base32 characters, 100 bits; 7-day expiry; at most 10 waiting at once) and emails the token to the principal's roster address, outside any turn's outbound context. A profile edit is dry-run first, so one that cannot apply is reported in the turn, before any email goes out. If the email fails, nothing is held.\n- **Keeping the token from any model.** The tool result never carries it, and `mcp_gateway.hide_roster_tokens` now scrubs `FC-` tokens as well as `RR-` ones (`FC-[hidden]`) from every Google Workspace result except the poller's own fetch of an inbound message. Act as me's reads of the principal's own Gmail, where the confirmation email lands, hide them too (`delegation.gmail.parse_message` and the thread search), so the drafting model never sees a live token either.\n- **The reply.** `_handle_one_email` hands every message to `try_email_fact_confirmation` right after the roster-answer check, before any model turn. It acts only on a reply from the principal's primary address carrying the token of a **pending** confirmation. A made-up, spent, cancelled or expired reference matches nothing and falls through to the ordinary path with the token hidden, so no old or forged token can make the Executive email the principal. A reply with a live token is read again as raw MIME (`read_raw`) and must pass the same Gmail DMARC check as the request; one that doesn't (or whose raw read fails) is refused, the change keeps waiting, and the principal is told. Then an **automatic reply** is consumed quietly — no answer, no model turn, the change keeps waiting: the printed headers catch a Gmail vacation reply (`Precedence: bulk`), and the raw headers catch what they don't show (`automatic_reply`: `Auto-Submitted` other than `no`, `X-Auto-Response-Suppress` and similar, `Precedence: auto_reply`, an out-of-office subject), since an Exchange out-of-office echoes the token from the principal's own address and may well say \"I'll confirm on my return\". The raw message starts at the tool's exact separator line (`\\n\\n--- RAW MIME ---\\n`), so a sender-written Subject imitating it cannot supply the headers. CONFIRM (or yes / approve) applies the change through `fact_tools.apply_confirmed`, the same apply step chat uses. CANCEL (or no) drops it, and an unclear reply leaves it waiting. The principal gets a one-line result either way. A compare-and-set on the row means two replies can apply it only once.\n- **Audit.** Private `fact_confirmation` rows record held / applied / cancelled / refused. The applied change also writes the fact tools' usual private rows, with `source_channel=\"email\"` as its provenance.\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. A listening Slack is amber while the listener hasn't resolved its own user id (`slack_bot.bot_user_id()`), since thread continuations are off until it does. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with. Gmail is also amber when startup priming could not find every pinned Google tool (`MCPGateway.prime_pinned_tools`, whose result the gateway keeps on `pinned_tools`): the row names a few of the missing tools and counts the rest, and points at the `MCPGateway` log lines. It is amber too while that probe has not finished, and when the probe itself failed — the one check that reads green is the one that ran and found everything, so a crashed probe is never silently fine. The row speaks for the whole `google_workspace` server, so a missing Docs or Drive tool shows up under Email (Gmail).\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\n**Conversations within a chat app.** A Telegram chat, a Slack or Discord DM and a person's @mentions in one channel (`slack:channel:…`, `discord:channel:…`) are each one endless stream, so they are cut into conversations (`memory.conversations`, shared helpers in `integrations/conversations.py`). Each adapter computes the stream's base id as before and asks `conversation_for` which conversation a message belongs to: the newest, unless the stream has been quiet for two hours (`CONVERSATION_GAP`), when the next one starts. The first conversation keeps the bare base id; later ones add `~2`, `~3`, … (`memory.conversation_ids`). A whole message of `/new`, \"new chat\" or \"new conversation\" starts a fresh one instead of a turn and is answered with the name of the one it ended; the new row has no messages and stays off the Chats page until its first turn. After a conversation's first exchange `title_after_turn` names it in the background with `utils.session_title.generate_session_title` (the first words of the message if that fails), as a web chat's first turn does. Threads (`slack:thread:…`, `discord:thread:…`), email and every other id are left whole. What has to see the whole stream compares base ids: the inbound resolver, so an approval asked before a cut is answered after it, and the session-scoped decisions and advice `format_for_prompt` renders. At boot `split_existing_streams` cuts history saved before this by the same rule, once (`app_migrations`), titling each part from its first message and carrying a read-mail lock to every part. An adapter installed outside the package adds its streams with `conversation_ids.register_rolling` and cuts its own old history once, with its own migration name and an `only` filter for its base ids, because the built-in sweep may already have run without it.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the tier `WORKSPACE_MCP_TOOL_TIER` names, `complete` by default, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The optional `WORKSPACE_MCP_TOOLS` (comma-separated service names, default `all`) limits which Google services it loads. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account).\n\n**What the model is told is connected.** `MCPGateway.start()` records the configured server names (`server_names`), and the Executive renders them with the channel settings into block 0's *Connected Systems* section (`prompts.connected_systems`; see the caching section). While Google is connected that section pins the Google tool names the Executive uses constantly (`GOOGLE_TOOL_MANIFEST`, narrowed by `connected_systems.google_tool_manifest` to the services and tier actually loaded) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. The narrowing is the point: a name pinned for a service workspace-mcp never imported is not in the index, so the model calls it, receives extensible-mcp's “has not been discovered via search_tools” refusal, and has no way to square that with its own instructions. extensible-mcp only runs a tool one of the session's searches has returned, and remembers it for the session's life, so the gateway does that discovery itself: the lifespan starts `MCPGateway.prime_pinned_tools()` in the background once the gateway is up with `google_workspace` configured (an exact-name search per pinned tool, the way `workflows.tool_catalog.resolve` does it, over the same narrowed set the prompt advertises — `connected_systems.pinned_google_tools`, so priming never probes a service that was not loaded). A name neither the prompt nor priming can account for is logged once, naming both causes: excluded by `WORKSPACE_MCP_TOOLS` / `WORKSPACE_MCP_TOOL_TIER`, or renamed by workspace-mcp since the pin. A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. All three per-Person DMs refuse a recipient id that matches no non-archived Person row (`schedule_tools._dm_recipient_on_roster`), which is what stops untrusted content in a turn — inbound mail, a chat message, a knowledge document — from directing a DM at an arbitrary workspace member. `send_slack_dm` previously consulted the roster only when the turn was already private to the principal, so on an ordinary turn it applied no roster check at all while its Discord and Telegram siblings did; the room-targeted tools are deliberately ungated, since those channels are team-visible. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected. Once the guard allows a send, the handlers apply the recipient's own notification settings to the Executive's own (tagged) outreach: in their quiet hours, or when they chose *In my briefs*, the DM is stored and returned as `{\"status\":\"held\"}` rather than sent, and goes when quiet hours end or with their next brief (`outbound_guard.check_hold`; see Org).\n\n### AI disclosure\n\nWhat the Executive sends says it is an AI assistant (`orchestrator.disclosure`), added by plain code so a reply the model writes can't leave it out. **Mail** from its own mailbox gets a line under the body, by default \"<EXEC_DISPLAY_NAME> is an AI assistant working for <company>. To reach a person, reply and ask, or write to <principal's address>.\": the MCP gateway adds it to every Gmail send and draft and every Outlook send, reply, forward and draft (`mcp_gateway._with_disclosure`) **after** every outbound gate has passed and only on what goes to the server, so the gates, the outbound-context record and the audit see the model's own words, and `send_from_executive` gets it the same way. It counts as already there only when it is the last line that shows (in a quoted earlier message or hidden in markup it doesn't), and a send of an existing draft and mail whose every recipient is the principal go as they are. HTML that could hide what follows (an unclosed comment, a style or script block, text styled out of sight: `disclosure.hides_what_follows`) is refused, so the line can't be hidden after it; the model is told to send plain text. The roster acknowledgement to a new sender, the one send to an address nobody checked, gets `BARE_MAIL_LINE` (\"This message was sent by an AI assistant.\"), which names no one, like the acknowledgement itself. **Chat** gets a shorter line (\"<name> · AI assistant\", in italics) on the Executive's replies in Slack, Telegram, Discord and Google Chat and on its own DMs and room posts (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`, `broadcast_tools._dispatch`), but only on the first message in a conversation and again after 24 hours without one (`with_chat_line`, kept in memory, so a restart shows it once more); session history keeps the reply without it. `AI_DISCLOSURE` (default on) turns it off; `AI_DISCLOSURE_MAIL_TEXT` / `AI_DISCLOSURE_CHAT_TEXT` reword the lines, and a wording that doesn't say \"AI\" is ignored for the built-in one. It fails open: a line that can't be built is left off, never a send refused. Replies sent *as a person* under Act as me are the delegation section's (**AI line on replies**).\n\n### Calendar & video links\n\nThe Executive books meetings through two typed tools over the configured calendar backend (`CALENDAR_PROVIDER`: Google Calendar via `manage_event`, or Outlook via `create-calendar-event` — see *Workspace providers*). `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Because nothing approves it, an instant meeting, and `cancel_calendar_event` too, runs only when someone on the team asked on a surface that verified who they are (the principal, or a rostered teammate in the app or their own chat); a turn an inbound email started gets a refusal to pass on instead, and a team-mode `create_calendar_event` the operations department would auto-execute is proposed instead. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.",
"mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop\"]\n Hold[\"roster request<br/>(hold + fixed ack,<br/>ask the principal)\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n GW[\"Google Workspace<br/>(workspace-mcp child)\"]\n M365[\"Microsoft 365<br/>(ms-365-mcp-server child:<br/>Outlook + OneDrive)\"]\n WP[\"workspace providers<br/>(poller / alerts / booking)\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Hold\n Hold -- \"approved: replay\" --> Exec\n Hold -- \"contact / declined\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n MCP -- \"roster egress gate\" --> GW\n MCP -- \"roster egress gate\" --> M365\n WP -- \"EMAIL_PROVIDER / CALENDAR_PROVIDER\" --> MCP\n WP --> Exec\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n Own[(\"Principal's own Gmail<br/>(Act as me: REST, drafts only)\")]\n Exec -- \"ghostwrite_email\" --> Own\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Hold compute\n class Exec hot\n class Attach compute\n class MCP external\n class GW external\n class M365 external\n class WP compute\n class Guard compute\n class Out compute\n class Own external",
- "generated_at": "2026-10-14T05:40:00Z"
+ "generated_at": "2026-10-14T06:15:00Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
index af53cf5b..fdd7cde2 100644
--- a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
+++ b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
@@ -1,7 +1,7 @@
{
"section_id": "lifecycle",
"title": "Request Lifecycle",
- "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. A tagged DM is also subject to the recipient's own notification settings: in their quiet hours, or when they chose *In my briefs*, the send handler stores it (`outbound_guard.check_hold`, `people.held_messages`) and returns `{\"status\": \"held\"}` instead of sending (see Org). Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.",
+ "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. A tagged DM is also subject to the recipient's own notification settings: in their quiet hours, or when they chose *In my briefs*, the send handler stores it (`outbound_guard.check_hold`, `people.held_messages`) and returns `{\"status\": \"held\"}` instead of sending (see Org). Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. While nothing else is going out — a slow tool call, a long specialist round — the route sends an SSE comment (`: keepalive`) every `CHAT_STREAM_KEEPALIVE_S` (15 s by default, 0 for none) so a browser or proxy does not drop the connection as idle; the step it waits on keeps running across it, and the whole-turn deadline is unchanged. Every call through the MCP gateway (Gmail, Calendar, Drive, Outlook, OneDrive, tool search) has its own ceiling, `MCP_TOOL_TIMEOUT_S` (120 s): past it the model gets an error saying the tool did not answer and may still have run, so it checks before calling again, and no outbound linkage is recorded for a send that timed out. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.",
"mermaid": "sequenceDiagram\n participant C as Client\n participant API as FastAPI /chat\n participant E as Executive\n participant CL as Claude\n participant S as Specialists\n participant KB as ChromaDB\n C->>API: POST /chat message\n API->>E: start turn\n E->>CL: messages (tool-use loop)\n CL-->>E: consult_specialist calls\n E->>S: route_parallel fan-out\n S->>KB: domain-filtered RAG\n KB-->>S: chunks\n S-->>E: analysis tool_results\n E->>CL: synthesize\n CL-->>E: streamed reply\n E-->>API: SSE chunks then done\n API-->>C: streamed response",
- "generated_at": "2026-10-13T18:00:00Z"
+ "generated_at": "2026-10-14T06:00:00Z"
}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index 17651587..8132e8d3 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -430,6 +430,12 @@ class Settings(BaseSettings):
# typically 5–12s.
committee_extra_timeout_s: float = Field(60.0, alias="COMMITTEE_EXTRA_TIMEOUT_S")
+ # How often a streaming chat turn sends an SSE comment while nothing else
+ # is going out (a slow tool call, a long specialist round). Browsers and
+ # proxies drop an idle stream, often after 30-60s, well inside the
+ # whole-turn deadline above. 0 turns it off.
+ chat_stream_keepalive_s: float = Field(15.0, alias="CHAT_STREAM_KEEPALIVE_S", ge=0)
+
# Per-call ceiling for the onboarding interview. It used to borrow
# chat_stream_timeout_s, which meant raising that to 300s would have let the
# wizard's 2-attempt retry loop hang for up to 600s before surfacing
@@ -503,6 +509,16 @@ class Settings(BaseSettings):
ai_disclosure_handle_it: bool = Field(True, alias="AI_DISCLOSURE_HANDLE_IT")
ai_disclosure_approved_sends: bool = Field(False, alias="AI_DISCLOSURE_APPROVED_SENDS")
email_poll_interval_seconds: int = Field(60, alias="EMAIL_POLL_INTERVAL_SECONDS")
+ # Whole-turn ceiling for the Executive's answer to one inbound email. The
+ # poller handles mail one message at a time, so a turn with no ceiling held
+ # every message behind it. A timed-out message is marked read and not tried
+ # again: the turn may already have replied.
+ email_turn_timeout_s: float = Field(300.0, alias="EMAIL_TURN_TIMEOUT_S", gt=0)
+ # Ceiling on one call through the MCP gateway (Gmail, Calendar, Drive,
+ # Outlook, OneDrive, tool search). A call past it is abandoned and reported
+ # as not answered, so a hung workspace server can't hold a turn, a brief or
+ # the email poller.
+ mcp_tool_timeout_s: float = Field(120.0, alias="MCP_TOOL_TIMEOUT_S", gt=0)
# Which Google services the co-located workspace-mcp child loads, and at
# which tier. These are the same two variables `docker/workspace-mcp-launch.sh`
diff --git a/packages/core/openexecutive/integrations/email_poller.py b/packages/core/openexecutive/integrations/email_poller.py
index c0b36d02..b60f8b79 100644
--- a/packages/core/openexecutive/integrations/email_poller.py
+++ b/packages/core/openexecutive/integrations/email_poller.py
@@ -49,6 +49,14 @@ POLL_INTERVAL_SECONDS = get_settings().email_poll_interval_seconds
# Prevents reprocessing the same message within a run (cleared on restart).
_processed_ids: set[str] = set()
+# Failed attempts per message this run. A message whose handling keeps
+# raising (a fetch that always fails, a bug its content trips) is given up
+# after _MAX_ATTEMPTS rather than retried every poll for the life of the
+# process, each attempt holding the queue behind it.
+_failed_attempts: dict[str, int] = {}
+_MAX_ATTEMPTS = 3
+# What a settings stub without `email_turn_timeout_s` gets (config's default).
+_DEFAULT_TURN_TIMEOUT_S = 300.0
_SKIP_SENDERS = ("noreply", "no-reply", "mailer-daemon", "postmaster", "do-not-reply")
@@ -59,6 +67,20 @@ def _mail_provider() -> MailProvider:
return get_mail_provider(get_settings())
+class EmailTurnTimeout(Exception):
+ """The Executive's turn for one email ran past ``EMAIL_TURN_TIMEOUT_S``."""
+
+ def __init__(self, timeout_s: float) -> None:
+ super().__init__(f"email turn ran past {timeout_s:.0f}s")
+ self.timeout_s = timeout_s
+
+
+def _turn_timeout_s() -> float:
+ """``EMAIL_TURN_TIMEOUT_S``, through this module's `get_settings` (tests
+ patch it with a stub that may not carry it)."""
+ return float(getattr(get_settings(), "email_turn_timeout_s", _DEFAULT_TURN_TIMEOUT_S))
+
+
# Section markers in the rendered inbound text (`workspace.mail.render_for_
# executive`, which mirrors get_gmail_message_content's layout): header
# lines, then the body, then an optional numbered attachment list whose lines
@@ -363,8 +385,25 @@ async def poll_once(gateway: MCPGateway, provider: MailProvider | None = None) -
try:
await _handle_email(gateway, mid, ref.thread_id, user_email, provider=provider)
_processed_ids.add(mid)
+ _failed_attempts.pop(mid, None)
except Exception:
- logger.exception("failed for message=%s", mid)
+ attempts = _failed_attempts.get(mid, 0) + 1
+ if attempts < _MAX_ATTEMPTS:
+ _failed_attempts[mid] = attempts
+ logger.exception("failed for message=%s (attempt %d of %d)", mid, attempts, _MAX_ATTEMPTS)
+ continue
+ logger.exception(
+ "failed for message=%s %d times — giving up on it; it is marked read",
+ mid, attempts,
+ )
+ _failed_attempts.pop(mid, None)
+ _processed_ids.add(mid)
+ # Marked read so a restart doesn't start the same failure over.
+ # The principal still finds it in the inbox, read.
+ try:
+ await _mark_read(gateway, mid, user_email, provider=provider)
+ except Exception:
+ logger.warning("could not mark message=%s read", mid, exc_info=True)
async def _handle_email(
@@ -589,6 +628,31 @@ async def _handle_one_email(
provider=provider,
teammate_authenticated=teammate_authenticated,
)
+ except EmailTurnTimeout as exc:
+ # Past EMAIL_TURN_TIMEOUT_S: the turn was cancelled where it
+ # stood. It is not run again, as with any turn that raised: it
+ # may already have replied, and running it again could reply
+ # twice. Marked read below, so the next message goes ahead.
+ timeout_s = exc.timeout_s
+ logger.error(
+ "Executive turn for message=%s ran past %.0fs — cut off; the message is marked read",
+ message_id, timeout_s,
+ )
+ audit_log(
+ "integration_inbound",
+ f"Answer to email from {from_addr} cut off after {timeout_s:.0f}s; "
+ "a reply may already have gone",
+ actor="email",
+ session_id=session_id,
+ details={
+ "channel": "email",
+ "message_id": message_id,
+ "from": from_addr,
+ "outcome": "turn_timeout",
+ "timeout_s": timeout_s,
+ },
+ private=private,
+ )
except Exception:
logger.exception("Executive raised for message=%s", message_id)
@@ -1005,17 +1069,30 @@ async def _run_executive(
# deeper Honcho prefetch) is a per-request opt-in on /chat only; it
# was previously forced on here for every inbound email, including
# off-roster senders the gateway will not let us reply to anyway.
- await executive.chat(
- user_message=base_message,
- session=session,
- retrieved_context=retrieve(query=raw_email[:500]),
- episodic_context=format_for_prompt(),
- person_id=person_id,
- co_present_person_ids=co_present_person_ids or None,
- # Only the sender's own words reach peer memory — see _email_memory_text.
- # An unrostered sender has no peer to record into, so skip the parse.
- memory_text=_email_memory_text(raw_email) if person_id is not None else None,
- )
+ #
+ # The poller handles one message at a time, so the turn has a ceiling
+ # (EMAIL_TURN_TIMEOUT_S): past it the turn is cancelled and
+ # EmailTurnTimeout reaches the caller, rather than one slow turn holding
+ # every message behind it. Any other TimeoutError from inside the turn
+ # passes through as it is.
+ timeout_s = _turn_timeout_s()
+ try:
+ async with asyncio.timeout(timeout_s) as deadline:
+ await executive.chat(
+ user_message=base_message,
+ session=session,
+ retrieved_context=retrieve(query=raw_email[:500]),
+ episodic_context=format_for_prompt(),
+ person_id=person_id,
+ co_present_person_ids=co_present_person_ids or None,
+ # Only the sender's own words reach peer memory — see _email_memory_text.
+ # An unrostered sender has no peer to record into, so skip the parse.
+ memory_text=_email_memory_text(raw_email) if person_id is not None else None,
+ )
+ except TimeoutError as exc:
+ if deadline.expired():
+ raise EmailTurnTimeout(timeout_s) from exc
+ raise
async def _mark_read(
diff --git a/packages/core/openexecutive/integrations/roster_intake.py b/packages/core/openexecutive/integrations/roster_intake.py
index c8d430b1..01362e59 100644
--- a/packages/core/openexecutive/integrations/roster_intake.py
+++ b/packages/core/openexecutive/integrations/roster_intake.py
@@ -27,6 +27,7 @@ from __future__ import annotations
import asyncio
import contextlib
import contextvars
+import json
import logging
import re
from collections.abc import Awaitable, Callable, Coroutine
@@ -100,6 +101,12 @@ def _suggest(channel: str, ref: str, display_name: str, profile_email: str | Non
return on_company, suggested
+class AckUncertain(Exception):
+ """Raised by an adapter's ``send_ack`` when it cannot tell whether the
+ acknowledgement went (the send timed out). Its claim is kept: a second
+ acknowledgement is worse than a missing one."""
+
+
class AckWithheld(Exception):
"""Raised by an adapter's ``send_ack`` to decline the acknowledgement
without sending anything — e.g. an email Gmail did not authenticate, whose
@@ -217,6 +224,14 @@ async def _acknowledge(
await asyncio.to_thread(
rr.release_ack, channel, request.channel_ref, request_id=request.id
)
+ except AckUncertain as uncertain:
+ # The send may have gone: the claim is kept, so the sender's next
+ # message does not draw a second acknowledgement.
+ _audit(
+ "roster_ack_uncertain",
+ f"Acknowledgement to a new {rr.channel_label(channel)} sender may have gone: {uncertain}",
+ {"request_id": request.id, "channel": channel},
+ )
except Exception:
logger.warning("roster_intake: acknowledgement on %s failed", channel, exc_info=True)
await asyncio.to_thread(
@@ -399,10 +414,22 @@ async def send_email_ack(gateway: Any, to: str) -> None:
"body": ACK_TEXT,
},
})
+ if _timed_out(result):
+ raise AckUncertain("the send did not answer in time; it may have gone")
if looks_like_error(result):
raise RuntimeError("acknowledgement email refused or failed")
+def _timed_out(result: Any) -> bool:
+ """Whether the gateway gave up waiting on the send (``timed_out`` in its
+ error payload), as opposed to refusing or failing it."""
+ try:
+ parsed = json.loads(result) if isinstance(result, str) else None
+ except ValueError:
+ return False
+ return isinstance(parsed, dict) and parsed.get("timed_out") is True
+
+
# Mail no human is waiting on an answer to. The header checks apply only to
# headers the Gmail tool prints; the address checks always do.
_AUTOMATED_LOCAL = re.compile(
diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.py
index 3bce8b27..58032dd2 100644
--- a/packages/core/openexecutive/orchestrator/executive.py
+++ b/packages/core/openexecutive/orchestrator/executive.py
@@ -2761,10 +2761,33 @@ class Executive:
logger.info("→ %s input=%s", tu["name"], _log_value(tu["name"], tu["input"]))
# Same isolation as the skill gather above: a gateway crash on
# one tool must not take the turn down with it.
- mcp_results = await asyncio.gather(
- *(_mcp_dispatch[tu["name"]](tu["input"]) for tu in mcp_tool_uses),
- return_exceptions=True,
- )
+ try:
+ mcp_results = await asyncio.gather(
+ *(_mcp_dispatch[tu["name"]](tu["input"]) for tu in mcp_tool_uses),
+ return_exceptions=True,
+ )
+ except asyncio.CancelledError:
+ # The turn was cut off (a deadline, a stop) with these
+ # calls in flight. A request already sent may still run
+ # on the server, a send included, so each gets its row,
+ # as run_script's calls do.
+ for tu in mcp_tool_uses:
+ tool_label = tu["input"].get("name", tu["name"]) if tu["name"] == "call_tool" else tu["name"]
+ audit_log(
+ "tool_invocation",
+ f"mcp:{tool_label} CANCELLED",
+ session_id=session_id,
+ turn_id=turn_id,
+ actor="executive",
+ details={
+ "tool": tool_label,
+ "kind": "mcp",
+ "iteration": iteration,
+ "ok": False,
+ "cancelled": True,
+ },
+ )
+ raise
for tu, raw in zip(mcp_tool_uses, mcp_results, strict=True):
tool_label = tu["input"].get("name", tu["name"]) if tu["name"] == "call_tool" else tu["name"]
if isinstance(raw, BaseException):
diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.py
index a556f48c..f71edaaa 100644
--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py
+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py
@@ -1851,6 +1851,35 @@ def _m365_implied_recipients(normalized: str, message: dict[str, Any]) -> list[s
_Discover = Callable[[str], Awaitable[bool]]
+class GatewayCallTimeout(TimeoutError):
+ """A call through the MCP gateway got no answer within
+ ``MCP_TOOL_TIMEOUT_S``. The workspace server may still have run it."""
+
+
+def _tool_timeout_s() -> float:
+ """``MCP_TOOL_TIMEOUT_S``; a settings stub without it (tests patch
+ ``get_settings`` here) gets config's default."""
+ return float(getattr(get_settings(), "mcp_tool_timeout_s", 120.0))
+
+
+async def _session_call(
+ session: Any, name: str, arguments: dict[str, Any], timeout: float | None = None,
+) -> Any:
+ """``session.call_tool`` with the per-call ceiling. Without one, a
+ workspace server that never answers (a hung Google or Microsoft request,
+ a stuck child process) held whatever awaited it for good: the email
+ poller, which handles one message at a time, a brief, a chat turn. The
+ call is cancelled on our side; the server may still finish it."""
+ if timeout is None:
+ timeout = _tool_timeout_s()
+ try:
+ return await asyncio.wait_for(session.call_tool(name, arguments), timeout=timeout)
+ except TimeoutError as exc:
+ tool = arguments.get("tool_name") if name == "call_tool" else name
+ logger.warning("MCPGateway: %s got no answer within %.0fs", str(tool)[:200], timeout)
+ raise GatewayCallTimeout(f"{str(tool)[:200]} got no answer within {timeout:.0f}s") from exc
+
+
async def _fetch_m365_json(
session: Any, tool_name: str, arguments: dict[str, Any], discover: _Discover | None = None,
) -> dict[str, Any] | None:
@@ -1860,8 +1889,8 @@ async def _fetch_m365_json(
that only searched for the reply tool never returned the lookup: then
``discover`` it and read once more."""
try:
- result = await session.call_tool(
- "call_tool", {"tool_name": tool_name, "arguments": arguments},
+ result = await _session_call(
+ session, "call_tool", {"tool_name": tool_name, "arguments": arguments},
)
text = result.content[0].text if result.content else ""
if (
@@ -1871,8 +1900,8 @@ async def _fetch_m365_json(
and _UNDISCOVERED_MARKER in text
and await discover(tool_name)
):
- result = await session.call_tool(
- "call_tool", {"tool_name": tool_name, "arguments": arguments},
+ result = await _session_call(
+ session, "call_tool", {"tool_name": tool_name, "arguments": arguments},
)
text = result.content[0].text if result.content else ""
parsed = json.loads(text) if isinstance(text, str) and text.strip() else None
@@ -2834,6 +2863,20 @@ class MCPGateway:
# the next call to one of that server's tools that answers without
# an authorization error.
self.needs_reconnect: set[str] = set()
+ # MCP_TOOL_TIMEOUT_S, read on first use (`_call_timeout`) and kept:
+ # `get_settings()` builds a fresh Settings on every call.
+ self._tool_timeout_s: float | None = None
+
+ def _call_timeout(self, settings: Settings | None = None) -> float:
+ """The per-call ceiling, read once per gateway (from ``settings``
+ when the caller already holds a read)."""
+ if self._tool_timeout_s is None:
+ self._tool_timeout_s = (
+ float(getattr(settings, "mcp_tool_timeout_s", 120.0))
+ if settings is not None
+ else _tool_timeout_s()
+ )
+ return self._tool_timeout_s
def mark_needs_reconnect(self, server: str, reason: str | None = None) -> bool:
"""Note that ``server``'s grant no longer works. True when this is
@@ -2895,7 +2938,7 @@ class MCPGateway:
# (extensible-mcp defaults to 5 results).
if isinstance(tool_input.get("top_k"), int):
args["top_k"] = tool_input["top_k"]
- result = await session.call_tool("search_tools", args)
+ result = await _session_call(session, "search_tools", args, self._call_timeout())
text = result.content[0].text if result.content else json.dumps({"tools": []})
return _drop_blocked_tools(text)
@@ -2958,6 +3001,7 @@ class MCPGateway:
settings = get_settings()
pinned = pinned_google_tools(settings)
+ self._call_timeout(settings)
try:
missing = [n for n in sorted(pinned) if not await self._discover(n, settings)]
except asyncio.CancelledError:
@@ -3135,21 +3179,32 @@ class MCPGateway:
if isinstance(disclosed, str):
return disclosed
wire_arguments = disclosed
- result = await session.call_tool(
- "call_tool",
- {"tool_name": tool_input["name"], "arguments": wire_arguments},
- )
- result_text = result.content[0].text if result.content else json.dumps({"result": None})
- # A pinned tool called before startup priming reached it: the prompt
- # told the model to call it directly, so discover it and retry once.
- # The refused call ran nothing, and every gate above has already
- # passed these same arguments.
- if _is_undiscovered_refusal(tool_name, result_text) and await self._discover(tool_name):
- result = await session.call_tool(
- "call_tool",
- {"tool_name": tool_input["name"], "arguments": wire_arguments},
- )
+ wire_input = {"tool_name": tool_input["name"], "arguments": wire_arguments}
+ try:
+ result = await _session_call(session, "call_tool", wire_input, self._call_timeout())
result_text = result.content[0].text if result.content else json.dumps({"result": None})
+ # A pinned tool called before startup priming reached it: the prompt
+ # told the model to call it directly, so discover it and retry once.
+ # The refused call ran nothing, and every gate above has already
+ # passed these same arguments.
+ if _is_undiscovered_refusal(tool_name, result_text) and await self._discover(tool_name):
+ result = await _session_call(session, "call_tool", wire_input, self._call_timeout())
+ result_text = result.content[0].text if result.content else json.dumps({"result": None})
+ except GatewayCallTimeout:
+ # An error payload, not a raise: the model reads it like any tool
+ # error, and every caller that checks for one (`_is_error_payload`)
+ # treats the call as failed. Not a failed send, though: the server
+ # may still have run it, so say to check before calling again.
+ # Nothing below runs: no outbound linkage or attachment row for a
+ # send that may not have happened, and no grant-health reading.
+ return json.dumps({
+ "error": (
+ f"{str(tool_name)[:200]} did not answer within "
+ f"{self._call_timeout():.0f}s. It may still have run: "
+ "check its effect before calling it again."
+ ),
+ "timed_out": True,
+ })
# On the final result, retry or not: roster answer tokens are hidden
# from every mailbox read (Google Workspace or Microsoft 365) but the
# poller's own.
@@ -3211,9 +3266,11 @@ class MCPGateway:
url: str = tool_input["url"]
if not url.startswith("https://"):
return json.dumps({"error": "load_mcp_server requires an HTTPS URL"})
- result = await session.call_tool(
+ result = await _session_call(
+ session,
"load_mcp_server",
{"name": tool_input["name"], "url": url},
+ self._call_timeout(),
)
return result.content[0].text if result.content else json.dumps({"ok": True})
diff --git a/packages/core/tests/unit/test_chat_route_timeout.py b/packages/core/tests/unit/test_chat_route_timeout.py
index 7d0c6d16..17006ed2 100644
--- a/packages/core/tests/unit/test_chat_route_timeout.py
+++ b/packages/core/tests/unit/test_chat_route_timeout.py
@@ -143,3 +143,78 @@ def test_debug_events_reach_only_the_callers_own_stream(
assert len({e.get("turn_id") for e in debug}) == 1
assert client.get("/debug/last-turn").status_code == 404
+
+
+def test_quiet_turn_sends_keepalives_then_the_answer(
+ temp_db: Path, patched_deps: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A slow step (a long tool call) no longer leaves the stream silent: SSE
+ comments go out while it runs, and the answer still arrives after them."""
+ from openexecutive.config import Settings
+ from openexecutive.orchestrator import executive as exec_mod
+
+ class _SlowExecutive:
+ _THINKING = exec_mod.Executive._THINKING
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def stream_chat(self, **_kwargs: Any) -> AsyncIterator[str]:
+ await asyncio.sleep(0.3)
+ yield "after the wait"
+
+ monkeypatch.setattr(exec_mod, "Executive", _SlowExecutive)
+ original_init = Settings.__init__
+
+ def _fast_keepalive_init(self: Settings, *args: Any, **kwargs: Any) -> None:
+ original_init(self, *args, **kwargs)
+ object.__setattr__(self, "chat_stream_keepalive_s", 0.05)
+
+ monkeypatch.setattr(Settings, "__init__", _fast_keepalive_init)
+
+ app = FastAPI()
+ app.include_router(chat_route.router)
+ resp = TestClient(app).post("/chat", json={"message": "slow one"})
+ assert resp.status_code == 200
+ lines = resp.text.splitlines()
+ keepalives = [i for i, ln in enumerate(lines) if ln == ": keepalive"]
+ answer = next(i for i, ln in enumerate(lines) if "after the wait" in ln)
+ assert len(keepalives) >= 2
+ assert keepalives[0] < answer
+ assert '"type": "error"' not in resp.text
+ assert '"type": "done"' in resp.text
+
+
+def test_keepalives_do_not_stretch_the_deadline(
+ temp_db: Path, patched_deps: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The whole-turn deadline still holds when keepalives fill the silence."""
+ from openexecutive.config import Settings
+ from openexecutive.orchestrator import executive as exec_mod
+
+ class _HangingExecutive:
+ _THINKING = exec_mod.Executive._THINKING
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def stream_chat(self, **_kwargs: Any) -> AsyncIterator[str]:
+ await asyncio.sleep(60)
+ yield "never"
+
+ monkeypatch.setattr(exec_mod, "Executive", _HangingExecutive)
+ original_init = Settings.__init__
+
+ def _short_init(self: Settings, *args: Any, **kwargs: Any) -> None:
+ original_init(self, *args, **kwargs)
+ object.__setattr__(self, "chat_stream_timeout_s", 0.3)
+ object.__setattr__(self, "chat_stream_keepalive_s", 0.05)
+
+ monkeypatch.setattr(Settings, "__init__", _short_init)
+
+ app = FastAPI()
+ app.include_router(chat_route.router)
+ resp = TestClient(app).post("/chat", json={"message": "hang"})
+ assert ": keepalive" in resp.text.splitlines()
+ assert "timed out" in resp.text.lower()
+ assert '"type": "done"' in resp.text
diff --git a/packages/core/tests/unit/test_chat_stream_step.py b/packages/core/tests/unit/test_chat_stream_step.py
index c6848172..3ace08fe 100644
--- a/packages/core/tests/unit/test_chat_stream_step.py
+++ b/packages/core/tests/unit/test_chat_stream_step.py
@@ -212,3 +212,73 @@ async def test_outer_cancellation_does_not_orphan_the_step() -> None:
# And it stays cancelled — it must not resume and finish its round later.
await asyncio.sleep(0.2)
assert state["phase"] == "cancelled"
+
+
+async def test_keepalive_interval_returns_the_step_still_running() -> None:
+ """Past the keepalive interval the step is handed back in flight, and
+ passing it back in delivers its item: nothing is restarted or lost."""
+ started = {"n": 0}
+
+ async def gen() -> Any:
+ started["n"] += 1
+ await asyncio.sleep(0.2)
+ yield "slow"
+
+ stream = gen().__aiter__()
+ step = await _next_stream_step(stream, None, 5.0, "t-ka", keepalive_s=0.05)
+ assert step.idle is True
+ assert step.pending is not None and not step.pending.done()
+ assert not step.timed_out
+
+ step = await _next_stream_step(
+ stream, None, 5.0, "t-ka", keepalive_s=1.0, pending=step.pending
+ )
+ assert step.produced is True and step.item == "slow"
+ assert started["n"] == 1
+
+
+async def test_keepalive_past_the_deadline_is_a_timeout() -> None:
+ """When the deadline is nearer than the keepalive, it is the deadline that
+ ends the wait, and the step is cancelled as before."""
+ cancelled = {"seen": False}
+
+ async def gen() -> Any:
+ try:
+ await asyncio.sleep(30)
+ yield "never"
+ except asyncio.CancelledError:
+ cancelled["seen"] = True
+ raise
+
+ step = await _next_stream_step(gen().__aiter__(), None, 0.05, "t-dl", keepalive_s=1.0)
+ assert step.timed_out is True and step.idle is False
+ assert cancelled["seen"] is True
+
+
+async def test_stop_during_a_kept_step_cancels_it() -> None:
+ """A step carried across a keepalive is still cut by the stop switch."""
+ cancelled = {"seen": False}
+
+ async def gen() -> Any:
+ try:
+ await asyncio.sleep(30)
+ yield "never"
+ except asyncio.CancelledError:
+ cancelled["seen"] = True
+ raise
+
+ stream = gen().__aiter__()
+ event = asyncio.Event()
+ waiter = _waiter(event)
+ step = await _next_stream_step(stream, waiter, 5.0, "t-st", keepalive_s=0.05)
+ assert step.idle is True
+ event.set()
+ step = await _next_stream_step(
+ stream, waiter, 5.0, "t-st", keepalive_s=0.05, pending=step.pending
+ )
+ assert step.stopped is True
+ assert cancelled["seen"] is True
+ await _drain(waiter)
diff --git a/packages/core/tests/unit/test_email_turn_deadline.py b/packages/core/tests/unit/test_email_turn_deadline.py
new file mode 100644
index 00000000..8c61493d
--- /dev/null
+++ b/packages/core/tests/unit/test_email_turn_deadline.py
@@ -0,0 +1,225 @@
+"""The email poller's turn deadline (EMAIL_TURN_TIMEOUT_S) and give-up rule.
+
+The poller handles mail one message at a time. A turn with no ceiling held
+every message behind it, and a message whose handling kept raising was tried
+again every poll for the life of the process. Now a turn past the ceiling is
+cut off, recorded, and its message marked read; a message that fails
+``_MAX_ATTEMPTS`` times is given up and marked read.
+"""
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+import openexecutive.integrations.email_poller as poller
+from openexecutive.integrations.workspace.mail import MessageRef
+from openexecutive.people import registry as people_registry
+from openexecutive.people import store as people_store
+
+TEAMMATE = "[email protected]"
+
+
[email protected](autouse=True)
+def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")
+ people_store.initialize_db()
+ people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email="[email protected]")
+ people_store.upsert_person(full_name="Alice", email=TEAMMATE)
+ people_registry.invalidate()
+ poller._processed_ids.clear()
+ poller._failed_attempts.clear()
+ # Audited code: keep its rows out of the shared default DB.
+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)
+
+
+def _settings(timeout_s: float = 0.05) -> Any:
+ return SimpleNamespace(
+ exec_email_address=EXEC, email_poll_interval_seconds=60, email_turn_timeout_s=timeout_s,
+ )
+
+
+class _SlowExecutive:
+ cancelled = False
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def chat(self, **_kwargs: Any) -> str:
+ try:
+ await asyncio.sleep(30)
+ except asyncio.CancelledError:
+ _SlowExecutive.cancelled = True
+ raise
+ return "never"
+
+
+def _run_executive_patches() -> Any:
+ return (
+ patch("openexecutive.orchestrator.executive.Executive", new=_SlowExecutive),
+ patch(
+ "openexecutive.onboarding.profile_builder.load_or_create_profile",
+ return_value=SimpleNamespace(is_empty=lambda: True),
+ ),
+ patch("openexecutive.knowledge.retriever.retrieve", new=lambda **_k: ""),
+ patch("openexecutive.memory.episodic.format_for_prompt", new=lambda: ""),
+ )
+
+
+def test_a_turn_past_the_ceiling_is_cut_off() -> None:
+ _SlowExecutive.cancelled = False
+ a, b, c, d = _run_executive_patches()
+ with (
+ a, b, c, d,
+ patch.object(poller, "get_settings", return_value=_settings()),
+ pytest.raises(poller.EmailTurnTimeout) as info,
+ ):
+ asyncio.run(asyncio.wait_for(
+ poller._run_executive(
+ gateway=AsyncMock(),
+ raw_email=f"Subject: hi\nFrom: {TEAMMATE}\n\n--- BODY ---\nhello\n",
+ message_id="m1",
+ thread_id="t1",
+ from_addr=TEAMMATE,
+ ),
+ timeout=5,
+ ))
+ assert info.value.timeout_s == 0.05
+ assert _SlowExecutive.cancelled is True
+
+
+def test_a_timeout_from_inside_the_turn_is_not_reported_as_the_deadline() -> None:
+ """Only the turn's own deadline reads as EmailTurnTimeout."""
+ class _Raises:
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def chat(self, **_kwargs: Any) -> str:
+ raise TimeoutError("something inside")
+
+ _a, b, c, d = _run_executive_patches()
+ with (
+ patch("openexecutive.orchestrator.executive.Executive", new=_Raises),
+ b, c, d,
+ patch.object(poller, "get_settings", return_value=_settings(timeout_s=5)),
+ pytest.raises(TimeoutError) as info,
+ ):
+ asyncio.run(poller._run_executive(
+ gateway=AsyncMock(),
+ raw_email=f"Subject: hi\nFrom: {TEAMMATE}\n\n--- BODY ---\nhello\n",
+ message_id="m1",
+ thread_id="t1",
+ from_addr=TEAMMATE,
+ ))
+ assert not isinstance(info.value, poller.EmailTurnTimeout)
+
+
+def test_a_cut_off_turn_is_recorded_and_its_message_marked_read() -> None:
+ rows: list[dict[str, Any]] = []
+ gateway = AsyncMock()
+ gateway.call_tool = AsyncMock(
+ return_value=f"Subject: Pilot\nFrom: {TEAMMATE}\nTo: {EXEC}\n\n--- BODY ---\nhello\n"
+ )
+ mark_read = AsyncMock()
+ with (
+ patch(
+ "openexecutive.audit.log_event",
+ side_effect=lambda event_type, summary, **kw: rows.append(
+ {"event_type": event_type, "summary": summary, **kw}
+ ),
+ ),
+ patch.object(poller, "get_settings", return_value=_settings()),
+ patch.object(poller, "_run_executive", new=AsyncMock(side_effect=poller.EmailTurnTimeout(0.05))),
+ patch.object(poller, "_mark_read", new=mark_read),
+ ):
+ asyncio.run(poller._handle_email(gateway, "m1", "t1", EXEC))
+
+ cut = [r for r in rows if r["details"].get("outcome") == "turn_timeout"]
+ assert len(cut) == 1
+ assert cut[0]["details"]["message_id"] == "m1"
+ assert cut[0]["details"]["from"] == TEAMMATE
+ assert cut[0]["session_id"] == "email:t1"
+ mark_read.assert_awaited_once()
+
+
+class _Provider:
+ name = "google"
+
+ def __init__(self, ids: list[str]) -> None:
+ self.ids = ids
+
+ async def list_unread(self, _gateway: Any, _email: str, _n: int) -> list[MessageRef]:
+ return [MessageRef(i, f"t-{i}") for i in self.ids]
+
+
+def test_a_message_that_keeps_failing_is_given_up_after_three_tries() -> None:
+ provider = _Provider(["bad", "good"])
+ handled: list[str] = []
+
+ async def handle(_gw: Any, mid: str, *_a: Any, **_k: Any) -> None:
+ handled.append(mid)
+ if mid == "bad":
+ raise RuntimeError("boom")
+
+ mark_read = AsyncMock()
+ with (
+ patch.object(poller, "get_settings", return_value=_settings()),
+ patch.object(poller, "_handle_email", new=handle),
+ patch.object(poller, "_mark_read", new=mark_read),
+ ):
+ for _ in range(4):
+ asyncio.run(poller.poll_once(AsyncMock(), provider)) # type: ignore[arg-type]
+
+ # The good one ran once, after the bad one, on the first poll.
+ assert handled.count("good") == 1
+ assert handled.count("bad") == poller._MAX_ATTEMPTS == 3
+ assert "bad" in poller._processed_ids
+ assert "bad" not in poller._failed_attempts
+ mark_read.assert_awaited_once()
+ assert mark_read.await_args.args[1] == "bad"
+
+
+def test_a_message_that_succeeds_on_retry_forgets_its_failures() -> None:
+ provider = _Provider(["flaky"])
+ calls = {"n": 0}
+
+ async def handle(*_a: Any, **_k: Any) -> None:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("once")
+
+ with (
+ patch.object(poller, "get_settings", return_value=_settings()),
+ patch.object(poller, "_handle_email", new=handle),
+ patch.object(poller, "_mark_read", new=AsyncMock()),
+ ):
+ asyncio.run(poller.poll_once(AsyncMock(), provider)) # type: ignore[arg-type]
+ assert poller._failed_attempts == {"flaky": 1}
+ asyncio.run(poller.poll_once(AsyncMock(), provider)) # type: ignore[arg-type]
+ assert poller._failed_attempts == {}
+ assert "flaky" in poller._processed_ids
+
+
+def test_the_cut_off_row_says_a_reply_may_have_gone() -> None:
+ rows: list[dict[str, Any]] = []
+ gateway = AsyncMock()
+ gateway.call_tool = AsyncMock(
+ return_value=f"Subject: Pilot\nFrom: {TEAMMATE}\nTo: {EXEC}\n\n--- BODY ---\nhello\n"
+ )
+ with (
+ patch(
+ "openexecutive.audit.log_event",
+ side_effect=lambda event_type, summary, **kw: rows.append({"summary": summary, **kw}),
+ ),
+ patch.object(poller, "get_settings", return_value=_settings()),
+ patch.object(poller, "_run_executive", new=AsyncMock(side_effect=poller.EmailTurnTimeout(0.05))),
+ patch.object(poller, "_mark_read", new=AsyncMock()),
+ ):
+ asyncio.run(poller._handle_email(gateway, "m1", "t1", EXEC))
+ cut = next(r for r in rows if r["details"].get("outcome") == "turn_timeout")
+ assert "may already have gone" in cut["summary"]
diff --git a/packages/core/tests/unit/test_executive_tool_error_isolation.py b/packages/core/tests/unit/test_executive_tool_error_isolation.py
index a0b9ecb6..dafbeb3a 100644
--- a/packages/core/tests/unit/test_executive_tool_error_isolation.py
+++ b/packages/core/tests/unit/test_executive_tool_error_isolation.py
@@ -273,3 +273,48 @@ def test_raising_mcp_tool_becomes_error_result_and_turn_survives(
assert len(failures) == 1
assert failures[0]["details"]["kind"] == "mcp"
assert failures[0]["details"]["tool"] == "gcal__list"
+
+
+class _HangingGateway(_ExplodingGateway):
+ async def call_tool(self, _input: dict[str, Any]) -> str:
+ await asyncio.sleep(30)
+ return "{}"
+
+
+def test_a_turn_cut_off_mid_mcp_call_records_the_call_as_cancelled(
+ _no_audit_writes: list[dict[str, Any]],
+) -> None:
+ """A deadline (the email turn's) can cancel a send already on its way to
+ the server; the call still gets its tool_invocation row."""
+ provider = _ScriptedProvider(
+ [
+ _FinalMsg(
+ [_ToolUseBlock(
+ "tu-send", "call_tool",
+ {"name": "google_workspace__send_gmail_message", "arguments": "{}"},
+ )],
+ stop_reason="tool_use",
+ ),
+ ]
+ )
+ exec_ = Executive(mcp_gateway=_HangingGateway()) # type: ignore[arg-type]
+
+ async def _go() -> None:
+ with patch("openexecutive.orchestrator.executive.get_provider", return_value=provider):
+ async with asyncio.timeout(0.2):
+ async for _item in exec_._stream_agent_loop(
+ system_blocks=[],
+ messages=[{"role": "user", "content": "do the thing"}],
+ model="claude-test",
+ ):
+ pass
+
+ with pytest.raises(TimeoutError):
+ asyncio.run(_go())
+ cancelled = [
+ row for row in _no_audit_writes
+ if row["event_type"] == "tool_invocation" and row.get("details", {}).get("cancelled")
+ ]
+ assert len(cancelled) == 1
+ assert cancelled[0]["details"]["tool"] == "google_workspace__send_gmail_message"
+ assert cancelled[0]["summary"].endswith("CANCELLED")
diff --git a/packages/core/tests/unit/test_mcp_gateway_timeout.py b/packages/core/tests/unit/test_mcp_gateway_timeout.py
new file mode 100644
index 00000000..4d836278
--- /dev/null
+++ b/packages/core/tests/unit/test_mcp_gateway_timeout.py
@@ -0,0 +1,129 @@
+"""A call through the MCP gateway has a ceiling (MCP_TOOL_TIMEOUT_S).
+
+Without one, a workspace server that never answered held whatever awaited it
+for good — the email poller, which handles one message at a time, a brief, a
+chat turn. Past the ceiling the model's call comes back as an error that says
+the tool may still have run; the gate lookups and tool search raise and are
+handled by their callers as any other failure.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+import openexecutive.audit
+import openexecutive.orchestrator.mcp_gateway as gw_module
+from openexecutive.orchestrator.mcp_gateway import GatewayCallTimeout, MCPGateway
+
+
[email protected](autouse=True)
+def _no_audit(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(openexecutive.audit, "log_event", lambda *a, **k: None)
+
+
+def _settings(timeout_s: float = 0.05) -> Any:
+ return SimpleNamespace(
+ exec_email_address="[email protected]",
+ email_poll_interval_seconds=60,
+ mcp_tool_timeout_s=timeout_s,
+ )
+
+
+def _result(text: str) -> Any:
+ result = MagicMock()
+ result.content = [MagicMock(text=text)]
+ return result
+
+
+def _gateway(call_tool: Any) -> MCPGateway:
+ gateway = MCPGateway()
+ session = MagicMock()
+ session.call_tool = call_tool
+ gateway._session = session
+ return gateway
+
+
+def test_a_hung_tool_call_comes_back_as_an_error_after_the_ceiling() -> None:
+ cancelled = {"seen": False}
+
+ async def hang(_name: str, _args: dict[str, Any]) -> Any:
+ try:
+ await asyncio.sleep(30)
+ except asyncio.CancelledError:
+ cancelled["seen"] = True
+ raise
+
+ gateway = _gateway(hang)
+ with patch.object(gw_module, "get_settings", return_value=_settings()):
+ text = asyncio.run(asyncio.wait_for(
+ gateway.call_tool({"name": "google_workspace__list_calendars", "arguments": {}}),
+ timeout=5,
+ ))
+ payload = json.loads(text)
+ assert payload["timed_out"] is True
+ assert "did not answer" in payload["error"]
+ assert "may still have run" in payload["error"]
+ assert gw_module._is_error_payload(text)
+ assert cancelled["seen"] is True
+
+
+def test_a_send_that_times_out_records_no_outbound_linkage() -> None:
+ """A send that never answered may not have gone: no reply context for it."""
+ async def hang(_name: str, _args: dict[str, Any]) -> Any:
+ await asyncio.sleep(30)
+
+ gateway = _gateway(hang)
+ with (
+ patch.object(gw_module, "get_settings", return_value=_settings()),
+ patch.object(gw_module, "_record_email_outbound_context") as record,
+ patch.object(gw_module, "_check_gmail_recipients", return_value=None),
+ patch.object(gw_module, "_with_disclosure", side_effect=lambda _t, _n, a, **_k: a),
+ ):
+ text = asyncio.run(gateway.call_tool({
+ "name": "google_workspace__send_gmail_message",
+ "arguments": {"to": "[email protected]", "subject": "s", "body": "b"},
+ }))
+ assert json.loads(text)["timed_out"] is True
+ record.assert_not_called()
+
+
+def test_a_call_inside_the_ceiling_is_unchanged() -> None:
+ async def quick(_name: str, _args: dict[str, Any]) -> Any:
+ return _result('{"ok": true}')
+
+ gateway = _gateway(quick)
+ with patch.object(gw_module, "get_settings", return_value=_settings(timeout_s=5)):
+ text = asyncio.run(
+ gateway.call_tool({"name": "google_workspace__list_calendars", "arguments": {}})
+ )
+ assert json.loads(text) == {"ok": True}
+
+
+def test_a_hung_tool_search_raises() -> None:
+ async def hang(_name: str, _args: dict[str, Any]) -> Any:
+ await asyncio.sleep(30)
+
+ gateway = _gateway(hang)
+ with (
+ patch.object(gw_module, "get_settings", return_value=_settings()),
+ pytest.raises(GatewayCallTimeout),
+ ):
+ asyncio.run(gateway.search_tools({"query": "calendar"}))
+
+
+def test_a_hung_gate_lookup_reads_as_a_failed_lookup() -> None:
+ """The M365 gates read an event or message first; a lookup that hangs is
+ a lookup that failed (None), which every gate already refuses on."""
+ async def hang(_name: str, _args: dict[str, Any]) -> Any:
+ await asyncio.sleep(30)
+
+ session = MagicMock()
+ session.call_tool = hang
+ with patch.object(gw_module, "get_settings", return_value=_settings()):
+ got = asyncio.run(gw_module._fetch_m365_json(session, "ms365__get-mail-message", {}))
+ assert got is None
diff --git a/packages/core/tests/unit/test_roster_intake.py b/packages/core/tests/unit/test_roster_intake.py
index 0209d170..1d5e94ef 100644
--- a/packages/core/tests/unit/test_roster_intake.py
+++ b/packages/core/tests/unit/test_roster_intake.py
@@ -630,3 +630,34 @@ def test_the_answer_token_is_hidden_from_every_other_read_of_the_mailbox(
return await gateway.call_tool(call)
assert token in asyncio.run(_poller_read())
+
+
+def test_an_ack_send_that_timed_out_raises_uncertain() -> None:
+ gateway = AsyncMock()
+ gateway.call_tool = AsyncMock(
+ return_value='{"error": "send did not answer within 120s", "timed_out": true}'
+ )
+ with pytest.raises(roster_intake.AckUncertain):
+ asyncio.run(roster_intake.send_email_ack(gateway, STRANGER))
+ gateway.call_tool = AsyncMock(return_value='{"error": "refused"}')
+ with pytest.raises(RuntimeError):
+ asyncio.run(roster_intake.send_email_ack(gateway, STRANGER))
+
+
+def test_an_ack_that_may_have_gone_keeps_its_claim(
+ roster: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A send that timed out may have reached the sender: the claim stays
+ taken, so their next message draws no second acknowledgement."""
+ rows: list[str] = []
+ monkeypatch.setattr(roster_intake, "_audit", lambda event, *_a: rows.append(event))
+
+ async def _unsure(_text: str) -> None:
+ raise roster_intake.AckUncertain("timed out")
+
+ with patch.object(roster_intake, "notify_principal", new=AsyncMock()):
+ asyncio.run(roster_intake.intake(
+ "email", STRANGER, external_id="m1", payload={"message_id": "m1"}, send_ack=_unsure,
+ ))
+ assert rows.count("roster_ack_uncertain") == 1
+ assert not rr.claim_ack("email", STRANGER)