AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(workflows): let chat fix a saved workflow on a card and say whose calendar a step reads (#629)
Rufus582449d787ab
diff --git a/.env.example b/.env.exampleindex 4a5fbecf..286e1f7a 100644--- a/.env.example+++ b/.env.example@@ -265,6 +265,12 @@ SLACK_APP_TOKEN=xapp-your-app-token# leave SLACK_APP_TOKEN unset, set the app's Signing Secret here, and point the# app's Event Subscriptions Request URL at https://<this API>/webhook/slack.# SLACK_SIGNING_SECRET=+# Approve and Skip buttons on approval cards in a Slack DM. Turn on+# Interactivity in the Slack app first (over HTTP, its Request URL is the same+# /webhook/slack) and give the bot the im:write scope, which a tap needs to+# check it came from the tapper's own DM; left off, a DM sends people to the+# web app to approve.+# SLACK_CARD_BUTTONS=true# Exec email address — REQUIRED. The Executive's own mailbox: the Google# account authenticated with Gmail MCP OAuth, or the Microsoft 365 mailboxdiff --git a/CLAUDE.md b/CLAUDE.mdindex ec8f5b03..4805f8f6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -150,7 +150,7 @@ and deploy configuration for a specific environment are kept outside this repo.## Environment Variables-See `.env.example`. Required: `ANTHROPIC_API_KEY`, `EXEC_EMAIL_ADDRESS` (no default). Signed callers (optional, recommended on a server, and required there for Act as me's Send): `CALLER_ASSERTION_PRIVATE_KEY` on the UI signs who is signed in, and `CALLER_ASSERTION_PUBLIC_KEYS` on the API checks it (`api/caller.py`, `scripts/make-caller-keys.py`, `docs/auth.md`). Routes read the caller only through `api/caller.py`, never the `x-caller-email` header. Optional integrations: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN`, `TELEGRAM_BOT_TOKEN` + `TELEGRAM_WEBHOOK_SECRET` (`docs/telegram_setup.md`), `DISCORD_BOT_TOKEN` + `DISCORD_APP_ID`, `GOOGLE_CHAT_PROJECT_NUMBER` + one of `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` / `_EMAIL` (`docs/google_chat_setup.md`). Email has no IMAP/SMTP settings: the poller (`integrations/email_poller.py`) reads and sends through the configured workspace backend (`integrations/workspace/`, chosen by `EMAIL_PROVIDER` / `CALENDAR_PROVIDER`, default `google`): the Gmail tools of the Google Workspace MCP (`GOOGLE_OAUTH_CLIENT_ID` / `GOOGLE_OAUTH_CLIENT_SECRET`) or the Outlook tools of the Microsoft 365 MCP (`MS365_MCP_CLIENT_ID` + a one-time `ms365-mcp-launch.sh --login`), signed in as `EXEC_EMAIL_ADDRESS`. Act as me (optional) reads the owner's *own* Gmail directly (`delegation/gmail.py`, never the MCP gateway) from a per-person credential in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, minted by `scripts/connect-own-gmail.py` (or an Outlook one, `delegation/outlook.py`, minted by `scripts/connect-own-outlook.py` with the `MS365_MCP_CLIENT_ID` app); `DELEGATION_COMPOSER_MODEL` / `DELEGATION_MAX_DRAFTS_PER_DAY` tune the drafts, and `DELEGATION_INBOX_POLL_MINUTES` / `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` / `DELEGATION_CLASSIFIER_MODEL` the inbox watcher (`delegation/inbox.py`, off until the owner turns on Draft replies to my inbox); `DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY` caps the replies it sends on its own under Handle it for me (`delegation/handle_it.py`, off until the person turns it on), and `DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY` the emails a workflow sends as its creator (`delegation/workflow_email.py`). Drive folder sync (optional): `DRIVE_SYNC_ENABLED` + `DRIVE_SYNC_SERVICE_ACCOUNT_FILE` + `DRIVE_SYNC_FOLDER_IDS` (`docs/drive_sync_setup.md`) reads shared folders as a `drive.readonly` service account (`knowledge/drive_client.py`, never the MCP gateway) into the isolated `drive_docs` collection. Confluence sync (optional): `CONFLUENCE_SYNC_ENABLED` + `CONFLUENCE_URL` + `CONFLUENCE_PERSONAL_TOKEN` (Server/DC) or `CONFLUENCE_USERNAME` / `CONFLUENCE_API_TOKEN` (Cloud) + `CONFLUENCE_SYNC_SPACE_KEYS` (`docs/confluence_sync_setup.md`) reads the listed spaces over the Confluence REST API (`knowledge/confluence_client.py`, never the MCP gateway; names shared with mcp-atlassian) into the isolated `confluence_wiki` collection, skipping restricted pages unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. OneDrive folder sync (optional): `ONEDRIVE_SYNC_ENABLED` + `ONEDRIVE_SYNC_FOLDERS` (`docs/onedrive_sync_setup.md`) reads as the Executive's Microsoft 365 sign-in, with a token from `ms365-mcp-launch.sh --access-token` (`knowledge/onedrive_account.py`, never the MCP gateway), into the isolated `onedrive_docs` collection.+See `.env.example`. Required: `ANTHROPIC_API_KEY`, `EXEC_EMAIL_ADDRESS` (no default). Signed callers (optional, recommended on a server, and required there for Act as me's Send): `CALLER_ASSERTION_PRIVATE_KEY` on the UI signs who is signed in, and `CALLER_ASSERTION_PUBLIC_KEYS` on the API checks it (`api/caller.py`, `scripts/make-caller-keys.py`, `docs/auth.md`). Routes read the caller only through `api/caller.py`, never the `x-caller-email` header. Optional integrations: `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` (+ `SLACK_CARD_BUTTONS` for Approve and Skip on cards in a DM, with Interactivity on), `TELEGRAM_BOT_TOKEN` + `TELEGRAM_WEBHOOK_SECRET` (`docs/telegram_setup.md`), `DISCORD_BOT_TOKEN` + `DISCORD_APP_ID`, `GOOGLE_CHAT_PROJECT_NUMBER` + one of `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` / `_EMAIL` (`docs/google_chat_setup.md`). Email has no IMAP/SMTP settings: the poller (`integrations/email_poller.py`) reads and sends through the configured workspace backend (`integrations/workspace/`, chosen by `EMAIL_PROVIDER` / `CALENDAR_PROVIDER`, default `google`): the Gmail tools of the Google Workspace MCP (`GOOGLE_OAUTH_CLIENT_ID` / `GOOGLE_OAUTH_CLIENT_SECRET`) or the Outlook tools of the Microsoft 365 MCP (`MS365_MCP_CLIENT_ID` + a one-time `ms365-mcp-launch.sh --login`), signed in as `EXEC_EMAIL_ADDRESS`. Act as me (optional) reads the owner's *own* Gmail directly (`delegation/gmail.py`, never the MCP gateway) from a per-person credential in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, minted by `scripts/connect-own-gmail.py` (or an Outlook one, `delegation/outlook.py`, minted by `scripts/connect-own-outlook.py` with the `MS365_MCP_CLIENT_ID` app); `DELEGATION_COMPOSER_MODEL` / `DELEGATION_MAX_DRAFTS_PER_DAY` tune the drafts, and `DELEGATION_INBOX_POLL_MINUTES` / `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` / `DELEGATION_CLASSIFIER_MODEL` the inbox watcher (`delegation/inbox.py`, off until the owner turns on Draft replies to my inbox); `DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY` caps the replies it sends on its own under Handle it for me (`delegation/handle_it.py`, off until the person turns it on), and `DELEGATION_WORKFLOW_MAX_SENDS_PER_DAY` the emails a workflow sends as its creator (`delegation/workflow_email.py`). Drive folder sync (optional): `DRIVE_SYNC_ENABLED` + `DRIVE_SYNC_SERVICE_ACCOUNT_FILE` + `DRIVE_SYNC_FOLDER_IDS` (`docs/drive_sync_setup.md`) reads shared folders as a `drive.readonly` service account (`knowledge/drive_client.py`, never the MCP gateway) into the isolated `drive_docs` collection. Confluence sync (optional): `CONFLUENCE_SYNC_ENABLED` + `CONFLUENCE_URL` + `CONFLUENCE_PERSONAL_TOKEN` (Server/DC) or `CONFLUENCE_USERNAME` / `CONFLUENCE_API_TOKEN` (Cloud) + `CONFLUENCE_SYNC_SPACE_KEYS` (`docs/confluence_sync_setup.md`) reads the listed spaces over the Confluence REST API (`knowledge/confluence_client.py`, never the MCP gateway; names shared with mcp-atlassian) into the isolated `confluence_wiki` collection, skipping restricted pages unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. OneDrive folder sync (optional): `ONEDRIVE_SYNC_ENABLED` + `ONEDRIVE_SYNC_FOLDERS` (`docs/onedrive_sync_setup.md`) reads as the Executive's Microsoft 365 sign-in, with a token from `ms365-mcp-launch.sh --access-token` (`knowledge/onedrive_account.py`, never the MCP gateway), into the isolated `onedrive_docs` collection.## Testingdiff --git a/packages/core/openexecutive/api/routes/decisions.py b/packages/core/openexecutive/api/routes/decisions.pyindex 1714cccd..ce24607c 100644--- a/packages/core/openexecutive/api/routes/decisions.py+++ b/packages/core/openexecutive/api/routes/decisions.py@@ -23,6 +23,7 @@ import jsonimport loggingfrom collections.abc import Awaitable, Callablefrom dataclasses import dataclass+from types import SimpleNamespacefrom typing import Any, Literalfrom fastapi import APIRouter, HTTPException, Request@@ -942,7 +943,31 @@ async def _reject(# The cards a chat app shows with Approve and Skip buttons# (integrations.channel_cards): the two a chat reply leaves for the person# chatting, as the web chat shows them under its reply.-CHAT_CARD_CLASSES = frozenset({_CALENDAR_CLASS, "delegation_actions"})+CHAT_CARD_CLASSES = frozenset({_CALENDAR_CLASS, "delegation_actions", "app_action"})+# Of the app_action cards (orchestrator.app_control), the ones a chat app's+# tap may carry out: those whose action checks the tapper itself, not a+# signed request (a workflow change, workflow_change.run).+CHAT_APP_ACTIONS = frozenset({"change_workflow"})+++def shown_in_chat(instance: DecisionInstance) -> bool:+ """Whether a chat app shows this card with Approve and Skip buttons."""+ if instance.decision_class not in CHAT_CARD_CLASSES:+ return False+ if instance.decision_class != _APP_ACTION.name:+ return True+ return _parse_payload(instance).get("action") in CHAT_APP_ACTIONS+++class _ChatTapRequest:+ """What an app_action card's action reads on a chat app's tap: the+ proven tap, and no signed caller (``workflow_change._tapper``)."""++ def __init__(self, tap: Any) -> None:+ self.state = SimpleNamespace(chat_tap=tap)+ self.headers: dict[str, str] = {}+ self.query_params: dict[str, str] = {}+ self.client = Noneasync def resolve_in_chat(instance_id: int, person: Any, *, approve: bool) -> DecisionInstance:@@ -958,7 +983,7 @@ async def resolve_in_chat(instance_id: int, person: Any, *, approve: bool) -> Defrom openexecutive.people.store import find_principal_personinstance = get_decision_instance(instance_id)- if instance is None or instance.decision_class not in CHAT_CARD_CLASSES or person.id is None:+ if instance is None or not shown_in_chat(instance) or person.id is None:raise HTTPException(status_code=404, detail="This card is no longer there.")spec = _spec_for(instance)principal = find_principal_person()@@ -976,6 +1001,9 @@ async def resolve_in_chat(instance_id: int, person: Any, *, approve: bool) -> Deraise HTTPException(status_code=409, detail="This card was already handled.")if instance.decision_class == _CALENDAR_CLASS:return await _book(instance, ApproveBody(), by_principal=is_principal, resolver=person.id)+ if instance.decision_class == _APP_ACTION.name:+ tap = ChatTap(normalize_email(person.email or ""))+ return await _carry_out_app_action(instance, ApproveBody(), _ChatTapRequest(tap), person.id) # type: ignore[arg-type]try:await approve_actions(instance, caller=ChatTap(normalize_email(person.email or "")), resolver=person.id,diff --git a/packages/core/openexecutive/api/routes/workflow_designer.py b/packages/core/openexecutive/api/routes/workflow_designer.pyindex df70ec40..72479022 100644--- a/packages/core/openexecutive/api/routes/workflow_designer.py+++ b/packages/core/openexecutive/api/routes/workflow_designer.py@@ -274,9 +274,10 @@ async def start_designer(body: WorkflowDesignerStartRequest, request: Request) -from openexecutive.delegation.workflow_email import available_forsession_id = uuid.uuid4().hex+ caller_id = _resolve_caller_person_id(request)session = DesignerSession(transcript=[Turn(role="user", text=text)],- context_block=build_context_block(as_me=available_for(_resolve_caller_person_id(request))),+ context_block=build_context_block(as_me=available_for(caller_id), user_email=_email_of(caller_id)),)_designer_sessions[session_id] = session# Sweep AFTER inserting so the cap holds on what is stored.@@ -290,6 +291,21 @@ async def start_designer(body: WorkflowDesignerStartRequest, request: Request) -raise+def _email_of(person_id: int | None) -> str:+ """The address of the person designing a workflow, or "" (a step that+ reads their calendar names it)."""+ from openexecutive.people.store import get_person++ if person_id is None:+ return ""+ try:+ person = get_person(person_id)+ except Exception:+ logger.warning("workflow designer: couldn't look up who is designing", exc_info=True)+ return ""+ return str(getattr(person, "email", "") or "").strip() if person is not None else ""++@router.post("/workflows/designer/edit", response_model=WorkflowDesignerTurnResponse)async def edit_designer(body: WorkflowDesignerEditRequest, request: Request) -> WorkflowDesignerTurnResponse:"""Open a design session on a saved workflow, to change it by conversation.@@ -312,9 +328,11 @@ async def edit_designer(body: WorkflowDesignerEditRequest, request: Request) ->session_id = uuid.uuid4().hex# Its steps write as its creator: offered only when that is who is editing.owner = get_owner(original.name)- as_me = owner is not None and owner == _resolve_caller_person_id(request) and available_for(owner)+ caller_id = _resolve_caller_person_id(request)+ as_me = owner is not None and owner == caller_id and available_for(owner)+ context = build_context_block(as_me=as_me, user_email=_email_of(caller_id))_designer_sessions[session_id] = DesignerSession(- context_block=f"{build_context_block(as_me=as_me)}\n\n{build_edit_note(original.name)}",+ context_block=f"{context}\n\n{build_edit_note(original.name)}",draft=WorkflowDraft(definition=original),editing=original.name,original=original,diff --git a/packages/core/openexecutive/api/routes/workflows.py b/packages/core/openexecutive/api/routes/workflows.pyindex 317312ed..83cdf032 100644--- a/packages/core/openexecutive/api/routes/workflows.py+++ b/packages/core/openexecutive/api/routes/workflows.py@@ -473,6 +473,70 @@ async def save_designer_edit(name: str, request: Request) -> dict[str, Any]:return _with_owner(stored)+def _tapper_person_id(who: Any) -> int | None:+ """The People entry of a card's tapper: a request's caller, or a chat+ app's proven tap (``ChatTap``)."""+ if isinstance(who, api_caller.Caller):+ return api_caller.person_id_for(who)+ from openexecutive.people.store import find_person_by_email++ email = str(getattr(who, "email", "") or "")+ person = find_person_by_email(email) if email else None+ return person.id if person is not None else None+++async def apply_chat_change(+ name: str, definition: dict[str, Any], base: Any, who: Any+) -> DynamicWorkflowDef:+ """Save a change chat staged on a card (``orchestrator.workflow_change``),+ on its person's tap. ``base`` is the version the card was made from: a+ workflow changed since is a 409, so the tap saves only what the card+ showed. ``who`` is the tapper (a request's caller, or a chat app's proven+ tap), checked as a save from the Workflows page is. The on/off state is+ kept."""+ from openexecutive.delegation.workflow_email import save_refusal+ from openexecutive.people.store import is_principal_or_self++ current = get_definition(name)+ if current is None:+ raise HTTPException(status_code=404, detail="That workflow isn't there any more.")+ if not _reviewed_matches(current, base):+ raise HTTPException(+ status_code=409,+ detail="This workflow changed since the card was made, so nothing was changed. Ask again in chat.",+ )+ try:+ defn = DynamicWorkflowDef.model_validate(definition)+ except ValidationError:+ raise HTTPException(status_code=422, detail="This change can't be read any more. Ask again in chat.") from None+ if defn.name != name:+ raise HTTPException(status_code=422, detail="This change is for a different workflow.")+ defn = defn.model_copy(update={"is_active": current.is_active})+ errors = await validate_definition_and_tools(defn)+ if errors:+ raise HTTPException(status_code=422, detail="; ".join(errors)[:300])+ owner = get_owner(name)+ # The card may be a day old: whoever taps must still be the account owner+ # or the workflow's creator, as when it was staged.+ if not is_principal_or_self(_tapper_person_id(who), owner):+ raise HTTPException(+ status_code=403,+ detail="Only the account owner or the person who created this workflow can change it.",+ )+ for checked, stored in ((defn, False), (current, True)):+ refused = save_refusal(checked, who, owner, check_tools=not stored)+ if refused is not None:+ raise HTTPException(status_code=403, detail=refused)+ saved = save_if_unchanged(defn, current)+ if saved is None:+ raise HTTPException(+ status_code=409,+ detail="This workflow changed while saving, so nothing was changed. Ask again in chat.",+ )+ _sync_cadence(saved)+ return saved++@router.post("/workflows/custom/{name}/activate")async def activate_custom_workflow(name: str, request: Request) -> dict[str, Any]:"""Turn a custom workflow on or off.diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex dea8ed07..cd8c8112 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -6947,11 +6947,23 @@ workflows:the approval is **Turn on workflow** on the review card that /jobs/{name}shows for an inactive custom workflow (POST /workflows/custom/{name}/activate, which re-runs validate_definition_and_tools when turning on).- Chat may keep revising a switched-off one, but draft/save REFUSE to- replace a switched-on workflow with action steps (any replacement, even- analysis-only): an inbound email steering the Executive could otherwise- switch off an approved job and stage new tools under its familiar name.- Those edits go through /jobs/new?edit=<name>. The refusal is decided from+ Chat may keep revising a switched-off one, but never replaces a+ switched-on workflow with action steps, or one that reads or sends email+ as its creator, directly (an inbound email steering the Executive could+ otherwise stage new tools under a familiar name). save_workflow with+ overwrite=true leaves a CHANGE CARD instead (orchestrator.workflow_change,+ decision class app_action, hidden catalog action change_workflow that+ do_in_app never offers): server-written lines name every step added,+ removed or changed, tools by plain name, schedule and title. Only a+ verified speaker in a private conversation who is the owner or the+ workflow's creator can stage one, and only where the card shows (web+ chat, or a chat app channel_cards.shows_cards). The tap+ (api.routes.workflows.apply_chat_change) saves it only if the stored+ workflow still matches the card's base (else 409), re-validates tools,+ runs workflow_email.save_refusal for the tapper (signed web caller or a+ ChatTap), keeps is_active, and saves with save_if_unchanged. Chat reads a+ saved definition with list_workflows(name=...) (owner or creator, private+ conversation). The refusal is decided froma read, so the save itself is conditional on that row(dynamic_store.save_if_unchanged: INSERT only if still absent, elseUPDATE ... WHERE updated_at = the read one) — an activation landing in@@ -7272,12 +7284,18 @@ workflows:the send. A workflow with the send tool is created/changed/activated onlyby its creator per verified.caller_refusal (403 from POST/PUT/workflows/custom, save-edit, activate; save_refusal); chat's- save_workflow refuses to replace one at all. At send:+ save_workflow only leaves a change card for one (workflow_change), saved+ on the creator's own verified tap. At send:is_enabled, handle_it.signing_ok, no client slot, draft unchanged(recipients exactly as written, from an own address, <=10, never theExecutive's). Results and the run report carry to/subject, never thebody; audit rows are private to the creator. The designer gets an- "Email as the user" line (build_context_block(as_me=...)).+ "Email as the user" line (build_context_block(as_me=...)) and a line on+ whose account the gateway's mail and calendar tools use (the+ Executive's, EXEC_EMAIL_ADDRESS): a calendar step that names no calendar+ reads the Executive's calendar, so the user's needs oe__my_calendar or+ their address (build_context_block(user_email=...)). DEFINITION_SCHEMA+ says the same to chat.Reads as the creator (delegation/workflow_reads.py): oe__search_my_email,oe__read_my_email, oe__my_email_awaiting_reply and oe__my_calendar run@@ -8487,14 +8505,24 @@ integrations:Approval cards with buttons. A private Telegram chat on a webhook onlyTelegram can call (``integrations.channel_cards.shows_cards``) gets the- cards a reply leaves (a meeting to book, a ``propose_actions`` card)+ cards a reply leaves (a meeting to book, a ``propose_actions`` card, a+ workflow change card: ``decisions.CHAT_APP_ACTIONS`` of the app_action+ cards, whose action checks the tapper itself)as messages with Approve and Skip buttons, and its ``<channel>`` blocksays so (``cards_here``). A tap is taken only when ``from.id`` is theprivate chat's id on the verified webhook, and``decisions.resolve_in_chat`` applies the web chat's who-may-deciderule, with ``delegation.verified.ChatTap`` standing in for the- signed-in caller. Every other chat app sends no card, and- ``propose_actions`` tells the model the card is on Today.+ signed-in caller. A Slack DM (with SLACK_CARD_BUTTONS on, which needs+ Interactivity in the Slack app and the im:write scope) and a Discord DM do the same: Slack+ sends Block Kit buttons (action ids oe_card_approve / oe_card_skip, the+ callback data as the value; text as plain_text), and a tap counts only+ when conversations.open for the tapper returns that very channel; a+ Discord View's buttons carry the callback data as custom_id and+ on_interaction takes a tap only in a DMChannel whose recipient is the+ tapper. Either way the tapper must be on the roster by their app id.+ Every other chat app (channels, threads, Google Chat) sends no card,+ and ``propose_actions`` tells the model the card is on Today.Errors. The catch-all logs with session/user/channel/thread/mode,writes an ``integration_inbound`` row withdiff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.jsonindex 440a77f8..c80e0b9c 100644--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json@@ -1,7 +1,7 @@{"section_id": "integrations","title": "Integrations",- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt app (`AsyncApp`) embedded in the lifespan, hearing Slack one of two ways: socket mode (`AsyncSocketModeHandler`, with `SLACK_APP_TOKEN`) or, with only `SLACK_SIGNING_SECRET`, the Events API over HTTP at `POST /webhook/slack` (`integrations.slack_events`), where the route checks each request's signature and age (and a 1 MB cap) before Bolt sees it, so unsigned traffic never reaches Bolt's logging; it then takes each signed request once, answering an identical replay (same signature) or Slack's re-signed retry of an `event_id` it already took with an empty 200 that never reaches Bolt (an in-memory, per-process set kept for twice the signature window and capped in size; keys are forgotten if Bolt fails, so a retry of a failed delivery still runs), and Bolt acknowledges at once while the listener runs. Either way a repeated event id is dropped (Slack resends what it thinks went unacknowledged), as is an event delivered for another workspace. Responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history. Replies (and every outbound Telegram message) go out as Telegram's HTML subset (`utils.markdown_telegram`: markdown-it-py with raw HTML and images off, text escaped), so the Executive's Markdown shows as formatting; links show as their text and target in plain text and never become tags, so quoted text can't hide where one goes; a chunk Telegram refuses is sent again as plain text.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it. It does look its sender up on People by the Google account email on the signed event, but hands that entry only to the department gate (`Session.gate_sender_person_id`): the principal's own sends and edits go, a teammate's meet their department's authority, and anyone else's wait for approval. It is never `caller_person_id`, so it grants nothing else.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The poller handles one message at a time, so each Executive turn on an email has a deadline, `EMAIL_TURN_TIMEOUT_S` (300 s): past it the turn is cut off, an `integration_inbound` row with outcome `turn_timeout` records it, and the message is marked read and not run again (it may already have replied). A message whose handling keeps raising is given up after three tries in a run and marked read, rather than retried every poll. Each gateway call it makes is bounded by `MCP_TOOL_TIMEOUT_S` (see Lifecycle). The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary in an alert for the principal instead. Mail from anyone not in People, a contact or a stranger, is held as outside content for its whole turn (`orchestrator.outside_content`): no connected-app write, contact change, follow-up, link, script or workflow, no direct message, only reads and an alert private to the principal. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\n **An email that got no reply goes to Needs you.** Mail from the team or the principal is answered by the model calling the mailbox's send tool, so a turn can end with nothing sent (a tool refused, the answer only written). The gateway marks on the conversation who each accepted send reached (`Session.mail_sent_to`: Gmail `send_gmail_message` to/cc, Outlook `send-mail` recipients; `mail_replied_ids`: the message an Outlook `reply-mail-message` / `reply-all-mail-message` answered). After the turn the poller (`_note_reply_outcome`) checks the sender, by any of their addresses, or the message id; with no reply it files a card through `integrations.unanswered_mail` (source `unanswered_email`, high, tagged `private:principal` and routed to the principal, so only their own /today shows it), whatever the model did. Repeats in the thread fold into it (one card per thread, occurrence count), and a later turn that does reply resolves it. A reply the poller sees is also logged (`unanswered_mail.record_reply`, a private `integration_outbound` row keyed by thread), and the briefs read both: each INBOUND email from the roster says \"the Executive replied\" only on that evidence, or \"no reply went out\" while its card is open (`open_thread_keys`), so the brief stops telling the principal to answer mail the Executive already answered. Only mail Gmail proved is the principal's (`Session.email_authenticated`) reads \"Your email got no reply\" with its subject and what the Executive wrote, which never reached them; a teammate's card names who is waiting and never their subject or text (their conversation is theirs alone); mail that only claims a teammate's or the principal's address says it could not be proven and carries nothing the sender wrote. A plain-text `Error …` tool result is not counted as a send. Contacts and senders off the team are not answered by design and keep their own paths. Why: the brief read the inbound log and said people were waiting while Needs you, which shows alerts only, stayed empty, since an alert depended on the model choosing `create_alert`.\n\n **Other mail sources** (`integrations.mail_sources`). Mail read from anywhere but the Executive's own mailbox (a hosted inbound address, a relay) follows the same rules through a vendor-neutral hook. Nothing is registered by default and the hook has no settings: a deployment registers a `MailSource` (its loop, an `enabled` check, and how to replay a held message), the lifespan starts the enabled ones, and each message goes to `handle_inbound` as an `InboundMail`: the parsed message, the address it came to, `prove_sender` (DMARC, or SPF and DKIM aligned, as the source can tell), `send_answer`, an optional attachment reader and what a held message keeps. `handle_inbound` runs the poller's own handling (`email_poller._handle_mail`): sender resolution, private-to-principal rows, the teammate's own rows only when proven, untrusted-content wrapping, the principal's proven mail, the forwarded-by-principal framing, hydration and the turn deadline. Because a source mails the answer itself (with the AI line, and an `integration_outbound` row) rather than the model calling a send tool, three things differ: a stranger is held for the principal silently, with no acknowledgement and no turn, and replayed through the source that read it (`replay_held_mail` dispatches on the payload's `mail_source`); a contact's mail, and mail claiming a teammate that nothing proves, is answered to the principal and never to the sender; and roster-request and fact confirmations are answered only from the mailbox they were sent from. A source must be registered to be handled, it does nothing while the Executive is paused (`handle_inbound` returns `PAUSED` and the source keeps the message), a stranger the request queue won't take is logged as not held, and a sender who is neither team nor contact by the time the turn runs gets no answer at all.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`. Google Chat's inbound audit row also carries the matched People id (`sender_person_id`), looked up before the row is written, so the brief can tell the principal's own messages apart by id, never by a display name anyone can set.\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). A From domain with no DMARC record (no verdict, or `dmarc=none`) passes only on a DKIM signature Gmail verified for exactly that domain, or Google Workspace's default key for it (`<domain-with-hyphens>.<date>.gappssmtp.com`, read back only for a two-label domain without hyphens). SPF alone never counts, since a domain that lists Google's servers passes anyone sending through Google. Mail a list or group resent (`List-Id`, `X-Google-Group-Id`, a Groups `+bnc` envelope) is never proven, since an open group in the domain's own Workspace resends an outsider's forged From under its signature, and a stamp echoing `smtp.helo=` proves nothing. 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### Picking people and rooms by name (chat directory)\n\nNobody has to copy a raw Slack, Discord or Telegram id. The person page, Add person and a department's Channels settings pick them by name from what the bots this instance runs can reach (`integrations/chat_directory.py`, served at `GET /chat-directory/people`, `/channels` and `/slack/lookup`, the principal's alone). The id is still what is saved; the by-hand field stays under \"Enter an ID by hand\", and is all there is for a provider with no bot.\n\n- **Slack** — channels from `conversations.list` (public, plus the private ones the bot is in; scopes `channels:read`, `groups:read`, and public only when `groups:read` is missing) and people from `users.list` (no bots, no deactivated accounts; `users:read`, and `users:read.email` for their profile email). A person with a work email is matched by it (`users.lookupByEmail`, after the cached list): the picker pre-selects \"Found by email\" with a \"Not them?\".\n- **Discord** — text and announcement channels of the servers the bot is in (only `DISCORD_GUILD_IDS` when set) and their members over the REST API. Members need the Server Members privileged intent; when Discord refuses, the list is empty with `members_available` false, not an error.\n- **Telegram** — there is no list API, so the webhook records each chat an update comes from in `telegram_chats` (`integrations/telegram_chats.py`): private chats are people, groups and supergroups are rooms. Only a webhook whose `TELEGRAM_WEBHOOK_SECRET` checked out records anything, since without it anyone could post a made-up name for a chat id. A row is a suggestion only and grants nothing: the roster still decides who is answered.\n\nA department's Slack and Discord pickers pre-select the room named most like the department; it is saved only when the person presses Save. Lists are cached in-process for 60 s and capped at 2,000; a provider that fails reads as an empty list. Tokens go only in the Authorization header to the provider's own API host and are never returned.\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.chat_topics.name_chat` (the first words of the message if that fails), as a web chat's first turn does: the same call files it under one of its owner's chat topics, so a Telegram or Slack conversation sits beside the web chats about the same matter in the Chats page's Topic view. 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 (except where a chat shows them, below), 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.\n\n**Approval cards with buttons (Telegram).** In a private Telegram chat on a webhook only Telegram can call (`TELEGRAM_WEBHOOK_SECRET` set and valid; `integrations.channel_cards.shows_cards`), the cards a reply leaves are sent as they are shown under a web chat reply: a meeting to book and a card of actions from `propose_actions`. `Executive.chat(cards=...)` collects their ids from the turn's `action_taken` events; the adapter sends each as a plain-text message with **Approve** and **Skip** inline buttons (`callback_data` `card:<id>:a|s`), and the `<channel>` block tells the model the card is there and that a typed yes does not approve it. A tap arrives as a `callback_query` and is taken only from a private chat whose sender is that chat (`from.id` = chat id), on the verified webhook; the chat's rostered person is the tapper. `api.routes.decisions.resolve_in_chat` applies the web chat's rule (a card of actions is its person's alone; a meeting is the principal's, or its approver's unless it is the principal's private booking), books or carries out the card exactly as stored (`delegation.verified.ChatTap` stands in for the signed-in caller on an action card), or records the skip. The card's message is then edited to show the outcome without buttons. Elsewhere (Slack, Discord, Google Chat, a group, an unverified webhook) no card is sent and `propose_actions` tells the model the card is on Today. 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/XLSX/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**Voice notes** are transcribed before the turn, since the model takes no audio. `providers.transcription` calls any OpenAI-compatible `POST {base}/audio/transcriptions` server: `TRANSCRIPTION_BASE_URL` (with `TRANSCRIPTION_API_KEY` / `TRANSCRIPTION_MODEL`) wins, otherwise OpenRouter when `OPENROUTER_API_KEY` is set (`elevenlabs/scribe-v2`), otherwise there is none and a voice note becomes a line asking the sender to type it. Recordings are capped at 25 MB and `TRANSCRIPTION_MAX_SECONDS` (300), the length read on the server from the Ogg, WebM, MP4 or WAV container (`recording_seconds`), since the servers bill by length and the browser's own stop can be skipped; a file whose length can't be read (mp3, flac, aac) is held to 16 KB per allowed second. A file can misstate its own length, so the bound that holds is bytes: at most `TRANSCRIPTION_MAX_MB_PER_DAY` (200) go to the speech server per UTC day, failed calls included. A voice note the sender recorded in the chat app (a Telegram voice or video note, a Discord voice message, a Slack clip; `AttachmentItem.voice_note`) becomes their own words (`[Voice note, transcribed]`; those senders are roster-gated). The reply is the answer alone, with no echo of what was heard. Any other audio (a Telegram audio file, an uploaded recording, anything on Google Chat) may hold someone else's voice, so its words are attachment text, untrusted-wrapped like a document's. An email's audio attachments (up to 2) are transcribed into attachment text, untrusted-wrapped like a document's. Each call writes one usage row (actor `transcription`, with the cost the server reports) and tells any `add_usage_listener` listener. The web chat mic records in the browser and posts to `POST /chat/transcribe`; the words go into the message box to read and send.\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). Image attachments (PNG/JPEG/GIF/WebP) go the same way into vision blocks for the turn: up to 3, none under 10 KB (signature logos, tracking pixels) and none over 3 MB (the model API's 5 MB base64 limit). A registered mail source's `read_attachments` may return images too (`EmailAttachments`). 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. A delete is sent the same way, except the typed `cancel_calendar_event` of a meeting the Executive booked, which keeps its cancellation notice. Google Docs, Sheets, Slides, Forms and Drive writes run only on files and folders the Executive's own Google account owns (`_check_google_file_write`, read through `get_drive_file_permissions` at call time, fail-closed; only a name starting with a read verb skips it), as OneDrive writes do. Someone added to People in the current turn is left out of the allow-list until the next turn. 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 pass through. `delete-calendar-event` makes Exchange mail every attendee, so it reads the event and roster-checks the attendees first, except the typed `cancel_calendar_event` of that same event. 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. Files Act as me's `save_my_email_attachment` copied from someone's own mail into the Executive's Drive or OneDrive (`delegation.saved_files`) are that person's alone: on any other turn the gateway refuses a call whose arguments name a recorded file id and drops the entries or lines of a result that name one, failing closed for the file tools when the record can't be read. The folders those copies go in are made by the save (never adopted by name) and recorded, and a model call naming one, by id or by an OneDrive path through it, is refused on every turn, the owner's too, with their ids hidden from results. That tool's own calls are the only Drive and OneDrive writes a turn that read the owner's mail may make: built in code, admitted past the lockdown as those exact objects (`code_built_call`), and still checked by every gate above.\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 read from `manage_event`'s plain-text reply (which also carries the event id, inside the event link's `eid`), 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. A proposal raised in the web chat by the person who approves it (the principal, or its approver when it isn't the principal's private booking) says `approve_here`; its `action_taken` chip then carries the `decision_id`, and the chat shows the approval card (Approve, Edit, Dismiss) under the reply as well as on the briefing — answering either clears both. A booked meeting whose event id was never read can't be cancelled from the app: both cancel paths refuse rather than report a cancel that left it on the calendar.\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: a sender is authenticated from Exchange's own stamp instead of Gmail's (`fact_confirmation.sender_authenticated` reads the message's Graph `internetMessageHeaders` and applies `delegation.outlook.exchange_authenticated`: the topmost `Authentication-Results` with EOP's `compauth=`, a DMARC pass for the From domain, or for a domain with no DMARC record a single DKIM pass with `header.d=` that domain, and never mail a list resent or a stamp echoing `smtp.helo=`; it relies on Exchange Online stamping every message, so a tenant whose mail arrives through another server without that stamp gets no real proof), but there is no acknowledgement to an unknown sender (the one-shot grant admits only Gmail's send tool); 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 in an alert for the principal instead. Mail from anyone not in People, a contact or a stranger, is held as outside content for its whole turn (`orchestrator.outside_content`): no connected-app write, contact change, follow-up, link, script or workflow, no direct message, only reads and an alert private to the principal. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\n **An email that got no reply goes to Needs you.** Mail from the team or the principal is answered by the model calling the mailbox's send tool, so a turn can end with nothing sent (a tool refused, the answer only written). The gateway marks on the conversation who each accepted send reached (`Session.mail_sent_to`: Gmail `send_gmail_message` to/cc, Outlook `send-mail` recipients; `mail_replied_ids`: the message an Outlook `reply-mail-message` / `reply-all-mail-message` answered). After the turn the poller (`_note_reply_outcome`) checks the sender, by any of their addresses, or the message id; with no reply it files a card through `integrations.unanswered_mail` (source `unanswered_email`, high, tagged `private:principal` and routed to the principal, so only their own /today shows it), whatever the model did. Repeats in the thread fold into it (one card per thread, occurrence count), and a later turn that does reply resolves it. A reply the poller sees is also logged (`unanswered_mail.record_reply`, a private `integration_outbound` row keyed by thread), and the briefs read both: each INBOUND email from the roster says \"the Executive replied\" only on that evidence, or \"no reply went out\" while its card is open (`open_thread_keys`), so the brief stops telling the principal to answer mail the Executive already answered. Only mail Gmail proved is the principal's (`Session.email_authenticated`) reads \"Your email got no reply\" with its subject and what the Executive wrote, which never reached them; a teammate's card names who is waiting and never their subject or text (their conversation is theirs alone); mail that only claims a teammate's or the principal's address says it could not be proven and carries nothing the sender wrote. A plain-text `Error …` tool result is not counted as a send. Contacts and senders off the team are not answered by design and keep their own paths. Why: the brief read the inbound log and said people were waiting while Needs you, which shows alerts only, stayed empty, since an alert depended on the model choosing `create_alert`.\n\n **Other mail sources** (`integrations.mail_sources`). Mail read from anywhere but the Executive's own mailbox (a hosted inbound address, a relay) follows the same rules through a vendor-neutral hook. Nothing is registered by default and the hook has no settings: a deployment registers a `MailSource` (its loop, an `enabled` check, and how to replay a held message), the lifespan starts the enabled ones, and each message goes to `handle_inbound` as an `InboundMail`: the parsed message, the address it came to, `prove_sender` (DMARC, or SPF and DKIM aligned, as the source can tell), `send_answer`, an optional attachment reader and what a held message keeps. `handle_inbound` runs the poller's own handling (`email_poller._handle_mail`): sender resolution, private-to-principal rows, the teammate's own rows only when proven, untrusted-content wrapping, the principal's proven mail, the forwarded-by-principal framing, hydration and the turn deadline. Because a source mails the answer itself (with the AI line, and an `integration_outbound` row) rather than the model calling a send tool, three things differ: a stranger is held for the principal silently, with no acknowledgement and no turn, and replayed through the source that read it (`replay_held_mail` dispatches on the payload's `mail_source`); a contact's mail, and mail claiming a teammate that nothing proves, is answered to the principal and never to the sender; and roster-request and fact confirmations are answered only from the mailbox they were sent from. A source must be registered to be handled, it does nothing while the Executive is paused (`handle_inbound` returns `PAUSED` and the source keeps the message), a stranger the request queue won't take is logged as not held, and a sender who is neither team nor contact by the time the turn runs gets no answer at all.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### Alert triage of chat messages\n\nEvery chat-app message that passes the roster gate (Telegram, Slack, Discord, Google Chat) is also handed to alert triage through `alerts.pipeline.schedule_chat_message_evaluation`. The sender is named by their People record (`full_name`), not by the name they typed into the chat app, so a person whose account there is called something else is never read as a stranger; the chat app's own name (or raw user id) is used only when nobody on the roster matched. The principal's own messages to their Executive are a conversation, not news for their brief, so they are not triaged at all. Triage sees the sender as `sender:` and the room as `channel:`. Google Chat's inbound audit row also carries the matched People id (`sender_person_id`), looked up before the row is written, so the brief can tell the principal's own messages apart by id, never by a display name anyone can set.\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). A From domain with no DMARC record (no verdict, or `dmarc=none`) passes only on a DKIM signature Gmail verified for exactly that domain, or Google Workspace's default key for it (`<domain-with-hyphens>.<date>.gappssmtp.com`, read back only for a two-label domain without hyphens). SPF alone never counts, since a domain that lists Google's servers passes anyone sending through Google. Mail a list or group resent (`List-Id`, `X-Google-Group-Id`, a Groups `+bnc` envelope) is never proven, since an open group in the domain's own Workspace resends an outsider's forged From under its signature, and a stamp echoing `smtp.helo=` proves nothing. 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### Picking people and rooms by name (chat directory)\n\nNobody has to copy a raw Slack, Discord or Telegram id. The person page, Add person and a department's Channels settings pick them by name from what the bots this instance runs can reach (`integrations/chat_directory.py`, served at `GET /chat-directory/people`, `/channels` and `/slack/lookup`, the principal's alone). The id is still what is saved; the by-hand field stays under \"Enter an ID by hand\", and is all there is for a provider with no bot.\n\n- **Slack** — channels from `conversations.list` (public, plus the private ones the bot is in; scopes `channels:read`, `groups:read`, and public only when `groups:read` is missing) and people from `users.list` (no bots, no deactivated accounts; `users:read`, and `users:read.email` for their profile email). A person with a work email is matched by it (`users.lookupByEmail`, after the cached list): the picker pre-selects \"Found by email\" with a \"Not them?\".\n- **Discord** — text and announcement channels of the servers the bot is in (only `DISCORD_GUILD_IDS` when set) and their members over the REST API. Members need the Server Members privileged intent; when Discord refuses, the list is empty with `members_available` false, not an error.\n- **Telegram** — there is no list API, so the webhook records each chat an update comes from in `telegram_chats` (`integrations/telegram_chats.py`): private chats are people, groups and supergroups are rooms. Only a webhook whose `TELEGRAM_WEBHOOK_SECRET` checked out records anything, since without it anyone could post a made-up name for a chat id. A row is a suggestion only and grants nothing: the roster still decides who is answered.\n\nA department's Slack and Discord pickers pre-select the room named most like the department; it is saved only when the person presses Save. Lists are cached in-process for 60 s and capped at 2,000; a provider that fails reads as an empty list. Tokens go only in the Authorization header to the provider's own API host and are never returned.\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.chat_topics.name_chat` (the first words of the message if that fails), as a web chat's first turn does: the same call files it under one of its owner's chat topics, so a Telegram or Slack conversation sits beside the web chats about the same matter in the Chats page's Topic view. 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 (except where a chat shows them, below), 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.\n\n**Approval cards with buttons (Telegram, Slack and Discord DMs).** In a private Telegram chat on a webhook only Telegram can call (`TELEGRAM_WEBHOOK_SECRET` set and valid; `integrations.channel_cards.shows_cards`), the cards a reply leaves are sent as they are shown under a web chat reply: a meeting to book, a card of actions from `propose_actions`, and a change to a saved workflow (`orchestrator/workflow_change.py`; of the `app_action` cards only those in `decisions.CHAT_APP_ACTIONS`, whose action checks the tapper itself). `Executive.chat(cards=...)` collects their ids from the turn's `action_taken` events; the adapter sends each as a plain-text message with **Approve** and **Skip** inline buttons (`callback_data` `card:<id>:a|s`), and the `<channel>` block tells the model the card is there and that a typed yes does not approve it. A tap arrives as a `callback_query` and is taken only from a private chat whose sender is that chat (`from.id` = chat id), on the verified webhook; the chat's rostered person is the tapper. `api.routes.decisions.resolve_in_chat` applies the web chat's rule (a card of actions is its person's alone; a meeting is the principal's, or its approver's unless it is the principal's private booking), books or carries out the card exactly as stored (`delegation.verified.ChatTap` stands in for the signed-in caller on an action card), or records the skip. The card's message is then edited to show the outcome without buttons. A Slack DM (with `SLACK_CARD_BUTTONS` on, which needs Interactivity turned on in the Slack app and the `im:write` scope) and a Discord DM work the same way. Slack gets Block Kit buttons (`oe_card_approve` / `oe_card_skip`, the callback data as the value, the card as plain text), and a tap counts only when `conversations.open` for the tapper returns that same DM. Discord gets a View whose buttons carry the callback data as `custom_id`, and `on_interaction` takes a tap only in a DM whose recipient is the tapper. Either way the tapper must be on the roster by their app id. Elsewhere (a Slack or Discord channel or thread, Google Chat, a Telegram group, an unverified webhook) no card is sent and `propose_actions` tells the model the card is on Today. 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/XLSX/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**Voice notes** are transcribed before the turn, since the model takes no audio. `providers.transcription` calls any OpenAI-compatible `POST {base}/audio/transcriptions` server: `TRANSCRIPTION_BASE_URL` (with `TRANSCRIPTION_API_KEY` / `TRANSCRIPTION_MODEL`) wins, otherwise OpenRouter when `OPENROUTER_API_KEY` is set (`elevenlabs/scribe-v2`), otherwise there is none and a voice note becomes a line asking the sender to type it. Recordings are capped at 25 MB and `TRANSCRIPTION_MAX_SECONDS` (300), the length read on the server from the Ogg, WebM, MP4 or WAV container (`recording_seconds`), since the servers bill by length and the browser's own stop can be skipped; a file whose length can't be read (mp3, flac, aac) is held to 16 KB per allowed second. A file can misstate its own length, so the bound that holds is bytes: at most `TRANSCRIPTION_MAX_MB_PER_DAY` (200) go to the speech server per UTC day, failed calls included. A voice note the sender recorded in the chat app (a Telegram voice or video note, a Discord voice message, a Slack clip; `AttachmentItem.voice_note`) becomes their own words (`[Voice note, transcribed]`; those senders are roster-gated). The reply is the answer alone, with no echo of what was heard. Any other audio (a Telegram audio file, an uploaded recording, anything on Google Chat) may hold someone else's voice, so its words are attachment text, untrusted-wrapped like a document's. An email's audio attachments (up to 2) are transcribed into attachment text, untrusted-wrapped like a document's. Each call writes one usage row (actor `transcription`, with the cost the server reports) and tells any `add_usage_listener` listener. The web chat mic records in the browser and posts to `POST /chat/transcribe`; the words go into the message box to read and send.\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). Image attachments (PNG/JPEG/GIF/WebP) go the same way into vision blocks for the turn: up to 3, none under 10 KB (signature logos, tracking pixels) and none over 3 MB (the model API's 5 MB base64 limit). A registered mail source's `read_attachments` may return images too (`EmailAttachments`). 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. A delete is sent the same way, except the typed `cancel_calendar_event` of a meeting the Executive booked, which keeps its cancellation notice. Google Docs, Sheets, Slides, Forms and Drive writes run only on files and folders the Executive's own Google account owns (`_check_google_file_write`, read through `get_drive_file_permissions` at call time, fail-closed; only a name starting with a read verb skips it), as OneDrive writes do. Someone added to People in the current turn is left out of the allow-list until the next turn. 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 pass through. `delete-calendar-event` makes Exchange mail every attendee, so it reads the event and roster-checks the attendees first, except the typed `cancel_calendar_event` of that same event. 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. Files Act as me's `save_my_email_attachment` copied from someone's own mail into the Executive's Drive or OneDrive (`delegation.saved_files`) are that person's alone: on any other turn the gateway refuses a call whose arguments name a recorded file id and drops the entries or lines of a result that name one, failing closed for the file tools when the record can't be read. The folders those copies go in are made by the save (never adopted by name) and recorded, and a model call naming one, by id or by an OneDrive path through it, is refused on every turn, the owner's too, with their ids hidden from results. That tool's own calls are the only Drive and OneDrive writes a turn that read the owner's mail may make: built in code, admitted past the lockdown as those exact objects (`code_built_call`), and still checked by every gate above.\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 read from `manage_event`'s plain-text reply (which also carries the event id, inside the event link's `eid`), 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. A proposal raised in the web chat by the person who approves it (the principal, or its approver when it isn't the principal's private booking) says `approve_here`; its `action_taken` chip then carries the `decision_id`, and the chat shows the approval card (Approve, Edit, Dismiss) under the reply as well as on the briefing — answering either clears both. A booked meeting whose event id was never read can't be cancelled from the app: both cancel paths refuse rather than report a cancel that left it on the calendar.\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: a sender is authenticated from Exchange's own stamp instead of Gmail's (`fact_confirmation.sender_authenticated` reads the message's Graph `internetMessageHeaders` and applies `delegation.outlook.exchange_authenticated`: the topmost `Authentication-Results` with EOP's `compauth=`, a DMARC pass for the From domain, or for a domain with no DMARC record a single DKIM pass with `header.d=` that domain, and never mail a list resent or a stamp echoing `smtp.helo=`; it relies on Exchange Online stamping every message, so a tenant whose mail arrives through another server without that stamp gets no real proof), but there is no acknowledgement to an unknown sender (the one-shot grant admits only Gmail's send tool); 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-20T16:00:00Z"+ "generated_at": "2026-10-25T12:03:39.155927+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.jsonindex c116a6c8..17d9537b 100644--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json@@ -1,7 +1,7 @@{"section_id": "workflows","title": "Workflows",- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review` and the weekly `goal_review`, which grades the goals no check-in covers; see Scheduler).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and built-ins: the Executive's own chat tools as `oe__<name>` (see *Chat's tools in action steps* below; `oe__create_alert`, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow but refuses to replace a switched-on one that has action steps (an inbound email steering the Executive could otherwise switch off an approved job and stage new tools under its name); those edits happen in the advanced editor. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list, each tool named in plain words (`plain_tool_name`: \"Google Workspace: get events\", never `google_workspace__get_events`; the held-writes question names tools the same way). The step's user turn gives the time now in the user's timezone, and the report gives times in it. Tool output is framed as data, never instructions.\n\n**Chat's tools in action steps.** A step can use almost everything the Executive uses in chat, so an idea from a conversation can become a workflow without a missing tool. `workflows/chat_tools.py` holds one list, `ACCESS`, that labels every chat tool: **use** (a step may list it as `oe__<name>`, e.g. `oe__send_slack_dm`, `oe__run_workflow`, `oe__update_department_goal`, `oe__web_search`), **as me** (Act as me tools, not yet in workflows), **covered** (the step already has its own path: gateway tools, `run_script`, specialist steps) or **chat only** (memory, company profile, roster changes, open loops, follow-up corrections and screen actions). A unit test fails when chat gains a tool without a label, so new chat tools reach workflows by one line rather than a second copy. A **use** tool runs through chat's own handler as an unattended chat turn would: an unattended `Session` bound as `current_session`, the workspace-mode filter (solo withholds department and company posts), and, in a team member's workflow, their department gate. Channels the instance has no token for are not offered. Saving the workflow is the person's permission, so Take the lead's approval gates don't apply, the same as the gateway tools before. `oe__run_workflow` refuses a workflow already running in its own chain and nests at most three deep. It and `oe__run_executive_research` get a 15-minute call timeout. `oe__web_search` is the model's server search: it is appended after the sorted tools, never called by the step, and a paused search turn is sent back as-is. Workflows have no tool handlers of their own any more: `oe__message_person` and `oe__create_alert` are the chat tools under the same names, and the old `oe__read_file` still resolves (to `read_document`) for saved workflows but isn't offered for new steps (`chat_tools.LEGACY_NAMES`). The designer lists every built-in by its first sentence, and chat's `draft_workflow` says chat tools are available as `oe__<name>`; the catalog's search ranks built-ins by how many query words they match.\n\n**Email as the creator.** Besides the chat tools, a step may use `oe__draft_email_as_me` (a draft in the workflow creator's own mailbox for them to send) or `oe__send_email_as_me` (sent as them), Act as me's two workflow tools (`delegation.workflow_email`, see the delegation section). The creator picks one when saving the workflow, by asking for it in chat or the designer, which is told whether they can; the gateway's mail tools still send from the Executive's own address. A workflow that sends as its creator can only be created, changed or switched on by that creator, verified (a 403 otherwise), and an email to their own address or one written in the goal of the step that emails goes without asking, while the first to any other address waits for their approval like any other first write. A step may also answer an email in the creator's inbox the way their Handle it for me does (`oe__answer_email_as_me`, naming only the thread: sent on its own when its rules allow, otherwise a card for them; see the delegation section). A step may also read the creator's own mail and calendar (`oe__search_my_email`, `oe__read_my_email`, `oe__my_email_awaiting_reply`, `oe__my_calendar`, `delegation.workflow_reads`). A workflow that does runs only for its creator (a scheduled run is created as theirs and reports to them alone), never when another workflow started it, and is locked down for all of its steps: no gateway tools, web search, scripts, other workflows, or posts to everyone (it may still email as the creator, under the same recipient rule), checked on save and at every step (see the delegation section).\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_document` (chat's `read_document`; saved workflows that list the old `oe__read_file` get the same tool) extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` or the company documents folder (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs a rostered recipient a few plain lines on what came of it, or nothing when there was nothing for them (`workflows/run_message`); the full report stays on the run. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).",+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. The activity feed never shows a run's log title (`\"Executive Research (periodic)\"`): `workflows/run_outcome.py` gives each finished run a plain name (\"Researched your market\", \"Checked in with Sales\", or the name it started with, less its date) and one line on what came of it, read from that stored artifact, so older runs read the same and nothing extra is written or called. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 25 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, with input from the hired function's specialist — `sales` for a sales role — kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status` (`department_check_in.persist_goal_verdicts`, shared with `weekly_review` and the weekly `goal_review`, which grades the goals no check-in covers; see Scheduler).\n- `weekly_review` — the principal's weekly look back and ahead (see *Weekly review* below).\n\n**Standing facts in unattended output.** `end_of_day_digest`, the weekly review's top-three call and the morning reflection append the standing facts (`memory.facts.with_standing_facts`; a teammate's marked `(per <name>)`) to their user turn, and the morning brief gets them through `render_briefing_context`. A workflow step that consults a specialist gets them through `route_to_specialist`. A correction made in chat therefore holds in every recurring brief and run. The morning brief also reads `facts.render_teammate_changes(since)` off the event loop and passes it to both `render_briefing_context` (a TEAMMATE CORRECTIONS SINCE LAST BRIEF block) and `build_brief_fingerprint`, so the principal hears of each correction a teammate made in the window, and that alone un-suppresses an otherwise unchanged brief. Proposals waiting for approval are listed only in a brief the principal reads privately (`include_proposed=_private_ok()`), and then mark the run private to them. The principal's own Always in the loop notes (`memory.history_brief`, only with their switch on) come in by a stricter rule, only on the scheduler's delivery (`PRINCIPAL_DELIVERY`), never a run from chat, whose tool result reaches the turn's shared audit row and peer memory: the morning brief's FROM YOUR NOTES — DUE SOON block and the end-of-day digest's FROM YOUR NOTES — TODAY block (what they committed to since the last digest, then what is due tomorrow). Either marks the run `private_to_principal` and moves its fingerprint; the digest, which had no private reads before, now emits that flag too. In the install's first week (`briefing.first_week`, seven days from the principal's People row) the morning brief also passes a GETTING STARTED block to `render_briefing_context(getting_started=)` and its keys to `build_brief_fingerprint`: onboarding goals, departments with no leader and, on the scheduler's delivery with Act as me and Draft replies to my inbox on, who wrote to the owner's own mailbox (sender and subject only) and, with Read my calendar on, today's meetings on their own calendar (time and title), either of which marks the run `private_to_principal`. The brief opens with **Getting started** and is never the quiet line while the block has anything in it (see Today).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler sends to the principal. Both are written with `briefing.narrative.brief_model()`, the Executive's own model (its Council pick, else `DEFAULT_MODEL`), since a brief is the Executive speaking; only the grounding repair stays on the fast model. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). The morning brief also reads the principal's **live world** since that window opened (`briefing.live_signals.gather_live_signals`): mail and chat the Executive handled (INBOUND, grouped by sender and subject, each email from the roster marked replied or not, earlier days dated), under a NOW line and THE PRINCIPAL line that names its reader so the brief writes \"you\" (the end-of-day digest gets the same line, and the team reflection a YOUR PRINCIPAL line under its roster; the reflection flags only what today's input still shows), what got stuck (STUCK: a reply the outbound gate held, a non-roster sender who got no reply, a Google Chat message left unanswered, chat drafts still in the principal's Gmail, after `live_signals.settle_principal_drafts` has marked the ones they since sent or deleted there), the principal's own chats, and — in both modes now, unless the solo top three already listed it — today's calendar, read fresh (`live_signals.refresh_calendar(max_age=0)`). The 07:30 reflection's **Flagged for the brief** bullets are carried across (`brief_state.reflection_flags_since`, the latest reflection run finished inside the window) instead of surviving only as an activity line with the run's title, and the rhythm runs themselves (`today.RHYTHM_WORKFLOWS`) are dropped from the brief's activity: their dated titles were noise and moved the fingerprint every day. At-risk departments name their slipping goals and each proposal carries its age. The period is the principal's local date. Section order: top call → **today** (the calendar's shape and anything stuck) → what changed (inbound first, naming who wrote) → handled overnight → needs you (new only) → waiting on → at risk (the slipping goal, or the department left out — never \"no detail yet\"). Quoted mail, chat, invite and reflection text is marked as data, never instructions. **Privacy:** the brief reads what is private to the principal — their contacts' alerts and mail, their drafts, their chats and their calendar — only on a run for them: the scheduler's (`morning_brief.PRINCIPAL_DELIVERY`) or the principal's own verified chat turn in a conversation only they can read (`delegation.settings.private_conversation`: the web chat, a Slack or Discord DM, a private Telegram chat — never a shared channel, where the reply is posted for everyone). A run anyone else starts (a teammate from chat in team mode, `POST /workflows/…/runs`) reads what everyone may see, as before. A run that did read a private row says so on its `result` event (`private_to_principal`: its live read differs from the shared one in any key or count), and the scheduler, `run_workflow` and `POST /workflows/{name}/runs` all then keep `persistence.PRIVATE_RUN_ARTIFACT` in the run history instead of the text. Text another pass wrote (the reflection's flags) renders as quoted ` > ` lines and every goal and headline field is one-lined, so none can start a line that reads as a block header. The fingerprint carries the live signals' time-free keys (who wrote about what, what is stuck, the calendar's shape) and the reflection flags when there are any, so \"nothing new\" means the principal's world was quiet too; the context summary is logged at INFO (`morning_brief: context since=… inbound=… stuck=… suppressed=…`). In **solo mode** (one person using Open Executive for themselves) both briefs speak to the principal, whatever their role: the morning brief runs top call → top three today → what changed (inbound and stuck first) → handled overnight → needs you → due this week (the principal's open loops overdue or due within 7 days, from `open_loops.principal_due_soon`) → goals at risk (named by area), the end-of-day digest what I did → open decisions → goals at risk tomorrow → sleep on this, over a context with goals at risk by area and no people-waiting or department block; the fingerprint carries the mode and ignores who is awaiting, and carries the due items as `(loop_id, state)` pairs when there are any. **Top three today** is picked in code, not by the model (`briefing.top_three`: overdue then due-today commitments, off-track then at-risk goals, commitments due later this week, then active projects, stalest first). The solo Briefing's *Top three today* card shows the same pick from the same code (`GET /today/top-three`, see Today). When the MCP gateway runs the Google Workspace server, one `google_workspace__get_events` call (4 s timeout) lists today's events on the principal's calendar — their address as the calendar id, read with the Executive's account (`primary` when the Executive is signed in as them) — and on a business day (`calendar_tools.is_business_day`, the rule the booking tools apply; at the weekend the day's events are still listed but no slot is suggested) each item gets its own free block inside `CALENDAR_BUSINESS_HOURS_START`–`_END`, rendered with a TODAY'S CALENDAR block — only a date-only event is all day, a zero-length one blocks nothing, and one whose times can't be read is left out; no gateway, no principal address, an error, a timeout or a reply it cannot read all mean no calendar and no slots, never a failed brief; the log records only the reply's length or the error's type, never calendar text. When the principal has Act as me and **Read my calendar** on (`delegation.calendar`) and their mailbox opens as theirs, `top_three.read_todays_calendar` also reads their own calendar through their own sign-in (Gmail or Outlook, same 4 s timeout, declined events left out), at the same time as the Executive's read, and merges the two: an event with the same title and times on both is listed once, and either read alone is enough. This read feeds the morning brief, the /today calendar cache (`live_signals.refresh_calendar`) and so the end-of-day digest and Right now; the solo top three adds it only on a run for the principal (`build_top_three(include_own=private_ok)`). The fingerprint carries the three items' keys (no dates, no slot times) and only a coarse hash of the day (busy blocks rounded to 15 minutes, no titles, no dates), so an unchanged day still suppresses. A day whose calendar read fails after one that worked (or the reverse) changes the fingerprint once, so that brief is written in full. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window. Both are written to their reader in code (`briefing.reader`): the principal's full name and addresses are masked to \"the reader\" throughout the context under a THE READER line, the prompt says \"you\" for the reader, nobody is \"the principal\" and the Executive is \"I\" / \"me\", and a draft that still slips is rewritten once (the morning brief) and fixed in code. **The end-of-day digest reads the day itself.** On the scheduler's delivery to the principal alone it leads with TODAY WITH YOU (`session_store.own_conversation_since`: the principal's own conversations with the Executive since the last digest, their words and its replies, never a conversation someone else owns) and the live blocks (`live_signals.render_live_blocks`: mail in, what got stuck), then COMING UP (the Executive's own follow-ups due in the next two days). It leaves out its own rhythm runs (`today.RHYTHM_WORKFLOWS`) and gets the reader's leave-out list (`brief_requests.render_parts`). Its shape is **Today**, **Done for you**, **Next** and an optional **Sleep on this**, at most 150 words, with no header for an empty section. Before this it read only the Executive's own bookkeeping, so on a day of real work it reported its own briefs and missed every number decided in chat.\n\n**Brief delivery.** `scheduler.runner._deliver_to_principal` maps the principal's `preferred_channel` (`slack` / `discord` / `telegram` / `email`) to its delivery channel and tries it first, then the other chat channels the principal has an id for, in the order Slack → Discord → Telegram. Email goes through the active MCP gateway (`google_workspace__send_gmail_message` as the Executive's own address, to the principal, subject `<title> — <date>`) and is used only for an explicit `email` preference, or for `any` when no chat channel resolves — an owner linked by email at setup has `any`, so one who also has Slack does not start getting two emails a day. When nothing can deliver (a web-only principal, or email with no gateway), the brief is still generated and stored as a run with its artifact, as before — a web-only principal reads it on the Artifacts page — it is just not delivered (audited), so the window does not advance, and the next occurrence is chained. The same delivery path carries the client-rotation digest and the weekly review.\n\n**Grounding.** Nothing an unattended pass writes is read by anyone before it goes, so `openexecutive.briefing.grounding` checks it deterministically — no model judges the model. A name (a run of two or more capitalised words once section headers, weekdays, imperative openers and org nouns are trimmed, or one capitalised word in a person slot like \"ask Marcus\" or \"Marcus wrote\") is grounded only when a single line of the pass's inputs holds all of it, or it belongs to a roster person some input mentions — being on the roster alone is not enough. A figure (money, a percentage, a k/M/B number, any bare number of 11 or more; never a date, time, year, duration, id, list marker, `Q3` or small count) is grounded when an input number matches it within the precision it is written with (`$1.2M` matches `$1,234,567`; `47 units` does not match 48). The inputs are the rendered context split into lines labelled by section (a header also carries its bullet count), the company profile and the department titles. `morning_brief` renders its context itself and hands it to the synthesizer as `rendered_context`, so the check reads exactly what the model read; after the quiet fallback, `ground_brief` runs on both briefs. When something is ungrounded it makes one repair call to the fast model (same system prompt, the list of items, \"remove or correct using only the context\"), re-checks, then drops each line still ungrounded and any header left empty, and appends \"_I left out N lines that named people or figures I couldn't match to your data. They're under Left out of your brief on Home._\" (everything ungrounded → one held-back line). Every held line goes in the `grounding` audit row's untruncated `full` payload (up to 30, 400 chars each; `details` keeps a five-line preview), and `grounding.recent_held_back` reads the last day's back for `GET /today`'s `held_back`, which Home lists under **Left out of your brief** for the principal alone — after the narrative inputs are taken, so the held lines never reach a prompt. Then each grounded figure gets a server-chosen ` [n]` — the matching input line with the most words in common with the figure's clause — and a `**Sources**` list closes the brief (`- [n] <section> — <snippet>`, at most 9, snippets quote inbound mail, so links are masked (\"(link removed)\"), Markdown, angle brackets and @-mentions stripped, and they are cut to 90 chars; never `[n]:` at a line start, which Markdown reads as a link definition). Text with nothing to change comes back byte-identical, the fingerprint hashes the inputs so suppression is unaffected, and the grounded text is what is delivered, stored and recorded as delivered. Both brief prompts and the digest prompts say the rule up front. `executive_reflection` wraps its handlers in a `GroundingScope`: `create_alert`, `message_person`, `send_department_message`, `send_company_broadcast` and `schedule_followup` refuse text with an ungrounded name or figure, returning a JSON error that names the items so the model can look the person up or leave the figure out (every tool result joins the inputs, so a `lookup_person` answer grounds the DM after it; the recipient's own name always counts). Its **Flagged for the brief** bullets are filtered the same way before the tool log is appended — the next brief quotes them, where they would ground themselves — and `brief_state.reflection_flags_since` now stops at the tool log's `---`. The reflection's `grounding` rows are private when a private-to-principal alert reached its context, and the digest's always are (its HANDLED block can quote one). Everything fails open. `GROUNDING_CHECKS=enforce` (default) acts, `report` only writes the `grounding` audit rows, `off` skips it; `GROUNDING_CITATIONS=false` drops the markers. Not yet grounded: the /today header (its cards sit beside it), `weekly_review`, the research synthesis, dates and meetings, and a real person named in the wrong role.\n\n### Weekly review (solo)\n\n`weekly_review` (background, inputs all defaulted) closes out the principal's week in six steps. **Goals**: every area with goals is graded by its own specialist, concurrently, with the department check-in's verdict contract (`_parse_verdicts`) and write-back (`persist_goal_verdicts` → `record_goal_review`, one `goal_status_review` audit row per area with actor `weekly_review`); an area with no goals is skipped, one without a specialist is listed ungraded, and one whose specialist fails is shown as last recorded. **Commitments**: `open_loops.principal_due_soon` — overdue or due within 7 days. **Projects**: active initiatives with no update for 7+ days. **Decisions**: the week's (`episodic.decisions_since`). **Revisit**: up to three decisions older than 30 days with an empty outcome (`episodic.decisions_awaiting_outcome`, newest first), listed as `[decision N]` under *How did these turn out?* — the principal's answer is recorded with `record_decision_outcome` (see Agents). **Assemble**: every section always renders (a one-line note when empty), ending with *Next week's top 3* from one fast-model call that follows the `weekly-review` playbook (a constant system prompt; the playbook rides in the user turn), trimmed to at most three list items — or, when that call fails or returns nothing, the same ranked pick the morning brief uses. In solo mode the scheduler fires it weekly (`principal_weekly_review`, see Scheduler) and delivers it through `_deliver_to_principal` like the briefs, recording the delivery outcome. The solo Briefing also shows the latest completed run to the principal (`GET /today/weekly-review`, see Today): `weekly_review.summarize_review` reads the artifact's title line (`TITLE_PREFIX`) and its last `TOP_THREE_HEADING` section back as plain text, so a principal no channel reaches still sees next week's top three. Wording is role-neutral; run by hand in team mode it says *department* instead of *area*.\n\n**Principal-only workflows.** A workflow can name the workspace modes in which only the principal may start it (`Workflow.principal_only_modes`): `weekly_review` in both modes (built from the principal's decision log, commitments and goals, and it re-grades the goals) and `morning_brief` in solo (built from the principal's commitments and calendar). Team `morning_brief` and every other workflow can be started by anyone as before. This decides who may start or trigger a run, not who may read one: stored runs, the scheduled briefs and weekly reviews included, are read under the existing `/workflows/runs` rules — which is why a morning brief that drew on the principal's private rows is stored as `PRIVATE_RUN_ARTIFACT`, not as its text.\n\n- **From chat**, `run_workflow` checks at dispatch, before any run row is created, that the turn is the principal on a verified surface — `create_goal`'s rule — and otherwise refuses with a plain error that does not spell out the rule.\n- **Over HTTP**, the Jobs page's `POST /workflows/{name}/runs` and `POST /evals/runs` (a workflow scenario runs the workflow on live data) call `refuse_principal_only_run`: only a caller signed in as the principal, or a request with no caller email (the CLI or local login), may start the run. Unlike the workspace settings, an install with no principal on the roster lets no signed-in caller in, as in chat. Anyone else gets a 403 (\"Only the principal can run this workflow.\") before any run row exists. The mode is the stored one, or an eval scenario's own `workspace_mode`. The eval route runs exactly the scenario list it checked.\n\nEvery refusal is audited `refused=true` with the workflow, the mode and the caller. The checks fail closed: a mode that cannot be read counts as principal-only, and a check that cannot read the roster refuses.\n\n**Knowledge in the reflection.** A chat turn looks the knowledge base up before the Executive answers; the reflection reads the org's state instead, so nothing looked it up for it. It now carries its own `search_knowledge` tool (`orchestrator.knowledge_tools`, not in the shared `_ALL_SKILL_TOOLS`), which runs the same `knowledge.retriever.retrieve` as chat — the review gate, the synced Drive / OneDrive / Confluence / Notion collections and the published-artifact rule (the pass has no viewer, so no one's private document comes back). The prompt (`_KNOWLEDGE_RULE`, both modes) asks it to search before acting on or flagging something that turns on a customer's or supplier's terms, a price, a policy, a plan or a past decision. Its passages come back up to 4,000 characters (`execute_tool_calls(wide_results=...)`) while other tools stay at their short preview, its result counts as grounding input like any tool result, and the run's tool log keeps each line to 160 characters. Read-only, so Take the lead never gates it. The loop has 5 iterations (was 4) to leave room for a search before acting.\n\nNeither the nightly reflection nor the research synthesis can call `ack_alert`: both run unattended with open alerts rendered into their context, and those headlines are minted from inbound mail and chat, so an injected \"the principal already dismissed 13\" would be acted on with nobody watching. Closing an alert is the alert review's job, with evidence.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence. It also renders an **OPEN LOOPS** block (up to 10, soonest due first, overdue flagged) from Attunement so the standup can connect a slipped promise to the rest of the org state; the nudge engine already chases overdue loops, so the prompt tells it not to DM about a loop merely for being overdue. A **WHAT LANDS** block (from the Attunement outcome ledger) shows, per person, how often each kind of proactive DM got answered over 30 days; the prompt steers DMs toward kinds that land and away from kinds a person reliably ignores. Reflection and research tag their tool execution as proactive (`tag_proactive`) so their DMs are counted. Resolving a wait-for-human approval (`resumer.apply_resolution`) marks the nudges that chased it `acted`. `close_open_loop` is withheld from reflection for the same reason as `ack_alert`: loop text is quoted from what people wrote. `unattended_toolkit` also drops `schedule_tools.UNATTENDED_WITHHELD_TOOLS` (today `create_goal`) from both passes in both modes: a goal is the principal's own decision, and these passes see only inbound text. A turn private to the principal (mail from one of their contacts, or mail they forwarded) cannot start a workflow either: `run_workflow` and `run_executive_research` are in `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, which the chat loop neither offers nor runs on such a turn, since a workflow's steps can reach anyone.\n\nIn **solo mode** the reflection is framed for the principal, whatever their role: they are the only person who uses Open Executive and the only one it takes direction from, it prefers `create_alert` and `schedule_followup` to the principal, and it never messages anyone else from an unattended pass — the people in the principal's world are contacts, so anything they should hear is flagged for the principal to raise. The team roster is replaced by one YOUR PRINCIPAL line (person_id and follow-up channels), its follow-up guard is seeded from the principal only, and department risk renders as areas with goals at risk. The research synthesis follows the same rule — its routing menu and roster name only the principal. In both, `send_department_message`, `send_company_broadcast` and `set_department_head` are withheld, and so are `create_calendar_event`, `create_instant_meeting` and `run_workflow` — a booking reaches its attendees and a workflow can do anything its steps do, so the principal books and starts workflows from chat — and `message_person` refuses anyone but the principal. These passes run unattended with inbound text in their context, so the rules are enforced in code, not only in the prompt.\n\nIn either mode, both passes now dispatch only the tools they offer: the handler map is built from the offered list, so a name the model emits without being offered it is skipped as an unknown tool. They used to look names up in the full handler registry, so tools they deliberately withhold — the raw DM tools (`send_slack_dm` has no roster check), `ack_alert`, `close_open_loop`, and in research the watchlist writes and `run_workflow` — still ran when the model emitted them. Both read the mode before binding their own session (so a caller's override, such as an eval's, counts) and pin it on that session, so their tool handlers use the same mode. They carry the principal's role across the same way (`effective_principal_role` of the caller's session, pinned as `turn_principal_role`), so a specialist or workflow started from either pass sees the role of the turn that started it. Team runs are unchanged.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run: the runner calls `save_checkpoint`, the `workflow_runs` row moves to `status='awaiting_human'`, and the serialized `WaitForHumanEvent` is stored in `state_json`. (Department authority is a *separate* mechanism — `propose_only` departments file a briefing alert via `departments.authority.propose_via_alert` and mark the scheduled action done; they do not route through this gate.)\n\n**Delivery.** Both checkpoint sites — the SSE route and the `run_workflow` chat tool — call `workflows.gate_delivery.deliver_gate_question` immediately *before* checkpointing, so `state_json` carries the routing fields a reply is matched against. Two modes. When the approver is the person already in the conversation (the chat session's `origin_channel` is set — to anything but `email`, whose answer is no chat reply and would never be sent — and its `caller_person_id` is the gate's `person_id`), nothing is sent — the question rides in the Executive's own reply — and the gate records `origin_session_id` plus the session's channel. The resolver compares base ids (`memory.conversation_ids.base_session_id`), so a question asked in one conversation of a Telegram chat or a DM is still answered by a reply after a quiet gap or /new has started the next. Otherwise the question is delivered through `schedule_tools.handle_message_person`, which picks the person's preferred channel, falls through on a failed send, and falls back to a briefing alert; the gate then records the channel, address and provider message id that send returned, plus the id of the DM session it landed in — that send is always 1:1, so the answer belongs in that conversation and nowhere else. Without it the gate matched on person and channel alone, so an unrelated @mention in a public channel resolved it and had the acknowledgement, run title included, posted where everyone could read it. The question is sent with `notifications.approval_send`, so the person's quiet hours and *In my briefs* never hold it, whatever their urgent setting: only a reply to it resolves the gate. Delivery is not guaranteed: the outbound guard can suppress it (duplicate, rate cap, quiet hours) and an unreachable person gets the alert fallback. Both cases leave the routing fields empty and report `delivery` as `suppressed` / `alerted` rather than claiming someone was asked, and the chat tool's presentation hint changes accordingly.\n\n**Matching a reply.** Each inbound adapter passes the message to `inbound_resolver.resolve_inbound_message` with its `session_id`. Matching is three-tier: an explicit `in_reply_to` against a stored `outbound_message_id`; otherwise a single open run on that channel; otherwise one utility-fast disambiguation call gated at 0.85 confidence. An unmatched explicit reference rules out only the candidates that carry a stored outbound id — the ones it could have matched — and the rest continue; rejecting outright meant an adapter that passes a thread id on every message (Slack's `thread_ts`) short-circuited the later tiers forever, and a global test let one delivered gate's id block an unrelated self-approval gate. Channel names are normalized (`slack_dm` ≡ `slack`), the delivered address is compared when both sides know it, a row whose `state_json` will not parse is refused (a corrupt row otherwise presents as a legacy one), and an empty stored channel is treated as a wildcard only for rows checkpointed before gate delivery existed. Two guards keep an open gate from swallowing unrelated traffic: a gate carrying an `origin_session_id` matches replies only from the conversations the adapter names (a Slack or Discord thread offers its parent channel session too, mirroring the history double-write, since a gate raised on a mention recorded that session while the answer arrives under the thread's — on Slack only when that person rooted the thread, or the alias would reach into a colleague's), and the parser can return `unrelated`, which declines to resolve and lets the message reach the normal chat path. The parser is handed the gate's own question, so a bare \"yes\" is judged against something. Its fallback is flagged by a key the model cannot emit rather than by a magic note string it could, and a fallback declines to resolve on *every* reply shape — recording the empty string a `free_text` fallback fabricates would close a sign-off on a parser outage. Every shape can answer `unrelated`, not just `approve_reject`: without it an open `free_text` gate turned the person's next message into its answer verbatim, and a `numeric` one swallowed any message containing a number. The parser has one caller outside workflows: its `roster_identity` shape — `{decision: approve|link|decline|unrelated, name, kind: team|contact|null}`, with `name` only as the person wrote it (never inferred) and a fallback of `unrelated` — reads the principal's emailed answer to a roster request (who a new sender is; see Org). It is not a gate reply shape, and a fallback or `unrelated` leaves the request waiting. `resumer.apply_resolution` then records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The outcome surfaces on the Today dashboard.\n\n**Resuming past the gate.** A paused run continues on its own. Re-entering it was long assumed to mean serializing a Python generator frame; it does not. The only state alive across a dynamic workflow's steps is its inputs (already persisted), a company-profile block that is recomputed, the completed steps' output strings, and the loop cursor — so the engine hands the checkpoint a small JSON `WorkflowResumeState` (workflow name, the gate's id and index, the next index, the outputs so far), stored in `workflow_runs.resume_state_json`, and `DynamicWorkflow.resume` replays its step loop from the recorded index. `run()` and `resume()` share that one loop, which is why a second gate needs no special handling — it is simply another pause raised from the same place. The payload rides on a `WaitForHumanEvent` field declared `exclude=True`, so it can never leak into `state_json`, whose exact key set the resolver branches on. A gate with no payload is *pause-only*: the decision is recorded and the run stops, which is what every caller got before resume existed.\n\n`resumer._process_resumable` claims a resolved run with one guarded UPDATE — `resolved` → `running`, stamping `resumed_at` and minting a claim token — and drives it to a terminal row. It runs two ways: immediately, via a task `apply_resolution` kicks off so a Slack approval starts moving in seconds, and every 60s from the poll loop as the durable backstop. Both share the claim, so a run executes exactly once even with two resumers against one database. The kicked task binds no chat session (`set_session(None)`), exactly like the poll loop: it is created inside the inbound handler that recorded the answer and would otherwise inherit that person's live turn — so a run resumed because the principal replied on Slack does not act with the principal's identity (it cannot, for example, reach the principal's contacts). It drops the handler's audit scope too (`audit.context.unscoped_audit_rows`): inherited, the principal's scope would make private every row of the run that names a contact, and whoever started the run would see those rows vanish after the approval. The poll runs the executor *after* the timeout loop, which is what finally makes `on_timeout='auto_proceed'` do what its name says: the timeout resolves the run and the same tick executes it. While the Executive is paused (`scheduler.pause`) the resumer does nothing — no startup sweep, no timeouts, no resumes — and `apply_resolution` still records the decision but skips the immediate kick; the first unpaused iteration catches up on all of it, so a timeout that lapsed during the pause applies its `on_timeout` policy then.\n\n**The claim is fenced, because it is not a lease.** The stale sweep decides a worker is dead from a wall-clock guess, so a slow but *alive* worker will eventually be declared dead and replaced. Every write the executor makes carries its claim token and is refused once superseded — otherwise the replaced worker's late completion lands on top of its replacement's result, or its checkpoint at a later gate resurrects an already-finished run and asks the approver a second time. The retry budget resets at each new gate (a gate is new work, not a retry), and a run that exhausts it is *ended* rather than dropped: an exhausted run sits in `running` with a payload, in neither queue, and would otherwise show as in-progress forever.\n\n**The gate fails closed.** Continuing is an allowlist — `approve` and the synthetic `auto_proceed` — not \"anything that is not a stop word\". `decision` is whatever a fast model extracted from free-form chat and it drifts; under a denylist, \"rejected\", \"Reject\", \"decline\" and \"no\" would all continue, so the approver declines and the deliverable is produced anyway. Reply shapes that ask a question rather than seek permission always continue, since the answer *is* the value. A stop ends the run at `error` with the human's note. Either way the decision becomes the gate step's own output, so it reads as a section *in* the artifact — capped and blockquoted, because that text reaches the synthesis specialist as prompt context.\n\n**A definition edited during the pause is refused.** Resume re-validates the payload's version, the recorded gate, *and* a fingerprint of the whole step list, and derives the index to continue at rather than reading it from the payload. Pinning only the gate would not be enough: definitions are overwritten by name and any rostered user can save one, so someone could keep the gate identical and replace every step after it — and the approver's sign-off would be recorded against work they never saw, which defeats the one thing an approval gate is for. No built-in workflow yields the gate; only user-created dynamic workflows do.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — literally the same code, since both call `workflows.gate.checkpoint_gate`, which delivers the question and writes the checkpoint in one place. It never hangs waiting on a human, and it reports both whether the question reached them and whether the run will continue by itself once answered. The runners that *cannot* pause — the schedulers, evals, client rotation, onboarding, the research tools — call `gate.ensure_workflow_event`, which raises on a gate rather than letting one be swallowed; the scheduler's dynamic-workflow branch used to ignore it and record a successful run containing nothing. `executive_research` is excluded (it has the dedicated `run_executive_research` tool). Running a workflow from chat delivers nothing on its own — it renders the artifact into the conversation, and the recurring principal briefs (`morning_brief`, `end_of_day_digest`) reach anyone only via the scheduler's own `_deliver_to_principal`. The tool description used to claim those two DM the principal when run and to confirm before firing them, which had the model soliciting a confirmation on a false premise; it now names `executive_reflection` as the one workflow that really does execute tool calls of its own (DMs to heads, broadcasts, alerts). A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat, the conversational wizard at `/jobs/new`, or the step-by-step advanced editor — without shipping code. The Workflows page (`/jobs`) opens on a *Start here* panel that leads to all three: the user describes the job in a sentence and *Start* opens the wizard with that text sent as its first message (handed over in `sessionStorage`, so a link cannot make the wizard send text the user never typed; where storage is blocked it falls back to `/jobs/new?describe=`, which only fills the composer and sends nothing), or picks *Step by step* (advanced editor) or *Talk it through in chat* (`/?new=1&draft=`). Below it come the user's own workflows, then four ready-made starter picks with the full built-in list folded behind *Browse all* (`?browse=1`). The picks and the example chips follow the workspace mode: a team gets the investor update, board prep, MBR and competitive teardown (and a board pre-read chip); a solo owner-operator gets the MBR, pricing review, churn deep dive and quarterly plan, with chips for a Friday cash and pipeline check, customers who stopped buying and a competitor digest (`lib/workflowStarters.ts`; a unit test pins every pick to a startable `WORKFLOW_REGISTRY` entry). A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of four kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **action** (get something done with tools — see below), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. At least one specialist or action step is required. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people (team members — never one of the principal's contacts, whom an unattended run may not message), and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The step-by-step advanced editor drives the `/workflows/custom` CRUD endpoints directly.\n\n**The New workflow wizard** (`/jobs/new`) is the default way to create one from the UI. It works like conversational onboarding: the user describes the job, the `workflow_designer` Council agent (`openexecutive/workflows/designer.py`) asks one clarifying question per turn — deliverable, per-run inputs, sign-off, schedule, recipient — with up to four clickable suggested answers, then emits a complete definition plus a plain-language summary and the assumptions it made. Every turn offers the model exactly three fixed, name-sorted tools (`ask_clarifying_question`, `emit_workflow_draft` — reusing the chat tool's `DEFINITION_SCHEMA` — and `search_available_tools`, which is answered inside the same turn from the tool catalog, up to four searches per turn, with the tool_use/tool_result pairs never stored in the plain-text transcript; every tool a search returns is remembered on the session and replayed into later turns, so a forced draft or a repair turn — which cannot search — still has the exact names); `tool_choice` flips to the emit tool once, when the six-question budget is spent or the user clicks *Draft it now*. The emitted definition goes through `validate_definition`, the tool-availability check, and a check against saved custom names, with one repair turn that feeds the errors back. The system prompt is a cached constant; the live context — specialists, the roster with person ids, the user's timezone (the one set through `PUT /workspace`, else `USER_TIMEZONE`; cadences stay UTC), and taken names — is rendered once per session into the first user turn, and while refining, the exact current draft is prepended to the latest user turn so the model edits it rather than re-deriving it. Roster names and roles are flattened to one line and capped at 80 characters before they enter that context, and the system prompt tells the model to treat the whole block as data, never instructions. Sessions live in memory (`/workflows/designer/*`, 2 h TTL, 50-session cap), run one model turn at a time (a second concurrent `/message` or `/draft` gets 409, and a failed turn is rolled back by identity), and never write: the review card saves through the same `POST /workflows/custom`, which re-validates, and *Edit details* opens the draft in the advanced editor (`/jobs/new?designer=<id>`) before saving.\n\n**Editing is a conversation too.** *Edit* on a saved workflow (`/jobs/new?edit=<name>`) opens the same designer through `POST /workflows/designer/edit`: the stored definition is the starting draft, so the user's first message (\"have Mark sign off and run it Fridays\") is applied to it like any refinement, and a note in the context block (a user turn, never the cached system block) tells the model it is changing a saved workflow. The draft always keeps the workflow's name — `_check_draft` puts it back and skips the taken-name check — and the route keeps its on/off state, so an edit can neither fork a copy nor switch on a tool workflow waiting for approval. The stored draft is handed to the model marked as data, not instructions. The review card lists *What changes* in plain words against the saved version (`lib/workflowChanges.ts`): every field is compared, with named sentences for the sign-off person and what it asks for — a sign-off moved off approve/reject is called out because the run then continues whatever the answer — the schedule, steps added/removed/reordered, inputs, tools and the tool-call budget, and a catch-all line for any other field. It names only the newly added tools that may change things. *Save changes* calls `POST /workflows/custom/{name}/save-edit`, which saves the session's own draft after re-validating it, only when it is the draft the card showed (the card sends what it displayed; a message that landed since is a 409), and only if the stored workflow has not changed since the conversation opened (409 otherwise), so an edit started before someone switched the workflow off cannot switch it back on. The step-by-step form stays as the advanced editor (`/jobs/new?edit=<name>&mode=advanced`).\n\n**Action steps (workflows that act).** An `action` step (`ActionStepSpec`: `goal`, `tools`, `max_tool_calls` 1–50, default 20) is run by the `workflow_actor` Council agent (`openexecutive/workflows/action_step.py`) as a bounded tool-use loop. Its `tools` list is an allowlist of exact tool names — MCP gateway tools (`server__tool`, e.g. `google_workspace__append_table_rows`) and built-ins: the Executive's own chat tools as `oe__<name>` (see *Chat's tools in action steps* below; `oe__create_alert`, in a workflow a team member created, raises the alert as theirs (`alert_tools.raised_for_workflow_owner`: source `team_member`, \"Raised by <name>\", never a company-wide broadcast) — plus any installed extension's tools registered with `workflow=True`, as `oe__<name>`, run inside `extensions.workflow_step(name)`; a built-in wins a name clash, and an extension tool counts as reading only when it says so) — and **clicking Create is the user's approval** of that list: the review card shows every tool, flags the ones that may change things (anything whose name doesn't say it reads, and any tool with a URL/URI/endpoint/webhook parameter anywhere in its schema, or whose schema couldn't be read, since a URL can carry data out), and names them in a \"this workflow can use these without asking again\" notice. Because that card is the approval, a workflow with action steps saved from chat (`draft_workflow`/`save_workflow`, whose confirmation is a token the model holds itself) is stored **switched off** (`is_active=false`) and `save_workflow` returns `status: saved_pending_review` with a `/jobs/{name}` link. An inactive workflow can't run or schedule (`get_workflow` and the scheduler skip it); `/jobs/{name}` shows it on the same review card, where **Turn on workflow** (`POST /workflows/custom/{name}/activate`, which re-validates the tools) is the approval — the click sends the definition the card showed, and the server refuses (409) if the stored one has changed since, so chat overwriting it while the card is open can't get new tools switched on. Chat may revise a switched-off workflow, but a switched-on one that has action steps, or one that reads or sends email as its creator, is never replaced directly (an inbound email steering the Executive could otherwise stage new tools under its name). Instead `save_workflow` leaves a **change card** (`orchestrator/workflow_change.py`): server-written lines naming each step added, removed or changed, tools included. Only the owner or the workflow's creator, verified and in a private conversation, can stage one, and only where the card shows (the web chat, or Telegram with Approve and Skip). The tap saves the change only if the workflow is still the version the card was made from (else 409), re-checks its tools and who may save it, and keeps it on or off as it was. Chat reads a saved definition with `list_workflows` and a `name`, so it can work out why a run went wrong and draft the fix. The builder and chat are both told that the gateway's mail and calendar tools act as the Executive's own account: a calendar step that names no calendar reads the Executive's calendar, so the user's needs `oe__my_calendar` or their address in the goal. The Workflows catalog (`/jobs`) lists switched-off workflows in a compact *Waiting for your approval* strip, and saving edits in the advanced editor keeps one off. `tool_catalog.py` resolves names to schemas through the gateway's `search_tools` (extensible-mcp's Markdown output is parsed; resolving is also the per-session discovery its `call_tool` requires) and validates availability at save time (`POST`/`PUT /workflows/custom`, chat `draft_workflow`/`save_workflow`, designer drafts) — an unknown, misspelled or deny-listed tool is a 422. The gateway meta-tools (`search_tools`, `call_tool`, `load_mcp_server`) can never be step tools. `run()` resolves every action step's tools before any step runs, so a vanished tool stops the run before an earlier step acts; `resume()` checks only the steps still to run, after the gate and decision are validated. The last turn of an action step always switches tools off so the agent can report. At run time only the allowlisted tools are offered (sorted; constant cached system block, per-run goal/inputs/earlier results in the user turn), every `tool_use` is re-checked against the allowlist, MCP calls go through `MCPGateway.call_tool` so the config deny-list and the Gmail/Calendar/Drive recipient gates still apply, the call budget is enforced (then a final tools-off turn asks for the report; running out of turns fails the step and lists what was already done), tool errors (the gateway's `Error:` / `Error calling tool` / `Tool error:` prefixes, or a truthy `error` field) return to the model as `is_error` results, each call emits a `progress` event and an audit row (`workflow_tool_call`: tool and outcome; for tools that may change things also a short digest of target arguments — ids, recipients, URLs, paths — so a redirected write is visible; content arguments are never logged), and the step's output is the agent's report plus an \"Actions taken\" list, each tool named in plain words (`plain_tool_name`: \"Google Workspace: get events\", never `google_workspace__get_events`; the held-writes question names tools the same way). The step's user turn gives the time now in the user's timezone, and the report gives times in it. Tool output is framed as data, never instructions.\n\n**Chat's tools in action steps.** A step can use almost everything the Executive uses in chat, so an idea from a conversation can become a workflow without a missing tool. `workflows/chat_tools.py` holds one list, `ACCESS`, that labels every chat tool: **use** (a step may list it as `oe__<name>`, e.g. `oe__send_slack_dm`, `oe__run_workflow`, `oe__update_department_goal`, `oe__web_search`), **as me** (Act as me tools, not yet in workflows), **covered** (the step already has its own path: gateway tools, `run_script`, specialist steps) or **chat only** (memory, company profile, roster changes, open loops, follow-up corrections and screen actions). A unit test fails when chat gains a tool without a label, so new chat tools reach workflows by one line rather than a second copy. A **use** tool runs through chat's own handler as an unattended chat turn would: an unattended `Session` bound as `current_session`, the workspace-mode filter (solo withholds department and company posts), and, in a team member's workflow, their department gate. Channels the instance has no token for are not offered. Saving the workflow is the person's permission, so Take the lead's approval gates don't apply, the same as the gateway tools before. `oe__run_workflow` refuses a workflow already running in its own chain and nests at most three deep. It and `oe__run_executive_research` get a 15-minute call timeout. `oe__web_search` is the model's server search: it is appended after the sorted tools, never called by the step, and a paused search turn is sent back as-is. Workflows have no tool handlers of their own any more: `oe__message_person` and `oe__create_alert` are the chat tools under the same names, and the old `oe__read_file` still resolves (to `read_document`) for saved workflows but isn't offered for new steps (`chat_tools.LEGACY_NAMES`). The designer lists every built-in by its first sentence, and chat's `draft_workflow` says chat tools are available as `oe__<name>`; the catalog's search ranks built-ins by how many query words they match.\n\n**Email as the creator.** Besides the chat tools, a step may use `oe__draft_email_as_me` (a draft in the workflow creator's own mailbox for them to send) or `oe__send_email_as_me` (sent as them), Act as me's two workflow tools (`delegation.workflow_email`, see the delegation section). The creator picks one when saving the workflow, by asking for it in chat or the designer, which is told whether they can; the gateway's mail tools still send from the Executive's own address. A workflow that sends as its creator can only be created, changed or switched on by that creator, verified (a 403 otherwise), and an email to their own address or one written in the goal of the step that emails goes without asking, while the first to any other address waits for their approval like any other first write. A step may also answer an email in the creator's inbox the way their Handle it for me does (`oe__answer_email_as_me`, naming only the thread: sent on its own when its rules allow, otherwise a card for them; see the delegation section). A step may also read the creator's own mail and calendar (`oe__search_my_email`, `oe__read_my_email`, `oe__my_email_awaiting_reply`, `oe__my_calendar`, `delegation.workflow_reads`). A workflow that does runs only for its creator (a scheduled run is created as theirs and reports to them alone), never when another workflow started it, and is locked down for all of its steps: no gateway tools, web search, scripts, other workflows, or posts to everyone (it may still email as the creator, under the same recipient rule), checked on save and at every step (see the delegation section).\n\n**Scripts in action steps.** Besides the step's own tools, the agent is offered one more, `run_script` (`openexecutive/workflows/step_script.py`), for work that repeats over many items — every file in a folder, every row, every email — or chains calls with simple logic. It writes a short Python script once instead of spending a model turn per call; each of the step's tools is a function in the script (`drive__move_file(file_id=…)`, or `call_tool(name, arguments)` by exact name), and only the script's final value and printed output come back. The script runs in **Monty** (`pydantic-monty`), a sandboxed Python interpreter for model-written code, in a worker process spawned per script: no files, network, environment, subprocesses or third-party imports — the step's tools are the only things it can reach. **A script is a faster way to make the same calls, never a way around them:** every call it makes goes through the same per-call path as a direct `tool_use` (`action_step._StepCalls`) — the allowlist, a call budget (a script's calls have their own: 10× the step's `max_tool_calls`, capped at `WORKFLOW_SCRIPT_MAX_CALLS`, default 500, because they cost no model turn each — so a step can work through a folder of hundreds of files while its direct calls stay capped at 1–50), the first-write target check (a held write comes back to the script as `{\"status\": \"held\", …}`) and one `workflow_tool_call` audit row per call — and the script itself is audited as `run_script`, with how many calls it made and how long it took. The step's \"Actions taken\" list collapses repeats into one line with a count. A step whose direct calls are spent keeps its tools on while the script budget has room, so it can still script the rest (a direct call is refused as over budget). When a tool returns a list of five or more items and the round didn't use `run_script`, the step adds the same `FANOUT_HINT` as chat (once a step), pointing the per-item work at one script. The worker is stepped from the step's own task (each call pauses it and is answered there), so cancelling the run stops the script and its in-flight call together, and each call's progress shows as it happens. At most `SCRIPT_MAX_WORKERS` (default 2) scripts run at once across the server, chat and workflows together; another waits for a slot within its own wall clock, else returns \"the server was busy\". A worker exists only while its script runs (about 8 MB idle). Execution time (excluding time waiting on tools), memory and recursion depth are capped inside the worker, the script has a wall-clock limit, and its text is size-capped; printed output past its cap is dropped. A failing script returns its error to the agent as an `is_error` result, with the calls it already made listed first (ahead of any long result, so a cut never drops them) so a fixed re-run doesn't repeat writes; a call cut off by the time limit is listed as `may_have_run`, and gets a `cancelled (may have run)` audit row. A workflow definition still holds no code; a script lives on only if the agent saves it as a tool (below). Because a step can loop at run time, the workflow designer keeps work that repeats over items (each email, file, row or listed follow-up) in ONE action step whose goal spells out the items, rather than a step per item; `run_script` is never a step tool, and a definition that lists it is rejected (`validate_definition`) so the designer's repair turn removes it. `WORKFLOW_STEP_SCRIPTS=false` turns the tool off, and a step then only calls its tools one by one.\n\n**Python jobs (`run_python_job`, `openexecutive/workflows/python_job.py`).** Monty can't run libraries, so library work on files (split or merge PDFs with pypdf, spreadsheets with openpyxl and pandas, charts with matplotlib, images with Pillow, and documents made from scratch or from files: Word with python-docx, PowerPoint with python-pptx, laid-out PDFs with fpdf2) runs as a Python job: Pyodide (Python in WebAssembly) executed by **Deno** in a process of its own per job. Pyodide alone is not a sandbox — its Python can call into the JavaScript runtime, which under plain Node reaches the server's environment, files and network — so Deno is what isolates it: it is started with read access to the sandbox folder and the worker script only, with no network, environment, writes or processes, and an empty process environment. Files go in on stdin and results come back on stdout. A job gets only what the call names: Knowledge-library files, the files attached to the chat message being answered (`attachment_files`, the uploads as sent, bound for that turn only by `POST /chat/upload` in `workflows/turn_files.py`, so the model never retypes an attachment's text), text the caller passes, and `inputs` (a dict the code reads); result files are kept 7 days under the company folder and served to the principal at `GET /python-jobs/{job}/{file}`, which the Executive links in its reply. A deployment can instead send jobs to a separate runner (`PYTHON_JOB_RUNNER_URL`, with `PYTHON_JOB_RUNNER_KEY` as a bearer token): `run_job` POSTs the same job (code, inputs, files, caps, time and memory limits) and reads back the same result object, at most as large as a local job's output, keeping only its known fields, so kept results, links and metering are unchanged; the local sandbox is then not needed, and the runner is trusted to isolate jobs. A runner can turn a job away with `{\"run_locally\": true}` (and an optional `reason`) in a non-200 reply, for example when the deployment's allowance for it is used up: the job then runs in the local sandbox if this machine has one, and otherwise fails with the runner's reason. Any other non-200 reply stays a job error, so a busy or broken runner never moves every job onto the machine. A runner with more libraries lists them in `PYTHON_JOB_EXTRA_LIBRARIES`, which the job tool's description then names, so the Executive doesn't refuse a job that needs one. The tool sits in the `workflows` tool group, labelled for jobs with or without attached files. The library set is fixed at build time: the API image installs Pyodide and Deno from npm and the compiled libraries from Pyodide's CDN, each checked against the sha256 in Pyodide's lock file, and a build smoke runs a job. Pyodide can't infer the compiled packages the pure-Python libraries import (lxml, Pillow, fonttools), so the worker loads them when a job imports docx, pptx or fpdf. Pyodide, Deno and the pure-Python libraries are pinned by hash too (an npm lock installed with `npm ci`, pip `--require-hashes`). One job runs at a time per process (200–450 MB each), with a `PYTHON_JOB_TIMEOUT_S` limit and a memory cap (`PYTHON_JOB_MEMORY_MB`, default 1536, as the process's data limit, plus V8 heap and WebAssembly memory caps); the worker returns at most 20 result files and 25 MB, and the API stops the job as soon as its reply passes that. The job runs at a lower CPU priority and is first in line if the machine runs out of memory, so a heavy job slows or loses itself rather than the API; Deno's own caches go in a temporary folder removed with the job; and kept results are capped at 200 MB in all, oldest first. The tool is chat-only, offered only on the principal's own turns (`PRINCIPAL_ONLY_TOOLS`), withheld on private turns, unattended passes and under the Act as me lockdown, and not offered at all without the sandbox (`PYTHON_JOBS_ENABLED`, `PYTHON_SANDBOX_DIR`).\n\nA job that worked can be kept the same way as a script (below): `save_as` and `description` keep its code as a Custom tool of kind `python`, and `run_python_job(tool=<name>, inputs={...})` with its files runs it again, recording the run, so a job done before costs no code-writing tokens. Python tools run only on the principal's own chat turns: they are never listed for workflow steps and never turn on for workflows (`PUT /saved-tools/{name}` answers 409), and `run_script` refuses one (and `run_python_job` a script tool). Every job writes one `python_job` audit row (`ok`, `duration_ms`, `cpu_ms` and `peak_mb` read from the process's /proc entry just before it is stopped, files and bytes in and out, attachments, the Custom tool it ran or kept), which `GET /audit/usage` sums into `python_jobs` with the model usage of the turns that ran one.\n\n**Saved tools.** A script that works can be kept to run again by name (`openexecutive/workflows/saved_tools.py`); each tool has a `kind`, `script` (`run_script`) or `python` (`run_python_job`, above). `run_script` takes `save_as` and `description` with a new script: if the script succeeds it is saved, with the set of tools it actually called, and a failed script is never saved. Later, `run_script(tool=<name>, inputs={...})` runs the saved script instead of new code, with `inputs` available to it as a dict. Only the principal's own turns save: a chat turn where the principal is speaking on a verified, interactive surface (the same test as `load_mcp_server`), never an inbound email, a teammate, an unattended run or a workflow step — a step is offered `tool=` but not `save_as`. A saved tool runs with the authority of whoever runs it, so its author must be trusted at least as much as anyone who may run it. For the same reason only a workflow step (its tools owner-approved) or the principal's own turn may run one: anyone else's chat turn is refused `tool=` and not offered `list_saved_tools`, so a stranger can neither list the principal's automations nor run one with inputs they choose. Descriptions are kept to one line of printable text (they are shown to models), and every save writes a `saved_tool_changed` audit row (`actor: executive`) beside the owner's own changes. Saving needs no approval beyond that, because a saved tool can do no more than the context running it: its calls go through the same per-call path as any script (in a step: the allowlist, budget, target check and audit), and a step runs one only when the step already allows every tool it used (otherwise the result names the `missing_tools`) and only at the version the owner turned on for workflows (`workflow_version`, Settings → Advanced → Custom tools → Use in workflows). A tool kept on a turn that read outside content could otherwise carry injected code into an unattended run, so keeping stays automatic and works in chat at once, but workflows wait for the owner; a newer save doesn't change the version workflows run, and pruning never drops it. Each step's `run_script` description lists the saved tools that step may run; chat asks `list_saved_tools`. Every save of changed content is a new version (the newest 20 are kept, plus the one that ran until then, so a rolled-back version the owner trusts survives later saves), every run is recorded (`saved_tool_runs`, the newest 200 per tool), and the owner can turn a tool off or switch it back to an earlier version on Settings → Advanced → Saved tools (`/saved-tools` routes, the owner's alone). A turned-off tool never runs, and a new version saved by the model does not turn it back on. `SAVED_TOOLS_ENABLED=false` stops saving and running saved tools everywhere.\n\n**Targets are chosen at run time — and a new one is confirmed once.** Approving a workflow approves its *tools*; which sheet, doc, recipient or URL each call hits is chosen by the model at run time, by design (a tab per month, a reply to whoever sent the invoice, a doc per client). What bounds that is the allowlist, the gateway's recipient gates, the audit digest, and **first-write confirmation**: a `TargetPolicy` (one per run) checks every call to a tool that may change things. `resource_targets` walks its arguments recursively for resource keys (snake- or camel-case ids, `to`/`cc`/`bcc`, recipients, addresses, attendees, members, users, owners, parents, URLs/links/hrefs, paths, channels, spaces, rooms, phones, hosts, buckets, tables, spreadsheet/document/folder/calendar/file); a matching key marks everything beneath it, even a `name`. Outside a resource, only a new item's own `name`/`title`/`subject`, message/thread/draft/label ids, `range`/`sheet` and workspace-mcp's acting `user_google_email` are skipped — and whatever the key, a bare value shaped like an email address, a URL or an international phone number is a target, except inside what the call writes (`rows`, `values`, `body`, `text` …). Key names are a heuristic, so this is a best-effort guard layered on the allowlist, the gateway gates and the audit. Float ids are compared as integers. Arguments too deep, naming too many targets, or holding an over-long value **fail closed** (the call is refused). A target is trusted only when it was approved for this workflow before (`workflow_approved_targets`, by value) or is an id a write in this run created — a top-level id/link field (`id`, `spreadsheetId`, `webViewLink` …) of the **structured JSON object** result of a tool whose name says it creates (create / insert / upload …) and that takes no URL — a tool whose schema couldn't be read is assumed to (free text, nested records and readers' or updaters' results are never read, so a fetched page, an echoed title, a shared page's links or a stranger in `ccRecipients` can't plant one); those survive a pause in the resume payload (`run_created`). Values written in the workflow's own text are *not* trusted, since anyone who can edit the workflow could change them without review: they are asked once, then remembered. Approvals are by value, for any of the workflow's tools, and are **cleared when the workflow's tool set changes** (a newly added tool must earn them again). Any other target makes the call **held**: it is not run and costs no budget, the model is told it is waiting for approval and carries on, and it is audited `held for approval` (at most 10 held per step, 16 KB each; an identical repeat is held once). Whether a call is checked at all follows the read-only label, which now never marks a tool whose name carries a write verb anywhere (`find_and_replace_doc`). After the step finishes, the run pauses with a `WaitForHumanEvent` to the workflow's **owner** (`owner_person_id`, the person who created it on the Workflows page or in chat; falling back to the principal if unknown or archived), `on_timeout=auto_proceed`, 48 h, and a `WorkflowResumeState` of `kind=\"held_writes\"` carrying the exact held calls. On resume (`_resume_held_writes`, fingerprint-checked like a gate, with the remaining steps' tools checked first), only `approve` runs them — each still has to be in the live step's allowlist and resolve; its targets are remembered first — and anything else (decline, timeout, unreadable) skips them; either way a *Held for approval* section is added to the step's output and the run continues at the next step. With no one to ask, held writes are skipped and noted; a step that fails or crashes after holding, or a resume that stops early (definition changed, a later tool missing), audits its held writes as dropped and says they did not run. The question quotes each target JSON-escaped (a value can't add its own lines) and always shows a URL's full scheme and host, saying how much of the rest is hidden. The owner answers by chat reply or with **Approve / Decline** on the run page (`POST /workflows/runs/{id}/decision`, which the principal may also use); remembered targets are listed and removable on the workflow page.\n\n`oe__read_document` (chat's `read_document`; saved workflows that list the old `oe__read_file` get the same tool) extracts text (PDF, Word, Excel, CSV, Markdown, text) only from files under `WORKFLOW_FILE_DIRS` or the company documents folder (default: workspace-mcp's attachment folder), resolving symlinks and `..` before the check (`tool_catalog.resolve_readable_file`, shared with the Executive's `read_document` tool). A scanned PDF is converted by `knowledge.pdf_reader` instead of failing as \"may be a scanned image\"; one that still cannot be read returns the reason. Action steps are allowed in scheduled workflows. Because they have external side effects, a resumed run heartbeats its claim (`touch_resume_claim`, at most once a minute as events flow — each tool call emits one; a busy database is retried on the next heartbeat, never treated as a lost claim; the sweep's requeue re-checks the claim's age in the same UPDATE, so a heartbeat landing between the sweep's read and its write wins), so the stale-claim sweep never requeues and replays a slow but live run, and a worker that finds its claim superseded stops at its next event. A worker that actually crashes mid-resume is still requeued; its action steps then run again, so goals should say how to avoid duplicates (the actor reads current state before writing). `GET /workflows/tools/search?q=` and `GET /workflows/tools/describe?names=` back the advanced editor's tool picker and the review card's labels.\n\nAn optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs a rostered recipient a few plain lines on what came of it, or nothing when there was nothing for them (`workflows/run_message`); the full report stays on the run. A gate followed by further steps pauses at `awaiting_human` and then resumes once answered, so gates no longer have to sit immediately before synthesis. They remain forbidden in cadence-enabled definitions: a scheduled fire has no interactive human to ask.\n\n`executive_research` keeps only its Markdown artifact in the run history; `parse_artifact_findings` reads its \"Findings reviewed\" lines back as `{severity, confidence, specialist, title, summary}` for Home's first-week card (see Today).\n\nBuilt-ins the system runs on its own (`morning_brief`, `end_of_day_digest`, `executive_reflection`, `executive_research`) set `background = True`, surfaced as `WorkflowMeta.background`; the `/jobs` ready-made list files them under a **System** chip instead of the default view. They stay runnable by hand.\n\n**Quick workflows** (`workflows/quick.py`) are one per playbook in effect that no built-in or custom workflow follows (switched-off custom ones count). They are derived whenever the catalog is read, never stored: `list_workflows()` returns built-ins, then Quick ones, then active custom ones, and `get_workflow` resolves a `quick_<playbook>` name after the registry (custom workflows may not take the `quick_` prefix). Each has one required field, `request`, and two steps: **Load context** (company profile plus RAG for the playbook category's specialist) and **Draft** (that specialist writes one Markdown document following the playbook). `WorkflowMeta.quick` is true for them. The 8 built-in playbooks no built-in follows are Quick workflows: board update memo, 1:1 agenda, layoff comms plan, positioning statement, post-mortem, customer interview plan, feature prioritization and market sizing. A company's own playbook shows up as one, hiding a built-in drops it, and a custom workflow that starts following one replaces it. If custom workflows can't be read, none are offered, since their followers are unknown.\n\n**Workflows vs. playbooks.** `/jobs` has two tabs: **Build** (`?tab=catalog`, the default) and **Runs** (`/skills` redirects to `/jobs`). A playbook is a skill (`knowledge/skills_repo.py`): *how* the Executive does a piece of work, with no inputs, schedule or side effects. A workflow is the runnable job. Workflows **follow** playbooks: a step that follows one gets its body appended to the step prompt via `workflows/playbooks.py` (`load_playbook` + `playbook_clause`). Six built-ins do — `board_prep` (`board-prep-deck`), `quarterly_plan` (`quarterly-okr-set`, `quarterly-forecast`), `mbr` (`monthly-business-review`, in the financial, KPI and function steps), `competitive_teardown` (`competitive-teardown`, in the four analysis steps), `fundraising_prep` (`fundraise-narrative`, narrative step) and `exec_search_brief` (`role-scorecard`, profile step). Each declares them in `Workflow.playbooks`; a unit test holds that declaration equal to the `load_playbook(\"…\")` calls in the module, and `WorkflowMeta.playbooks` exposes it. A custom workflow's `specialist` step may name a `playbook` (validated to exist at save; appended after `{field}` rendering, so braces in a playbook are never treated as placeholders). The lookup resolves the playbook in effect, so a company's customized copy changes the workflow's output, and a hidden, missing or malformed one falls back to the step's own prompt plus RAG — a workflow never fails over a playbook (`load_playbook` catches everything; a custom step whose playbook is unavailable emits a `progress` event saying so). Because an approved scheduled workflow reads its playbook at each run, chat never creates or changes a playbook: it saves repeatable work as a workflow (`draft_workflow`, confirmed by the user), and only a person can change what a workflow follows: a workflow's page shows each playbook it follows as **How it's done** (`components/jobs/HowItsDone.tsx`), with **Edit** (`PUT /skills/{name}`; on a built-in that saves the company's customized copy) and, for a customized copy, **Reset to original** (`DELETE`, which reverts). The chat summary of a drafted workflow names each step's playbook. `playbook_users()` maps each playbook to the workflows that follow it — built-ins, every custom workflow (switched-off ones included: turning one on approves its definition) and the Quick ones; the skills API reports it as `used_by`, and the Executive's `search_skills` hits carry it as `workflows`.\n\nCompleted artifacts are discoverable in the unified artifacts section (`/artifacts`, labelled **Documents** in the UI) alongside their run-detail page at `/jobs/runs/{run_id}`. A run someone starts by hand (`POST /workflows/{name}/runs`, `run_workflow`, research in chat) stores them as `workflow_runs.owner_person_id` and its history and output are theirs alone (plus the person a gate waits on); scheduled and system runs keep no owner and stay the team's. Workflow output stays Markdown — the scheduler DMs it and reflection rereads it as text — and gains other formats only on the way out: any run can be downloaded as Word (`/artifacts/run:<id>/download?as=docx`), and the Executive can repackage one with `get_artifact` → `draft_artifact(format=…, supersedes=\"run:<id>\")`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.\n\nWith Take the lead as the Executive on (`orchestrator.take_the_lead`), reflection and research build their toolkit through `unattended_toolkit(..., source=...)`. That keeps solo's booking and `run_workflow` tools and an unrestricted `message_person` (teammates as well as the principal). Every acting tool goes through the gate, and a held action waits on Today as a `take_the_lead_action` decision. Reflection also gets the MCP gateway's `search_tools` and `call_tool` (`_with_lead_tools`; `call_tool` behind the gate, `load_mcp_server` left out), so it can find and use whatever the deployment has connected, such as building a sheet to track something. A note in the user turn (never the cached system prompt) tells it to act rather than only report, and it gets more room: 10 iterations, 4000 tokens, and tool results up to 4000 characters. The grounding check still refuses outward text naming people or figures the pass didn't see. New mail and chat also wake the reflection early (scheduler section). In training (`take_the_lead.training`) every acting call that isn't allowed waits too, as a training card for the principal, and both passes append `take_the_lead.learned_note()` to their user turn: that it's in training, and the principal's own edits on earlier cards as examples of how they want those done (never in the cached system blocks).","mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"workflow_runs<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Documents\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved → claim\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",- "generated_at": "2026-10-23T12:46:17Z"+ "generated_at": "2026-10-25T11:56:36.113188+00:00"}diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.pyindex 607c8be6..9c38fd60 100644--- a/packages/core/openexecutive/config.py+++ b/packages/core/openexecutive/config.py@@ -491,6 +491,11 @@ class Settings(BaseSettings):# The other way to hear Slack: with this set and no SLACK_APP_TOKEN, Slack# posts events to POST /webhook/slack, signed with the app's signing secret.slack_signing_secret: str | None = Field(None, alias="SLACK_SIGNING_SECRET")+ # Approve and Skip buttons on the cards a reply leaves in a Slack DM+ # (integrations.channel_cards). Needs Interactivity turned on in the Slack+ # app's settings (with SLACK_SIGNING_SECRET, its Request URL is+ # /webhook/slack); off, a DM points to the web app instead.+ slack_card_buttons: bool = Field(False, alias="SLACK_CARD_BUTTONS")# Company-wide broadcast channels — when set, OE can post to "the# whole team" on a given integration without picking a specific# human or department. Used by `send_company_broadcast`. Each isdiff --git a/packages/core/openexecutive/integrations/channel_cards.py b/packages/core/openexecutive/integrations/channel_cards.pyindex c5a635d9..9571bd5a 100644--- a/packages/core/openexecutive/integrations/channel_cards.py+++ b/packages/core/openexecutive/integrations/channel_cards.py@@ -8,10 +8,18 @@ each as a short message with two buttons, and passes a tap to``api.routes.decisions.resolve_in_chat``, which applies the web chat's rulefor who may decide it.-Telegram is the one so far. A tap proves who made it only in a private chat-(the chat is the person; ``from.id`` must equal the chat id) on a webhook-only Telegram can call (``TELEGRAM_WEBHOOK_SECRET`` set and valid), the same-bar as a verified speaker there (``people_tools._is_verified_speaker_surface``).+Where a tap proves who made it, the same bar as a verified speaker there+(``people_tools._is_verified_speaker_surface``):++- Telegram: a private chat (the chat is the person; ``from.id`` must equal+ the chat id) on a webhook only Telegram can call (``TELEGRAM_WEBHOOK_SECRET``+ set and valid).+- Slack: a DM, with ``SLACK_CARD_BUTTONS`` on (Interactivity turned on in+ the Slack app). Slack signs the tap (Socket Mode, or the signing secret+ over HTTP), and it counts only from the user whose DM with the bot it is.+- Discord: a DM. The tap comes over the bot's own gateway connection, and+ counts only from the user whose DM with the bot it is.+Anywhere else no card is shown and the Executive is told the card is on Today."""from __future__ import annotations@@ -23,7 +31,8 @@ from typing import Anylogger = logging.getLogger(__name__)-# Telegram callback_data: "card:<decision id>:a" (Approve) or ":s" (Skip).+# A button's data (Telegram callback_data, a Slack button value, a Discord+# custom_id): "card:<decision id>:a" (Approve) or ":s" (Skip)._PREFIX = "card"APPROVE = "a"SKIP = "s"@@ -39,6 +48,7 @@ _resolving: set[int] = set()_CLASS_LABEL = {"meeting_scheduling": "Meeting to book","delegation_actions": "Waiting for your approval",+ "app_action": "Waiting for your OK",}@@ -50,20 +60,34 @@ def telegram_proves_taps() -> bool:return bool(s.telegram_bot_token and s.telegram_webhook_secret and s.telegram_webhook_secret_valid)+def _dm_proves_taps(channel: str) -> bool:+ """Whether a Slack or Discord DM here can show cards with buttons."""+ from openexecutive.config import get_settings++ s = get_settings()+ if channel == "slack":+ return bool(s.slack_bot_token and s.slack_card_buttons)+ return bool(s.discord_bot_token)++def shows_cards(session: Any) -> bool:"""Whether this turn's chat shows its cards with buttons: a privateTelegram chat with someone on the roster, on a webhook only Telegram can- call. Fails closed."""- if session is None or getattr(session, "origin_channel", "") != "telegram":- return False- ref = str(getattr(session, "origin_channel_ref", "") or "")- if not ref.isdigit() or getattr(session, "caller_person_id", None) is None:+ call, or a Slack or Discord DM with someone on the roster. Fails closed."""+ channel = str(getattr(session, "origin_channel", "") or "") if session is not None else ""+ if getattr(session, "caller_person_id", None) is None:return Falsetry:- return telegram_proves_taps()+ if channel == "telegram":+ ref = str(getattr(session, "origin_channel_ref", "") or "")+ return ref.isdigit() and telegram_proves_taps()+ if channel in ("slack", "discord"):+ from openexecutive.delegation.settings import private_conversation++ return private_conversation(session) and _dm_proves_taps(channel)except Exception:- logger.warning("channel_cards: couldn't read the Telegram settings", exc_info=True)- return False+ logger.warning("channel_cards: couldn't read the %s settings", channel, exc_info=True)+ return Falsedef card_here(session: Any) -> bool:@@ -102,11 +126,11 @@ def _when(start: Any, end: Any) -> str:def card_text(decision_id: int) -> str | None:"""What the card says, or None when it isn't one a chat shows or isn'twaiting any more."""- from openexecutive.api.routes.decisions import CHAT_CARD_CLASSES+ from openexecutive.api.routes.decisions import shown_in_chatfrom openexecutive.memory.decision_ledger import STATUS_PROPOSED, get_decision_instanceinstance = get_decision_instance(decision_id)- if instance is None or instance.decision_class not in CHAT_CARD_CLASSES:+ if instance is None or not shown_in_chat(instance):return Noneif instance.status != STATUS_PROPOSED:return None@@ -126,6 +150,10 @@ def card_text(decision_id: int) -> str | None:who = [str(a) for a in payload.get("attendee_emails") or [] if a][:10]if who:lines.append("With " + ", ".join(who))+ elif instance.decision_class == "app_action":+ # Written by the server from the change itself (workflow_change.card_text).+ # Never cut: workflow_change stages only a card that fits.+ lines.append(str(payload.get("card") or "").strip())else:why = str(payload.get("why") or "").strip()[:300]if why:diff --git a/packages/core/openexecutive/integrations/discord_bot.py b/packages/core/openexecutive/integrations/discord_bot.pyindex 5deb0184..cf0e3cec 100644--- a/packages/core/openexecutive/integrations/discord_bot.py+++ b/packages/core/openexecutive/integrations/discord_bot.py@@ -669,6 +669,97 @@ def _find_discord_sender(discord_user_id: str) -> object:return find_person_by_discord_id(discord_user_id)+# Discord caps a message at 2000 characters.+_MAX_CARD_TEXT = 1900+++def _card_view(decision_id: int) -> Any:+ """A card's Approve and Skip buttons. Their custom ids carry the card+ (``channel_cards.callback_data``); ``on_interaction`` takes the tap, so it+ still works after a restart."""+ import discord++ from openexecutive.integrations import channel_cards++ view = discord.ui.View(timeout=None)+ view.add_item(discord.ui.Button(+ label="Approve", style=discord.ButtonStyle.success,+ custom_id=channel_cards.callback_data(decision_id, channel_cards.APPROVE),+ ))+ view.add_item(discord.ui.Button(+ label="Skip", style=discord.ButtonStyle.secondary,+ custom_id=channel_cards.callback_data(decision_id, channel_cards.SKIP),+ ))+ return view+++async def _send_cards(send_card: Callable[[int, str], Awaitable[None]], cards: list[int]) -> None:+ from openexecutive.integrations import channel_cards++ for decision_id in cards[: channel_cards.MAX_CARDS]:+ try:+ text = await asyncio.to_thread(channel_cards.card_text, decision_id)+ if text:+ await send_card(decision_id, text[:_MAX_CARD_TEXT])+ except Exception:+ logger.exception("Discord: couldn't send card %d", decision_id)+++async def handle_card_tap(interaction: Any) -> None:+ """A tap on a card's Approve or Skip button (``channel_cards``). It came+ over the bot's own gateway connection; it counts only in the tapper's own+ DM with the bot, from someone on the roster, and+ ``decisions.resolve_in_chat`` decides whether the card is theirs."""+ import discord++ from openexecutive.audit import log_event as audit_log+ from openexecutive.integrations import channel_cards+ from openexecutive.people.store import find_person_by_discord_id++ data = getattr(interaction, "data", None) or {}+ parsed = channel_cards.parse_callback(data.get("custom_id") if isinstance(data, dict) else None)+ if parsed is None:+ return # not one of ours+ user_id = str(getattr(getattr(interaction, "user", None), "id", "") or "")+ channel = getattr(interaction, "channel", None)+ recipient = getattr(channel, "recipient", None)+ if isinstance(channel, discord.DMChannel):+ own_dm = str(getattr(recipient, "id", "") or "") == user_id+ else:+ # A DM the bot hasn't cached since it restarted comes as a partial+ # channel with no recipient. A one-to-one DM outside any server has+ # one person besides the bot, so the tapper is the one it's with.+ own_dm = (getattr(interaction, "guild_id", None) is None+ and getattr(channel, "type", None) == discord.ChannelType.private)+ person = await asyncio.to_thread(find_person_by_discord_id, user_id) if user_id and own_dm else None+ if person is None:+ await interaction.response.send_message("This card is no longer there.", ephemeral=True)+ return+ decision_id, approve = parsed+ # Deciding can take longer than Discord's three seconds.+ await interaction.response.defer()+ line = await channel_cards.resolve(decision_id, person, approve=approve)+ choice = "approve" if approve else "skip"+ await asyncio.to_thread(+ audit_log,+ "integration_inbound",+ f"Discord card {decision_id}: tapped {choice.capitalize()}: {line[:120]}",+ actor="discord",+ details={"channel": "discord", "discord_user": user_id, "decision_id": decision_id,+ "choice": choice, "outcome": channel_cards.outcome_of(line), "person_id": person.id},+ )+ try:+ if line == channel_cards.BUSY:+ await interaction.followup.send(line, ephemeral=True)+ return+ # The card keeps what it said, with the outcome under it and no buttons.+ shown = str(getattr(getattr(interaction, "message", None), "content", "") or "")+ text = f"{shown}\n\n{line}" if shown else line+ await interaction.edit_original_response(content=text[:2000], view=None)+ except Exception:+ logger.exception("Discord: couldn't update card %d after the tap", decision_id)++# The rows this handler writes before the turn binds its session (the inbound# row, the knowledge retrieval, alert triage) are private when the principal# sent the message and they name one of their contacts.@@ -696,6 +787,7 @@ async def _handle_message(attachment_count: int = 0,co_present_discord_user_ids: list[str] | None = None,response_router: Callable[[str], Awaitable[MentionRouteResult]] | None = None,+ send_card: Callable[[int, str], Awaitable[None]] | None = None,) -> None:"""Core handler shared by on_message and slash commands.@@ -979,6 +1071,13 @@ async def _handle_message(person=sender_person,)+ from openexecutive.integrations.channel_cards import shows_cards++ # A DM shows the reply's cards with Approve and Skip buttons+ # (integrations.channel_cards), sent by ``send_card``.+ cards_here = is_dm and send_card is not None and shows_cards(session)+ cards: list[int] = []+executive = Executive(mcp_gateway=get_active_gateway())response = await executive.chat(user_message=chat_user_message,@@ -987,7 +1086,8 @@ async def _handle_message(episodic_context=episodic_context,attachment_blocks=attachment_blocks or None,briefing_context=briefing_context,- channel_context_block=build_channel_context_block("discord"),+ channel_context_block=build_channel_context_block("discord", cards_here=cards_here),+ cards=cards if cards_here else None,person_id=person_id,co_present_person_ids=co_present_person_ids or None,)@@ -1021,6 +1121,8 @@ async def _handle_message(reply = with_chat_line(response, f"discord:{session_id}")for chunk in _split_message(reply):await effective_send_fn(chunk)+ if cards and send_card is not None:+ await _send_cards(send_card, cards)else:logger.info("Discord: executive returned empty response for session %s — "@@ -1330,6 +1432,12 @@ def create_discord_bot():await bot.tree.sync()logger.info("Discord slash commands synced globally")+ @bot.event+ async def on_interaction(interaction: discord.Interaction) -> None:+ # A card's Approve or Skip button; slash commands go to the tree.+ if interaction.type == discord.InteractionType.component:+ await handle_card_tap(interaction)+@bot.eventasync def on_message(message: discord.Message) -> None:if message.author == bot.user:@@ -1572,9 +1680,15 @@ def create_discord_bot():exc_info=True,)+ send_card: Callable[[int, str], Awaitable[None]] | None = None+ if is_dm:+ async def send_card(decision_id: int, text: str) -> None:+ await message.channel.send(text, view=_card_view(decision_id), suppress_embeds=True)+# Use the channel id as thread_id so WaitForHuman resolution can match# replies that arrive in the same DM or thread channel.await _handle_message(+ send_card=send_card,text=cleaned,attachment_count=len(message.attachments or []),discord_user_id=discord_user_id,diff --git a/packages/core/openexecutive/integrations/slack_bot.py b/packages/core/openexecutive/integrations/slack_bot.pyindex 6bb65d1f..54550c44 100644--- a/packages/core/openexecutive/integrations/slack_bot.py+++ b/packages/core/openexecutive/integrations/slack_bot.py@@ -476,6 +476,116 @@ async def _read_shared_files(return "\n\n".join(p for p in (*notes, text) if p), blocks+# A card's buttons (integrations.channel_cards): one action id each, the+# card's id and choice in the button's value.+_CARD_ACTION_APPROVE = "oe_card_approve"+_CARD_ACTION_SKIP = "oe_card_skip"+_CARD_ACTION_RE = re.compile(rf"^({_CARD_ACTION_APPROVE}|{_CARD_ACTION_SKIP})$")+_MAX_CARD_TEXT = 2900+++def _card_blocks(text: str, decision_id: int | None = None) -> list[dict[str, Any]]:+ """A card as Slack blocks: its text as plain text (it may quote what+ someone else wrote, so never mrkdwn), with the two buttons while it waits."""+ from openexecutive.integrations import channel_cards++ blocks: list[dict[str, Any]] = [+ {"type": "section", "text": {"type": "plain_text", "text": text[:_MAX_CARD_TEXT], "emoji": False}},+ ]+ if decision_id is not None:+ blocks.append({"type": "actions", "elements": [+ {"type": "button", "action_id": _CARD_ACTION_APPROVE, "style": "primary",+ "text": {"type": "plain_text", "text": "Approve"},+ "value": channel_cards.callback_data(decision_id, channel_cards.APPROVE)},+ {"type": "button", "action_id": _CARD_ACTION_SKIP,+ "text": {"type": "plain_text", "text": "Skip"},+ "value": channel_cards.callback_data(decision_id, channel_cards.SKIP)},+ ]})+ return blocks+++async def _send_cards(client: Any, channel: str, cards: list[int]) -> None:+ """Post each card a DM reply left, with Approve and Skip buttons."""+ from openexecutive.integrations import channel_cards++ if not channel:+ return+ for decision_id in cards[: channel_cards.MAX_CARDS]:+ try:+ text = await asyncio.to_thread(channel_cards.card_text, decision_id)+ if text:+ await client.chat_postMessage(+ channel=channel, text=text[:_MAX_CARD_TEXT], blocks=_card_blocks(text, decision_id),+ unfurl_links=False, unfurl_media=False,+ )+ except Exception:+ logger.exception("Slack: couldn't send card %d", decision_id)+++async def _is_own_dm(client: Any, user_id: str, channel_id: str) -> bool:+ """Whether ``channel_id`` is the bot's DM with ``user_id``: Slack's own+ answer, not the payload's."""+ if not user_id or not channel_id.startswith("D"):+ return False+ try:+ opened = await client.conversations_open(users=user_id)+ except Exception:+ logger.warning("Slack: couldn't check the DM for a card tap", exc_info=True)+ return False+ return str(((opened or {}).get("channel") or {}).get("id") or "") == channel_id+++async def handle_card_tap(body: dict[str, Any], client: Any) -> None:+ """A tap on a card's Approve or Skip button (``channel_cards``). Slack+ signed it; it counts only in the tapper's own DM with the bot, from+ someone on the roster, and ``decisions.resolve_in_chat`` decides whether+ the card is theirs."""+ from openexecutive.audit import log_event as audit_log+ from openexecutive.integrations import channel_cards+ from openexecutive.people.store import find_person_by_slack_id++ user_id = str((body.get("user") or {}).get("id") or "")+ channel_id = str((body.get("channel") or {}).get("id") or "")+ message = body.get("message") or {}+ ts = str((body.get("container") or {}).get("message_ts") or message.get("ts") or "")+ actions = body.get("actions") or []+ parsed = channel_cards.parse_callback(actions[0].get("value") if actions else None)+ person = await asyncio.to_thread(find_person_by_slack_id, user_id) if user_id else None+ if parsed is None or person is None or not await _is_own_dm(client, user_id, channel_id):+ logger.warning("Slack: ignored a card tap that isn't from its own DM")+ if user_id and channel_id:+ try:+ await client.chat_postEphemeral(channel=channel_id, user=user_id,+ text="This card is no longer there.")+ except Exception:+ logger.warning("Slack: couldn't answer an ignored card tap", exc_info=True)+ return+ decision_id, approve = parsed+ line = await channel_cards.resolve(decision_id, person, approve=approve)+ choice = "approve" if approve else "skip"+ await asyncio.to_thread(+ audit_log,+ "integration_inbound",+ f"Slack card {decision_id}: tapped {choice.capitalize()}: {line[:120]}",+ actor="slack",+ details={"channel": "slack", "slack_user": user_id, "decision_id": decision_id,+ "choice": choice, "outcome": channel_cards.outcome_of(line), "person_id": person.id},+ )+ if line == channel_cards.BUSY or not ts:+ return+ # The card keeps what it said, with the outcome under it and no buttons.+ shown = ""+ for block in message.get("blocks") or []:+ if block.get("type") == "section":+ shown = str((block.get("text") or {}).get("text") or "")+ break+ text = f"{shown}\n\n{line}" if shown else line+ try:+ await client.chat_update(channel=channel_id, ts=ts, text=text[:_MAX_CARD_TEXT], blocks=_card_blocks(text))+ except Exception:+ logger.exception("Slack: couldn't update card %d after the tap", decision_id)++async def create_slack_app():"""Build the async Bolt app and how it hears Slack: a Socket Mode handlerwith ``SLACK_APP_TOKEN``, else an ``slack_events.HttpEventsListener`` that@@ -1021,6 +1131,13 @@ async def create_slack_app():# Before the words, as Discord and Telegram inline it.chat_user_message = f"{att_text}\n\n{chat_user_message}"+ from openexecutive.integrations.channel_cards import shows_cards++ # A DM shows the reply's cards with Approve and Skip buttons+ # (SLACK_CARD_BUTTONS, integrations.channel_cards).+ cards_here = mode == "dm" and shows_cards(session)+ cards: list[int] = []+executive = Executive(mcp_gateway=get_active_gateway())response = await executive.chat(user_message=chat_user_message,@@ -1028,7 +1145,8 @@ async def create_slack_app():retrieved_context=retrieved_context,episodic_context=episodic_context,briefing_context=briefing_context,- channel_context_block=build_channel_context_block("slack"),+ channel_context_block=build_channel_context_block("slack", cards_here=cards_here),+ cards=cards if cards_here else None,person_id=person_id,co_present_person_ids=co_present_person_ids or None,attachment_blocks=att_image_blocks or None,@@ -1045,6 +1163,8 @@ async def create_slack_app():text=with_chat_line(response, f"slack:{session_id}"),thread_ts=thread_ts, unfurl_links=False, unfurl_media=False,)+ if cards and client is not None:+ await _send_cards(client, str(event.get("channel") or ""), cards)# Persist AFTER the reply lands, and never let a persistence# failure trigger the user-facing error path — the user@@ -1141,6 +1261,11 @@ async def create_slack_app():session_id,)+ @app.action(_CARD_ACTION_RE)+ async def card_tap(ack, body: dict, client) -> None:+ await ack()+ await handle_card_tap(body, client)+@app.event("app_mention")async def handle_mention(event: dict, say, client) -> None:# Bolt auto-injects `client` (an AsyncWebClient) when listed in thediff --git a/packages/core/openexecutive/orchestrator/action_chips.py b/packages/core/openexecutive/orchestrator/action_chips.pyindex 477cc05b..851f78ca 100644--- a/packages/core/openexecutive/orchestrator/action_chips.py+++ b/packages/core/openexecutive/orchestrator/action_chips.py@@ -72,6 +72,8 @@ SIDE_EFFECTING_TOOLS: frozenset[str] = frozenset({"ack_alert",# Universal workflow launcher (any built-in / custom workflow from chat)"run_workflow",+ # Saves a workflow, or leaves a card for a change to one (workflow_change)+ "save_workflow",# Research artifacts flagged for review"draft_artifact",# MCP — generic, classified by underlying tool name at runtime@@ -241,7 +243,7 @@ def summarize_action(if (parsed is not Noneand parsed.get("status") == "waiting_for_approval"- and tool_name not in ("propose_actions", "do_in_app")+ and tool_name not in ("propose_actions", "do_in_app", "save_workflow")and not extension):# Held for someone's approval (a team member's send or change, the@@ -586,6 +588,24 @@ def summarize_action(return Nonepayload["summary"] = f"Open {(parsed or {}).get('screen') or 'it'}"payload["link"] = link+ elif tool_name == "save_workflow":+ status = (parsed or {}).get("status")+ name = str((parsed or {}).get("name") or "").replace("_", " ")+ if status == "waiting_for_approval":+ payload["summary"] = "Waiting for your OK: a change to a workflow"+ # The chat shows the card itself under its message, by this id.+ decision_id = (parsed or {}).get("decision_id")+ if isinstance(decision_id, int) and not isinstance(decision_id, bool):+ payload["decision_id"] = decision_id+ elif status == "saved":+ payload["summary"] = f"Saved the workflow {name}" if name else "Saved the workflow"+ elif status == "saved_pending_review":+ payload["summary"] = f"Saved the workflow {name}, switched off" if name else "Saved the workflow, switched off"+ else:+ return None+ link = (parsed or {}).get("name")+ if isinstance(link, str) and link and status != "waiting_for_approval":+ payload["link"] = f"/jobs/{link}"elif tool_name == "run_workflow":wf = str(tool_input.get("workflow", "")).replace("_", " ")run_id = (parsed or {}).get("run_id")diff --git a/packages/core/openexecutive/orchestrator/app_control.py b/packages/core/openexecutive/orchestrator/app_control.pyindex 504d36cb..23afd76d 100644--- a/packages/core/openexecutive/orchestrator/app_control.py+++ b/packages/core/openexecutive/orchestrator/app_control.py@@ -113,6 +113,9 @@ class Action:card: str = ""principal_only: bool = Falseprepare: Preparer | None = None+ # Not offered to do_in_app: only a card another tool leaves runs it (a+ # workflow change ``save_workflow`` stages, ``workflow_change``).+ hidden: bool = Falsedef needs_tap(self, item_id: str, value: str) -> bool:return self.confirm(item_id, value) if callable(self.confirm) else bool(self.confirm)@@ -156,8 +159,9 @@ def _rebuild() -> None:"required": ["kind"],},})+ offered = sorted(name for name, action in CATALOG.actions.items() if not action.hidden)lines = []- for name in sorted(CATALOG.actions):+ for name in offered:action = CATALOG.actions[name]extra = f" value: {action.value}." if action.value else ""lines.append(f"- {name} ({action.kind}): {action.does}.{extra}")@@ -174,7 +178,7 @@ def _rebuild() -> None:"input_schema": {"type": "object","properties": {- "action": {"type": "string", "enum": sorted(CATALOG.actions)},+ "action": {"type": "string", "enum": offered},"id": {"type": "string", "description": "The item's id from find_in_app, or \"this\" for this chat."},"value": {"type": "string", "description": "The action's value, when it takes one."},},@@ -451,7 +455,7 @@ async def handle_do_in_app(tool_input: dict[str, Any]) -> str:if not _private_here():return _error(_NOT_PRIVATE)action = CATALOG.actions.get(str(tool_input.get("action") or ""))- if action is None:+ if action is None or action.hidden:return _error("Unknown action. Pick one from the list.")kind = CATALOG.kinds[action.kind]if (action.principal_only or kind.principal_only) and not getattr(person, "is_principal", False):@@ -546,6 +550,15 @@ def _leave_card()+def leave_card(person_id: int, action: str, item_id: str, value: str, title: str, card: str) -> int:+ """Leave a card for a hidden action another tool stages (its ``value``+ may be longer than ``do_in_app`` takes). Returns the decision id."""+ found = CATALOG.actions.get(action)+ if found is None:+ raise ValueError(f"unknown action {action!r}")+ return _leave_card(person_id, _session(), found, item_id, value, title, card)++def card_stale(created_at: str, now: datetime | None = None) -> bool:try:made = datetime.fromisoformat(created_at)diff --git a/packages/core/openexecutive/orchestrator/app_control_catalog.py b/packages/core/openexecutive/orchestrator/app_control_catalog.pyindex dd478faa..3cd40674 100644--- a/packages/core/openexecutive/orchestrator/app_control_catalog.py+++ b/packages/core/openexecutive/orchestrator/app_control_catalog.py@@ -437,6 +437,12 @@ async def _turn_workflow(request: Any, name: str, on: bool) -> str:return f"Turned {_q(title)} {'on' if on else 'off'}"+async def _change_workflow(request: Any, name: str, value: str) -> str:+ from openexecutive.orchestrator import workflow_change++ return await workflow_change.run(request, name, value)++async def _delete_workflow(request: Any, name: str, value: str) -> str:from openexecutive.api.routes import workflows@@ -837,6 +843,9 @@ _ACTIONS = (Action("turn_off_workflow", "workflow", "Turn a workflow off", _fixed(_turn_workflow, False)),Action("delete_workflow", "workflow", "Delete a workflow for good", _delete_workflow, confirm=True,card="Delete the workflow {title}"),+ # Only a card save_workflow stages runs it (orchestrator.workflow_change).+ Action("change_workflow", "workflow", "Save a change to a workflow", _change_workflow, confirm=True,+ card="Change the workflow {title}", hidden=True),Action("rerun_workflow_run", "workflow_run", "Run a failed scheduled run again", _rerun),Action("approve_workflow_step", "workflow_run", "Approve a run's step that is waiting for a yes",_fixed(_decide_run, "approve"), confirm=True, card="Approve the waiting step in {title}"),diff --git a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.pyindex f1110688..f39215db 100644--- a/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py+++ b/packages/core/openexecutive/orchestrator/workflow_authoring_tools.py@@ -30,6 +30,7 @@ from typing import Anyfrom pydantic import ValidationError+from openexecutive.orchestrator import workflow_changefrom openexecutive.orchestrator.schedule_tools import current_sessionlogger = logging.getLogger(__name__)@@ -79,7 +80,11 @@ DEFINITION_SCHEMA: dict[str, Any] = {"calendar (the same condition): 'oe__search_my_email', ""'oe__read_my_email', 'oe__my_email_awaiting_reply', 'oe__my_calendar', and ""'oe__answer_email_as_me' answers a thread from those as their Handle it "- "for me would; "+ "for me would. The gateway's mail and calendar tools "+ "(google_workspace__*, microsoft_365__*) act as YOUR account, not theirs: "+ "a calendar step with no calendar named reads your own calendar. To read "+ "the user's, use 'oe__my_calendar', or write their email address into the "+ "step's goal as the calendar to read; ""a workflow that reads them runs only for them, reports only to them, ""and can't also use web search, scripts, gateway tools or other ""workflows. Write the addresses they name into the step's goal: an "@@ -124,7 +129,9 @@ DRAFT_WORKFLOW_TOOL: dict[str, Any] = {"user has identified. If validation fails, the response lists exactly ""what to fix; re-draft and try again. A workflow with action (tool) ""steps is saved switched OFF: after saving, give the user the link so "- "they can review its tools and turn it on."+ "they can review its tools and turn it on. To fix or change a saved "+ "workflow, read it first (list_workflows with its name) and draft the "+ "whole corrected definition under the same name."),"input_schema": {"type": "object",@@ -144,7 +151,11 @@ SAVE_WORKFLOW_TOOL: dict[str, Any] = {"mismatch) — re-draft if you need to change anything. On success the ""workflow appears in /jobs and is immediately runnable — except one ""with action (tool) steps, which stays off until the user reviews its "- "tools and turns it on at the returned deep_link."+ "tools and turns it on at the returned deep_link. Replacing a switched-on "+ "workflow that uses tools, or one that reads or sends email as its "+ "creator, changes nothing yet: it leaves a card spelling out the change "+ "for the user to approve, and it is saved, staying on, when they tap "+ "Approve."),"input_schema": {"type": "object",@@ -178,25 +189,6 @@ def _canonical_token(definition: dict[str, Any]) -> str:return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:32]-def _approved_tool_workflow_error(name: str, existing: Any) -> str | None:- """Refuse chat overwrites of a switched-on tool workflow (``existing``).-- A person approved its tools. Chat (including a turn steered by an inbound- email) replacing it would switch it off and stage different tools under- the same familiar name, so edits to it happen on the Workflows page instead.- """- from openexecutive.config import get_settings-- if existing is None or not existing.is_active or not _needs_review(existing):- return None- base = get_settings().ui_base_url.rstrip("/")- return (- f"{name!r} is a switched-on workflow whose tools the user approved; it "- "can't be replaced from chat. Pick a different name for a new "- f"workflow, or tell the user to edit it at {base}/jobs/new?edit={name}"- )--def _session_caller_id() -> int | None:"""The person chatting — recorded as a new workflow's owner."""from openexecutive.workflows.gate_delivery import session_caller_id@@ -269,8 +261,10 @@ async def handle_draft_workflow(tool_input: dict[str, Any]) -> str:from openexecutive.workflows.dynamic_store import get_definitiondefn, error = await _build_def(tool_input.get("definition"))- if error is None:- error = _approved_tool_workflow_error(defn.name, get_definition(defn.name))+ existing = get_definition(defn.name) if error is None else None+ on_card = error is None and workflow_change.needs_card(existing, defn)+ if on_card:+ error = workflow_change.may_stage(defn.name)if error is None:error = _reads_refusal(defn)if error is not None:@@ -280,7 +274,13 @@ async def handle_draft_workflow(tool_input: dict[str, Any]) -> str:"Show this summary to the user. After they confirm, call ""save_workflow with the same definition and this confirm_token.")- if _needs_review(defn):+ if on_card:+ note += (+ " It changes a saved workflow, so saving (overwrite=true) doesn't change it "+ "right away: it leaves a card showing the change, in this chat and their chat "+ "app, and it is saved when they tap Approve."+ )+ elif _needs_review(defn):note += (" It uses tools, so it will be saved switched OFF: tell the user ""that after saving they review its tools and turn it on from the "@@ -310,7 +310,6 @@ async def handle_save_workflow(tool_input: dict[str, Any]) -> str:from openexecutive.audit import log_event as audit_logfrom openexecutive.config import get_settingsfrom openexecutive.delegation.lockdown import outside_reach_refusal- from openexecutive.delegation.workflow_email import as_creatorfrom openexecutive.workflows.dynamic_store import get_definition, save_if_unchangedif (refused := outside_reach_refusal("save_workflow")) is not None:@@ -334,20 +333,6 @@ async def handle_save_workflow(tool_input: dict[str, Any]) -> str:})existing = get_definition(defn.name)- approved_error = _approved_tool_workflow_error(defn.name, existing)- if approved_error is not None:- return json.dumps({"error": approved_error})- if existing is not None and (as_creator(existing) or as_creator(defn)):- # Only its creator, verified, may change one that sends or reads as- # them (workflow_email.save_refusal), and chat can't verify anyone:- # nor may chat add a send or a read to an existing one, which would- # act as its creator, not as whoever asked.- base = get_settings().ui_base_url.rstrip("/")- return json.dumps({"error": (- f"{defn.name!r} would send or read email as the person who created it, so it "- "can't be replaced from chat. Pick a different name, or tell the user to edit "- f"it at {base}/jobs/new?edit={defn.name}"- )})if (refused := _reads_refusal(defn)) is not None:return json.dumps({"error": refused})@@ -359,6 +344,25 @@ async def handle_save_workflow(tool_input: dict[str, Any]) -> str:"overwrite=true to replace it.")})+ if workflow_change.needs_card(existing, defn):+ # A person approved its tools, or it sends or reads email as its+ # creator, whom chat can't verify: the change waits on a card that+ # spells it out, saved on their own tap (workflow_change).+ try:+ staged = workflow_change.stage(defn, existing)+ except Exception:+ logger.exception("save_workflow: couldn't leave the change card")+ return json.dumps({"error": "Couldn't leave the card just now. Try again in a moment."})+ if "decision_id" in staged:+ session = current_session.get()+ audit_log(+ "app_action_proposed",+ f"Left a card: change the workflow {defn.name!r}",+ session_id=getattr(session, "session_id", None) if session is not None else None,+ actor="executive",+ details={"action": workflow_change.ACTION, "id": defn.name, "decision_id": staged["decision_id"]},+ )+ return json.dumps(staged)# A tool-using workflow waits for a person to turn it on from its review# card. Applied after the token check so the token still covers exactlydiff --git a/packages/core/openexecutive/orchestrator/workflow_change.py b/packages/core/openexecutive/orchestrator/workflow_change.pynew file mode 100644index 00000000..1373f17e--- /dev/null+++ b/packages/core/openexecutive/orchestrator/workflow_change.py@@ -0,0 +1,230 @@+"""A change to a saved workflow that waits for its person's tap.++Chat can't change a workflow a person already approved the tools of (one+switched on with action steps), nor one that reads or sends email as its+creator, by saving over it: the save would put tools nobody looked at under a+familiar name. So ``save_workflow`` stages such a change as a card instead+(decision class ``app_action``, hidden action ``change_workflow``) that spells+out every step it adds, removes or changes, tools included. Tapping Approve is+the person seeing the change, as turning it on from its review card is: the+change is saved and the workflow keeps its on/off state.++The card goes where the chat is: under the reply in the web chat, and with+Approve and Skip buttons in a chat app that proves who taps+(``integrations.channel_cards``). A chat that can show neither gets no card:+the person is asked to ask again where one shows. On the tap:++- the workflow must still be the version the card was made from, else+ nothing changes and the person is asked to look again;+- the new definition is validated again, tools included;+- one that reads or sends as its creator is saved only for that creator,+ verified (``workflow_email.save_refusal``): a signed web sign-in, or a tap+ a chat app proved was theirs.+"""+from __future__ import annotations++import json+import logging+from typing import Any++logger = logging.getLogger(__name__)++ACTION = "change_workflow"+# The longest card a chat app shows whole (Discord's 2000 characters, with+# room for the outcome line). A change that needs more isn't staged: a card+# never cuts a line short, so every step, goal and tool it saves is on it.+MAX_CARD_CHARS = 1800+++def needs_card(existing: Any, defn: Any) -> bool:+ """Whether replacing ``existing`` with ``defn`` from chat waits for a tap:+ a switched-on workflow with action steps, or one that reads or sends as+ its creator (before or after)."""+ from openexecutive.delegation.workflow_email import as_creator+ from openexecutive.workflows.dynamic_models import ActionStepSpec++ if existing is None:+ return False+ approved = existing.is_active and any(isinstance(s, ActionStepSpec) for s in existing.steps)+ return bool(approved or as_creator(existing) or as_creator(defn))+++def _tools(step: Any) -> list[str]:+ from openexecutive.workflows.action_step import plain_tool_name++ return [plain_tool_name(t) for t in getattr(step, "tools", None) or []]+++def _flat(text: str) -> str:+ return " ".join(str(text or "").split())+++def _does(step: Any) -> str:+ """What a step does, in full, for the card."""+ kind = getattr(step, "kind", "")+ if kind in ("action", "specialist"):+ return _flat(step.goal)+ if kind == "approval_gate":+ return f"Asks person {step.person_id}: {_flat(step.question)}"+ return _flat(getattr(step, "instructions", "") or "Writes the result.")+++def _what(step: Any) -> str:+ if getattr(step, "kind", "") == "action":+ return f"{_does(step)} Tools: {', '.join(_tools(step)) or 'none'}."+ return _does(step)+++def change_lines(old: Any, new: Any) -> list[str]:+ """One line per difference between two versions of a workflow, written+ from the definitions, so the card says exactly what a tap saves."""+ lines: list[str] = []+ before = {s.id: s for s in old.steps}+ after = {s.id: s for s in new.steps}+ for sid, step in after.items():+ was = before.get(sid)+ if was is None:+ lines.append(f"New step “{_flat(step.title)}”: {_what(step)}")+ continue+ if was.model_dump() == step.model_dump():+ continue+ parts: list[str] = []+ if _tools(was) != _tools(step):+ added = [t for t in _tools(step) if t not in _tools(was)]+ removed = [t for t in _tools(was) if t not in _tools(step)]+ if added:+ parts.append("now uses " + ", ".join(added))+ if removed:+ parts.append("no longer uses " + ", ".join(removed))+ if _does(was) != _does(step):+ parts.append("now: " + _does(step))+ if not parts:+ parts.append("its settings change")+ lines.append(f"Step “{_flat(step.title)}”: " + "; ".join(parts))+ for sid, step in before.items():+ if sid not in after:+ lines.append(f"Removed step “{_flat(step.title)}”")+ if [s.id for s in old.steps if s.id in after] != [s.id for s in new.steps if s.id in before]:+ lines.append("Steps run in a new order")+ if (old.cadence, old.cadence_person_id) != (new.cadence, new.cadence_person_id):+ lines.append(+ f"Schedule: {new.cadence or 'none'}"+ + (f", delivered to person {new.cadence_person_id}" if new.cadence else "")+ )+ if old.title != new.title:+ lines.append(f"Renamed to “{_flat(new.title)}”")+ rest = {"description", "section", "estimated_minutes", "input_fields"}+ if old.model_dump(include=rest) != new.model_dump(include=rest):+ lines.append("Its description or form fields change")+ return lines+++def card_text(old: Any, new: Any) -> str:+ head = f"Change the workflow “{_flat(old.title)}”"+ lines = change_lines(old, new)+ if not lines:+ return head + "\nNothing else changes."+ return head + "\n" + "\n".join(f"- {line}" for line in lines)+++def _speaker() -> Any:+ from openexecutive.orchestrator.correction_tools import _speaker as speaker++ return speaker()+++def may_read(name: str) -> str | None:+ """Why this turn may not read or change workflow ``name``, or None: it+ needs a verified speaker, in a conversation only they read, who is the+ account owner or the workflow's creator."""+ from openexecutive.orchestrator.app_control import _NOT_PRIVATE, _private_here+ from openexecutive.workflows.dynamic_store import get_owner++ person = _speaker()+ if person is None or getattr(person, "id", None) is None:+ return (+ "I can only do this with a saved workflow when I know who is asking: in the web "+ "app signed in, or your own chat app."+ )+ if not _private_here():+ return _NOT_PRIVATE+ if not getattr(person, "is_principal", False) and get_owner(name) != person.id:+ return "Only the account owner or the person who created this workflow can do that."+ return None+++def may_stage(name: str) -> str | None:+ """Why this turn can't leave a change card for workflow ``name``, or None:+ as ``may_read``, in a chat that shows the card."""+ from openexecutive.integrations.channel_cards import card_here+ from openexecutive.orchestrator.app_control import _session++ refused = may_read(name)+ if refused is not None:+ return refused+ if not card_here(_session()):+ return (+ "I can't show the change for your OK in this chat. Ask me in the web app, or in "+ "your own chat with me on Telegram, Slack or Discord, and I'll leave it there for "+ "you to approve."+ )+ return None+++def stage(defn: Any, existing: Any) -> dict[str, Any]:+ """Leave the card for changing ``existing`` into ``defn``. Returns the+ tool result for save_workflow."""+ from openexecutive.orchestrator import app_control, app_control_catalog++ app_control_catalog.install() # where the hidden action is registered+ refused = may_stage(defn.name)+ if refused is not None:+ return {"error": refused}+ person = _speaker()+ text = card_text(existing, defn)+ if len(text) > MAX_CARD_CHARS:+ return {"error": (+ "That change is too big to show on one card. Change a few steps at a time, or "+ "edit it on the Workflows page."+ )}+ value = json.dumps({+ "definition": defn.model_dump(mode="json", exclude={"is_active", "created_at", "updated_at"}),+ "base": existing.model_dump(mode="json", exclude={"is_active", "created_at", "updated_at"}),+ })+ decision_id = app_control.leave_card(person.id, ACTION, defn.name, value, existing.title, text)+ return {+ "status": "waiting_for_approval",+ "decision_id": decision_id,+ "card": text,+ "note": (+ "Nothing has changed yet. A card showing the change goes with this reply, with "+ "Approve and Skip: it is saved when they tap Approve, keeping the workflow on or "+ "off as it is. Tell them it is waiting for their OK."+ ),+ }+++def _tapper(request: Any) -> Any:+ """Who tapped: a chat app's proven tap, else the request's own caller."""+ from openexecutive.api import caller as api_caller++ tap = getattr(getattr(request, "state", None), "chat_tap", None)+ return tap if tap is not None else api_caller.caller(request)+++async def run(request: Any, name: str, value: str) -> str:+ """Carry out a change card on its person's tap (``app_control.carry_out``)."""+ from openexecutive.api.routes.workflows import apply_chat_change+ from openexecutive.orchestrator.app_control import Refused++ try:+ staged = json.loads(value)+ except ValueError:+ staged = None+ if not isinstance(staged, dict) or not isinstance(staged.get("definition"), dict):+ raise Refused("This card can't be read any more. Ask again in chat.")+ stored = await apply_chat_change(name, staged["definition"], staged.get("base"), _tapper(request))+ return f"Changed the workflow “{stored.title}”"+++__all__ = ["ACTION", "card_text", "change_lines", "may_read", "may_stage", "needs_card", "run", "stage"]diff --git a/packages/core/openexecutive/orchestrator/workflow_run_tools.py b/packages/core/openexecutive/orchestrator/workflow_run_tools.pyindex 0ec2778a..f3e0757b 100644--- a/packages/core/openexecutive/orchestrator/workflow_run_tools.py+++ b/packages/core/openexecutive/orchestrator/workflow_run_tools.py@@ -142,9 +142,19 @@ LIST_WORKFLOWS_TOOL: dict[str, Any] = {"title, description, section, estimated_minutes, and the input fields ""it expects (name → type/description/required). Call this when the ""principal asks what you can run, or to discover a workflow's name and "- "required inputs before calling run_workflow."+ "required inputs before calling run_workflow. Pass `name` of a custom "+ "workflow to read its full definition (steps, tools, schedule), e.g. to "+ "work out why a run went wrong and draft a fix with draft_workflow."),- "input_schema": {"type": "object", "properties": {}},+ "input_schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "A custom workflow's name, to get its full definition instead of the list.",+ },+ },+ },}@@ -239,9 +249,38 @@ def _input_fields(input_schema: dict[str, Any]) -> dict[str, Any]:return fields+def _definition_of(name: str) -> str:+ """A custom workflow's full definition, for the account owner or its+ creator in a conversation only they read: its steps can quote addresses+ and what it does."""+ from openexecutive.orchestrator.workflow_change import may_read+ from openexecutive.workflows.dynamic_store import get_definition++ # Refused before looking it up, so a refusal doesn't say whether it exists.+ refused = may_read(name)+ if refused is not None:+ return _err("list_workflows", refused)+ defn = get_definition(name)+ if defn is None:+ return _err("list_workflows", f"There is no custom workflow named {name!r}.")+ _audit("list_workflows", "read", True, f"list_workflows read {name}", {"name": name})+ return json.dumps({+ "definition": defn.model_dump(mode="json", exclude={"created_at", "updated_at"}),+ "note": (+ "is_active says whether it is switched on. To fix it, draft the whole corrected "+ "definition under the same name with draft_workflow, then save_workflow with "+ "overwrite=true."+ ),+ })++async def handle_list_workflows(tool_input: dict[str, Any]) -> str:from openexecutive.workflows import list_workflows as _list_workflows+ name = str(tool_input.get("name") or "").strip()+ if name:+ return _definition_of(name)+try:workflows = _list_workflows()except Exception as exc:diff --git a/packages/core/openexecutive/workflows/designer.py b/packages/core/openexecutive/workflows/designer.pyindex cc717f25..6556b68a 100644--- a/packages/core/openexecutive/workflows/designer.py+++ b/packages/core/openexecutive/workflows/designer.py@@ -239,11 +239,35 @@ def _email_as_line(as_me: bool) -> str:)-def build_context_block(*, as_me: bool = False) -> str:+def _accounts_line(as_me: bool, exec_email: str, user_email: str) -> str:+ """Whose mailbox and calendar each kind of tool reads."""+ from openexecutive.delegation.workflow_reads import TOOLS as READ_TOOLS++ yours = f" ({user_email})" if user_email else ""+ line = (+ "Whose account the gateway's mail and calendar tools use: the Executive's own"+ + (f" ({exec_email})" if exec_email else "")+ + ", never the user's. A calendar step that names no calendar reads the "+ "Executive's calendar, so it finds none of the user's meetings."+ )+ if as_me:+ mine = next((t for t in sorted(READ_TOOLS) if t.endswith("calendar")), "")+ return line + (+ f" To read the user's own calendar{yours}, use {mine}. With a gateway "+ "calendar tool, write their address into the step's goal as the calendar to read."+ )+ return line + (+ f" To read the user's calendar{yours}, write their address into the step's goal "+ "as the calendar to read (it must be shared with the Executive's account)."+ )+++def build_context_block(*, as_me: bool = False, user_email: str = "") -> str:"""Render the live facts the designer needs, for the FIRST user turn.``as_me``: the person designing it may have its emails written as them- (``workflow_email.available_for``).+ (``workflow_email.available_for``). ``user_email``: their address, so a+ calendar step reads their calendar and not the Executive's.Read once per session by the route and stored, so the replayed first turnstays identical across the conversation. Every source degrades to an@@ -312,10 +336,20 @@ def build_context_block(*, as_me: bool = False) -> str:"the Executive uses in chat, so anything it did in chat a step can ""do too):\n" + "\n".join(builtins) + "\n\n"+ _email_as_line(as_me) + "\n\n"+ + _accounts_line(as_me, _exec_email(), _one_line(user_email, 254)) + "\n\n""Workflow names already taken (do not reuse): " + ", ".join(taken))+def _exec_email() -> str:+ from openexecutive.config import get_settings++ try:+ return str(get_settings().exec_email_address or "").strip()+ except Exception:+ return ""++def _first_sentence(text: str) -> str:"""The first sentence of a tool description, kept to one short line.diff --git a/packages/core/tests/unit/test_action_chips.py b/packages/core/tests/unit/test_action_chips.pyindex b4c073a3..37db5c40 100644--- a/packages/core/tests/unit/test_action_chips.py+++ b/packages/core/tests/unit/test_action_chips.py@@ -340,6 +340,8 @@ _KNOWN_READ_ONLY_TOOLS: frozenset[str] = frozenset({"search_tools",# workflow_run_tools — catalog read (run_workflow is in SIDE_EFFECTING_TOOLS)"list_workflows",+ # workflow_authoring_tools — a draft saves nothing (save_workflow is side-effecting)+ "draft_workflow",# mail_read_tools — reads of the speaker's own mailbox (Act as me)"my_calendar","search_my_email",@@ -372,6 +374,7 @@ def _all_registered_tool_names() -> set[str]:from openexecutive.orchestrator.people_tools import PEOPLE_TOOL_HANDLERSfrom openexecutive.orchestrator.schedule_tools import SCHEDULE_TOOL_HANDLERSfrom openexecutive.orchestrator.skills_tools import SKILL_TOOL_HANDLERS+ from openexecutive.orchestrator.workflow_authoring_tools import WORKFLOW_AUTHORING_TOOL_HANDLERSfrom openexecutive.orchestrator.workflow_run_tools import WORKFLOW_RUN_TOOL_HANDLERSreturn (@@ -388,6 +391,7 @@ def _all_registered_tool_names() -> set[str]:| set(DRAFT_ARTIFACT_TOOL_HANDLERS)| set(MCP_TOOL_NAMES)| set(WORKFLOW_RUN_TOOL_HANDLERS)+ | set(WORKFLOW_AUTHORING_TOOL_HANDLERS)| set(APP_TOOL_HANDLERS)# Act as me: its own registry, offered per turn (never _ALL_SKILL_TOOLS).| set(DELEGATION_TOOL_HANDLERS)diff --git a/packages/core/tests/unit/test_app_control.py b/packages/core/tests/unit/test_app_control.pyindex aaab7907..90d81630 100644--- a/packages/core/tests/unit/test_app_control.py+++ b/packages/core/tests/unit/test_app_control.py@@ -316,7 +316,7 @@ def test_the_catalog_is_whole() -> None:if action.needs_tap("x", "on"):assert action.card, action.nameschema = app_control.DO_IN_APP_TOOL["input_schema"]["properties"]["action"]["enum"]- assert schema == sorted(catalog.actions)+ assert schema == sorted(name for name, action in catalog.actions.items() if not action.hidden)for name in ("pin_chat", "rename_chat", "delete_chat"):assert name in app_control.DO_IN_APP_TOOL["description"]for name, action in catalog.actions.items():diff --git a/packages/core/tests/unit/test_chat_app_card_buttons.py b/packages/core/tests/unit/test_chat_app_card_buttons.pynew file mode 100644index 00000000..20b6cb0b--- /dev/null+++ b/packages/core/tests/unit/test_chat_app_card_buttons.py@@ -0,0 +1,187 @@+"""Approve and Skip buttons on cards in a Slack or Discord DM+(integrations/channel_cards.py, slack_bot.handle_card_tap,+discord_bot.handle_card_tap)."""+from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from openexecutive.integrations import channel_cards, discord_bot, slack_bot+from openexecutive.orchestrator.session import Session++PERSON = SimpleNamespace(id=1, email="[email protected]")++[email protected](autouse=True)+def chat_apps(monkeypatch: pytest.MonkeyPatch) -> list[tuple[int, Any, bool]]:++ monkeypatch.setenv("SLACK_BOT_TOKEN", "xoxb-test")+ monkeypatch.setenv("SLACK_CARD_BUTTONS", "true")+ monkeypatch.setenv("DISCORD_BOT_TOKEN", "discord-test")+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *_a, **_k: None)+ resolved: list[tuple[int, Any, bool]] = []++ async def resolve(decision_id: int, person: Any, *, approve: bool) -> str:+ resolved.append((decision_id, person, approve))+ return "Approved." if approve else "Skipped."++ monkeypatch.setattr(channel_cards, "resolve", resolve)+ yield resolved+++def _dm(channel: str, session_id: str, person_id: int | None = 1) -> Session:+ return Session(session_id=session_id, origin_channel=channel, origin_channel_ref="U1",+ caller_person_id=person_id)+++def test_slack_and_discord_dms_show_cards(monkeypatch: pytest.MonkeyPatch) -> None:++ assert channel_cards.shows_cards(_dm("slack", "slack:dm:U1"))+ assert channel_cards.shows_cards(_dm("discord", "discord:dm:42"))+ # A channel or thread is everyone in it; nobody on the roster proves nothing.+ assert not channel_cards.shows_cards(_dm("slack", "slack:C1:123.4"))+ assert not channel_cards.shows_cards(_dm("discord", "discord:thread:9"))+ assert not channel_cards.shows_cards(_dm("slack", "slack:dm:U1", person_id=None))+ # Slack needs Interactivity, so the buttons wait for SLACK_CARD_BUTTONS.+ monkeypatch.setenv("SLACK_CARD_BUTTONS", "false")+ assert not channel_cards.shows_cards(_dm("slack", "slack:dm:U1"))+++class FakeSlack:+ def __init__(self, dm: str = "D1") -> None:+ self.dm = dm+ self.updates: list[dict[str, Any]] = []+ self.posts: list[dict[str, Any]] = []+ self.ephemeral: list[dict[str, Any]] = []++ async def conversations_open(self, users: str) -> dict[str, Any]:+ return {"channel": {"id": self.dm}}++ async def chat_update(self, **kwargs: Any) -> None:+ self.updates.append(kwargs)++ async def chat_postMessage(self, **kwargs: Any) -> None: # noqa: N802 - Slack's name+ self.posts.append(kwargs)++ async def chat_postEphemeral(self, **kwargs: Any) -> None: # noqa: N802 - Slack's name+ self.ephemeral.append(kwargs)+++def _slack_tap(channel: str = "D1", value: str = "card:7:a") -> dict[str, Any]:+ return {+ "user": {"id": "U1"}, "channel": {"id": channel},+ "container": {"message_ts": "111.2"},+ "message": {"ts": "111.2", "blocks": slack_bot._card_blocks("Change the workflow", 7)},+ "actions": [{"action_id": "oe_card_approve", "value": value}],+ }+++def test_a_slack_tap_in_its_own_dm_decides_the_card(+ chat_apps: list[Any], monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("openexecutive.people.store.find_person_by_slack_id", lambda uid: PERSON)+ client = FakeSlack()+ asyncio.run(slack_bot.handle_card_tap(_slack_tap(), client))+ assert chat_apps == [(7, PERSON, True)]+ update = client.updates[0]+ assert update["ts"] == "111.2" and "Approved." in update["text"]+ assert [b["type"] for b in update["blocks"]] == ["section"] # no buttons left+++def test_a_slack_tap_anywhere_else_is_ignored(chat_apps: list[Any], monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("openexecutive.people.store.find_person_by_slack_id", lambda uid: PERSON)+ # A channel, or a DM that isn't this user's with the bot.+ asyncio.run(slack_bot.handle_card_tap(_slack_tap(channel="C1"), FakeSlack()))+ elsewhere = FakeSlack(dm="D1")+ asyncio.run(slack_bot.handle_card_tap(_slack_tap(channel="D9"), elsewhere))+ assert elsewhere.ephemeral[0]["text"] == "This card is no longer there." and elsewhere.updates == []+ asyncio.run(slack_bot.handle_card_tap(_slack_tap(value="junk"), FakeSlack()))+ monkeypatch.setattr("openexecutive.people.store.find_person_by_slack_id", lambda uid: None)+ asyncio.run(slack_bot.handle_card_tap(_slack_tap(), FakeSlack()))+ assert chat_apps == []+++def test_slack_cards_go_out_as_plain_text_with_buttons(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(channel_cards, "card_text", lambda decision_id: f"*card* {decision_id}")+ client = FakeSlack()+ asyncio.run(slack_bot._send_cards(client, "D1", [3]))+ blocks = client.posts[0]["blocks"]+ assert blocks[0]["text"]["type"] == "plain_text"+ assert [e["value"] for e in blocks[1]["elements"]] == ["card:3:a", "card:3:s"]+++class FakeResponse:+ def __init__(self) -> None:+ self.sent: list[str] = []+ self.deferred = False++ async def send_message(self, text: str, **_: Any) -> None:+ self.sent.append(text)++ async def defer(self) -> None:+ self.deferred = True+++def _discord_tap(dm: bool = True, recipient: str = "42", custom_id: str = "card:7:s",+ partial: Any = None, guild_id: int | None = None) -> Any:+ import discord++ edits: list[dict[str, Any]] = []+ channel: Any+ if partial is not None:+ channel = SimpleNamespace(type=partial) # not cached: no recipient+ elif dm:+ channel = discord.DMChannel.__new__(discord.DMChannel)+ channel.recipients = [SimpleNamespace(id=int(recipient))]+ else:+ channel = SimpleNamespace()++ async def edit_original_response(**kwargs: Any) -> None:+ edits.append(kwargs)++ return SimpleNamespace(+ data={"custom_id": custom_id}, user=SimpleNamespace(id=42), channel=channel, guild_id=guild_id,+ message=SimpleNamespace(content="Change the workflow"), response=FakeResponse(),+ edit_original_response=edit_original_response, edits=edits,+ )+++def test_a_discord_tap_in_its_own_dm_decides_the_card(+ chat_apps: list[Any], monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("openexecutive.people.store.find_person_by_discord_id", lambda uid: PERSON)+ tap = _discord_tap()+ asyncio.run(discord_bot.handle_card_tap(tap))+ assert chat_apps == [(7, PERSON, False)]+ assert tap.response.deferred and tap.edits[0]["view"] is None+ assert "Skipped." in tap.edits[0]["content"]+++def test_a_discord_tap_still_counts_after_a_restart(+ chat_apps: list[Any], monkeypatch: pytest.MonkeyPatch,+) -> None:+ import discord++ monkeypatch.setattr("openexecutive.people.store.find_person_by_discord_id", lambda uid: PERSON)+ asyncio.run(discord_bot.handle_card_tap(_discord_tap(partial=discord.ChannelType.private)))+ assert chat_apps == [(7, PERSON, False)]+ for tap in (_discord_tap(partial=discord.ChannelType.group),+ _discord_tap(partial=discord.ChannelType.private, guild_id=5)):+ asyncio.run(discord_bot.handle_card_tap(tap))+ assert tap.response.sent == ["This card is no longer there."]+ assert len(chat_apps) == 1+++def test_a_discord_tap_anywhere_else_is_turned_away(+ chat_apps: list[Any], monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("openexecutive.people.store.find_person_by_discord_id", lambda uid: PERSON)+ for tap in (_discord_tap(dm=False), _discord_tap(recipient="99")):+ asyncio.run(discord_bot.handle_card_tap(tap))+ assert tap.response.sent == ["This card is no longer there."]+ other = _discord_tap(custom_id="something_else")+ asyncio.run(discord_bot.handle_card_tap(other))+ assert other.response.sent == [] and chat_apps == []diff --git a/packages/core/tests/unit/test_workflow_authoring_tools.py b/packages/core/tests/unit/test_workflow_authoring_tools.pyindex b2ba2308..bc7409bd 100644--- a/packages/core/tests/unit/test_workflow_authoring_tools.py+++ b/packages/core/tests/unit/test_workflow_authoring_tools.py@@ -190,17 +190,18 @@ def test_chat_saves_tool_workflow_switched_off(scheduled: list[str]) -> None:def test_chat_cannot_replace_an_approved_tool_workflow(scheduled: list[str]) -> None:"""Replacing a switched-on tool workflow from chat (e.g. steered by an- inbound email) would switch it off and stage new tools under a familiar- name — refused at draft and save; edits happen on the Jobs page."""+ inbound email) would stage new tools under a familiar name. It waits on a+ card its person taps (workflow_change), so a turn with nobody verified to+ leave it for is refused at draft and save."""from openexecutive.workflows.dynamic_models import DynamicWorkflowDefdynamic_store.upsert_definition(DynamicWorkflowDef.model_validate(_action_definition()))d = _action_definition()d["title"] = "Weekly Watch v2"drafted = _draft(d)- assert "error" in drafted and "/jobs/new?edit=weekly_watch" in drafted["error"]+ assert "error" in drafted and "know who is asking" in drafted["error"]saved = _save(d, wat._canonical_token(d), overwrite=True)- assert "error" in saved and "approved" in saved["error"]+ assert "error" in saved and "know who is asking" in saved["error"]# An analysis-only replacement is refused too — it would still drop the tools the user approved.assert "error" in _save(_valid_definition(), wat._canonical_token(_valid_definition()), overwrite=True)stored = dynamic_store.get_definition("weekly_watch")diff --git a/packages/core/tests/unit/test_workflow_change.py b/packages/core/tests/unit/test_workflow_change.pynew file mode 100644index 00000000..32801f6a--- /dev/null+++ b/packages/core/tests/unit/test_workflow_change.py@@ -0,0 +1,336 @@+"""A change to a saved workflow from chat that waits for its person's tap+(orchestrator/workflow_change.py): the card, the tap in the web app or in+Telegram, and the builder's note on whose calendar a step reads."""+from __future__ import annotations++import asyncio+import json+from collections.abc import Iterator+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest+from fastapi import HTTPException++from openexecutive.api.routes import decisions as decisions_route+from openexecutive.api.routes import workflows as workflows_route+from openexecutive.delegation.verified import ChatTap+from openexecutive.memory import decision_ledger, episodic, session_store+from openexecutive.orchestrator import app_control, workflow_change+from openexecutive.orchestrator import workflow_authoring_tools as wat+from openexecutive.orchestrator import workflow_run_tools as wrt+from openexecutive.orchestrator.action_chips import summarize_action+from openexecutive.orchestrator.schedule_tools import set_session+from openexecutive.orchestrator.session import Session+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store+from openexecutive.workflows import approved_targets, dynamic_cadence, dynamic_store+from openexecutive.workflows.dynamic_models import DynamicWorkflowDef++GATEWAY_READ = "google_workspace__get_events"++[email protected](autouse=True)+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:+ monkeypatch.chdir(tmp_path)+ path = Path("./episodic_memory.db").resolve()+ monkeypatch.setattr(episodic, "DB_PATH", path)+ monkeypatch.setattr(session_store, "DB_PATH", path)+ monkeypatch.setattr(people_store, "DB_PATH", path)+ monkeypatch.setattr(dynamic_store, "DB_PATH", path)+ monkeypatch.setattr(approved_targets, "DB_PATH", path)+ monkeypatch.setattr(decision_ledger, "_db_path", lambda: path)+ episodic.initialize_db(path)+ people_store.initialize_db(path)+ dynamic_store.initialize_dynamic_workflows_db(path)+ for var in ("OE_LOCAL_LOGIN", "OE_PUBLIC_DEPLOYMENT", "BACKEND_SHARED_SECRET"):+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *_a, **_k: None)+ monkeypatch.setattr(dynamic_cadence, "cancel_cadence_rows", lambda _name: 0)+ monkeypatch.setattr(dynamic_cadence, "schedule_dynamic_workflow_cadence", lambda _defn: 1)++ async def no_errors(_defn: Any) -> list[str]:+ return []++ # The gateway isn't running here; its tool names are checked elsewhere.+ monkeypatch.setattr(wat, "_build_def", _build_without_gateway)+ monkeypatch.setattr(workflows_route, "validate_definition_and_tools", no_errors)+ people_registry.invalidate()+ yield path+ people_registry.invalidate()+++async def _build_without_gateway(definition: Any) -> tuple[Any, str | None]:+ return DynamicWorkflowDef.model_validate(definition), None+++def owner() -> Any:+ pid = people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email="[email protected]")+ people_registry.invalidate()+ return people_store.get_person(pid)+++def _prep(goal: str = "List John's calendar events for tomorrow.", tools: list[str] | None = None) -> dict[str, Any]:+ return {+ "name": "meeting_prep",+ "title": "Meeting prep",+ "steps": [+ {"kind": "action", "id": "find", "title": "Find meetings", "goal": goal,+ "tools": tools or [GATEWAY_READ]},+ {"kind": "synthesis", "id": "wrap", "title": "Wrap up"},+ ],+ }+++def _stored(owner: int | None = None) -> DynamicWorkflowDef:+ defn = DynamicWorkflowDef.model_validate(_prep())+ saved = dynamic_store.save_if_unchanged(defn, None, owner_person_id=owner)+ assert saved is not None+ return saved+++def _web(person: Any) -> Session:+ return Session(session_id="s-1", from_web_chat=True, caller_person_id=person.id, web_caller_signed_in=True)+++def _call(handler: Any, args: dict[str, Any], session: Session | None) -> dict[str, Any]:+ async def go() -> str:+ if session is None:+ return str(await handler(args))+ with set_session(session):+ return str(await handler(args))++ return dict(json.loads(asyncio.run(go())))+++def _fix() -> dict[str, Any]:+ return _prep(goal="List events on [email protected]'s calendar for tomorrow.")+++def _save_fix(session: Session | None) -> dict[str, Any]:+ d = _fix()+ return _call(wat.handle_save_workflow, {"definition": d, "confirm_token": wat._canonical_token(d),+ "overwrite": True}, session)+++# --------------------------------------------------------------------------- #+# The card+# --------------------------------------------------------------------------- #+++def test_the_card_says_what_changes_in_each_step() -> None:+ old = DynamicWorkflowDef.model_validate(_prep())+ new = DynamicWorkflowDef.model_validate(_prep(tools=["oe__my_calendar"]))+ text = workflow_change.card_text(old, new)+ assert text.startswith("Change the workflow “Meeting prep”")+ assert "Step “Find meetings”: now uses My calendar; no longer uses Google Workspace: get events" in text+ assert "wrap" not in text.lower()+++def test_new_removed_and_rescheduled_steps_are_named() -> None:+ old = DynamicWorkflowDef.model_validate(_prep())+ added = {"kind": "action", "id": "mail", "title": "Send it", "goal": "Email it.", "tools": ["oe__send_email"]}+ new = DynamicWorkflowDef.model_validate({**_prep(), "steps": [added, _prep()["steps"][1]]})+ lines = workflow_change.change_lines(old, new)+ assert any(line.startswith("New step “Send it”") and "Tools: Send email" in line for line in lines)+ assert "Removed step “Find meetings”" in lines+++def test_every_change_is_on_the_card_whole() -> None:+ old = DynamicWorkflowDef.model_validate(_prep())+ extra = [{"kind": "specialist", "id": f"s{i}", "title": f"Check {i}", "specialist": "finance",+ "goal": f"Look at item {i}."} for i in range(8)]+ long_goal = "List events on [email protected]'s calendar for tomorrow. " * 5+ new = DynamicWorkflowDef.model_validate({**_prep(goal=long_goal, tools=["oe__my_calendar"]),+ "steps": [*_prep(goal=long_goal, tools=["oe__my_calendar"])["steps"],+ *extra]})+ text = workflow_change.card_text(old, new)+ assert "now uses My calendar" in text+ assert long_goal.strip() in text+ assert all(f"“Check {i}”" in text for i in range(8))+ assert "more changes" not in text+++def test_a_change_too_big_for_one_card_isnt_staged(owner: Any) -> None:+ _stored()+ d = _prep(goal="List events on [email protected]'s calendar for tomorrow. " * 40)+ out = _call(wat.handle_save_workflow, {"definition": d, "confirm_token": wat._canonical_token(d),+ "overwrite": True}, _web(owner))+ assert "too big" in out["error"]+ assert decision_ledger.list_instances("app_action") == []+++def test_a_step_whose_settings_change_still_gets_a_line() -> None:+ old = DynamicWorkflowDef.model_validate(_prep())+ new_spec = _prep()+ new_spec["steps"][0]["max_tool_calls"] = 3+ new = DynamicWorkflowDef.model_validate(new_spec)+ assert "Step “Find meetings”: its settings change" in workflow_change.change_lines(old, new)+++def test_a_switched_on_tool_workflow_changes_only_on_a_card() -> None:+ approved = DynamicWorkflowDef.model_validate(_prep())+ pending = approved.model_copy(update={"is_active": False})+ assert workflow_change.needs_card(approved, approved)+ assert not workflow_change.needs_card(pending, pending)+ assert not workflow_change.needs_card(None, approved)+++# --------------------------------------------------------------------------- #+# Staging it from chat+# --------------------------------------------------------------------------- #+++def test_save_leaves_a_card_and_changes_nothing_yet(owner: Any) -> None:+ _stored()+ out = _save_fix(_web(owner))+ assert out["status"] == "waiting_for_approval"+ assert "[email protected]" in out["card"]+ stored = dynamic_store.get_definition("meeting_prep")+ assert stored is not None and "John's calendar" in stored.steps[0].goal # type: ignore[union-attr]+ card = decision_ledger.get_decision_instance(out["decision_id"])+ assert card is not None and card.decision_class == "app_action" and card.approver_person_id == owner.id+ chip = summarize_action(tool_name="save_workflow", tool_input={}, tool_result=json.dumps(out))+ assert chip is not None and chip["decision_id"] == out["decision_id"]+++def test_no_card_without_a_verified_speaker_or_where_it_cant_show(owner: Any) -> None:+ _stored()+ assert "know who is asking" in _save_fix(None)["error"]+ slack = Session(session_id="slack-dm-U1", origin_channel="slack", origin_channel_ref="U1",+ caller_person_id=owner.id)+ assert "error" in _save_fix(slack)+++def test_only_the_owner_or_its_creator_may_stage_a_change(owner: Any) -> None:+ ben_id = people_store.upsert_person(full_name="Ben Teammate", email="[email protected]")+ people_registry.invalidate()+ ben = people_store.get_person(ben_id)+ _stored()+ with set_session(_web(ben)):+ refused = workflow_change.may_read("meeting_prep")+ assert refused is not None and "account owner" in refused+++# --------------------------------------------------------------------------- #+# The tap+# --------------------------------------------------------------------------- #+++def _staged(owner: Any) -> int:+ _stored()+ return int(_save_fix(_web(owner))["decision_id"])+++def test_approving_on_the_web_saves_it_and_keeps_it_on(owner: Any) -> None:+ decision_id = _staged(owner)+ instance = decision_ledger.get_decision_instance(decision_id)+ request = SimpleNamespace(state=SimpleNamespace(), headers={"x-caller-email": "[email protected]"})+ asyncio.run(decisions_route._carry_out_app_action(instance, decisions_route.ApproveBody(), request, owner.id)) # type: ignore[arg-type]+ stored = dynamic_store.get_definition("meeting_prep")+ assert stored is not None and stored.is_active is True+ assert "[email protected]" in stored.steps[0].goal # type: ignore[union-attr]+ done = decision_ledger.get_decision_instance(decision_id)+ assert done is not None and done.status == decision_ledger.STATUS_APPROVED_UNCHANGED+++def test_a_telegram_tap_saves_it(owner: Any) -> None:+ decision_id = _staged(owner)+ instance = decision_ledger.get_decision_instance(decision_id)+ assert instance is not None and decisions_route.shown_in_chat(instance)+ asyncio.run(decisions_route.resolve_in_chat(decision_id, owner, approve=True))+ stored = dynamic_store.get_definition("meeting_prep")+ assert stored is not None and "[email protected]" in stored.steps[0].goal # type: ignore[union-attr]+++def test_a_tap_from_someone_no_longer_its_creator_changes_nothing(owner: Any, db: Path) -> None:+ import sqlite3++ tess = people_store.get_person(people_store.upsert_person(full_name="Tess Team", email="[email protected]"))+ people_registry.invalidate()+ _stored(owner=tess.id) # type: ignore[union-attr]+ out = _save_fix(_web(tess))+ assert out["status"] == "waiting_for_approval"+ with sqlite3.connect(db) as conn: # handed to someone else before the tap+ conn.execute("UPDATE dynamic_workflows SET owner_person_id = ? WHERE name = ?", (owner.id, "meeting_prep"))+ card = decision_ledger.get_decision_instance(out["decision_id"])+ assert card is not None+ staged = json.loads(json.loads(card.proposed_payload_json or "{}")["value"])+ with pytest.raises(HTTPException) as exc:+ asyncio.run(workflows_route.apply_chat_change(+ "meeting_prep", staged["definition"], staged["base"], ChatTap("[email protected]"),+ ))+ assert exc.value.status_code == 403+ stored = dynamic_store.get_definition("meeting_prep")+ assert stored is not None and "John's calendar" in stored.steps[0].goal # type: ignore[union-attr]+++def test_a_workflow_changed_since_the_card_is_left_alone(owner: Any) -> None:+ decision_id = _staged(owner)+ current = dynamic_store.get_definition("meeting_prep")+ assert current is not None+ dynamic_store.upsert_definition(current.model_copy(update={"title": "Renamed on the page"}))+ with pytest.raises(HTTPException) as exc:+ asyncio.run(decisions_route.resolve_in_chat(decision_id, owner, approve=True))+ assert exc.value.status_code == 409+ stored = dynamic_store.get_definition("meeting_prep")+ assert stored is not None and "John's calendar" in stored.steps[0].goal # type: ignore[union-attr]+++def test_a_change_that_reads_as_its_creator_needs_that_creator(owner: Any) -> None:+ ben_id = people_store.upsert_person(full_name="Ben Teammate", email="[email protected]")+ people_registry.invalidate()+ _stored(owner=ben_id)+ mine = _prep(tools=["oe__my_calendar"])+ with pytest.raises(HTTPException) as exc:+ asyncio.run(workflows_route.apply_chat_change(+ "meeting_prep", mine, dynamic_store.get_definition("meeting_prep").model_dump(), # type: ignore[union-attr]+ ChatTap("[email protected]"),+ ))+ assert exc.value.status_code == 403+++def test_other_app_cards_still_stay_out_of_chat_apps(owner: Any) -> None:+ decision_id = decision_ledger.create_decision_instance(+ decision_class="app_action", department="", originating_session_id=None,+ proposed_payload={"action": "delete_chat", "id": "s-1", "value": "", "title": "x", "card": "Delete"},+ idempotency_key=None, gate_mode="propose", approver_person_id=owner.id, confidence=None,+ )+ instance = decision_ledger.get_decision_instance(decision_id)+ assert instance is not None and not decisions_route.shown_in_chat(instance)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(decisions_route.resolve_in_chat(decision_id, owner, approve=True))+ assert exc.value.status_code == 404+++def test_do_in_app_cant_reach_the_hidden_action(owner: Any) -> None:+ assert workflow_change.ACTION not in app_control.DO_IN_APP_TOOL["input_schema"]["properties"]["action"]["enum"]+ out = _call(app_control.handle_do_in_app, {"action": workflow_change.ACTION, "id": "meeting_prep",+ "value": "{}"}, _web(owner))+ assert "Unknown action" in out["error"]+++# --------------------------------------------------------------------------- #+# Reading one, and the builder's note on whose calendar+# --------------------------------------------------------------------------- #+++def test_list_workflows_reads_one_for_its_owner(owner: Any) -> None:+ _stored()+ out = _call(wrt.handle_list_workflows, {"name": "meeting_prep"}, _web(owner))+ assert out["definition"]["steps"][0]["tools"] == [GATEWAY_READ]+ assert "know who is asking" in _call(wrt.handle_list_workflows, {"name": "meeting_prep"}, None)["error"]+++def test_the_builder_is_told_whose_calendar_gateway_tools_read(monkeypatch: pytest.MonkeyPatch) -> None:+ from openexecutive.workflows import designer++ monkeypatch.setattr(designer, "_exec_email", lambda: "[email protected]")+ mine = designer._accounts_line(True, "[email protected]", "[email protected]")+ assert "Executive's own ([email protected])" in mine and "oe__my_calendar" in mine+ assert "[email protected]" in mine+ theirs = designer._accounts_line(False, "[email protected]", "[email protected]")+ assert "oe__my_calendar" not in theirs and "write their address" in theirs+ assert "YOUR account" in json.dumps(wat.DEFINITION_SCHEMA)diff --git a/packages/core/tests/unit/test_workflow_designer_route.py b/packages/core/tests/unit/test_workflow_designer_route.pyindex d192eb2d..fbd5dd11 100644--- a/packages/core/tests/unit/test_workflow_designer_route.py+++ b/packages/core/tests/unit/test_workflow_designer_route.py@@ -590,7 +590,7 @@ def as_me_seen(monkeypatch: pytest.MonkeyPatch) -> list[bool]:seen: list[bool] = []- def _context(*, as_me: bool = False) -> str:+ def _context(*, as_me: bool = False, user_email: str = "") -> str:seen.append(as_me)return "CTX"diff --git a/packages/core/tests/unit/test_workflow_email.py b/packages/core/tests/unit/test_workflow_email.pyindex 98ec83e7..8e248f57 100644--- a/packages/core/tests/unit/test_workflow_email.py+++ b/packages/core/tests/unit/test_workflow_email.py@@ -412,7 +412,7 @@ def test_chat_cannot_replace_a_workflow_that_sends(people, monkeypatch: pytest.M{"definition": definition, "confirm_token": "tok", "overwrite": True},)))- assert "can't be replaced from chat" in out["error"] and saved == []+ assert "know who is asking" in out["error"] and saved == []def test_a_step_timeout_cannot_cut_a_send_short(on, composed) -> None:@@ -467,7 +467,6 @@ def test_chat_cannot_add_a_send_to_someone_elses_workflow(people, monkeypatch: pmonkeypatch.setattr(wat, "_build_def", build)monkeypatch.setattr(wat, "_canonical_token", lambda definition: "tok")- monkeypatch.setattr(wat, "_approved_tool_workflow_error", lambda name, existing: None)saved: list[Any] = []monkeypatch.setattr(dynamic_store, "save_if_unchanged", lambda *a, **k: saved.append(a))@@ -475,7 +474,7 @@ def test_chat_cannot_add_a_send_to_someone_elses_workflow(people, monkeypatch: p{"definition": {"name": "weekly_update"}, "confirm_token": "tok", "overwrite": True},)))- assert "can't be replaced from chat" in out["error"] and saved == []+ assert "know who is asking" in out["error"] and saved == []# ── Who an email goes to without asking ──────────────────────────────────────diff --git a/packages/ui/src/components/ChatAppActionCard.tsx b/packages/ui/src/components/ChatAppActionCard.tsxindex 3f6e0a48..2c45685b 100644--- a/packages/ui/src/components/ChatAppActionCard.tsx+++ b/packages/ui/src/components/ChatAppActionCard.tsx@@ -88,7 +88,7 @@ export default function ChatAppActionCard({ id }: { id: number }) {return (<article className="mt-3 rounded-2xl border border-line bg-surface-elevated p-4 sm:p-5"><div className="text-xs font-semibold uppercase tracking-wide text-accent">Needs your OK</div>- <div className="mt-1 text-base sm:text-[17px] font-semibold leading-snug text-fg break-words">+ <div className="mt-1 text-base sm:text-[17px] font-semibold leading-snug text-fg break-words whitespace-pre-line">{payload.card}</div>{done ? (