AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(delegation): let Drive, Docs and Sheets reads run after a mail read (#396)
Rufus643287cdfb1e
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 5cc8a0e6..3cec2e5f 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -7620,8 +7620,12 @@ integrations:result is rewritten from base64 to the file's text(_onedrive_content_as_text: drive_sync._extract on PDF / docx / xlsx /txt / md / csv, 20 MB, 200k chars; any other type gets a note pointing at- the ?format=pdf target). search-onedrive-files is in- PRIVATE_TURN_MCP_TOOLS beside search_drive_files. Not yet in+ the ?format=pdf target). search-onedrive-files, list-drives,+ get-drive-root-item, list-folder-files and get-drive-item are in+ PRIVATE_TURN_MCP_TOOLS beside the Google Drive reads, and download-bytes+ runs on a private or mail-touched turn only with a OneDrive content+ target (schedule_tools.is_onedrive_file_read; mail attachments stay out,+ as Gmail's do). Not yet inmemory.drive_reads (Google only).OneDrive sync token: `ms365-mcp-launch.sh --access-token` (only argumentallowed; after the placeholder scrub and cache-path defaults) execs@@ -7971,8 +7975,12 @@ integrations:exact allow-list: the Google Workspace reads the code already uses ordocuments (search_gmail_messages and get_gmail_message_content from theemail poller; get_events, list_calendars and query_freebusy from the- calendar surface below and the decisions route; search_drive_files, a- read in the Drive gate's tests) and the two gated Gmail tools+ calendar surface below and the decisions route; the Drive, Docs and+ Sheets reads search_drive_files, get_drive_file_content,+ list_drive_items, search_docs, get_doc_content, list_docs_in_folder,+ list_spreadsheets, get_spreadsheet_info, read_sheet_values and+ list_sheet_tables, each marked read-only by workspace-mcp and run with a+ read-only scope) and the two gated Gmail tools(send_gmail_message, draft_gmail_message), which the Gmail gate narrowsto the principal on such a turn. Not a server prefix: at the completetier much of Google Workspace reaches people with no recipient check —@@ -9192,9 +9200,16 @@ delegation:later turns read (the roster, goals, skills, alerts, open loops,decisions, standing facts, artifacts). Through MCP call_tool only theGoogle Workspace reads stay — Gmail message and thread content, Gmail- search, calendar and Drive search, and their Microsoft 365 twins- (MAIL_TOUCHED_MCP_READS, a subset of- PRIVATE_TURN_MCP_TOOLS). Every tool the Executive can be offered is in+ search, calendar, and Drive, Docs and Sheets search and file reads, and+ their Microsoft 365 twins, OneDrive file content included+ (MAIL_TOUCHED_MCP_READS, a subset of PRIVATE_TURN_MCP_TOOLS). File reads+ stay so "check my mail against the statements on the Drive" works in one+ conversation: in the reading turn nothing they return can reach anyone,+ and Drive reads are not remembered on such a turn+ (drive_reads.may_remember). Accepted residual: opening a file someone+ else owns registers a view in their file activity, so mail planted to+ steer which shared file opens could signal a few bits per read; no file+ content leaves. Every tool the Executive can be offered is inexactly one of MAIL_TOUCHED_ALLOWED_TOOLS / MAIL_TOUCHED_WITHHELD_TOOLS(a test fails on an unclassified one) and an unclassified name iswithheld. The dispatch guard in executive._stream_agent_loop refuses atdiff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex b843401a..288674c9 100644--- a/packages/core/openexecutive/architecture/prebuilt/agents.json+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json@@ -1,7 +1,7 @@{"section_id": "agents","title": "Agent Council",- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. `ask_about_person` reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive / OneDrive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`, today `load_mcp_server` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. On every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. `search_tools` is for anything not listed. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered whenever the gateway runs unless `CHAT_SCRIPTS=false`): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run, and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, or more than about ten items, while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5-5`, `claude-sonnet-5`, `claude-haiku-5-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. A **Quality** choice above the agents (`agents.presets`) sets every agent's model and deep reasoning at once: **Fast** puts every agent on a small model (`claude-haiku-5-5`, else `claude-haiku-4-5`) with deep reasoning off, **Balanced** returns each agent to its built-in defaults, and **Thorough** puts the Executive and the domain specialists on the largest allowed model (`claude-opus-5-5`, else `claude-opus-5`) with deep reasoning on where the model supports it, leaving triage and the helpers below on their defaults. Presets change quality only; they never cap spend. Each preset resolves against the install's model allowlist at request time and is offered only when one of its models is allowed. Applying one writes ordinary per-agent overrides (model and deep reasoning only), so history, rollback and later per-agent edits keep working; an agent changed on its own afterwards shows as **Custom**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by a shared picker in setup (`/onboard`, after the workspace choice) and in Settings → Executive, which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). One tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, or a team member once the owner lets them, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. From the round that calls it until the turn ends, the dispatch guard refuses every tool that reaches anyone else, fetches an outside address or writes shared or remembered state (`delegation.lockdown`; only reads, specialists and more drafts remain), without changing the offered list. The lockdown is that turn's alone (`TurnDelegation.read_mail`): a later turn in the conversation stays private to its owner and may again message and invite people on the roster (`lockdown.CARRIED_RELEASED_TOOLS`, each checked in its handler), but everything else the reading turn refuses — fetches, scripts, research, broadcasts, queued work, and writes others or later turns read — stays off for the whole conversation, since a reply can repeat what the mail planted. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**).\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.\n\n**Take the lead** (`orchestrator.take_the_lead`) is how the Executive acts on its own, behind one gate. It has two switches, both off until someone turns them on. **As the Executive** is the principal's alone (`PUT /take-the-lead`). With it on, the unattended passes (reflection, research, the scheduler's proactive trigger) keep the acting tools solo mode otherwise withholds from them: booking, starting workflows, and messaging teammates rather than only the principal. `schedule_tools.unattended_toolkit` and the chat loop's unattended path then wrap every acting tool (`ACTING_TOOLS`, plus any MCP tool whose name sends, creates, updates, deletes or shares) in `gated_handlers` / `gated_call_tool`. The principal-only tools (`UNATTENDED_WITHHELD_TOOLS`) stay withheld, and every guard inside a handler still applies, including department approval levels (a booking in a department on Proposes is still a proposal) and the contact-egress rule. New mail or chat (any turn with an `origin_channel`) wakes the existing reflection early (`take_the_lead.wake`): one run waiting at most, five minutes after the first message and no more than every 30 minutes, as a one-off `take_the_lead_wake` scheduled action. Pause holds it like any scheduled work. **As you** is the Handle it for me dial's top step (delegation section).\n\n**The gate** is plain code (`take_the_lead.check`). Six kinds of action wait for a yes first, each with an Ask first switch, all on to start. The switch is the decision ledger's own mode for the class `take_the_lead_action:<kind>` (`propose` asks first, the default; `auto_execute` doesn't). The kinds are money, contracts and legal, hiring and people decisions, deleting/cancelling/sharing, someone new (an address on neither the roster nor the contacts) and big sends (a broadcast or department message, or more than five people). On top of these, the company (set by the principal) and each person (for their own As you) add structured rules: a person or address, a domain, words, or an amount at or above a figure. Added rules always hold, and an error reading them holds the action. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. A held action becomes a `take_the_lead_action` decision instance with a companion `DECISION_ALERT_SOURCE` card on Today, routed to the first teammate holding one of its People approval ranges (`take_the_lead.approval_ranges`, plain code, closest fit first: money to `spend_lt_2k`, `spend_lt_10k` or `spend_gt_10k` by its largest amount, with a higher range able to approve a lower one and no amount read as large, or to `customer_credit` for credit and payment terms; vendor contracts to `vendor_onboarding` then `legal_sign`, other contracts to `legal_sign`; hiring to `hiring_signoff`; anything else about the board or investors to `board_comms`; in Personal as in team mode), or else the principal through the authority gate's fallback (`departments.authority._route_proposal`). Deletes and shares always go to the principal. Only the principal and that approver see or resolve it (`DecisionClassSpec.principal_and_approver`). Approving it claims the row and carries out the exact call once (`take_the_lead.carry_out`: the unwrapped handler, or the gateway's `call_tool`, on an unattended session, with contact egress only when the principal approves). Declining drops it. Everything done or held is a row in `take_the_lead_log`. What it did and what was approved show in Recent activity (`today._build_activity`, kind `took_the_lead`), named but never quoted, since that feed is the team's. The held card's own `decision_resolved` row is left out because its payload quotes the message. `GET /today/activity` also adds the caller's own Handle it sends (kind `sent_as_you`, actor `you`), which are never in the shared feed.",+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. `assign_open_loop` opens one on request (\"ask Ben to send me the Q3 numbers by Friday\") for the principal or a rostered teammate on a verified surface — never an email, a turn private to the principal or an unattended run, which are also withheld the tool — and only when `task` appears verbatim in what the speaker typed this turn, at most 5 per turn; that turn's extraction pass then opens no second loop for the same owner. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `email_aliases` (other addresses the person writes from — the full list, replacing the current one; they match mail and may be emailed but never sign in, and one already on someone else is refused), and after every write any pending roster request whose sender now matches someone is closed and its held messages replayed. `resolve_roster_request` answers a **roster request** — someone not on the People list who wrote in and is waiting (see Org): `approve` (a new person; `kind` defaults to team for a company-domain sender, else contact, when the principal did not say), `link` (someone already listed, by `person_id`; `replace_channel_id` only when the principal said so) or `decline`. It has the roster tools' gate (the principal on a verified surface; audited refusal otherwise), is in `UNATTENDED_WITHHELD_TOOLS`, and answers only an id in `Session.trusted_roster_request_ids` — the ids the server printed that turn in a `<roster_requests>` block (`briefing.context.format_roster_requests_for_prompt`, up to 10 pending requests), which `render_and_trust` appends to the `<briefing>` digest on the principal's own verified turn only and records on the session in the same step, so an id the model invents or reads out of a message adds nobody. Each line is server-derived — id, channel, address or account id, the sender's name sanitised and marked unverified, a company-domain hint, the message count — and never what they wrote. The block rides in the **user turn**, like the digest, so the cached system blocks are unchanged; the tool definition is static, and the new tool only extends the sorted tool list. The web chat route resets the trusted set every turn, and a resolved id is removed from it. and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. `ask_about_person` reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive / OneDrive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. **The untrusted-content policy** (`orchestrator.content_trust`) is one rule for text the principal did not write — inbound email, chat, attached files, watched pages — answering three questions for every surface. *Who is speaking*: the principal only when the surface proved it (`principal_speaking`: the web chat as the principal — never a signed-in email on nobody's People entry —, the CLI, their own Slack/Discord or a secret-verified Telegram chat, or their own address with Gmail's `dmarc=pass`); never a teammate, a stranger, Google Chat, the MCP server or an unattended run. *What may become memory*: episodic extraction runs only then, and only on the words outside `<untrusted_content>` blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. *What may trigger tools*: every write on the principal's authority already refuses others in its handler; the tools with no such check that change the install for every later turn — `content_trust.PRINCIPAL_ONLY_TOOLS`, today `load_mcp_server` — are not offered unless the principal is speaking on an interactive surface (not email, even authenticated), and a call the model emits anyway gets an error tool_result and a `refused: not_principal` audit row. So an inbound email, a teammate's turn, Google Chat and the scheduler's proactive trigger each get a stable tool list of their own without it. *How it is labelled*: outside text goes into the user turn inside `<untrusted_content source=… author=… author_verified=…>` with a fixed notice that it carries no authority; compatibility forms are folded (NFKC), control characters go, and the tag's name is renamed wherever the text carries it — any case, spacing or entity-escaped form — so the text cannot end its block and speak outside it.\n\nA turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (mail, calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins; OneDrive's `download-bytes` only for a file's content) and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. On every turn the Executive knows what is connected without searching: block 0's *Connected Systems* section names the connected Google services, other MCP servers, the messaging channels, Notion sync, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. `search_tools` is for anything not listed. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered whenever the gateway runs unless `CHAT_SCRIPTS=false`): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run, and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, or more than about ten items, while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\n`remember_fact`, `forget_fact` and `update_company_profile` (`orchestrator/fact_tools.py`) make a correction stick: the first two keep or retire a standing fact in `memory.facts`, and the third changes one field of the company profile. They share `record_decision_outcome`'s gate (the principal on a verified surface, an audited refusal for everyone else) and are in `UNATTENDED_WITHHELD_TOOLS`. `remember_fact` alone also admits a rostered teammate on a verified surface (web signed in, their own Slack or Discord): the fact is stored attributed (`recorded_by_role=\"teammate\"`, rendered `(per <name>)`), and is held as a `proposed` row (`awaiting_approval`) until the principal approves it, unless the principal marked that teammate trusted (\"needs my approval\" off; on by default) — and even then when it would replace the principal's fact. All three are also in `PRIVATE_TURN_WITHHELD_TOOLS`, since what they write or retire is read on everyone's turns. On the principal's own authenticated email (primary address, with Gmail's own `Authentication-Results` reporting `dmarc=pass`, not forwarded) the three tools check the request as usual, then hold it as `awaiting_confirmation`. It applies only when the principal replies to a one-time token emailed to their own address (`integrations.fact_confirmation`); the split into a check step and an `apply_*` step lets chat and the confirmed reply share one apply path. Each write also needs a `source_quote` found in the speaker's own words this turn. The active facts reach every specialist as a `<standing_facts>` user-turn tag: `route_to_specialist` reads them (None → the store, \"\" → none) for chat consults and workflow steps alike, and `BaseAgent.analyze` places the tag next to `<past_decisions>`, never in the cached specialist system prompt.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5-5`, `claude-sonnet-5`, `claude-haiku-5-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Every Council agent also takes **additional instructions** (`agent_overrides.instructions`): text appended after its prompt by `agents.overrides.append_instructions` inside an `<additional_instructions>` block. `BaseAgent.base_system_prompt()` is the built-in prompt or its full replacement (what the Council's editor shows); `effective_system_prompt()` is that plus the instructions (what every call sends), and the Executive gets the same text through `build_system_blocks(persona_instructions=…)`. Unlike a replaced prompt, instructions leave the agent on its built-in prompt, so prompt improvements keep reaching it. A **Quality** choice above the agents (`agents.presets`) sets every agent's model and deep reasoning at once: **Fast** puts every agent on a small model (`claude-haiku-5-5`, else `claude-haiku-4-5`) with deep reasoning off, **Balanced** returns each agent to its built-in defaults, and **Thorough** puts the Executive and the domain specialists on the largest allowed model (`claude-opus-5-5`, else `claude-opus-5`) with deep reasoning on where the model supports it, leaving triage and the helpers below on their defaults. Presets change quality only; they never cap spend. Each preset resolves against the install's model allowlist at request time and is offered only when one of its models is allowed. Applying one writes ordinary per-agent overrides (model and deep reasoning only), so history, rollback and later per-agent edits keep working; an agent changed on its own afterwards shows as **Custom**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by a shared picker in setup (`/onboard`, after the workspace choice) and in Settings → Executive, which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). One tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, or a team member once the owner lets them, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. From the round that calls it until the turn ends, the dispatch guard refuses every tool that reaches anyone else, fetches an outside address or writes shared or remembered state (`delegation.lockdown`; only reads, specialists and more drafts remain), without changing the offered list. The lockdown is that turn's alone (`TurnDelegation.read_mail`): a later turn in the conversation stays private to its owner and may again message and invite people on the roster (`lockdown.CARRIED_RELEASED_TOOLS`, each checked in its handler), but everything else the reading turn refuses — fetches, scripts, research, broadcasts, queued work, and writes others or later turns read — stays off for the whole conversation, since a reply can repeat what the mail planted. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**).\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. A run whose `result` event reports `private_to_principal` (the morning brief on the principal's own verified turn, when it read their private rows) still returns its artifact into that turn, but the stored run keeps `persistence.PRIVATE_RUN_ARTIFACT` instead of the text, since run history is readable by everyone signed in. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.\n\n**Take the lead** (`orchestrator.take_the_lead`) is how the Executive acts on its own, behind one gate. It has two switches, both off until someone turns them on. **As the Executive** is the principal's alone (`PUT /take-the-lead`). With it on, the unattended passes (reflection, research, the scheduler's proactive trigger) keep the acting tools solo mode otherwise withholds from them: booking, starting workflows, and messaging teammates rather than only the principal. `schedule_tools.unattended_toolkit` and the chat loop's unattended path then wrap every acting tool (`ACTING_TOOLS`, plus any MCP tool whose name sends, creates, updates, deletes or shares) in `gated_handlers` / `gated_call_tool`. The principal-only tools (`UNATTENDED_WITHHELD_TOOLS`) stay withheld, and every guard inside a handler still applies, including department approval levels (a booking in a department on Proposes is still a proposal) and the contact-egress rule. New mail or chat (any turn with an `origin_channel`) wakes the existing reflection early (`take_the_lead.wake`): one run waiting at most, five minutes after the first message and no more than every 30 minutes, as a one-off `take_the_lead_wake` scheduled action. Pause holds it like any scheduled work. **As you** is the Handle it for me dial's top step (delegation section).\n\n**The gate** is plain code (`take_the_lead.check`). Six kinds of action wait for a yes first, each with an Ask first switch, all on to start. The switch is the decision ledger's own mode for the class `take_the_lead_action:<kind>` (`propose` asks first, the default; `auto_execute` doesn't). The kinds are money, contracts and legal, hiring and people decisions, deleting/cancelling/sharing, someone new (an address on neither the roster nor the contacts) and big sends (a broadcast or department message, or more than five people). On top of these, the company (set by the principal) and each person (for their own As you) add structured rules: a person or address, a domain, words, or an amount at or above a figure. Added rules always hold, and an error reading them holds the action. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. A held action becomes a `take_the_lead_action` decision instance with a companion `DECISION_ALERT_SOURCE` card on Today, routed to the first teammate holding one of its People approval ranges (`take_the_lead.approval_ranges`, plain code, closest fit first: money to `spend_lt_2k`, `spend_lt_10k` or `spend_gt_10k` by its largest amount, with a higher range able to approve a lower one and no amount read as large, or to `customer_credit` for credit and payment terms; vendor contracts to `vendor_onboarding` then `legal_sign`, other contracts to `legal_sign`; hiring to `hiring_signoff`; anything else about the board or investors to `board_comms`; in Personal as in team mode), or else the principal through the authority gate's fallback (`departments.authority._route_proposal`). Deletes and shares always go to the principal. Only the principal and that approver see or resolve it (`DecisionClassSpec.principal_and_approver`). Approving it claims the row and carries out the exact call once (`take_the_lead.carry_out`: the unwrapped handler, or the gateway's `call_tool`, on an unattended session, with contact egress only when the principal approves). Declining drops it. Everything done or held is a row in `take_the_lead_log`. What it did and what was approved show in Recent activity (`today._build_activity`, kind `took_the_lead`), named but never quoted, since that feed is the team's. The held card's own `decision_resolved` row is left out because its payload quotes the message. `GET /today/activity` also adds the caller's own Handle it sends (kind `sent_as_you`, actor `you`), which are never in the shared feed.","mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo / sales<br/>board_comms / triage\"]\n Mode{{\"Team or solo<br/>(persona + tools per turn)\"}} --> Exec\n Exec -->|\"ghostwrite_email (Act as me)\"| Gw[\"ghostwriter<br/>(tool-less, not a Council agent)\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Mode compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external\n class Gw compute",- "generated_at": "2026-10-08T16:00:00Z"+ "generated_at": "2026-10-08T16:30:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/delegation.json b/packages/core/openexecutive/architecture/prebuilt/delegation.jsonindex 9e1a9983..7dabfdcf 100644--- a/packages/core/openexecutive/architecture/prebuilt/delegation.json+++ b/packages/core/openexecutive/architecture/prebuilt/delegation.json@@ -1,7 +1,7 @@{"section_id": "delegation","title": "Act as Me (Delegation)",- "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFour read-only tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply goes into their Drafts and waits on a private card on Today; nothing is sent until they tap **Send** (below). The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit in Gmail** (or **Edit in Outlook**) opens it there, to change the draft first or send it from there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Settings card shows it under the switch with how many went today.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. A follow-up such as \"book it\" therefore runs; the reply it builds on is the Executive's own, and every message, invite and email still reaches only people the roster allows. Only those come back: a later turn releases just `lockdown.CARRIED_RELEASED_TOOLS` (the DMs, `message_person` and calendar invites, each checked against the roster in its handler) and, through `call_tool`, `PRIVATE_TURN_MCP_TOOLS`. Everything else the reading turn refuses stays refused for the whole conversation, and an unclassified tool too: outside fetches and scripts (a URL could carry the mail anywhere), broadcasts and channel posts (no named recipient), queued work (follow-ups and workflows run later unattended, where they may fetch and research) and writes to state others or later turns read (facts, skills, the profile, the roster, documents), which would keep text the mail planted. The dispatch guard refuses them (`carried_withholds`) and the handlers that reach outside or post to everyone check again (`lockdown.outside_reach_refusal`). A channel adapter's own pre-turn rows are written as before. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also stops reaching anyone else (`delegation.lockdown`). From the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses every tool that sends, posts, invites, queues or starts work, fetches an outside address, or writes state that others or later turns read: the DMs and `message_person`, broadcasts, calendar bookings and cancellations, follow-ups, workflows and research, `read_document` and the watchlist, `load_mcp_server`, `run_python_job` (library work on files, kept for download), `run_script` (a script over the gateway tools is withheld whole, saved tools included; `list_saved_tools`, a local read of their names, stays allowed), roster, goal, skill and alert changes, open loops, decisions and standing facts. Through MCP `call_tool`, only the Google Workspace reads remain (the Executive's own Gmail message and thread reads, its calendar and Drive search). Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in a new message. The offered tool list never changes mid-turn, so the cached prefix holds. The send paths check again on their own (`_guard_outbound`, the broadcast, calendar, workflow, research and follow-up handlers, the gateway's `call_tool` and `load_mcp_server`). The server-side web search stays, as on a turn private to the principal. The lockdown lasts for that turn only.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and it tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, the **Write drafts as me** switch, the **Draft replies to my inbox** switch with its status in plain words, when it last checked and **Check now**, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit in Gmail** or **Edit in Outlook**, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Settings → Your Executive** (`app/settings/executive`, where `/settings/on-its-own` lands): the pause, **Take the lead** and **Book meetings without asking** (as the Executive). **Handle it for me** (the Off / Easy ones / People I know / Most mail / Everything dial, what each sends, how many went today and what it sent this week, as you) sits under the mailbox card on **Settings → Act as me**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.",+ "markdown": "The **delegation** module (`openexecutive.delegation`) is **Act as me**: the one place the Executive writes *as* a person instead of as itself. Everywhere else it has its own Google account and bots and signs as itself. Here — when the person asks, or, with a second switch, for mail in their inbox that needs them — it writes an email in their voice and saves it as a **draft in their own mailbox** — Gmail or Outlook — for them to review and send. The one thing it ever sends is one of those inbox drafts, exactly as it is in their mailbox: when the person taps **Send** on its card, or, with a third switch, **Handle it for me**, on its own when plain-code rules allow it (below); chat never sends. The principal can turn it on for themselves, and so can each team member once the owner lets them. It is off by default, and off changes nothing: the prompts, tool lists and prompt caches are byte-identical to an install without it.\n\n## Who can have it, and when it is offered\n\n`delegation.settings.can_delegate(person)` is the single rule for who may turn it on: the principal (a non-archived team member flagged `is_principal`), and any other non-archived team member — never a contact — once team members may have it (`team_members_enabled`). That takes two things: the install allows it (`DELEGATION_TEAM_MEMBERS`, default off, which offers the owner the switch) and the owner turned on **Let team members use it** (`PUT /delegation/team`, principal only, one row in `delegation_team`). Turning the owner's switch off takes it away from every team member from their next message, and their inbox watchers stop at their next check; their own switches, drafts and cards are kept. Everything is keyed by `person_id`. A person turns it on for themselves (`PUT /delegation`); nobody turns it on for anyone else. The setting is one row per person in `delegation_settings`, and a missing, unreadable or zero row all mean off.\n\nAt the start of every chat turn (`Executive.stream_chat` and the committee path) `pin_turn_delegation(session, speaker_text)` runs next to the workspace-mode pin and records a `TurnDelegation` on the session. `ghostwrite_email` is **offered** only when all of these hold:\n\n- the speaker may have it and turned it on — read fresh every turn, so turning it off applies from the next message;\n- the speaker is on a surface that verified it is them — the principal through `people_tools.is_principal_on_verified_surface`, a team member through `teammate_on_verified_surface` (the web app signed in, their own Slack or Discord, never an email turn) — and a web turn also carried a signed-in caller (`Session.web_caller_signed_in`, set from `x-caller-email`) or runs under local login — a request with no caller header is not a sign-in and never gets it (whoever holds the shared secret is trusted as the UI proxy that stamps that header, as on every principal-only route);\n- the conversation is private to the speaker: the web chat, a Slack or Discord DM, or a verified private Telegram chat — never a shared channel or thread, where the draft's preview or the matching threads would be posted for everyone and other people's messages sit in the model's context;\n- the turn is neither unattended (the scheduler's proactive run) nor private to the principal (the email poller's turns), so inbound text can never reach it. The MCP server, workflows, reflection and research never carry it at all.\n\nThe mailbox connection is deliberately **not** part of the offer: the handler checks it on every call and says how to fix it, so the cached tool prefix never flips when a token lapses. The pin lives in a context variable for the turn's task as well as on the session, so two turns running at once on one session (a second browser tab) each read their own. It also carries the speaker's own words for the turn (a new email may go to an address they just typed — the turn's message joins the history only once the turn ends), a per-turn draft count, and `touched_mail` (see Privacy). `own_words` reads those words back for every own-words check (addresses here, facts and task assignments elsewhere): it first removes the hydrated `<outbound_reply_context>` backstory by its exact, anchored shape, so a look-alike closing tag quoted inside it cannot pass the rest off as the speaker's, then drops other adapter tag blocks, and returns nothing for a message carrying an attachment.\n\n## The tool: `ghostwrite_email`\n\nIt lives in its own registry (`orchestrator.delegation_tools.DELEGATION_TOOLS` / `DELEGATION_TOOL_HANDLERS`), **never** `_ALL_SKILL_TOOLS`, so no other toolkit can carry it. On a turn it is offered to, the agent loop adds it to the pool *before* the sort and builds that turn's handler map from both registries; on any other turn a call to it is an unknown tool. The handler re-checks the pin and the surface anyway, then:\n\n1. **Caps** — at most 5 drafts per turn, and `DELEGATION_MAX_DRAFTS_PER_DAY` (default 50, at most 1000) per person per UTC day, shared with the inbox watcher (`delegation.caps`). It is counted from `delegation_drafts`, one row of ids per draft saved from either place, with a count kept in the process as a floor in case a row was lost. Each slot is taken before the first await — a round's tool calls run concurrently, so otherwise every call in it would pass the caps before any counted — and handed back if nothing was drafted. If the rows can't be read it refuses rather than guess.\n2. **Marks the turn** — sets `TurnDelegation.touched_mail` *before* its first read of the mailbox.\n3. **Checks the mailbox** — `gmail_status` asks Google or Microsoft whose mailbox the credential opens and compares it with the person's People email, on every call: a roster email can change, and a client slot swaps the roster.\n4. **Finds the thread** — by `thread_id` (checked against the mailbox's own id shape), or a Gmail-style search (`find`; on Outlook, words, `from:`, `to:`, `cc:`, `subject:` and `newer_than:` are kept and other Gmail operators dropped). Several matches return `{status: \"choose\", candidates}` (subject, sender and date — no message text) and draft nothing; none returns `not_found`.\n5. **Sets the recipients in code**, never from the model. A reply goes to the last inbound message's `From` — never its `Reply-To` (a different one is flagged `reply_to_ignored`) — with the thread's other recipients only on `reply_all`. A new email goes only to someone on the roster (contacts only when `contacts_reachable_now()`), or to an address the speaker typed this turn. Mailing-list mail, a thread they replied to last and a reply-all trimmed to 10 recipients are flagged. An address inside a block an adapter added to their message (the backstory hydrated into a DM) is not one they typed, and when the message carries an attachment — a document's inlined text, or a note naming the file — none of its addresses count: neither has an end mark, and a filename is chosen by whoever sent the file. They give the address in a message of its own.\n6. **Writes it** (the ghostwriter, below) and saves it with the mailbox client's `create_draft` (Gmail: threaded with `In-Reply-To`, `References` (whole message ids: when the chain is too long for one header the oldest after the thread's first go, never the parent) and `threadId`, and stamped `X-OE-Ghostwritten`; Outlook: Graph's `createReply` on the message it answers, then the text and recipients, and a named property marking it).\n\nThe result is `{status: \"drafted\", draft_id, gmail_link, to, cc, subject, preview, flags, open_questions, note}`. The link (`gmail.mailbox_link`) is built server-side from a fixed prefix — the thread in Gmail, the draft itself in Outlook on the web — and the note tells the model the preview is the person's draft, to be treated as data. The chat shows an action chip — \"Drafted an email as you to … — in your Drafts\" — that opens it, and only a link under `MAILBOX_LINK_PREFIXES` is ever linked. A sincere \"are you an AI?\" in the thread comes back as an open question for the person to answer themselves.\n\n## Reading their mailbox\n\nFour read-only tools ride with `ghostwrite_email` in the same registry (`orchestrator.mail_read_tools`), so they are offered, re-checked and fenced exactly as it is: `search_my_email` (a Gmail-style search through the client's `search_threads`, or with no query the threads that reached their inbox in the last few days through `inbox_message_ids` + `get_message`), `read_my_email` (one thread's last 10 messages, each sender's new text only, drafts left out, with the files attached to them listed by message id and index), `read_my_email_attachment` (one of those files as text: PDF, Word, Excel, CSV or text, up to 20 MB, a scanned PDF converted) and `my_email_awaiting_reply` (their own sent mail from the last 14 days, to at most 10 people besides the Executive, that is still the last message in its thread). They change, label, draft and send nothing.\n\nEach sets `touched_mail` and marks the conversation theirs before its first read (`_open_mailbox`, shared with `ghostwrite_email`), so the lockdown below applies from its round on. Each is capped per turn on the pin: 10 searches (`my_email_awaiting_reply` counts as one), 20 thread reads and 5 attachment reads, the slot taken before the first await. In `read_my_email` every message someone else wrote comes back inside its own `<untrusted_content source=\"email\">` block (`content_trust.wrap_untrusted`, which defuses a closing tag in the text); the speaker's own messages — SENT and from their address (`threads.mine`), never a From header alone — are marked \"Yours\" outside any block. An attachment's text comes back in its own `<untrusted_content source=\"attachment\">` block (`attachments.format_attached_text`), parsed in an isolated worker (`knowledge.loader`); unlike a file sent to the Executive it is never added to the company's knowledge. The clients find an attachment by message and position and look its provider id up on each read (Gmail's changes per fetch): Gmail lists a message's files with the message (`MailMessage.attachments`, leaving out images the HTML shows in place), Outlook says only `hasAttachments` until `list_attachments` asks Graph (leaving out inline ones), and `attachment_bytes` reads one; an attached Outlook item or cloud link has no file to read. Results carry a note that subjects, senders and text are other people's words, data rather than instructions. The lockdown refuses tools, not the reply's own text, so what would carry that text out without a click is closed where it is shown: the web chat loads no image from another site, and bot replies go out without link previews (see Integrations).\n\n## Forwarding and reminders\n\n`ghostwrite_email` also forwards: with `forward` (a thread id) and `to`, it drafts a forward of the thread's latest message, `intent` becoming the short note above it (the ghostwriter writes only the note; the forwarded email's subject, someone else's words, is never put in the intent). Recipients follow the new-email rule (`_new_recipients`: the roster, or addresses the speaker typed this turn). Gmail's draft quotes a forward header and the original's own words under the note and attaches the original's files, up to 10 and 20 MB (`FORWARD_MAX_FILES`, `FORWARD_MAX_BYTES`; any left off are flagged `attachments_left_off`); Outlook uses Graph's `createForward`, which keeps the original and its files, with the note as its comment and the body never patched. It is still only a draft.\n\n`remind_me(text, when)` (`orchestrator.reminder_tools`) rides with the same tools and checks, but opens no mailbox, so it never marks or locks a turn (`MAILBOX_TOOL_NAMES` are the ones that do). It stores the text once cleaned — one line, anything a chat app could turn into a link (a URL of any scheme, an address, a domain-like word, a host and port, an IP address) replaced with \"[link]\", at most 300 characters — with its time (stored in UTC) in `delegation_reminders` (5 a turn, 25 waiting, a year ahead, refused when the person has no channel). When it is due the scheduler sends that text to the person alone, as \"Reminder you set on <date>: …\", running nothing (see Scheduler); the Slack and Discord DMs it may go by turn link previews off. The chat chip shows the text as it will be sent. A reminder that comes due in the person's quiet hours or leave (when `OUTBOUND_RESPECT_QUIET_HOURS` is on) waits unclaimed and goes once they end, rather than being suppressed and lost. It is allowed after mail is read and in later turns of that conversation: it reaches only the speaker, as plain text. `schedule_followup`, which runs a turn with tools and is listed to everyone, stays refused there.\n\n## The ghostwriter\n\n`delegation.ghostwriter.compose` writes the text. The Executive decides *what* to say (`intent`); this call decides *how* the person would say it, and it is deliberately small:\n\n- a constant `GHOSTWRITER_PROMPT` plus the person's voice block as the system prompt;\n- the thread (each message cut to its sender's own words, every line scrubbed, all labelled alike), then the writer's own earlier words in it (`<writer_said>`, from their sent mail only), the intent and the recipients' names in the user turn — no company profile, memory or roster;\n- with Always in the loop on, `<writer_noted>`: what the writer's own notes say they told these same people in earlier Act as me replies (`memory.history_drafts.notes_for_draft`: only notes from mail **every** recipient of the new draft was on, so nothing told to one person reaches another; chat notes name no recipient and never qualify; at most 8, newest first, the person's own words or their correction, with dates). The prompt's rule 6 makes it a consistency check, never content: a draft that contradicts it is still written as the intent says, and the conflict becomes an open question on the card, which only the writer sees. Both the chat tool and the inbox watcher pass it;\n- **no tools** but the forced `compose_reply` return, so text in the thread can ask for anything and there is nothing to do it with.\n\nIt is not a Council agent — the Council's edit routes have no principal check — and runs on `DELEGATION_COMPOSER_MODEL` (default: the default model), logged as `ghostwriter` usage. `lint` then runs in code on what comes back: a link or an email address survives only if it appears in the intent, the signature or the recipients, so a link planted in the thread is removed and flagged; the Executive's own name is flagged; and the body is capped, cut at a paragraph, line or word break in its last fifth. A draft with nothing left after that is refused. The signature from the person's Gmail settings (or the one already stored, for Outlook) is appended.\n\n## How I write\n\n`delegation.voice` learns how a person writes *their own* email (`attunement.style` learns how the Executive should write *to* someone). `POST /delegation/voice/learn` reads up to 40 recent sent messages, keeps only what they wrote (quoted replies stripped with the email poller's `sender_new_text`), skips automatic mail, every thread chat drafted into, and every sent message that began as a draft written for them (`delegation_drafts.sent_message_id`), and makes one forced-tool call (`record_voice_profile`). Code validates every field before it is stored:\n\n- greetings per audience (their team, their contacts, anyone else), a sign-off of at most two lines, and a usual length and tone (a backslash-n the model wrote instead of a line break is read as one, keeping the first lines that fit, which also repairs a profile stored before that rule);\n- up to 8 habits and 6 things to avoid, through the same deny-list as working-style rules — no actions, links, handles, amounts, tool names or names of people;\n- up to 3 short exemplars, each checked to be verbatim from a sample, with addresses and phone numbers masked — and none while a client slot is active, so one client's mail never lands in another's state.\n\nThe signature comes from Gmail's `sendAs` settings, not the model (Outlook gives apps no way to read one, so a learn keeps the stored signature and `POST /delegation/voice/signature` answers 409 `signature_unavailable` rather than clearing it), as plain text with its lines kept (`gmail.html_to_text`: a `<br>` always ends a line, and a block tag, opening or closing, ends one when it has text, so Gmail's layout of a first line followed by one `<div>` per line comes out line by line). `POST /delegation/voice/signature` reads it again without relearning: nothing else changes and a locked profile stays locked, so it picks up a changed Gmail signature and undoes **Don't add my signature**. A person can also describe their style in their own words: `POST /delegation/voice/describe` applies the description to the profile they have through the same forced tool (a separate system prompt, no exemplars) and the same validation, keeps their signature and writing examples, and returns the result with a short sample reply for them to review. It saves nothing and needs no mailbox; Save stores it as an ordinary edit. The person can edit the profile, lock it (a locked profile is never relearned) and reset it, and every change is kept in `delegation_voice_history`. One learn runs at a time per person, and a lock or an edit made while it runs wins: the learned profile is dropped (`changed`).\n\n## Draft replies to my inbox\n\nA second switch under Act as me, **Draft replies to my inbox** (`delegation.inbox`), has the Executive watch the person's own inbox and write a first reply to mail that needs them. The reply goes into their Drafts and waits on a private card on Today; nothing is sent until they tap **Send** (below). The switch is one row per person in `delegation_inbox_watch`. Turning it on needs Act as me on and their mailbox connected, and sets `watch_since` to now every time, so it never drafts for mail that arrived before; turning Act as me off turns it off too. Off means no mailbox call and no row written, with one exception: a send the person started that the mailbox never confirmed is still followed through until it is settled.\n\n### When it looks\n\nA throttled hook in the scheduler tick (`_maybe_scan_inbox`, after the pause, company-profile and rotation gates) checks each person whose switch is on every `DELEGATION_INBOX_POLL_MINUTES` (default 5). It is not a scheduled action, because those are listed on `/scheduled` for everyone and anyone may cancel them. One scan task runs at a time, one scan per person, and none while a client slot is active. **Check now** on the Settings card runs the same scan. Every row a scan writes is private and the person's own (`audit.rows_for_person`: a team member's rows are hidden from the principal too, see Privacy), and the process log carries counts and codes, never an address or a line of mail. The scan never marks mail read or changes a label.\n\n### What it drafts for\n\nA scan first settles the open cards (below), and stops with `backlog_full` once 25 are waiting, counting the ones it makes. It then lists the inbox since `watch_since` (`inbox_message_ids`) — not chats, not mail from the person, and not the promotions, social, updates or forums tabs (on Outlook: the Focused inbox only) — up to 100 messages, and takes the newest message of each thread that still needs a look, at most 10: settled threads and threads with an open card are passed over first, so a burst of mail, or a pause for a limit or a back-off, never hides older threads for good. `delegation_inbox_messages` is its durable cursor: one row per message (`UNIQUE(person_id, message_id)`) with what happened to it, the reason, how many tries it took, and the draft and card ids. It stores a hash of the sender's address, never the address. A message is skipped, with the reason recorded, when:\n\n- it came before `watch_since`, or more than three days ago;\n- it is from the person or one of their send-as addresses, from the Executive, or one of this module's own drafts;\n- it is automatic — `Auto-Submitted`, a bulk or auto-reply `Precedence`, a bounce, a calendar invite or a no-reply sender — or from a mailing list, or in a Gmail tab, spam or trash;\n- the person is not in To or Cc, or it has more than 10 recipients;\n- the person replied last, or a draft already sits in the thread.\n\nThree kinds are left unrecorded, so a later scan looks again: mail under 10 minutes old (mail the person answers straight away never gets a card), mail in a thread whose card is still open, and mail a daily limit holds back.\n\n### Deciding, then writing\n\nTwo model calls, and code decides between them. The classifier (`delegation.inbox_classifier`) is one forced-tool call, `classify_email`, returning whether the email needs a personal reply, what kind it is and how sure it is. It sees a few one-lined header lines and the sender's own new words (at most 3000 characters, every line scrubbed) inside one `<email>` block marked as data, and it has no other tools, context or memory, so an email can ask for anything and there is nothing to do it with. A reply is drafted only for a question, a request, scheduling, an introduction or a follow-up, and only when the confidence clears a bar that rises the less the sender is known: 0.6 for their team or a contact (the principal's contacts count only for the principal: a team member's mail is weighed by the team and their own sent mail), 0.7 for someone they have written to before (`has_written_to`, a search of their sent mail), 0.85 for a stranger. Pitches, notes of thanks, FYIs, notifications, newsletters and phishing get nothing, and so does any failure. An email that also went to other people is drafted for only when the person is in To and it asks them themselves: the classifier is told their name, whether they are in To or Cc and how many others it went to, and lists the names the email greets or asks by name (`asked_names`). Code matches those against the person's name, whole name parts only (\"Alexis\" never counts for \"Alex\", and a nickname misses, which means no draft), so mail that greets someone else (\"Good morning, Brennan, could you sign ...\") is never theirs, whatever the model makes of it as a whole. When it names nobody, the model's `asked_of_them` decides, false for a question to the group at large. One that only copies them is never drafted for. Either is recorded `not_needed` with the reason `asks_someone_else`. It runs on `DELEGATION_CLASSIFIER_MODEL`, else the routing model. A sender whose address Gmail couldn't authenticate is handled as a stranger whatever the roster says — anyone can put a colleague's or a client's address in From — so they get the stranger's bar, a holding reply and the stranger limits; the card still says who they claim to be, and that the address isn't verified.\n\nThe reply is written by the same ghostwriter, in the person's voice, but from a fixed intent the module builds rather than words the person typed. Because the intent lets it restate the person's own earlier words, which words are theirs is never written inside the thread, where a sender could imitate any marker with a look-alike: every message there is labelled alike, and the person's own words come in a separate `<writer_said>` block after the thread, taken only from mail their own mailbox sent. Nothing inside the thread can close the thread block or open another. The intent: acknowledge the sender; say again only what the person's *own* earlier messages in the thread already said; commit to nothing new — no yes or no, date, time, price, fact or promise — and say they will get back to them; and put every question it could not answer from their words in **open questions**. A stranger always gets a short holding reply. The lint still strips any link or address that isn't the person's own. The reply goes to the sender (never `Reply-To`) and, on a group email, to everyone else it went to as Cc (reply to all, never the person's own addresses or the Executive); a stranger's holding reply goes to the sender alone. The card says when others were on the email, and its `draft_to` lists everyone, which Send checks.\n\nThe order: record the message, classify, reserve a slot in the shared daily limit, write, save the draft in Gmail (from the alias the mail went to, when it went to one) and store its id, then create the card (idempotent on the message) and mark it drafted. Nothing that fails along the way loses the message. A failure that may pass — the classifier or the writer failing, Gmail refusing the draft, a card that couldn't be made (its draft is deleted first, so no draft is left without a card), any other error with that one message — leaves it for a later scan (`retry`), and it is given up on only after three tries; one message's trouble never holds up the rest. A daily limit reached while it was being read leaves it for later without counting as a try.\n\n### The reply cards\n\nA card is a `delegation_reply` decision whose class is **its approver's alone** (`DecisionClassSpec.approver_only`): only the person it was drafted for sees or resolves it on any decisions route — a team member's card answers 404 to the principal too — and it is never an alert: alerts feed chat turns, which would put other people's mail into memory. It carries the sender with who they are to the person and whether Gmail could verify the address (SPF/DKIM/DMARC, through `fact_confirmation.headers_authenticated`), the subject, what they wrote, the draft, the open questions and its warnings. `GET /delegation/replies` lists the open ones from the database alone, so Today never waits on Google.\n\n- **Send** approves the card, which sends its draft exactly as it is in their mailbox (see *Send on your tap*). **Edit in Gmail** (or **Edit in Outlook**) opens it there, to change the draft first or send it from there.\n- **Dismiss** rejects the card; the class's after-reject step then deletes the draft if nobody edited it — its message id is still the one it was saved with, since Gmail gives an edited draft a new one, and the Outlook client makes a draft's message id `<id>.<changeKey>` so an edit there changes it too — and keeps it otherwise. What happened is recorded even when Gmail fails.\n- Each scan first **settles** what Gmail already settled: a draft sent from Gmail, a draft deleted there, a reply the person wrote themselves, a thread that is gone, or a card left for 7 days (its draft stays in Gmail). Each is a compare-and-set close with the reason. A newer message from someone else flags the card instead. A card being sent at that moment is left alone.\n\n### Send on your tap\n\n`delegation.reply_send` is the only thing in Act as me that sends, and all it can send is the draft on a card, by its id: `DelegateGmail.send_draft` posts `{\"id\": …}` to Gmail's `drafts.send`, and `DelegateOutlook.send_draft` posts an empty body to that draft's Graph `send`, and nothing else, so no text, recipient or header is ever passed. It has two doors: `send_approved_reply`, reached only from `POST /decisions/{id}/approve` — a class only the card's own person may resolve — and `send_on_its_own`, reached only from the inbox watcher under Handle it for me (below). AST tests pin both call sites, so no model, chat turn, workflow, scheduled job or MCP call can. A tap is checked like this: At send time it checks everything again:\n\n1. **Who is asking.** The caller is the card's person and the API knows it: signed callers are on and the request carries that person's signed assertion (or the operator's, under local login), or the API runs for local login and answers this computer only. Anything else is a 409 `caller_signing_required` — with only the shared secret, whoever holds it could send as the owner — so on a server Send needs signed sign-ins.\n2. **The switches.** Act as me and Draft replies to my inbox are on, and no client slot is active.\n3. **The mailbox.** Their mailbox is connected.\n4. **The draft.** It still exists, in the same thread, and they haven't replied there themselves since; otherwise the card closes.\n5. **Who it goes to.** To, Cc and Bcc hold between 1 and 10 addresses, never the Executive's own, and it is from one of their own addresses.\n6. **What changed.** Recipients that differ from the card's, or a newer message from someone else, need a second yes: the first tap gets a 409 `confirm` naming the recipients and the reason, and the person approves again with what they were shown.\n\nThen it claims the card (`claim_for_execution`, proposed → executing, a compare-and-set, so a double tap sends once) and reads the draft once more: `drafts.send` sends whatever the draft is when Gmail gets the request, so if it was edited since the checks read it — in another tab, by a delegate — nothing is sent and the card comes back (`draft_changed`). Then it sends, and records the result: `approved_with_edit` when the draft was edited in Gmail, the sent message's id, the draft row's `sent_message_id`, and a private `delegation_reply_sent` row. A refusal that proves nothing went — a 4xx, a lapsed sign-in, a rate limit, a draft already gone — hands the card back. A failure that leaves it unclear — a timeout, a 5xx — leaves it `executing` and says to check the Sent folder, and the next scans ask Gmail: their message in the thread means it was sent; anything else is judged on the second scan that sees it: the draft still there and nothing sent means it was not (Gmail deletes a draft it sends), and the card comes back, flagged; the draft gone and nothing sent means it was deleted. Nothing is ever retried on its own. Sending is the person's own act, so it works while the Executive is paused.\n\n### Limits and failures\n\nAt most 5 drafts a scan; `DELEGATION_INBOX_MAX_DRAFTS_PER_DAY` (default 20) a day, inside the shared `DELEGATION_MAX_DRAFTS_PER_DAY` it shares with chat; 200 classifications, 2 drafts per sender (1 for a stranger) and 10 for strangers in all per day; and never more than 25 open cards. A lapsed Gmail sign-in sets the status and is looked at again every 30 minutes; a rate limit, an error reaching Gmail or a crash backs off from 5 minutes, doubling up to 2 hours. Neither turns the switch off: the Settings card shows the status in plain words.\n\n## Handle it for me\n\nA third switch under Act as me, **Handle it for me** (`delegation.handle_it`), lets the inbox watcher send some of its replies itself instead of leaving them on a card. It is one row per person in `delegation_handle_it` (`enabled`, `mode`); no row means off. One setting says how much goes without them, the way quality does on the Agent Council (`handle_it.RULES`): **Easy ones** (`careful`) sends only replies to people they know (someone on their team, a contact or someone they have written to) of at most 400 characters when the classifier is at least 0.9 sure; **People I know** (`balanced`), where it starts, sends replies to people they know up to 1200 characters at 0.8; **Most mail** (`bold`) also answers strangers, up to 2000 characters, and lets a link or an amount through when the classifier is at least 0.9 sure. Everything else waits on a card as before, so turning it on never drafts less. A table from before the setting gets the `mode` column on its next open (`schema._add_handle_it_mode`): someone who had strangers set to send keeps that as Bold, everyone else gets Balanced. Only the person turns it on (`PUT /delegation/handle-it`), from a session the API knows is theirs: the same rule Send uses (`delegation.verified.caller_refusal`), so with only the shared secret it answers 409 `caller_signing_required`. Turning it on needs Act as me and Draft replies to my inbox on, and turning the inbox watcher off (or Act as me, which turns it off) turns it off too.\n\n**No model decides whether a reply goes.** The watcher's two model calls are unchanged and tool-less, so text in an email can at most change the verdict and the draft. After the draft is written, `handle_it.refusal` — plain code — decides, and anything it refuses becomes the usual card with the reason kept on it (`handle_it_reason`). It refuses when:\n\n- it's off, or the sender is a stranger and the setting isn't Bold, or on a server signed sign-ins are off (`signing_ok`: signed callers, or local login);\n- Gmail couldn't authenticate the sender, whatever the roster says;\n- the email isn't a question, request, scheduling, introduction or follow-up, or the classifier was less sure than the setting needs (0.9 on Easy ones, 0.8 otherwise);\n- the reply goes to anyone the email didn't already go to (its From, To and Cc, less the person's own and the Executive's addresses), leaves out the sender, or goes to more than 10;\n- the email's subject, the sender's new words, or the reply touch money, contracts, legal, hiring, pay, layoffs, the board, investors, mergers, the press, health, or credentials and secrets (passwords, logins, tokens, API keys); or the reply carries an amount, a percentage or a link (a scheme, `www.`, a bare host with a path such as `bit.ly/…`, or a bare host on a common top-level domain) unless it's Bold and at least 0.9 sure, or runs over the setting's length (400, 1200 or 2000 characters);\n- the draft carries any flag but *others on the thread* or *Executive on the thread* (they asked if it's an AI, recipients were trimmed, …);\n- it already sent one in this thread in the last day, or the person's last message in the thread was itself sent on its own (no auto-reply ping-pong);\n- the day's limit is reached (`DELEGATION_HANDLE_IT_MAX_SENDS_PER_DAY`, default 20, within the watcher's drafts limit), or it can't be counted. Any error in the rules counts as a refusal.\n\nA reply the rules allow gets a card with `gate_mode` `auto_execute`, and the watcher sends it at once through `reply_send.send_on_its_own`, the second and last door into the send path (an AST test pins both callers: the approve route and the watcher). It runs the same send-time checks as a tap — switches, mailbox, draft, recipients, the claim and the last re-read — with no caller, and adds its own: the card must be `auto_execute`, Handle it for me still on with the setting still allowing that sender (or, for a follow-up, that recipient), signing still on, the once-a-thread-a-day rule and the daily limit counted again, and the draft untouched since it was saved (an edit in Gmail means the person has taken it over: `draft_changed`, the card waits for them). Every refusal hands the card back to the person (`decision_ledger.hand_back`, a compare-and-set to `propose`), with the reason kept on it when there are words for it, and a failure never stops the scan. Every card it left for the person says why on Today (`waited_because` on `GET /delegation/replies`). A reply sent on its own finishes as `executed` (not approved), is recorded in `delegation_handled` (for the per-thread and daily rules) and writes a private `delegation_reply_handled` row; an unconfirmed one is settled by the reconciler the same way. No History note is taken from it, since notes come only from the person's own words. It runs inside the watcher's scan, so it stops while the Executive is paused.\n\n**Follow-ups as you** (`delegation.follow_ups`). While Handle it for me is on, the watcher's scan also looks at the person's own sent mail, at most once an hour (`LOOK_EVERY`), for an email of theirs that asked something (a question mark in their own words), is 3 to 10 days old, went to at most 10 people other than the Executive, and is still the last message in its thread. Plain code picks it; each gets one follow-up ever (its `delegation_inbox_messages` row), at most two a look, within the drafts limit. The ghostwriter, tool-less as always, writes a short nudge in their voice from the thread, saved as a draft in that thread to exactly the people the email went to. `handle_it.follow_up_refusal` — plain code — decides whether it goes: by the setting it never goes on Easy ones, goes to their team and contacts on People I know and to anyone they wrote to on Most mail (`follow_up_refused` otherwise: `follow_up_level`); it also refuses on any change of recipients, a sensitive topic, an amount or a link, more than 600 characters, a flag, and the same per-thread and daily counts as replies. It goes through `send_on_its_own` on an ordinary `delegation_reply` card marked `source: follow_up`, which rechecks the setting for that recipient. A refused one waits on Today as **Follow-up waiting**, and closes by itself (its untouched draft deleted) when anyone answers in the thread first.\n\n**What it sent** is the person's alone: `GET /delegation/handled` lists the last 7 days (who, subject, the reply, the questions it left them and a link to the thread in their mailbox), and the Settings card shows it under the switch with how many went today.\n\n### Take the lead as you\n\nOn Settings → Act as me, Handle it for me is one dial: **Off**, **Easy ones**, **People I know**, **Most mail** and, for the owner, **Everything**, which uses **Take the lead** (`PUT /delegation/take-the-lead`, one row `person:<id>` in `take_the_lead`; turning it on turns Handle it for me on). While it is on, `handle_it.refusal` drops the setting's limits: strangers, the classifier's confidence, amounts, and the length up to a 4000-character ceiling. A reply with a link still waits for a tap (refusal `link`). In their place it checks the company's and the person's own added rules (`take_the_lead.reply_hit`, refusal `lead_rule`). Everything Handle it always keeps still holds: signed sign-ins, an authenticated sender, a reply kind, exactly the thread's people, the topics that always wait, draft flags, never twice in a row, one a thread a day and the daily limit. Follow-ups under it may go to anyone the person wrote to, with the same sensitive, amount, link and length checks plus the added rules. `reply_send.send_on_its_own` accepts the card while both switches are on. Each person adds and removes their own rules (`/delegation/take-the-lead/rules`). Removing one needs a caller the API can tie to them.\n\n## The mailbox client\n\n`delegation.gmail.DelegateGmail` talks to the Gmail REST API directly and is **never registered with the MCP gateway**, so the model reaches the mailbox only through the typed handler. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR`, named from a hash of the address (0600 in a 0700 directory), minted by `scripts/connect-own-gmail.py` on the Executive's own OAuth client with the scopes `gmail.readonly` and `gmail.compose`. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address. Besides reading threads and saving drafts it lists the inbox and checks whether they have written to an address, reads one message or draft, lists the person's send-as addresses and deletes a draft. Its **one send method**, `send_draft`, sends an existing draft by its id and nothing else — never `messages.send`, which sends any text it is given — and unit tests pin the method set, the endpoint, the request body and its single caller. A failed request says whether it may have been carried out anyway (a timeout after connecting, a 5xx), which is what the send path needs to know. A parsed message carries when it arrived, whether it is bulk, a bounce or a calendar invite, and whether Gmail's authentication results vouch for its sender.\n\n`gmail_status` answers `connected`, `not_configured`, `needs_reconnect` (Google refused the saved sign-in — an app in Testing mode has its tokens expire after 7 days; a rate limit, though Gmail may send it as a 403, is an `error` to retry, not a reconnect), `mismatch`, `no_email`, `shared_mailbox` or `error`. `shared_mailbox` means the person's address *is* the Executive's; it is refused before asking Google, because then everything the Executive writes would look like theirs. The gateway closes the other door: every `google_workspace__*` call must act as the Executive's own account, and a `user_google_email` naming anyone else is refused and audited (see Integrations).\n\n### Outlook\n\nA person may connect an Outlook mailbox instead (work, school or personal), with `scripts/connect-own-outlook.py`: a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, tenant `MS365_MCP_TENANT_ID` or `common`) asking for `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. It writes the same per-person file with `\"provider\": \"microsoft\"`, so a person has one mailbox for Act as me, and `gmail_for` hands back `delegation.outlook.DelegateOutlook`, which keeps `DelegateGmail`'s methods, return types and errors, so every caller above runs unchanged. It talks to Microsoft Graph directly, never through the Microsoft 365 MCP server the Executive's own Outlook uses, and is never registered with the gateway. Microsoft rotates the refresh token on use; the new one is written back into the file (atomically, keeping every other key, and only if the file still holds the old one). Graph is asked for immutable ids, so a sent draft keeps its id; a thread is Outlook's `conversationId`. Gmail's labels are mapped onto what the callers read: `SENT` only for mail in their Sent Items folder (a From line set to their address by someone else never counts), `DRAFT`, `INBOX`, and Focused Inbox's Other read as a tab. A sender counts as authenticated only when the topmost `Authentication-Results` — the one Exchange wrote, above anything the sender added — holds exactly one DMARC verdict, a pass for From's own domain, and Exchange Online Protection's own `compauth=` verdict, so a header the sender wrote on mail EOP never stamped doesn't count. `delete_draft` refuses anything that isn't a draft, and deletes with the draft's etag (`If-Match`), so a draft sent in between — it keeps its id — is left alone. No client secret is ever written into a person's file, and Graph has no signature setting to read.\n\n## Privacy\n\nWhat a person's mailbox touches is theirs. For the principal that means private to the principal, as every private row is. For a team member it means theirs alone, the principal included: an audit row carries `private_to_person` (set by `audit.rows_for_person` around the inbox watcher, a card's Send and Dismiss and their settings changes, and by `people_tools.audit_row_owner` on a turn that read their mail) and is left out of every audit read — the log, a session's timeline, a row by id, the brief — with only the usage totals counting it; their reply cards are theirs alone (above); and the owner's view of their use is counts only (drafts and sends in 30 days, and whether their inbox watcher is on). The conversation itself becomes its owner's alone before the mailbox is first read: `ghostwrite_email` marks the session `mail_private` (`session_store.mark_mail_private`, creating a channel adapter's row early, with its owner) and refuses to read the mailbox if that can't be stored or the conversation already belongs to someone else (which it then leaves unmarked); from then on only its owner may open it (`chat._session_access`), and working-style learning skips it. Every later turn there starts private (`settings.pin_turn_delegation` reads the flag and fails closed, setting `touched_mail`), so a follow-up answered from history alone is still private to its owner and teaches no memory, and the web chat's rows before the turn (the inbound message and the knowledge lookup) are theirs too. It does not start locked down: the lockdown is `read_mail`, set only by a turn that reads the mailbox or notes itself, because history keeps only the speaker's words and the Executive's replies, never the mail a tool returned. A follow-up such as \"book it\" therefore runs; the reply it builds on is the Executive's own, and every message, invite and email still reaches only people the roster allows. Only those come back: a later turn releases just `lockdown.CARRIED_RELEASED_TOOLS` (the DMs, `message_person` and calendar invites, each checked against the roster in its handler) and, through `call_tool`, `PRIVATE_TURN_MCP_TOOLS`. Everything else the reading turn refuses stays refused for the whole conversation, and an unclassified tool too: outside fetches and scripts (a URL could carry the mail anywhere), broadcasts and channel posts (no named recipient), queued work (follow-ups and workflows run later unattended, where they may fetch and research) and writes to state others or later turns read (facts, skills, the profile, the roster, documents), which would keep text the mail planted. The dispatch guard refuses them (`carried_withholds`) and the handlers that reach outside or post to everyone check again (`lockdown.outside_reach_refusal`). A channel adapter's own pre-turn rows are written as before. Anyone else speaking in it is not offered Act as me.\n\nOnce `touched_mail` is set, every audit row the turn writes is private (`people_tools.audit_row_private_to_principal`), and a team member's is theirs alone: the tool row (its input and result redacted, since `ghostwrite` is a sensitive tool name), the reply's `chat_turn` row that carries the preview, the model-call rows, and the background passes, which run under `private_rows`. The Honcho peer and department syncs are skipped, because peer memory is read on other people's turns. No memory is learned from the turn at all: the episodic, open-loop and working-style passes are skipped too, since its reply quotes a draft built from other people's mail. The `delegation_*` audit events are always private and carry metadata only — ids, counts and flags, never the draft or the thread. The inbox watcher is private the same way: every row a scan or a card action writes is its person's alone, and it starts no chat turn, alert, scheduled action or workflow run and teaches no memory.\n\nThe turn also stops reaching anyone else (`delegation.lockdown`). From the round that calls `ghostwrite_email` or one of the mailbox reads — a round's tools run together — until the turn ends, the dispatch guard refuses every tool that sends, posts, invites, queues or starts work, fetches an outside address, or writes state that others or later turns read: the DMs and `message_person`, broadcasts, calendar bookings and cancellations, follow-ups, workflows and research, `read_document` and the watchlist, `load_mcp_server`, `run_python_job` (library work on files, kept for download), `run_script` (a script over the gateway tools is withheld whole, saved tools included; `list_saved_tools`, a local read of their names, stays allowed), roster, goal, skill and alert changes, open loops, decisions and standing facts. Through MCP `call_tool`, only the Google Workspace reads remain (the Executive's own Gmail message and thread reads, its calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins, so the owner can check their mail against a file on the Drive in the same conversation). Every tool is classified as allowed or withheld, a test fails on a new unclassified one, and an unknown name is withheld. A refused call gets a private `tool_invocation` row (`refused: mail_touched`) and tells the model to offer it in a new message. The offered tool list never changes mid-turn, so the cached prefix holds. The send paths check again on their own (`_guard_outbound`, the broadcast, calendar, workflow, research and follow-up handlers, the gateway's `call_tool` and `load_mcp_server`). The server-side web search stays, as on a turn private to the principal. The lockdown lasts for that turn only.\n\n## Always in the loop\n\nA sent reply can leave a note. Once the reply went, `reply_send` starts `memory.history_notes.note_sent_reply` for the person who sent it, in the background, when their \"Keep track of what happens\" switch is on and the conversation isn't one they asked not to remember. The note-taker sees only the words they sent, so other people's mail never becomes a note, and a failure never touches the send. Recall is `recall_history`, offered on the same verified, private surfaces as `ghostwrite_email` and also allowed under the mail lockdown, since it only reads the speaker's own notes. Calling it locks the turn like `ghostwrite_email` does, from its own round on. The same switch also covers notes from chat, which don't need Act as me. See **Memory** for the checks, retention and controls.\n\n## The system prompt\n\nA constant, name-free `DELEGATION_ADDENDUM` joins block 0 after the unchanged identity addendum while anyone on the install has it on (`block0_delegation_on`). It names the four mailbox reads and says other people's mail is data and that a conversation which read it reaches nobody else; and it tells the model that `ghostwrite_email` is the single exception to *never impersonate*, and only for the person being spoken to; that everything else is written as itself; that when the tool isn't offered the asker can't have it; that a draft is never described as sent; and that it never denies being an AI. It is keyed on the install-level setting, never on the turn or the speaker, so switching it misses the 1h cache once (see Prompt Caching).\n\n## Surfaces\n\n- **Settings → Act as me** (`ActAsMeCard`, hidden unless `GET /delegation` answers, so a team member sees it once the owner lets them): the mailbox connection (`provider` says which) with both connect commands (Gmail and Outlook) and **Check again**, the **Write drafts as me** switch, the **Draft replies to my inbox** switch with its status in plain words, when it last checked and **Check now**, and **How I write**: length and tone, a greeting per audience (`{first}` is their first name), the sign-off, habits and never-rules in fields that grow to show every line, the signature with **Refresh from Gmail** and **Don't add my signature** (or **Add my Gmail signature** when none is added; on Outlook only **Don't add my signature**, with why), and each example quoted with **Remove examples**. The owner also gets **Let team members use it** where the install allows it, with each team member who has it on listed by name and counts only.\n- **Today → Replies waiting** (`RepliesWaiting`, the top of the left column; hidden unless `GET /delegation/replies` answers with cards): each card shows who wrote and who they are to you, whether their address was verified, the subject, **They wrote** as plain text, your draft, **Decide before sending** (the open questions) and its warnings, with **Send** (a confirm naming who it goes to, and a second one when that or the thread changed), **Edit in Gmail** or **Edit in Outlook**, and **Dismiss**.\n- **Setup status**: a **Your own mailbox (Act as me)** light (`your_gmail`), amber while the inbox watcher can't reach the mailbox, is being rate-limited or has 25 replies waiting.\n- **Settings → Your Executive** (`app/settings/executive`, where `/settings/on-its-own` lands): the pause, **Take the lead** and **Book meetings without asking** (as the Executive). **Handle it for me** (the Off / Easy ones / People I know / Most mail / Everything dial, what each sends, how many went today and what it sent this week, as you) sits under the mailbox card on **Settings → Act as me**.\n- **API**: `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/handle-it` and `GET /delegation/handled` — the caller's own delegation only — and `PUT /delegation/team`, the owner's switch (see API Reference). Send is `POST /decisions/{id}/approve`; Dismiss is `POST /decisions/{id}/reject`.\n- **Evals**: a scenario's `delegation:` block runs the turn against an in-memory mailbox (`evals.mailbox.ScenarioMailbox`) and hands the saved drafts to the judge (`delegation_001`–`003`). A `type: inbox` scenario runs the watcher's two model calls on one thread: whether it drafts must match the scenario, and a draft is judged on saying nothing the person hadn't, copying no link or address, and listing every open question (`delegation_inbox_001`–`007`; the last checks a draft never claims anything was sent).\n\nActing within rules the person sets and standing in for them are later, separate changes, each behind its own switch, off by default.","mermaid": "flowchart TD\n Ask[\"Principal or team member, verified<br/>'reply to Dana as me: yes'\"] --> Pin[\"pin_turn_delegation<br/>may have it? on? verified? private? attended?\"]\n Pin -->|\"offered\"| Loop[\"Executive tool loop<br/>with ghostwrite_email\"]\n Pin -->|\"not offered\"| Self[\"writes as itself<br/>(unknown tool this turn)\"]\n Loop --> Tool[\"ghostwrite_email handler<br/>caps, mailbox check, recipients in code\"]\n Tool -->|\"touched_mail\"| Private[\"turn's rows and conversation<br/>theirs alone, no memory\"]\n Tool --> Client[\"DelegateGmail or DelegateOutlook<br/>REST, outside the MCP gateway\"]\n Tick[\"Scheduler tick or Check now<br/>Draft replies to my inbox on\"] --> Scan[\"inbox scan, rows theirs alone<br/>skip rules, limits, ledger\"]\n Scan --> Client\n Client --> Box[(\"The person's own Gmail or Outlook\")]\n Scan --> Classify[\"classifier, no tools<br/>needs a reply? kind, confidence\"]\n Classify -->|\"worth a draft\"| Gw\n Voice[(\"delegation_voice<br/>How I write\")] --> Gw[\"ghostwriter<br/>no tools: voice + intent + thread\"]\n Tool --> Gw\n Gw --> Lint[\"lint: links and addresses<br/>only the person's own\"]\n Lint --> Draft[\"create_draft, threaded\"]\n Draft --> Box\n Draft --> Chip[\"chat chip: open the draft<br/>chat never sends\"]\n Draft --> Card[\"Today: Replies waiting<br/>their own card\"]\n Card -->|\"Send, confirmed\"| SendPath[\"reply_send: checks again,<br/>claim, send the draft by id\"]\n SendPath --> Box\n class Ask entry\n class Pin compute\n class Loop compute\n class Self compute\n class Tool compute\n class Private compute\n class Client compute\n class Tick entry\n class Scan compute\n class Classify compute\n class Box external\n class Voice storage\n class Gw compute\n class Lint compute\n class Draft hot\n class Chip entry\n class Card entry\n class SendPath hot",- "generated_at": "2026-10-07T23:00:00Z"+ "generated_at": "2026-10-08T16:30:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.jsonindex f0ee1c30..1e42a92c 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 socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from 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.\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, `search_drive_files`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the `complete` tier, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The 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`) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. 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; a name the search no longer finds is logged as workspace-mcp drift). A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & 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. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.",+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person — the chat adapters via `find_person_by_{slack,discord,telegram}_id`, the email poller via `people.identity.resolve_email_sender` (a primary address or an alias, then the company-domain rule; see Org) — and threads `person_id` into `Executive.chat()`. A sender who resolves to nobody is no longer simply dropped: see **New senders (roster requests)** below.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — MCP poll loop over the Executive's own mailbox — Gmail via `workspace-mcp` or Outlook via `ms-365-mcp-server`, chosen by `EMAIL_PROVIDER` (see *Workspace providers* below); it starts only once the MCP gateway is up, never surfaces Reply-To redirects, filters auto-replies. Its sessions carry `origin_channel=\"email\"`: the untrusted-content policy (`orchestrator.content_trust`) reads that tag to tell mail from the principal's own surfaces — left empty, as it once was, every stranger's body reached the decision extractor as the principal's words. The mail goes into the turn inside an `<untrusted_content source=\"email\" author=\"<sender>\" author_verified=\"no\">` block that says it carries none of the principal's authority, with the framing line and any `[POLICY]` notice outside it; mail from the principal's primary address that Gmail authenticated (`dmarc=pass`) is their own words — but only their new text goes in unwrapped: when the mail quotes or forwards another message (`_new_text_lines` cut something), the message as received follows in an `<untrusted_content source=\"email_quoted\">` block, since a stranger's text they replied to or passed on is not theirs. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed from the rendered message with any trailing `--- REPLY ---` block dropped first, without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. The poller's `integration_inbound` row keeps the mail's text for the audit log, the way the reply's `chat_turn` row keeps the Executive's answer: `full.message` is the sender's new text (what web chat keeps for a turn), `full.attachments` the attachment filenames, and `details.preview` the first 120 characters of the new text, so /audit shows what was asked next to what was answered (the summary still reads `Inbound email from <sender>: <subject>`). The whole body with its quoted chain (`full.body`) is kept only on a row private to the principal: the chain is other people's mail — a contact's, on the principal's reply to one — and every signed-in user reads a public row. Each field is cut by its escaped JSON length (20,000 characters of text, 8,000 of attachment names), the measure the logger's 64 KB cap uses, so a long mail in a non-Latin script loses its tail rather than the row's structure. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway with the configured backend's send tool (`google_workspace__send_gmail_message` or `microsoft_365__send-mail`, via `workspace.registry.send_from_executive`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an ordinary email turn cannot change the People list — the one email that can is the principal's tokened reply to a roster-request email, which is parsed before any model turn; see below). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message never reaches the Executive (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). What happens next is the roster request below — except for a contact, a thread continuation, a Telegram group or an unverified Telegram webhook, which stay silent. Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying). Slack only continues a thread it has replied in: it reads the thread with `conversations_replies` (5 s bound) and looks for its own user id, which `auth_test` resolves at startup. If that lookup fails, mentions and DMs still work and thread continuations stop until a retry succeeds (`slack_bot._resolve_bot_user_id`, at most once a minute, from the channel `message` listener). When Slack doesn't return the thread in time, the thread's stored history (`slack:thread:{channel}:{thread_ts}`, written on every turn the bot answers there) stands in: with history, a rostered sender gets an ephemeral \"I couldn't read this thread just now… @-mention me\" and the drop is audited (`outcome=dropped_thread_unreadable`). A thread the bot never answered in stays silent. A message the gate skips is audited (`outcome=skipped_gate`, with the gate's reason) and gets an :eyes: reaction (`reactions_add`, which needs the bot's `reactions:write` scope; without it the reaction is skipped), so a sender the gate misjudged can see the message was read and @-mention the bot.\n\n**No link previews on replies.** The Executive's replies go out with previews off — Telegram `sendMessage` carries `link_preview_options.is_disabled`, Slack's reply `say` passes `unfurl_links=False` / `unfurl_media=False`, and every Discord reply send passes `suppress_embeds=True`. The direct messages the Executive starts are the same: `send_slack_dm` posts with `unfurl_links=False` / `unfurl_media=False`, and Discord's `send_dm` sets the `SUPPRESS_EMBEDS` flag on each chunk, so a reminder or a brief sent by DM carries no preview either. Otherwise the chat service fetches a link in the text on its own, so a reply that quotes someone's mail (Act as me reads it) could carry data to a sender's server with no click. The web chat does the same for images: `Message.tsx` loads only an image the app itself serves (`lib/markdownImages.loadsInline`) and shows any other as a link.\n\n### New senders (roster requests)\n\nSomeone who writes in and is not on the People list — and is not one of the principal's contacts — is **held, acknowledged and asked about** instead of dropped (`integrations.roster_intake.intake` over the `people.roster_requests` ledger; lifecycle in Org). Each adapter calls it after its gate:\n\n- **Slack** — a DM or an `@mention` (not a thread continuation: the bot was not addressed there). The name and profile email come from `users_info` (5 s timeout). The acknowledgement goes in the DM, or as an **ephemeral** message for a mention, so nobody else in the channel learns who is and is not on the roster. The held event keeps only a fixed set of keys (text, user, channel, ts, thread, files).\n- **Discord** — a DM or a mention (not a thread the bot merely follows). The acknowledgement goes in the DM, or by DM for a channel mention; `/ask` answers the interaction with an ephemeral acknowledgement first (Discord allows 3 s), then holds the prompt. Its old \"ask the admin to add you\" reply is gone.\n- **Telegram** — only a **private** chat, and only when `TELEGRAM_WEBHOOK_SECRET` is set and valid: Telegram identifies the chat rather than the sender, and without the secret anyone could forge an update. A group, or an unverified webhook, stays silent as before. Attachment file ids are held and downloaded only on replay.\n- **Email** — non-roster mail that is not private to the principal (so never a contact's) and does not look machine-sent (`looks_automated`: a no-reply / notifications / billing-style local part, a `List-Id` / `List-Unsubscribe` / `Auto-Submitted` / bulk `Precedence` header, or a DMARC failure). The mail is **still triaged** by the Executive on this pass; its `[POLICY]` notice now says the sender was already told their message is waiting and the principal was asked who they are, so the model raises no second alert just to add them, and that the email will come back once they are added.\n\nEvery path skips a contact first (`find_person_by_*_id(..., include_contacts=True)`, or the email poller's private-mail rule): a contact has no chat access and gets no request and no acknowledgement, and the team-visible `rejected_unknown_sender` / `accepted_non_roster` rows read the same for a contact as for a stranger.\n\n**The acknowledgement** is one fixed text (`roster_intake.ACK_TEXT` — \"your message arrived … waiting for confirmation\"), never the model and never an echo of what they wrote, so a forged sender gains nothing by triggering it. It is sent at most once per sender per `ROSTER_ACK_WINDOW_DAYS` (7) and at most `ROSTER_ACK_DAILY_CAP` (20) a day across all senders (`claim_ack`, one transaction; a failed send releases its claim). An email acknowledgement is the one send the MCP gateway lets reach an address off the roster: `send_email_ack` sets `mcp_gateway.roster_ack_grant`, a one-shot ContextVar grant that admits a single `send_gmail_message` with exactly the granted recipient (a plain string, no list), subject and body and no other key, then is spent (audited `integration_outbound`, `kind: roster_ack`, private). An email sender is acknowledged only when Gmail authenticated them: once `claim_ack` succeeds, the poller's `send_ack` re-reads the mail as raw MIME and needs Gmail's own topmost `Authentication-Results` reporting `dmarc=pass` for the From domain (`fact_confirmation.sender_authenticated`, fail-closed). The printed headers the poller reads never carry that header, so without the second read a forged From would draw the acknowledgement to whoever it names — backscatter from the Executive's mailbox. An unauthenticated sender makes `send_ack` raise `roster_intake.AckWithheld`: the claim is released, and they are held silently. `authenticated_by_gmail` strips quoted strings and comments before reading the verdict — Gmail copies the envelope sender and DKIM tags into its own stamp, and a quoted local part could otherwise carry a fake `dmarc=pass` — and needs exactly one `dmarc=` verdict reading exactly `dmarc=pass header.from=<domain>` (Gmail may follow it with its own `dara=` resinfo, so its position is not checked). Residual: when Gmail writes no verdict at all (a From domain without DMARC) and echoes an unsanitised `;dmarc=pass header.from=…` elsewhere in its stamp, that echo would read as the verdict; bounded by the acknowledgement caps. A withheld acknowledgement is audited `roster_ack_withheld`. `intake` acknowledges before surfacing the card and telling the principal, and both follow the request's `ack_sent_at`: a withheld, failed or capped acknowledgement reads \"haven't been told anything yet\" on the Today card, in the principal's prompt and in the email `[POLICY]` notice.\n\n**Telling the principal.** A new request puts a private card on the principal's `/today` (see Today) and pushes a prompt on their delivery plan — preferred chat DM, then the others, then email — for a chat sender or an email sender on the company's own domain; an outside email sender waits on the card, as does everything past `ROSTER_REQUEST_DAILY_CAP` (30) pushes a day (the same cap bounds how many requests open a day; a declined sender is not raised again for 30 days). A chat prompt can be answered in place (\"that's Annamarie, add her to the team\"). An email prompt carries a one-time token (`RR-` + 20 base32 characters, stored hashed); the poller checks every inbound mail for one **before** triage (`try_email_roster_answer`): the reply must come from the principal's primary address exactly (not an alias, not the company-domain rule), carry the token of a pending request, not be an automatic reply, and not fail DMARC where the header is visible; and is parsed by `parse_decision`'s `roster_identity` shape — anything else falls through to the ordinary path. The token is hidden (`RR-[hidden]`) in every other Google Workspace result the gateway returns — the confirmation sits in the Executive's Sent folder, and any turn could otherwise read it — except the poller's own fetch of an inbound message (`mcp_gateway.reveal_roster_tokens`); a token-bearing mail that is not an answer is scrubbed before triage.\n\n**Replay.** Once the principal answers (web card, chat tool, email reply) — or a People-page / `upsert_person` write makes the sender match someone (`after_roster_write`) — the held messages are replayed through the adapter that received them (`register_replayer`: Slack re-runs the held event, Discord and Telegram their held text, email re-fetches the message from Gmail and handles it as mail from a known sender), oldest first, now attributed to the new Person. A teammate gets every held message; a new contact only held email (it takes the private contact path; held chat is dropped); a decline drops everything. Replays run in a **fresh `contextvars.Context`**: the answer may have come from the principal's own verified turn, and a stranger's message must never be read with the principal's session — and their contacts — still bound.\n\n### Standing facts by email (confirm by reply)\n\nThe principal can ask for a standing fact, a retirement or a company-profile edit by email, and the fact tools check it exactly as in chat (the own-words gates run on `_email_memory_text`, the sender's new text, not the quoted chain or attachments). An email's From line proves nothing, though, and a standing fact is read by every later prompt as the principal's own account. So an emailed change is **held, never applied**, until the principal's own mailbox confirms it (`integrations.fact_confirmation`, `memory.facts.fact_confirmations`):\n\n- **Who may ask.** The poller stamps every email turn with `Session.email_from` (the bare lowercased From address) and `email_authenticated`. The text the poller reads never carries `Authentication-Results` (workspace-mcp prints a fixed set of headers), so for mail claiming the principal's primary address it reads the message again as raw MIME (`fact_confirmation.sender_authenticated`) and requires Gmail's own stamp: the **topmost** `Authentication-Results` header (Gmail adds it on receipt, above anything the sender wrote), authserv-id `mx.google.com`, reporting `dmarc=pass` for the From address's domain, with the raw From matching (`authenticated_by_gmail`). It fails closed: no header, `dmarc=none`, a temporary error or a failed read all leave the turn unauthenticated. Mail from 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.\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — inside an `<untrusted_content source=\"attachment\" author=\"<name>\">` block (`content_trust.wrap_untrusted`, whose closing tag the text cannot forge), under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" and the decision extractor strips before it reads the turn — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive, Outlook mail and calendar — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, Drive share grantees, and Microsoft 365 recipients/attendees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. Three more refusals close paths around those gates: every Apps Script tool (code running as the Executive's account, outside the gates, and since workspace-mcp 1.29.0 schedulable to keep running); any argument that makes the server fetch a URL (`fileUrl` / `file_url` on the Drive and import tools, a Gmail attachment given as a `url`), since the fetch can carry data out in its query string before any recipient gate matters; and text Google would mail to someone the roster never checked (`rsvp_comment` to an event's organizer, an out-of-office `decline_message` to whoever invites the Executive). Every gate reads its arguments by normalized spelling: workspace-mcp 1.29.0 renames a camelCase key such as `Attendees`, `userGoogleEmail` or `rsvpComment` to the real parameter, so a gate matching the exact key would never see it. Arguments that are not a JSON object are refused for the same reason. Google-side fetches are refused too: any key ending in `url` / `uri` at any depth whose value has a URL scheme (a Slides image or page background, a Docs or Forms image; a document hyperlink and a meeting link are stored, not fetched, and pass, as does a Drive file id), (a value is a URL after the characters a URL parser strips are removed, and `//host` counts), and on every tool that can write cells — the Sheets tools and the Drive create / update / import tools, which turn CSV into a Sheet — any string anywhere holding a formula call that fetches (`IMPORTDATA`, `IMPORTXML`, `IMPORTHTML`, `IMPORTFEED`, `IMAGE`), JSON-encoded or mid-CSV included: a string argument that encodes JSON is read as the server decodes it (one too large to read is refused), text is also scanned with character references decoded and comments / CDATA removed, and an upload that would become a native Sheet may only be text `content` — a `base64_content` or server-side `file_path` upload there is refused, since an XLSX hides its formulas behind zip members and XML encodings; a PNG to Drive or a DOCX to Docs is untouched. Not covered, unverified: whether Drive's HTML / Markdown import fetches an `<img src>` when it converts `content` into a Doc. A `manage_event` call that names no attendees is sent with `send_updates=\"none\"`, so the event's existing guests are not emailed text the gate never checked. The allow-list (`_egress_sets`, built by `_roster_allow_set` as a `people.identity.RosterAllow`) is every team member's email and email aliases plus the Executive's own address, always, and — for a teammate — any address on one of the company's own domains whose local part (`+tag` dropped) matches theirs, the same rule inbound mail is matched by; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). The single exception to the roster rule is the fixed roster-request acknowledgement above, under its one-shot `roster_ack_grant`. A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, and the Drive, Docs and Sheets reads such as `search_drive_files`, `get_drive_file_content`, `get_doc_content` and `read_sheet_values`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the `complete` tier, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees and pins notifications, nothing else) reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The 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`) and tells it to call them with `call_tool` directly, with no `search_tools` round trip. 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; a name the search no longer finds is logged as workspace-mcp drift). A pinned call that still comes back with extensible-mcp's \"has not been discovered via search_tools\" refusal, for example before priming finished, is discovered and retried once. That happens after every gate has passed the same arguments, and only for pinned names: any other tool still needs the model's own search, and nothing here widens what a call may do, including the private-turn allow-list.\n\n**Microsoft 365** is the Outlook twin: `@softeria/ms-365-mcp-server` (a Node package, pinned) is installed in a throwaway Node build stage and only the `node` binary plus the package are copied into the API image, launched by `docker/ms365-mcp-launch.sh` as the `microsoft_365` entry with an **explicit tool allow-list** (`--enabled-tools`, an anchored regex) rather than the upstream `mail,calendar` preset — that preset also registers inbox forwarding rules, mailbox settings (external auto-reply), calendar sharing and event forwarding, which can address people the gateway never sees. Exactly the Outlook mail + calendar tools and the OneDrive tools are exposed (`microsoft_365__send-mail`, `microsoft_365__create-calendar-event`, `microsoft_365__search-onedrive-files`, …; hyphenated Graph endpoint aliases, proxied verbatim), and every admitted tool is either roster-gated or carries no recipient; the gate also covers the excluded writers in case an operator widens the list. Both servers can be configured at once. Auth is the MSAL device-code flow against the operator's own Entra app registration (`MS365_MCP_CLIENT_ID` is required; the server's built-in public client is refused); the refresh token persists at `/data/ms365_credentials` and is seeded once with `ms365-mcp-launch.sh --login` from inside the container — the server has a native device-code CLI, so there is no mint script and nothing to copy. The launcher scrubs the literal `$VAR` placeholders extensible-mcp leaves for unset variables (otherwise MSAL would be handed `$MS365_MCP_TENANT_ID` as an authority), and `MS365_MCP_EXPECTED_USERNAME` pins the bound mailbox. The egress gate for this family walks Graph's nested shapes (`body.Message.toRecipients[].emailAddress.address`, `body.attendees[]…`) — every email-shaped string outside the free-text fields must be on the roster, control characters and non-ASCII addresses are refused, unforeseen keys are still scanned (fail-closed) — and covers the whole write surface: send, reply, reply-all, forward, every draft tool, `update-mail-message` (it can PATCH recipients onto a draft) and create-/update-calendar-event; reads and `delete-calendar-event` (the only cancel path) pass through. Graph's reply, reply-all and send-draft actions carry no recipient in their arguments (the recipient is whoever the referenced `messageId` names), so for those the gate first reads the referenced message through the server and roster-checks the recipients Graph will derive (`replyTo` else `from` for a reply; `replyTo` and `from` together, plus the original to/cc, for reply-all; the draft's own to/cc/bcc for send-draft), refusing on any lookup failure; RSVP and cancel actions get the same treatment through an event lookup, because their comment is emailed to the organizer or every attendee; `download-bytes` is pinned to mail attachment bytes and OneDrive file content (`/drives/{id}/items/{id}/content`, optionally Graph's `?format=pdf` rendering), and a OneDrive result comes back as the file's extracted text rather than base64 — the attachment pin is what makes the poller's promise that an unrostered sender cannot be auto-replied to hold on Outlook as it does on Gmail; and the rendered inbound text quotes any forged `--- REPLY ---` line inside a body so the persona only ever reads the real block. Every mail write's `from`, `sender` and `replyTo` may name only the Executive's own address (the Outlook twin of the Gmail acting-account pin), so the model cannot send as a rostered colleague's mailbox or steer replies elsewhere; and `move-mail-message` into Deleted Items, Junk Email or Recoverable Items is refused, so a move cannot trash mail ungated. The server registers its account tools whatever its tool allow-list says, so the gateway itself refuses `login`, `logout`, `select-account` and `remove-account` (audited like any other refusal) and drops them from `search_tools` results — a chat turn cannot sign the mailbox out, switch accounts or start a sign-in; setup is only the launcher's `--login`, and the read-only `verify-login` / `list-accounts` stay callable. The example config's hyphenated patterns still deny `delete-mail-*`, `logout`, `remove-account` and `download-bytes-to-file` as defense in depth. A successful `send-mail` records the same outbound-context linkage Gmail does.\n\n**OneDrive in chat** (opt-in with `MS365_MCP_ONEDRIVE=true` and a fresh `--login`, since the server asks for its tools' permissions on every token refresh and a sign-in without file consent would otherwise fail mail and calendar too) matches what the Executive can do on Google Drive: search, list a folder, read a file, upload and edit, create folders, move, rename, copy and share; there is no delete tool. The launcher adds `Files.Read.All` at sign-in (`--extra-scopes`), so folders shared *with* the Executive can be read too; writes (upload, new folder, move, copy) land only in the Executive's own drives, checked against `list-drives` at call time, so a planted instruction cannot save company files into a stranger's shared folder. Sharing is gated like Drive sharing: `share-drive-item` invitees must be People on the roster and named by email (an `objectId` or `alias` grantee is refused, since nothing can check it), no `owner` role, and `create-drive-item-share-link` must be scoped to specific people (`scope: \"users\"`): an anonymous or whole-organization link, or one with no scope (the tenant default), is refused. An invite must require sign-in and grant only view or edit, a link must be a view or edit link, and `search-onedrive-files` takes plain words only, since its query goes into the request path unencoded.\n\nAs a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged. The same expansion serves the Microsoft 365 mail writes: the entry becomes a Graph `#microsoft.graph.fileAttachment` (`name`, `contentType`, `contentBytes`) placed where Graph expects it for that tool (`body.Message.attachments` for `send-mail`, reply, forward and the createReply drafts; `body.attachments` for `create-draft-email`), whether the model put it at the top level or inside the message; an entry anywhere else, one on `update-mail-message` or `send-draft-message` (their requests cannot carry attachments), or one behind a body that is not an object is refused rather than forwarded unexpanded.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & 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. Both attach a video-meeting link by default (`add_video_link`; opt out for in-person) — a **Google Meet** link parsed from the created event's `conferenceData`, or a **Microsoft Teams** link from `onlineMeeting.joinUrl` — surfaced to the caller plus persisted on the decision ledger as `meet_link`. The tool descriptions are static, backend-neutral text, so the cached tool block never depends on settings; the pre-rename `add_google_meet` key is still honoured for old ledger rows. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Workspace providers\n\nThe Executive can *discover* any mail or calendar tool the gateway exposes, but three code paths call a fixed backend with no model in the loop and used to spell Gmail tool names inline: the inbound mailbox poller (list unread → fetch → mark read), alert email dispatch plus the scheduler's email send-tool hint, and the typed booking tools plus the approval-time conflict check. `integrations.workspace` puts those behind two Protocols (`MailProvider`, `CalendarProvider`) with one module per backend (`google.py`, `microsoft.py`) and a registry keyed on `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` — separate switches (Outlook mail with a Google calendar is legitimate), both defaulting to `google`, so an existing install changes nothing until an operator opts in. The Google backend is the old inline code moved verbatim; tests pin its argument dicts byte-for-byte. The Microsoft backend polls only the Inbox folder (`list-mail-folder-messages` with `isRead eq false`, never the all-folders listing that includes Junk), converts Graph's HTML bodies to text with a real parser, lists a message's attachments so the names appear in the same `N. name (mime, size KB)` shape Gmail's text uses (and reach peer memory), marks read with `update-mail-message`, sends through `send-mail`'s nested shape, books with `isOnlineMeeting` + `onlineMeetingProvider=teamsForBusiness`, cancels with `delete-calendar-event`, and answers the advisory conflict check from the Executive's **own** calendar view (delegated permissions cannot read attendees' free/busy — narrower than Google's `query_freebusy`).\n\nEvery backend renders an inbound message into the same `Subject:` / `From:` / `To:` / `Cc:` + `--- BODY ---` text the persona already expects, and the poller adds a `--- REPLY ---` block naming the exact reply tool and threading ids for *that* message (Gmail: `send_gmail_message` + `thread_id`; Outlook: `reply-mail-message` + `messageId`) after the mail's `<untrusted_content>` block, never inside it. The block rides in the user turn — which is what lets the cached persona say \"use the reply tool in the REPLY block\" instead of naming a vendor tool — and the scheduler's proactive-email trigger names the backend's send tool the same way. Providers never raise on a malformed backend response (they return empty / `None` / `{\"error\": …}`), so one bad cycle never kills a loop, and a chosen backend whose MCP server is missing from `mcp_servers.json` is logged at startup and skipped by the poller: fail-soft, never a boot failure. The poller's newer checks run on that rendered text for both backends (contacts and private turns, roster requests and their emailed answers, the audit row), with three Outlook differences that fail closed: no sender is ever authenticated (the `dmarc=pass` read is Gmail's), so there is no acknowledgement to an unknown sender, no emailed fact confirmation and no principal-authenticated mail; attachments stay a list (the download is Gmail's); and the brief's calendar block is skipped (its listing is Google Calendar's). The code's own emails to the principal (roster prompts, fact confirmations, scheduled deliveries) go through `workspace.registry.send_from_executive`, and `runner.email_ready` follows `EMAIL_PROVIDER`. A private turn's allow-list (`schedule_tools.PRIVATE_TURN_MCP_TOOLS`) and Act as me's mail-touched reads include the Outlook twins of the Gmail and Calendar tools, and roster answer tokens are hidden from Microsoft 365 results as from Google's.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message` or `microsoft_365__send-mail`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### OneDrive folder sync\n\nThe Microsoft twin of the Drive folder sync below (`knowledge.onedrive_sync`, `ONEDRIVE_SYNC_ENABLED`; setup in `docs/onedrive_sync_setup.md`). It copies the files in `ONEDRIVE_SYNC_FOLDERS` (`<drive id>/<item id>` pairs; `openexecutive onedrive-folder <link>` resolves a sharing link) into the isolated `onedrive_docs` collection on its own heartbeat, and shows them on the knowledge page as \"OneDrive\" rows with a **Sync now** button. Microsoft has no service account that sees only what is shared with it (app-only Graph access covers the whole tenant), so it reads as the Executive's own Microsoft 365 sign-in, and the folder list is the scope. It never stores a credential: each tick asks the launcher for a token (`ms365-mcp-launch.sh --access-token`, which runs `docker/ms365-access-token.mjs` through the server's own token cache and will only mint file-read tokens), keeps it in memory, and sends it only to Graph. `knowledge.onedrive_client` issues GETs only, follows a paging link only back to Graph, and fetches a file's pre-authenticated download link without the token; errors never carry that link. PowerPoint and older Office formats are read through Graph's PDF rendering.\n\n### Google Drive folder sync\n\nThe synced files show on the knowledge page's Company documents list as \"Google Drive\" rows (sync time, last edit in Drive, an Open in Drive link and a text view), and the page's source card shows the last run, any sign-in error or count of files that failed to sync, and a **Sync now** button that runs one tick on demand.\n\n\nSeparate from the Drive tools the gateway proxies. The optional folder sync (`knowledge.drive_sync`, `DRIVE_SYNC_ENABLED`; setup in `docs/drive_sync_setup.md`) copies the files in `DRIVE_SYNC_FOLDER_IDS` into the isolated `drive_docs` knowledge collection on a scheduler heartbeat, so the Executive knows those folders without searching Drive live (see RAG). It calls the Drive v3 API directly (`knowledge.drive_client`, `httpx`) as a **service account** with the `drive.readonly` scope (`DRIVE_SYNC_SERVICE_ACCOUNT_FILE`), not as the Executive's own account through workspace-mcp. Google enforces the folder scope, because the account sees only what is shared with it, and the sync can change nothing. Structured JSON means no display text to parse, and every file or folder id is checked against `[A-Za-z0-9_-]{1,128}` before it goes into a URL or a query. The two paths meet in two places. A synced chunk carries its Drive file id and sync time, so the Executive can open the live file with its own `get_drive_file_content`. The setup doc says to share each synced folder with the Executive's account too, so that live open works.\n\n### Confluence space sync\n\nThe optional Confluence sync (`knowledge.confluence_sync`, `CONFLUENCE_SYNC_ENABLED`; setup in `docs/confluence_sync_setup.md`) copies the pages of the spaces in `CONFLUENCE_SYNC_SPACE_KEYS` into the isolated `confluence_wiki` knowledge collection on a scheduler heartbeat, so the Executive knows the company wiki without a tool call (see RAG). It works with Confluence Cloud and Server/Data Center: `knowledge.confluence_client` calls the v1 REST API both serve, directly with `httpx`, signing in with a personal access token (Server/DC) or a username and API token (Cloud). It reads only, never follows a redirect (so the token stays on the configured site), streams responses with a 20 MB cap, and checks page ids and space keys before they reach a URL or a CQL query. The URL must be `https://` unless `CONFLUENCE_SYNC_ALLOW_HTTP` is set, and `CONFLUENCE_SSL_VERIFY` takes `true`, `false` or a CA bundle path for a private certificate authority. With `CONFLUENCE_SYNC_PUBLIC_HOSTS_ONLY` (off by default, for an install where whoever sets the URL must not reach the backend's own network) every request resolves the site's host, refuses it when any address is not public (loopback, private, link-local, shared), and connects to the checked address with the site's name kept for the Host header and the TLS certificate check, directly rather than through a proxy. `confluence_client.config_problem` is the same settings check the app runs at start, for a caller that writes these settings on someone's behalf.\n\nIt is separate from a Confluence MCP server such as mcp-atlassian, which a deployment can add to `mcp_servers.json` for live reads and edits in chat. The two share the env names `CONFLUENCE_URL`, `CONFLUENCE_PERSONAL_TOKEN`, `CONFLUENCE_USERNAME`, `CONFLUENCE_API_TOKEN` and `CONFLUENCE_SSL_VERIFY`, so one set of values serves both, and a synced chunk carries its page id so the Executive can open the live page with such a tool. A Confluence token is a user's, and what the sync reads becomes retrievable by everyone who talks to the Executive, so the space list is required and pages with a read restriction (their own or a parent's) are skipped unless `CONFLUENCE_SYNC_SKIP_RESTRICTED=false`. That keeps any existing member's token safe to use, without a dedicated licence. Manual runs: `openexecutive sync-confluence` / `purge-confluence`.\n\n### Your own Gmail or Outlook (Act as me)\n\nA second, separate mail connection, for **Act as me** (see **Act as Me (Delegation)**): a person's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; the only send is `drafts.send` of an existing draft by id, when the person taps Send on its reply card (`delegation.reply_send`). A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own mailbox (Act as me)**.\n\nThe same file can instead hold an Outlook sign-in (`\"provider\": \"microsoft\"`), minted by `scripts/connect-own-outlook.py --email <you>` with a device-code sign-in on the Executive's own Entra app (`MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, default `common`) and the delegated scopes `User.Read`, `Mail.ReadWrite`, `Mail.Send` and `offline_access`. `delegation.gmail.gmail_for` then hands back `delegation.outlook.DelegateOutlook`, which talks to Microsoft Graph directly — never the Microsoft 365 MCP server the Executive's own Outlook uses — with the same methods and the same one send: Graph's `send` on an existing draft, with no body. Microsoft rotates the refresh token on use and the new one is written back into the file. A sender counts as verified only from the topmost `Authentication-Results`, the one Exchange wrote, and only mail in their Sent Items counts as theirs.","mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop\"]\n Hold[\"roster request<br/>(hold + fixed ack,<br/>ask the principal)\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n GW[\"Google Workspace<br/>(workspace-mcp child)\"]\n M365[\"Microsoft 365<br/>(ms-365-mcp-server child:<br/>Outlook + OneDrive)\"]\n WP[\"workspace providers<br/>(poller / alerts / booking)\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Hold\n Hold -- \"approved: replay\" --> Exec\n Hold -- \"contact / declined\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n MCP -- \"roster egress gate\" --> GW\n MCP -- \"roster egress gate\" --> M365\n WP -- \"EMAIL_PROVIDER / CALENDAR_PROVIDER\" --> MCP\n WP --> Exec\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n Own[(\"Principal's own Gmail<br/>(Act as me: REST, drafts only)\")]\n Exec -- \"ghostwrite_email\" --> Own\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Hold compute\n class Exec hot\n class Attach compute\n class MCP external\n class GW external\n class M365 external\n class WP compute\n class Guard compute\n class Out compute\n class Own external",- "generated_at": "2026-10-07T17:00:00Z"+ "generated_at": "2026-10-08T16:30:00Z"}diff --git a/packages/core/openexecutive/delegation/lockdown.py b/packages/core/openexecutive/delegation/lockdown.pyindex a927c03b..8a612b9b 100644--- a/packages/core/openexecutive/delegation/lockdown.py+++ b/packages/core/openexecutive/delegation/lockdown.py@@ -123,23 +123,43 @@ MAIL_TOUCHED_WITHHELD_TOOLS: frozenset[str] = frozenset({})# The Google Workspace reads call_tool may still run: never a draft, a send or-# a change (each of these is also in PRIVATE_TURN_MCP_TOOLS).+# a change (each of these is also in PRIVATE_TURN_MCP_TOOLS). Drive, Docs and+# Sheets reads stay so "check my mail against the file on the Drive" works in+# one conversation: what they return can reach no one while the lockdown holds,+# and Drive reads are not remembered on such a turn (drive_reads.may_remember).+# Accepted residual: opening a file someone else owns shows in their file+# activity, so mail that steers which file opens could signal a few bits.MAIL_TOUCHED_MCP_READS: frozenset[str] = frozenset({+ "google_workspace__get_doc_content",+ "google_workspace__get_drive_file_content","google_workspace__get_events","google_workspace__get_gmail_message_content","google_workspace__get_gmail_thread_content",+ "google_workspace__get_spreadsheet_info","google_workspace__list_calendars",+ "google_workspace__list_docs_in_folder",+ "google_workspace__list_drive_items",+ "google_workspace__list_sheet_tables",+ "google_workspace__list_spreadsheets","google_workspace__query_freebusy",+ "google_workspace__read_sheet_values",+ "google_workspace__search_docs","google_workspace__search_drive_files","google_workspace__search_gmail_messages",- # The same reads of an Outlook mailbox (EMAIL_PROVIDER=microsoft).+ # The same reads of an Outlook mailbox and OneDrive (EMAIL_PROVIDER=microsoft);+ # a OneDrive file opens through download-bytes (is_onedrive_file_read)."microsoft_365__get-calendar-event","microsoft_365__get-calendar-view",+ "microsoft_365__get-drive-item",+ "microsoft_365__get-drive-root-item","microsoft_365__get-mail-message","microsoft_365__list-calendar-events","microsoft_365__list-calendars",+ "microsoft_365__list-drives",+ "microsoft_365__list-folder-files","microsoft_365__list-mail-folder-messages","microsoft_365__list-mail-messages",+ "microsoft_365__search-onedrive-files",})# What a later turn of a conversation that once read the owner's mail may do@@ -184,8 +204,13 @@ def mail_touched_withholds(tool_name: str, tool_input: Any) -> bool:"""Whether a call to ``tool_name`` is refused once the turn has read theowner's mail. Anything unclassified is (fail closed)."""if tool_name == "call_tool":+ from openexecutive.orchestrator.schedule_tools import is_onedrive_file_read+inner = tool_input.get("name") if isinstance(tool_input, dict) else None- return not (isinstance(inner, str) and inner in MAIL_TOUCHED_MCP_READS)+ return not (+ (isinstance(inner, str) and inner in MAIL_TOUCHED_MCP_READS)+ or is_onedrive_file_read(tool_input)+ )return tool_name not in MAIL_TOUCHED_ALLOWED_TOOLS@@ -193,10 +218,9 @@ def carried_withholds(tool_name: str, tool_input: Any) -> bool:"""Whether a call to ``tool_name`` is refused in a conversation that onceread the owner's mail (every later turn, not only the reading one)."""if tool_name == "call_tool":- from openexecutive.orchestrator.schedule_tools import PRIVATE_TURN_MCP_TOOLS+ from openexecutive.orchestrator.schedule_tools import private_turn_allows_mcp_call- inner = tool_input.get("name") if isinstance(tool_input, dict) else None- return not (isinstance(inner, str) and inner in PRIVATE_TURN_MCP_TOOLS)+ return not private_turn_allows_mcp_call(tool_input)# Fail closed: anything neither a read nor released stays refused.return tool_name not in MAIL_TOUCHED_ALLOWED_TOOLS and tool_name not in CARRIED_RELEASED_TOOLSdiff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.pyindex d27a158d..f1bcc80f 100644--- a/packages/core/openexecutive/orchestrator/schedule_tools.py+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py@@ -1835,30 +1835,46 @@ PRIVATE_TURN_WITHHELD_TOOLS: frozenset[str] = frozenset({# refuses a `call_tool` naming anything else. Names are exact, as the# gateway's own gates match them; each is one the code already calls or# documents: the poller's Gmail reads (`email_poller`), the calendar reads in-# the gateway notes and `decisions` (free/busy), and the Drive search the-# Drive gate's tests treat as a read. Add a name only for a tool that reads,-# or whose every recipient the gateway checks.+# the gateway notes and `decisions` (free/busy), and the Drive, Docs and+# Sheets reads (workspace-mcp marks each read-only and calls it with a+# read-only scope). Add a name only for a tool that reads, or whose every+# recipient the gateway checks.PRIVATE_TURN_MCP_TOOLS: frozenset[str] = frozenset({"google_workspace__draft_gmail_message",+ "google_workspace__get_doc_content",+ "google_workspace__get_drive_file_content","google_workspace__get_events","google_workspace__get_gmail_message_content","google_workspace__get_gmail_thread_content",+ "google_workspace__get_spreadsheet_info","google_workspace__list_calendars",+ "google_workspace__list_docs_in_folder",+ "google_workspace__list_drive_items",+ "google_workspace__list_sheet_tables",+ "google_workspace__list_spreadsheets","google_workspace__query_freebusy",+ "google_workspace__read_sheet_values",+ "google_workspace__search_docs","google_workspace__search_drive_files","google_workspace__search_gmail_messages","google_workspace__send_gmail_message",# The Microsoft 365 twins, for an Executive whose mailbox is Outlook- # (EMAIL_PROVIDER=microsoft): its mail, calendar and OneDrive search reads, and the two+ # (EMAIL_PROVIDER=microsoft): its mail, calendar and OneDrive reads, and the two# mail writes whose every recipient `_check_m365_recipients` checks# against the same narrowed `_roster_allow_set`. Hyphenated, exactly as- # ms-365-mcp-server names them.+ # ms-365-mcp-server names them. Opening a OneDrive file goes through+ # `download-bytes`, allowed only for a file's content+ # (`private_turn_allows_mcp_call`)."microsoft_365__create-draft-email","microsoft_365__get-calendar-event","microsoft_365__get-calendar-view",+ "microsoft_365__get-drive-item",+ "microsoft_365__get-drive-root-item","microsoft_365__get-mail-message","microsoft_365__list-calendar-events","microsoft_365__list-calendars",+ "microsoft_365__list-drives",+ "microsoft_365__list-folder-files","microsoft_365__list-mail-folder-messages","microsoft_365__list-mail-messages","microsoft_365__search-onedrive-files",@@ -1873,16 +1889,43 @@ def private_turn_allows_mcp_tool(tool_name: object) -> bool:return isinstance(tool_name, str) and tool_name in PRIVATE_TURN_MCP_TOOLS+def is_onedrive_file_read(call_input: Any) -> bool:+ """Whether a ``call_tool`` input is ``download-bytes`` fetching one+ OneDrive file's content, the twin of ``get_drive_file_content`` and the+ only shape a private turn may run it with. Its other target, a mail+ attachment, stays out, as Gmail's attachment read does."""+ from openexecutive.orchestrator.mcp_gateway import (+ _M365_DOWNLOAD_TOOL,+ _M365_DRIVE_CONTENT_TARGET_RE,+ _normalize_tool_name,+ _unsafe_id_segment,+ )++ name = call_input.get("name") if isinstance(call_input, dict) else None+ if not isinstance(name, str) or _normalize_tool_name(name) != _M365_DOWNLOAD_TOOL:+ return False+ arguments = call_input.get("arguments")+ target = arguments.get("target") if isinstance(arguments, dict) else None+ match = _M365_DRIVE_CONTENT_TARGET_RE.fullmatch(target) if isinstance(target, str) else None+ return match is not None and not any(_unsafe_id_segment(g) for g in match.groups()[:2])+++def private_turn_allows_mcp_call(call_input: Any) -> bool:+ """Whether a turn private to the principal may run this ``call_tool``+ input: a tool in ``PRIVATE_TURN_MCP_TOOLS``, or a OneDrive file read."""+ named = call_input.get("name") if isinstance(call_input, dict) else None+ return private_turn_allows_mcp_tool(named) or is_onedrive_file_read(call_input)++def private_turn_withholds(tool_name: str, tool_input: Any) -> bool:"""Whether a turn private to the principal may not run this tool use: atool in ``PRIVATE_TURN_WITHHELD_TOOLS``, or a gateway ``call_tool`` that- names a tool outside ``PRIVATE_TURN_MCP_TOOLS``."""+ ``private_turn_allows_mcp_call`` does not allow."""if tool_name in PRIVATE_TURN_WITHHELD_TOOLS:return Trueif tool_name != "call_tool":return False- named = tool_input.get("name") if isinstance(tool_input, dict) else None- return not private_turn_allows_mcp_tool(named)+ return not private_turn_allows_mcp_call(tool_input)def private_turn_withheld_error(tool_name: str) -> str:diff --git a/packages/core/openexecutive/prompts/connected_systems.py b/packages/core/openexecutive/prompts/connected_systems.pyindex bfe0693f..0080d507 100644--- a/packages/core/openexecutive/prompts/connected_systems.py+++ b/packages/core/openexecutive/prompts/connected_systems.py@@ -50,15 +50,20 @@ GOOGLE_TOOL_MANIFEST: dict[str, tuple[str, ...]] = {"Drive": ("google_workspace__search_drive_files","google_workspace__get_drive_file_content",+ "google_workspace__list_drive_items","google_workspace__create_drive_file",),"Docs": ("google_workspace__search_docs","google_workspace__get_doc_content",+ "google_workspace__list_docs_in_folder","google_workspace__create_doc",),"Sheets": ("google_workspace__read_sheet_values",+ "google_workspace__list_spreadsheets",+ "google_workspace__get_spreadsheet_info",+ "google_workspace__list_sheet_tables","google_workspace__modify_sheet_values","google_workspace__create_spreadsheet",),diff --git a/packages/core/tests/unit/test_mail_touched_lockdown.py b/packages/core/tests/unit/test_mail_touched_lockdown.pyindex 6b682c0b..8ddf2d14 100644--- a/packages/core/tests/unit/test_mail_touched_lockdown.py+++ b/packages/core/tests/unit/test_mail_touched_lockdown.py@@ -297,6 +297,72 @@ def test_the_gateway_runs_only_reads_after_the_turn_read_mail() -> None:current_session.reset(token)+_FILE_READS = (+ "google_workspace__get_drive_file_content",+ "google_workspace__list_drive_items",+ "google_workspace__get_doc_content",+ "google_workspace__search_docs",+ "google_workspace__read_sheet_values",+ "google_workspace__get_spreadsheet_info",+ "microsoft_365__list-folder-files",+ "microsoft_365__search-onedrive-files",+)+_ONEDRIVE_FILE = {+ "name": "microsoft_365__download-bytes",+ "arguments": {"target": "/drives/d1/items/i1/content"},+}++[email protected]("name", _FILE_READS)+def test_opening_a_file_runs_after_the_turn_read_mail_and_later_in_the_conversation(name: str) -> None:+ # "Check my mail against the statements on the Drive": the files open in+ # the reading turn and in every later turn of that conversation.+ assert not lockdown.mail_touched_withholds("call_tool", {"name": name})+ assert not lockdown.carried_withholds("call_tool", {"name": name})+++def test_a_onedrive_file_opens_but_a_mail_attachment_does_not() -> None:+ attachment = {+ "name": "microsoft_365__download-bytes",+ "arguments": {"target": "/me/messages/m1/attachments/a1/$value"},+ }+ escaped = {+ "name": "microsoft_365__download-bytes",+ "arguments": {"target": "/drives/../items/i1/content"},+ }+ for withholds in (lockdown.mail_touched_withholds, lockdown.carried_withholds):+ assert not withholds("call_tool", _ONEDRIVE_FILE)+ assert not withholds("call_tool", {**_ONEDRIVE_FILE, "name": "microsoft_365__download_bytes"})+ assert withholds("call_tool", attachment)+ assert withholds("call_tool", escaped)+ assert withholds("call_tool", {"name": "microsoft_365__download-bytes"})+ assert withholds("call_tool", {**_ONEDRIVE_FILE, "arguments": "not a dict"})++[email protected]("read_mail", [True, False])+def test_the_gateway_opens_a_drive_file_in_a_conversation_that_read_mail(read_mail: bool) -> None:+ from openexecutive.orchestrator.mcp_gateway import MCPGateway++ gateway = MCPGateway.__new__(MCPGateway)+ session = Session()+ session.turn_delegation = TurnDelegation( # type: ignore[attr-defined]+ enabled=True, offered=True, touched_mail=True, read_mail=read_mail, session_id=session.session_id,+ )+ token = current_session.set(session)+ try:+ with patch.object(MCPGateway, "_require_session", side_effect=AssertionError("reached the server")):+ with pytest.raises(AssertionError, match="reached the server"):+ asyncio.run(gateway.call_tool({+ "name": "google_workspace__get_drive_file_content", "arguments": {"file_id": "f1"},+ }))+ send = asyncio.run(gateway.call_tool({+ "name": "fetch__fetch_url", "arguments": {"url": "https://x.example/"},+ }))+ assert "read the user's own mail" in json.loads(send)["error"]+ finally:+ current_session.reset(token)++class _Collect(logging.Handler):def __init__(self) -> None:super().__init__(logging.WARNING)diff --git a/packages/core/tests/unit/test_private_turns.py b/packages/core/tests/unit/test_private_turns.pyindex 72e85ba8..f83d6814 100644--- a/packages/core/tests/unit/test_private_turns.py+++ b/packages/core/tests/unit/test_private_turns.py@@ -1333,6 +1333,11 @@ def test_the_private_turn_allow_list_is_reads_and_gated_gmail_only() -> None:("google_workspace__list_calendars", True),("google_workspace__query_freebusy", True),("google_workspace__search_drive_files", True),+ ("google_workspace__get_drive_file_content", True),+ ("google_workspace__get_doc_content", True),+ ("google_workspace__read_sheet_values", True),+ ("microsoft_365__list-folder-files", True),+ ("microsoft_365__download-bytes", False), # only with a OneDrive file's target*((tool, False) for tool, _ in _REFUSED_CALLS),("google_workspace__modify_gmail_message_labels", False),("google_workspace__manage_drive_access", False),@@ -1356,6 +1361,23 @@ def test_which_mcp_tools_a_private_turn_may_call(name: Any, allowed: bool) -> Noassert private_turn_withholds("load_mcp_server", {"name": name}) is True[email protected](("target", "allowed"), [+ ("/drives/d1/items/i1/content", True),+ ("/drives/d1/items/i1/content?format=pdf", True),+ ("/me/messages/m1/attachments/a1/$value", False),+ ("/drives/%2e%2e/items/i1/content", False),+ ("/me/messages/m1/$value", False),+ (None, False),+])+def test_a_private_turn_opens_a_onedrive_file_and_nothing_else_with_download_bytes(+ target: Any, allowed: bool+) -> None:+ from openexecutive.orchestrator.schedule_tools import private_turn_withholds++ call = {"name": "microsoft_365__download-bytes", "arguments": {"target": target}}+ assert private_turn_withholds("call_tool", call) is not allowed++def test_a_normal_turn_offers_and_runs_them_unchanged(roster: SimpleNamespace) -> None:from openexecutive.orchestrator import executive as executive_modulefrom openexecutive.orchestrator.content_trust import PRINCIPAL_ONLY_TOOLS