AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(chat): keep a teammate's mail with the Executive private to them (#433)
Rufus80c297b3fc97
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex b662c214..573a9000 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -86,6 +86,7 @@ system:- The Executive never signs messages under the name of company personnel or impersonates them. An identity addendum in system block 0 instructs the model to use its own exec name/email only. The single exception is Act as me (delegation) — with the person's own switch on and on their own verified turn in a conversation private to them, `ghostwrite_email` writes an email in their voice as a DRAFT in their own Gmail, never sent from chat (only that exact draft, when they tap Send on its reply card), never from the Executive's own account or bots, and never for anyone who has not turned it on (the principal, and team members once the owner lets them). The identity addendum itself is unchanged; the constant DELEGATION_ADDENDUM after it names the exception.- Voice follows the account. Text written as a person leaves only from that person's own Gmail (always as a draft first, sent only when they send it in Gmail or tap Send on its card); the Executive's own mailbox and bots always sign as the Executive.- The model cannot reach a delegated mailbox. delegation.gmail.DelegateGmail talks to the Gmail REST API directly and is never registered with the MCP gateway, so only typed handlers (ghostwrite_email, the voice learner) call it, and its credential never lives in WORKSPACE_MCP_CREDENTIALS_DIR. Every google_workspace__* call through the gateway acts as the Executive's own account (mcp_gateway._check_acting_account refuses any other user_google_email).+ - A teammate's own mail with the Executive is private to them. Every mailbox call the model makes through the MCP gateway (call_tool, a script's calls, a workflow step run from chat) passes through orchestrator.teammate_mail.guard_call_tool. Searches exclude every other teammate's address (Gmail query -from/-to/-cc, headers forced on; Outlook lists always select the parties) and are filtered entry by entry; any other call naming a message or thread must use an id a filtered search returned to the same reader in this conversation (Session.mail_ids_seen, keyed by reader) or the inbound email the turn answers (email_poller seeds it); an Outlook call acting on a message (forward, reply, attachment) first reads its parties and is refused when it is another teammate's; a conversation where a non-principal teammate was shown their own mail is marked mail-private (session_store.mark_mail_private); Gmail thread/batch/search/attachment results are redacted in the audit log; reads are filtered message by message (a message naming another teammate is left out unless the reader is in its From / To / Cc); a Gmail reply with quote_original into a thread holding such a message is refused; Outlook search tools are refused. The reader is the principal or a teammate on a verified surface, or the teammate whose own email the turn answers when Gmail authenticated its From (Session.email_sender_authenticated); anyone else sees no teammate's mail. A background run the model drives (schedule_followup, reflection) reads as the principal; a workflow step outside any session reads as nobody (filters on, id gate off). Outlook mail rules / mailbox settings that forward or name another teammate are refused. The first turn that shows a non-principal teammate their own mail also marks that turn's remaining audit rows (its answer included) private to them. Internal callers (poller, brief) are unaffected. Fails closed when the roster can't be read.- The Executive never offers to loop in, DM, or notify the human it is currently talking to. Each chat turn carries a <current_speaker> hint in the user turn (resolved from the caller's person_id, principal-flagged) and the persona "Choosing Who to Tell" rule forbids routing to anyone already in the room — so the principal reading a brief is never told the Executive will "loop Jordan in."- Specialists run in parallel via route_parallel() for cross-domain questions.- The untrusted-content policy (orchestrator.content_trust) is the one rule for text the principal did not write — inbound email, chat, attached files, watched pages. WHO SPEAKS - the principal only when the surface proved it (principal_speaking - web chat as the principal, CLI, their own Slack/Discord or secret-verified Telegram, their own address with Gmail dmarc=pass); an empty origin_channel is never read as trust. MEMORY - episodic extraction only then, and only on words outside <untrusted_content> blocks; peer memory and open loops are recorded under the speaker's own name, never as the principal's. TOOLS - writes on the principal's authority refuse others in their handlers; PRINCIPAL_ONLY_TOOLS (load_mcp_server - it connects the install to any URL; list_saved_tools and run_python_job - the principal's own automations and library files; run_script - it runs code the model just wrote, spending the turn's whole call budget) are not offered unless the principal is speaking on an interactive surface (email excluded, even authenticated), and a call emitted anyway is refused with a not_principal audit row. LABEL - outside text sits in the user turn inside <untrusted_content source author author_verified> with a fixed no-authority notice; NFKC folds compatibility forms, control characters are dropped and the tag's name is renamed wherever the text carries it (any case, spacing, entity-escaped), so the text cannot close its block. The principal's authenticated mail is theirs, but what it quotes or forwards still goes in a block (source email_quoted). A new inbound surface is an entry in this module, not a gate invented at its call site.diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex 928076ac..6789fb1b 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 two skill tools, `search_skills` and `load_skill` (skills are shown to users as **playbooks**, and every playbook belongs to a workflow: one that follows it, or its own Quick workflow). Chat finds and reads playbooks but never creates or changes one: work worth repeating is offered as a workflow through `draft_workflow`, with the method written into its steps, because workflows read playbooks at run time (approved scheduled ones included) and this loop also runs on inbound email and chat, so only a person 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, Quick ones included, 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`: `load_mcp_server`, `list_saved_tools`, `run_python_job` and `run_script` — 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`. Both the service list and the pinned names are narrowed to what workspace-mcp actually loaded (`WORKSPACE_MCP_TOOLS`, `WORKSPACE_MCP_TOOL_TIER`), so a service left out is not named and its tools are not pinned — being told a tool is already available when it is not in the index costs a failed call the model cannot explain to itself. `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 when the gateway runs, unless `CHAT_SCRIPTS=false`, and only on the principal's own turns — `PRINCIPAL_ONLY_TOOLS`, withheld on an unattended pass too, because it spends the turn's whole call budget on code the model just wrote): 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, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), 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 (3 built-in and 2 company chunks by default, see the RAG section) 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. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. 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 only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), 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\n**Extensions** (`orchestrator.extensions`). An install can add chat tools and kinds of document without changing this code. `OPENEXECUTIVE_EXTENSIONS` names Python modules. The first turn, or the first Documents read, imports each one and calls its `register()`. A module that fails is logged and skipped. `register_tool` takes an `ExtraTool`: a definition, an async handler, an optional `tool_groups` group (new or existing) and an optional chip. It refuses a name the loop already knows (`executive.builtin_tool_names`). An extension tool is never in `_ALL_SKILL_TOOLS`, so reflection, research and the synthesis never see it. The chat loop adds it per turn, like the Act as me tools, but never on an unattended run, a turn private to the principal or to a speaker who isn't on the People list (mail from a stranger), and only where its own `offered(session)` says. That predicate depends only on the kind of turn, so each kind of turn keeps one cached tool list. Act as me's lockdown refuses it once the turn has read the owner's mail, because it is unclassified and the lockdown fails closed. Its chip goes through `action_chips.summarize_action`, which applies the same no-chip rules for an error or refusal and keeps a link to a path inside the app. `register_collection` adds a kind of document: a drafted artifact tagged `collection:<name>` carries that collection on its record. The Documents page gives each collection its own filter. The collection's `on_change` hears about archive, restore and delete before they happen; if it raises, the change does not happen. `draft_artifact(supersedes=…)` refuses a collection's document. The alert pipeline strips `collection:` tags, so only the extension's own code files a document in its collection. A module that fails partway through `register()` leaves nothing registered. A tool registered with `workflow=True` is also offered to workflow action steps as `oe__<name>` (see Workflows); `read_only=True` marks one that only reads. A step runs with nobody in the turn, so `offered` isn't asked: `extensions.in_workflow_step(name)` is True for that tool, during its call only, and the handler decides what an unattended call may do.\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.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve, **Approve + allow**, **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me is the second (`act_as_me`, per person, `delegation.training`), with a training switch per setting (Replies, Follow-ups, Suggested actions, Drafts): its rows carry the person's id and the setting in their key, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.",+ "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 two skill tools, `search_skills` and `load_skill` (skills are shown to users as **playbooks**, and every playbook belongs to a workflow: one that follows it, or its own Quick workflow). Chat finds and reads playbooks but never creates or changes one: work worth repeating is offered as a workflow through `draft_workflow`, with the method written into its steps, because workflows read playbooks at run time (approved scheduled ones included) and this loop also runs on inbound email and chat, so only a person 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, Quick ones included, 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. A teammate's own mail with the Executive is theirs the same way: every mailbox call the model makes through the MCP gateway (Gmail or Outlook, by `call_tool`, from a script, or a workflow step run from chat) passes through `orchestrator.teammate_mail`. A search excludes every other teammate's address server-side and is filtered again entry by entry; any other call that names a message or thread (read, attachment, reply, forward, label) must use an id a filtered search returned to the same reader in this conversation (`Session.mail_ids_seen`) or the inbound email the turn answers; reads are filtered message by message, so a message naming another teammate is left out unless the reader is in its From / To / Cc; a reply that would quote such a thread, or an Outlook forward, reply or attachment read of such a message, is refused; and a conversation in which a teammate other than the principal was shown their own mail becomes theirs alone, as Act as me's do. Outside mail and the reader's own are untouched; an email turn reads as its sender only when Gmail authenticated it, and any other unverified reader sees no teammate's mail, a background run the model drives reads as the principal and a workflow step outside any session as nobody, an Outlook inbox rule that forwards or names another teammate is refused, and the poller and the brief, which read the mailbox themselves, are unaffected. 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`: `load_mcp_server`, `list_saved_tools`, `run_python_job` and `run_script` — 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`. Both the service list and the pinned names are narrowed to what workspace-mcp actually loaded (`WORKSPACE_MCP_TOOLS`, `WORKSPACE_MCP_TOOL_TIER`), so a service left out is not named and its tools are not pinned — being told a tool is already available when it is not in the index costs a failed call the model cannot explain to itself. `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 when the gateway runs, unless `CHAT_SCRIPTS=false`, and only on the principal's own turns — `PRINCIPAL_ONLY_TOOLS`, withheld on an unattended pass too, because it spends the turn's whole call budget on code the model just wrote): 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, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), 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 (3 built-in and 2 company chunks by default, see the RAG section) 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. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. 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 only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), 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\n**Extensions** (`orchestrator.extensions`). An install can add chat tools and kinds of document without changing this code. `OPENEXECUTIVE_EXTENSIONS` names Python modules. The first turn, or the first Documents read, imports each one and calls its `register()`. A module that fails is logged and skipped. `register_tool` takes an `ExtraTool`: a definition, an async handler, an optional `tool_groups` group (new or existing) and an optional chip. It refuses a name the loop already knows (`executive.builtin_tool_names`). An extension tool is never in `_ALL_SKILL_TOOLS`, so reflection, research and the synthesis never see it. The chat loop adds it per turn, like the Act as me tools, but never on an unattended run, a turn private to the principal or to a speaker who isn't on the People list (mail from a stranger), and only where its own `offered(session)` says. That predicate depends only on the kind of turn, so each kind of turn keeps one cached tool list. Act as me's lockdown refuses it once the turn has read the owner's mail, because it is unclassified and the lockdown fails closed. Its chip goes through `action_chips.summarize_action`, which applies the same no-chip rules for an error or refusal and keeps a link to a path inside the app. `register_collection` adds a kind of document: a drafted artifact tagged `collection:<name>` carries that collection on its record. The Documents page gives each collection its own filter. The collection's `on_change` hears about archive, restore and delete before they happen; if it raises, the change does not happen. `draft_artifact(supersedes=…)` refuses a collection's document. The alert pipeline strips `collection:` tags, so only the extension's own code files a document in its collection. A module that fails partway through `register()` leaves nothing registered. A tool registered with `workflow=True` is also offered to workflow action steps as `oe__<name>` (see Workflows); `read_only=True` marks one that only reads. A step runs with nobody in the turn, so `offered` isn't asked: `extensions.in_workflow_step(name)` is True for that tool, during its call only, and the handler decides what an unattended call may do.\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.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve, **Approve + allow**, **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me is the second (`act_as_me`, per person, `delegation.training`), with a training switch per setting (Replies, Follow-ups, Suggested actions, Drafts): its rows carry the person's id and the setting in their key, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.","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-09T23:01:59Z"}diff --git a/packages/core/openexecutive/audit/redaction.py b/packages/core/openexecutive/audit/redaction.pyindex c5561ce7..0dc1f619 100644--- a/packages/core/openexecutive/audit/redaction.py+++ b/packages/core/openexecutive/audit/redaction.py@@ -39,6 +39,13 @@ _SENSITIVE_SUBSTRINGS = ("apikey",# Email/chat content tools — bodies are too long and may contain PII."get_gmail_message_content",+ # The rest of Gmail's readers: a thread, a batch, a search listing+ # (subjects and senders) and an attachment.+ "gmail_thread",+ "gmail_threads",+ "gmail_messages_content",+ "search_gmail_messages",+ "gmail_attachment","read_file_content","download_file_content","get_thread",diff --git a/packages/core/openexecutive/integrations/email_poller.py b/packages/core/openexecutive/integrations/email_poller.pyindex 4c1b0c48..3b2516fc 100644--- a/packages/core/openexecutive/integrations/email_poller.py+++ b/packages/core/openexecutive/integrations/email_poller.py@@ -774,6 +774,11 @@ async def _run_executive(# through the decision extractor as the principal's own words# (`content_trust.principal_speaking`).session = Session(**session_kwargs, origin_channel="email")+ # The email this turn answers is one it may read, reply in or quote,+ # whoever sent it (orchestrator.teammate_mail).+ from openexecutive.orchestrator.teammate_mail import allow_mail_ids++ allow_mail_ids(session, message_id, thread_id)if from_addr:# Who the mail claims to be from, and whether Gmail authenticated it:# the fact tools let the principal's own authenticated mail ask for a@@ -794,6 +799,19 @@ async def _run_executive(session.email_authenticated = bool(principal) and session.email_from == principal and (await sender_authenticated(gateway, message_id, from_addr))+ if not session.email_authenticated:+ # A teammate's own mail is theirs to read back only when Gmail+ # vouches the email is from them (orchestrator.teammate_mail).+ from openexecutive.people.identity import resolve_email_sender++ try:+ sender = resolve_email_sender(from_addr)+ if sender is not None and not sender.is_principal:+ session.email_sender_authenticated = await sender_authenticated(+ gateway, message_id, from_addr+ )+ except Exception: # noqa: BLE001 - optional step; must not lose the email.+ logger.warning("sender check failed; teammate mail stays private this turn", exc_info=True)if from_addr:# Only register the sender as a schedulable channel_ref if they# are in the People roster. Without this guard, an attacker whodiff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.pyindex 9c85346a..ae23d9ef 100644--- a/packages/core/openexecutive/orchestrator/executive.py+++ b/packages/core/openexecutive/orchestrator/executive.py@@ -143,6 +143,7 @@ from openexecutive.orchestrator.schedule_tools import ()from openexecutive.orchestrator.session import Sessionfrom openexecutive.orchestrator.skills_tools import SKILL_TOOL_HANDLERS, SKILL_TOOLS+from openexecutive.orchestrator.teammate_mail import guard_call_toolfrom openexecutive.orchestrator.turn_inbox import (TurnInbox,render_added_messages,@@ -2724,9 +2725,11 @@ class Executive:)if mcp_tool_uses and self._mcp_gateway is not None:+ # A teammate's mail with the Executive stays theirs: every+ # mailbox read the model makes is filtered (teammate_mail)._mcp_dispatch = {"search_tools": self._mcp_gateway.search_tools,- "call_tool": (+ "call_tool": guard_call_tool(take_the_lead.gated_call_tool(self._mcp_gateway.call_tool, source="scheduled")if leadingelse self._mcp_gateway.call_tool@@ -2815,7 +2818,7 @@ class Executive:# matters: the gateway's own gates (discovery, deny-list,# recipients), Take the lead's gate on an unattended run, and# the same chip and audit row, as each call happens.- script_call = (+ script_call = guard_call_tool(take_the_lead.gated_call_tool(self._mcp_gateway.call_tool, source="scheduled")if leadingelse self._mcp_gateway.call_tooldiff --git a/packages/core/openexecutive/orchestrator/session.py b/packages/core/openexecutive/orchestrator/session.pyindex 5f47d570..df46cd4f 100644--- a/packages/core/openexecutive/orchestrator/session.py+++ b/packages/core/openexecutive/orchestrator/session.py@@ -32,6 +32,11 @@ class Session:# Used by schedule_followup to refuse scheduling sends to refs the user# never actually used — anti-spam guard.seen_channel_refs: set[tuple[str, str]] = field(default_factory=set)+ # Mailbox message and thread ids this conversation was shown by a search+ # that left other teammates' mail out (or the inbound email it answers).+ # The model may reach the Executive's mailbox only by these+ # (orchestrator.teammate_mail).+ mail_ids_seen: set[str] = field(default_factory=set)# Which inbound channel this session arrived on ("slack", "discord",# "telegram", "google_chat", "email"), and the address on it. Empty for# web/CLI turns and runs nobody started from a channel. Used when a@@ -142,6 +147,10 @@ class Session:# (``orchestrator.fact_tools``) — a From line alone proves nothing.email_from: str = ""email_authenticated: bool = False+ # Whether Gmail authenticated the From of a teammate's (not the+ # principal's) inbound email: only then does the turn read the mailbox as+ # that teammate (orchestrator.teammate_mail).+ email_sender_authenticated: bool = False# Act as me for the turn in progress (``delegation.settings.TurnDelegation``),# pinned at its start by ``pin_turn_delegation``: whether the speaker has# it on, whether ``ghostwrite_email`` is offered, and whether the turn hasdiff --git a/packages/core/openexecutive/orchestrator/teammate_mail.py b/packages/core/openexecutive/orchestrator/teammate_mail.pynew file mode 100644index 00000000..e20d3e44--- /dev/null+++ b/packages/core/openexecutive/orchestrator/teammate_mail.py@@ -0,0 +1,610 @@+"""A teammate's mail with the Executive is theirs: the chat reaches the+Executive's mailbox only around it.++Teammates email the Executive the way they would message it in chat, and the+Executive's mailbox keeps every one of those threads. The gateway's mail+tools (Gmail through Google Workspace, Outlook through Microsoft 365) reach+whatever the mailbox holds, so without this any turn that may call them (the+principal's, an admin's) could search "from:" a teammate and read, quote or+forward what they sent. ``guard_call_tool`` wraps every mailbox call the+model makes (the chat's ``call_tool``, a script's calls, a workflow step run+from chat) with three rules:++1. **Searches leave teammates out.** A Gmail search gets ``-from: -to: -cc:``+ for every other teammate's address and always asks for headers; an+ Outlook list always selects who a message is from and to. What comes back+ is filtered again, entry by entry.+2. **Mail is reached only by an id the conversation was shown.** Every other+ mail call that names a message or thread (read it, its attachments,+ reply in it, forward it, label it) must name one a filtered search or+ list returned to this same reader in this conversation+ (``Session.mail_ids_seen``), or the inbound email the turn is answering.+ An id from anywhere else is refused. An Outlook call that forwards,+ replies to or downloads from a message first reads who it is between,+ and is refused when it is another teammate's.+3. **Reads are filtered message by message.** A message, or a message inside+ a thread or batch, is another teammate's when an address of a rostered+ teammate other than the reader appears anywhere in it and none of the+ reader's own addresses is in its From / To / Cc headers. A thread keeps+ the rest and says how many it left out; a single read is withheld. A+ reply that would quote such a thread (``quote_original``) is refused.++Outside mail (vendors, counsel, the principal's contacts) and the reader's+own mail are untouched. The reader is the principal or a teammate on a+surface that proved who they are, or the teammate whose own email the turn+is answering when Gmail authenticated it; on any other turn every+teammate's mail is left out. A conversation in which a teammate other than+the principal was shown their own mail becomes theirs alone, as Act as me's+do (``session_store.mark_mail_private``), and so do the rest of that turn's+audit rows. A background run the model drives (a follow-up, the reflection)+reads as the principal it reports to; a workflow step outside any session+reads as nobody. An Outlook inbox rule that forwards, or names another+teammate, is refused. The internal callers that reach the gateway directly+(the email poller, the brief) are unaffected. Fails closed: when the roster+can't be read, the call is refused.+"""+from __future__ import annotations++import json+import logging+import re+from collections.abc import Awaitable, Callable, Iterator+from dataclasses import dataclass, field+from typing import Any++from openexecutive.people.identity import RosterAllow, addresses_of++logger = logging.getLogger(__name__)++_GW_PREFIX = "google_workspace__"+_M365_PREFIX = "microsoft_365__"++_ADDRESS_RE = re.compile(r"[\w.%+'-]+@[\w.-]+\.\w{2,}", re.UNICODE)+# The header lines that say who a message is between, in workspace-mcp's+# plain-text output ("From: Ada <[email protected]>").+_HEADER_RE = re.compile(r"^\s*(?:from|to|cc|reply-to)\s*:(.*)$", re.IGNORECASE | re.MULTILINE)+# Where each message of a thread or batch read starts. A body line that+# looks like one only splits it further, which can hide more, never less.+_MESSAGE_START_RE = re.compile(r"^(?=Message ID:|=== Message \d+ ===)", re.MULTILINE)+_THREAD_MESSAGE_RE = re.compile(r"^(?==== Message \d+ ===)", re.MULTILINE)+# A Gmail search listing: its entries (" 3. Message ID: ...") up to the+# usage notes.+_SEARCH_HEAD_RE = re.compile(r"^📧 MESSAGES:\s*$", re.MULTILINE)+_SEARCH_ENTRY_RE = re.compile(r"^ \d+\. Message", re.MULTILINE)+_SEARCH_TAIL_RE = re.compile(r"^💡 USAGE:", re.MULTILINE)+_LISTED_ID_RE = re.compile(r"^\s*(?:\d+\.\s*)?(?:Message|Thread) ID:\s*(\S+)", re.MULTILINE)+# Gmail argument keys that name a message or thread.+_GMAIL_ID_KEYS = frozenset({"message_id", "message_ids", "thread_id", "thread_ids"})+# Outlook: argument keys that name a message (normalized), and a Graph path+# that does.+_M365_ID_KEYS = frozenset({"messageid"})+_M365_PATH_ID_RE = re.compile(r"/messages/([^/?$]+)", re.IGNORECASE)+_M365_LIST_TOOLS = frozenset({"list_mail_messages", "list_mail_folder_messages"})+_M365_PARTY_FIELDS = "id,conversationId,from,sender,toRecipients,ccRecipients,bccRecipients"+_GRAPH_PARTY_KEYS = frozenset({+ "from", "sender", "torecipients", "ccrecipients", "bccrecipients", "replyto",+})++PRIVATE_NOTE = (+ "This email involves another teammate and is their own mail with the "+ "Executive, so it is private to them. Say so plainly and suggest asking "+ "them directly; don't guess what it says."+)+BATCH_NOTE = (+ "At least one of these emails involves another teammate and is their own "+ "mail with the Executive, so it is private to them, and the batch was not "+ "returned. Read the others one at a time; don't guess what the private ones say."+)+LEFT_OUT_NOTE = (+ "Left out {count} {noun} involving another teammate: a teammate's own mail "+ "with the Executive is private to them."+)+UNSEEN_ID_NOTE = (+ "{tool} was not run: it names an email this conversation hasn't found. "+ "Search the mailbox first and use an id from the results."+)+QUOTE_NOTE = (+ "{tool} was not run: that thread holds another teammate's own mail with "+ "the Executive, which is private to them, so it can't be quoted. Send "+ "without quote_original."+)+SEARCH_REFUSED_NOTE = (+ "{tool} is not available for the mailbox here. Use list-mail-messages "+ "with a search or filter instead."+)+ROSTER_NOTE = "{tool} was not run: the roster could not be read. Try again."+RULE_NOTE = (+ "{tool} was not run: a mailbox rule that forwards mail, or names another "+ "teammate, could pass on a teammate's own mail with the Executive, which "+ "is private to them."+)+QUERY_NOTE = (+ "{tool} was not run: close every quote and bracket in the query and try again."+)+OUTLOOK_THEIRS_NOTE = (+ "{tool} was not run: that email involves another teammate and is their "+ "own mail with the Executive, which is private to them."+)+++@dataclass+class _Sides:+ reader: RosterAllow+ others: RosterAllow+ other_addresses: list[str]+ reader_id: int | None = None+ reader_is_principal: bool = False+ seen: set[str] = field(default_factory=set)+ # Off only outside any session (a scheduled workflow step), which has+ # nowhere to keep what it was shown; its searches and reads stay filtered.+ gate_ids: bool = True++ @property+ def key(self) -> str:+ return str(self.reader_id) if self.reader_id is not None else "-"++ def saw(self, mail_id: str) -> bool:+ return f"{self.key}:{mail_id}" in self.seen or f"*:{mail_id}" in self.seen++ def remember(self, mail_id: str) -> None:+ self.seen.add(f"{self.key}:{mail_id}")+++def _norm(name: str) -> str:+ return name.strip().lower().replace("-", "_")+++def _gmail(name: str) -> bool:+ n = _norm(name)+ return n.startswith(_GW_PREFIX) and "gmail" in n+++def _m365_ids(value: Any, key: str = "", depth: int = 0) -> Iterator[str]:+ """Every message id an Outlook call's arguments name: by key, or in a+ Graph path (``/me/messages/{id}/attachments/...``)."""+ if depth > 8:+ return+ if isinstance(value, dict):+ for k, v in value.items():+ yield from _m365_ids(v, str(k), depth + 1)+ elif isinstance(value, list):+ for v in value:+ yield from _m365_ids(v, key, depth + 1)+ elif isinstance(value, str):+ if re.sub(r"[^a-z]", "", key.lower()) in _M365_ID_KEYS:+ yield value+ yield from (m.group(1) for m in _M365_PATH_ID_RE.finditer(value))+++def _gmail_ids(arguments: dict[str, Any]) -> list[str]:+ out: list[str] = []+ for key, value in arguments.items():+ if str(key).lower() not in _GMAIL_ID_KEYS:+ continue+ for v in value if isinstance(value, list) else [value]:+ if v not in (None, ""):+ out.append(str(v))+ return out+++def is_mail_call(tool_name: object, arguments: Any) -> bool:+ """Whether a gateway call reaches the Executive's mailbox: any Gmail tool,+ any Outlook mail, message or search tool, or an Outlook call naming a+ message."""+ if not isinstance(tool_name, str):+ return False+ if _gmail(tool_name):+ return True+ n = _norm(tool_name)+ if not n.startswith(_M365_PREFIX):+ return False+ tail = n[len(_M365_PREFIX):]+ if "search" in tail and "onedrive" not in tail:+ # A Graph search can return mail hits without naming a message.+ return True+ return "mail" in tail or "message" in tail or any(True for _ in _m365_ids(arguments))+++def _reader_id(session: Any) -> int | None:+ """Who is reading: the principal or a teammate on a surface that proved+ it, or the teammate whose own email this turn answers. None otherwise."""+ from openexecutive.orchestrator.content_trust import principal_speaking+ from openexecutive.orchestrator.people_tools import teammate_on_verified_surface+ from openexecutive.people.store import find_principal_person, get_person++ caller = getattr(session, "caller_person_id", None)+ if getattr(session, "unattended", False) is True:+ # A background run (a follow-up, the reflection) works for the+ # principal and reports to them: it reads as them.+ principal = find_principal_person()+ return principal.id if principal is not None else None+ if principal_speaking(session):+ if caller is not None:+ return int(caller)+ principal = find_principal_person()+ return principal.id if principal is not None else None+ teammate = teammate_on_verified_surface(session)+ if teammate is not None:+ return int(teammate.id)+ if (+ str(getattr(session, "origin_channel", "") or "") == "email"+ and caller is not None+ and getattr(session, "email_sender_authenticated", False) is True+ ):+ person = get_person(int(caller))+ if person is not None and person.kind == "team" and not person.archived:+ return int(person.id) if person.id is not None else None+ return None+++def _sides(session: Any) -> _Sides | None:+ """This turn's reader and other teammates, or None when the roster can't+ be read."""+ from openexecutive.people.store import list_people++ try:+ reader_id = _reader_id(session) if session is not None else None+ team = [p for p in list_people() if p.kind == "team"]+ except Exception:+ logger.warning("teammate_mail: roster read failed — refusing", exc_info=True)+ return None+ reader = [p for p in team if reader_id is not None and p.id == reader_id]+ others = [p for p in team if reader_id is None or p.id != reader_id]+ seen = getattr(session, "mail_ids_seen", None) if session is not None else None+ return _Sides(+ reader=RosterAllow(reader),+ others=RosterAllow(others),+ other_addresses=sorted({a.strip().lower() for p in others for a in addresses_of(p) if a}),+ reader_id=reader_id,+ reader_is_principal=any(p.is_principal for p in reader),+ seen=seen if isinstance(seen, set) else set(),+ gate_ids=session is not None,+ )+++def allow_mail_ids(session: Any, *ids: str) -> None:+ """Let this conversation reach these mailbox ids (the inbound email a+ turn is answering)."""+ seen = getattr(session, "mail_ids_seen", None)+ if isinstance(seen, set):+ seen.update(f"*:{i}" for i in ids if i)+++def _addresses(text: str) -> list[str]:+ return _ADDRESS_RE.findall(text)+++def _theirs(unit: str, headers: str, sides: _Sides) -> bool:+ """Whether ``unit`` is another teammate's mail: one of their addresses+ is anywhere in it and none of the reader's is in ``headers``."""+ if not any(a in sides.others for a in _addresses(unit)):+ return False+ return not any(a in sides.reader for a in _addresses(headers))+++def _text_headers(unit: str) -> str:+ """The From / To / Cc / Reply-To values of a message's header block: the+ lines before its first blank line. A body line that looks like a header+ (a quoted "To: ...") is the sender's text and never counts."""+ block = re.split(r"\n[ \t]*\n", unit.lstrip("\n"), maxsplit=1)[0]+ return "\n".join(m.group(1) for m in _HEADER_RE.finditer(block))+++def _reader_in_headers(name: str, text: str, sides: _Sides) -> bool:+ """Whether a result shows the reader mail they are on: their address in+ a message's From / To / Cc, not anywhere in a body."""+ if _gmail(name):+ units = [u for u in _MESSAGE_START_RE.split(text) if u.strip()]+ headers = "\n".join(_text_headers(u) for u in units)+ return any(a in sides.reader for a in _addresses(headers))+ try:+ data = json.loads(text)+ except (ValueError, RecursionError):+ return False+ items = data.get("value") if isinstance(data, dict) else data+ items = items if isinstance(items, list) else [data]+ return any(a in sides.reader for i in items for a in _addresses(_graph_parties(i)))+++def _left_out(count: int) -> str:+ return LEFT_OUT_NOTE.format(count=count, noun="message" if count == 1 else "messages")+++def _refusal(note: str) -> str:+ return json.dumps({"error": note})+++# ── before the call ──────────────────────────────────────────────────────+++def _balanced(query: str) -> bool:+ """Whether the model's query leaves the exclusions appended to it alone:+ quotes paired, brackets closed."""+ if query.count('"') % 2:+ return False+ for open_, close in ("()", "{}"):+ depth = 0+ for ch in query:+ depth += (ch == open_) - (ch == close)+ if depth < 0:+ return False+ if depth:+ return False+ return True+++def _gmail_query(query: str, sides: _Sides) -> str:+ excluded = " ".join(f"-{{from:{a} to:{a} cc:{a}}}" for a in sides.other_addresses)+ if not excluded:+ return query+ return f"({query}) {excluded}" if query.strip() else excluded+++def _with_party_fields(select: Any) -> Any:+ fields = _M365_PARTY_FIELDS.split(",")+ if isinstance(select, list):+ return [*select, *(f for f in fields if f not in select)]+ if isinstance(select, str) and select.strip():+ return f"{select},{_M365_PARTY_FIELDS}"+ return select+++def _prepare(name: str, arguments: dict[str, Any], sides: _Sides) -> tuple[str | None, dict[str, Any]]:+ """``(refusal, arguments to send)`` for a mailbox call."""+ n = _norm(name)+ if _gmail(name):+ if n == _GW_PREFIX + "search_gmail_messages":+ if not _balanced(str(arguments.get("query") or "")):+ return _refusal(QUERY_NOTE.format(tool=name)), arguments+ return None, {+ **arguments,+ "query": _gmail_query(str(arguments.get("query") or ""), sides),+ "include_headers": True,+ }+ if sides.gate_ids and any(not sides.saw(i) for i in _gmail_ids(arguments)):+ return _refusal(UNSEEN_ID_NOTE.format(tool=name)), arguments+ return None, arguments+ tail = n[len(_M365_PREFIX):]+ if "search" in tail and "onedrive" not in tail:+ return _refusal(SEARCH_REFUSED_NOTE.format(tool=name)), arguments+ if "rule" in tail or "mailbox_settings" in tail:+ # An inbox rule or mailbox setting acts on mail still to come: one+ # that forwards, or names another teammate, is refused.+ text = json.dumps(arguments, ensure_ascii=False).lower()+ if "forward" in text or "redirect" in text or any(a in sides.others for a in _addresses(text)):+ return _refusal(RULE_NOTE.format(tool=name)), arguments+ if sides.gate_ids and any(not sides.saw(i) for i in _m365_ids(arguments)):+ return _refusal(UNSEEN_ID_NOTE.format(tool=name)), arguments+ if tail in _M365_LIST_TOOLS or tail == "get_mail_message":+ return None, {+ k: _with_party_fields(v) if re.sub(r"[^a-z]", "", str(k).lower()) == "select" else v+ for k, v in arguments.items()+ }+ return None, arguments+++# ── after the call ───────────────────────────────────────────────────────+++def _filter_listing(text: str, sides: _Sides) -> str | None:+ """A Gmail search listing with other teammates' entries dropped and the+ kept ids remembered, or None when ``text`` is not one."""+ head = _SEARCH_HEAD_RE.search(text)+ if head is None:+ return None+ tail = _SEARCH_TAIL_RE.search(text, head.end())+ body_end = tail.start() if tail else len(text)+ body = text[head.end():body_end]+ starts = [m.start() for m in _SEARCH_ENTRY_RE.finditer(body)]+ if not starts:+ return "No messages to show."+ entries = [body[s:e] for s, e in zip(starts, [*starts[1:], len(body)], strict=True)]+ # An entry whose headers didn't come back can't be checked: dropped.+ kept = [e for e in entries if "From:" in e and not _theirs(e, _text_headers(e), sides)]+ for entry in kept:+ for mail_id in _LISTED_ID_RE.findall(entry):+ sides.remember(mail_id)+ dropped = len(entries) - len(kept)+ if not dropped:+ return text+ if not kept:+ return f"No messages to show. {_left_out(dropped)}"+ return text[:head.end()] + "\n" + "".join(kept) + _left_out(dropped) + "\n\n" + text[body_end:]+++def _filter_thread(text: str, sides: _Sides) -> str:+ parts = _THREAD_MESSAGE_RE.split(text)+ head, messages = parts[0], parts[1:]+ if not messages:+ if _theirs(text, _text_headers(text), sides):+ return json.dumps({"withheld": True, "note": PRIVATE_NOTE})+ return text+ kept = [m for m in messages if not _theirs(m, _text_headers(m), sides)]+ dropped = len(messages) - len(kept)+ if not dropped:+ return text+ if not kept:+ return json.dumps({"withheld": True, "note": PRIVATE_NOTE})+ # The head's subject is the first message's, which may be one left out.+ head = "".join(line for line in head.splitlines(keepends=True) if line.startswith("Thread ID:"))+ return head + "\n" + "".join(kept) + "\n" + _left_out(dropped)+++def _graph_parties(item: Any) -> str:+ if not isinstance(item, dict):+ return ""+ return "\n".join(+ json.dumps(v, ensure_ascii=False)+ for k, v in item.items()+ if isinstance(k, str) and k.lower() in _GRAPH_PARTY_KEYS+ )+++def _graph_theirs(item: Any, sides: _Sides) -> bool:+ return _theirs(json.dumps(item, ensure_ascii=False), _graph_parties(item), sides)+++def _filter_graph(text: str, sides: _Sides, listing: bool) -> str:+ try:+ data = json.loads(text)+ except (ValueError, RecursionError):+ data = None+ if data is None:+ if _theirs(text, _text_headers(text), sides):+ return json.dumps({"withheld": True, "note": PRIVATE_NOTE})+ return text+ items = data.get("value") if isinstance(data, dict) else data if isinstance(data, list) else None+ if isinstance(items, list):+ kept = [i for i in items if not _graph_theirs(i, sides)]+ if listing:+ for item in kept:+ if isinstance(item, dict) and isinstance(item.get("id"), str):+ sides.remember(item["id"])+ dropped = len(items) - len(kept)+ if not dropped:+ return text+ base = data if isinstance(data, dict) else {}+ return json.dumps({**base, "value": kept, "private_note": _left_out(dropped)}, ensure_ascii=False)+ if _graph_theirs(data, sides):+ return json.dumps({"withheld": True, "note": PRIVATE_NOTE})+ return text+++def _filter(name: str, text: str, sides: _Sides) -> str:+ n = _norm(name)+ if not _gmail(name):+ return _filter_graph(text, sides, listing=n[len(_M365_PREFIX):] in _M365_LIST_TOOLS)+ if n == _GW_PREFIX + "search_gmail_messages":+ listing = _filter_listing(text, sides)+ return text if listing is None else listing+ if not any(a in sides.others for a in _addresses(text)):+ return text+ if "batch" in n:+ # Decided message by message: one of the reader's in the batch must+ # not carry a teammate's along with it.+ units = [u for u in _MESSAGE_START_RE.split(text) if u.strip()]+ if any(_theirs(u, _text_headers(u), sides) for u in units):+ return json.dumps({"withheld": True, "note": BATCH_NOTE})+ return text+ if "thread" in n:+ return _filter_thread(text, sides)+ if _theirs(text, _text_headers(text), sides):+ return json.dumps({"withheld": True, "note": PRIVATE_NOTE})+ return text+++# ── the wrapper ──────────────────────────────────────────────────────────+++CallTool = Callable[[dict[str, Any]], Awaitable[str]]+++async def _quotes_teammate(call: CallTool, arguments: dict[str, Any], sides: _Sides) -> bool:+ """Whether a Gmail send / draft with ``quote_original`` would quote a+ thread holding another teammate's mail. A failed read counts as yes."""+ thread_id = arguments.get("thread_id")+ if not arguments.get("quote_original") or not thread_id:+ return False+ try:+ text = await call({+ "name": _GW_PREFIX + "get_gmail_thread_content",+ "arguments": {+ "thread_id": thread_id,+ "user_google_email": arguments.get("user_google_email", ""),+ },+ })+ except Exception:+ logger.warning("teammate_mail: thread read for quote_original failed — refusing", exc_info=True)+ return True+ return not isinstance(text, str) or _filter_thread(text, sides) != text+++_M365_PARTY_READ = _M365_PARTY_FIELDS + ",body"+++async def _outlook_theirs(call: CallTool, name: str, arguments: dict[str, Any], sides: _Sides) -> bool:+ """Whether an Outlook call that acts on a message (forward, reply, an+ attachment) names another teammate's. A failed read counts as yes."""+ tail = _norm(name)[len(_M365_PREFIX):]+ if tail == "get_mail_message" or tail in _M365_LIST_TOOLS:+ return False+ for message_id in set(_m365_ids(arguments)):+ try:+ text = await call({+ "name": _M365_PREFIX + "get-mail-message",+ "arguments": {"messageId": message_id, "select": _M365_PARTY_READ},+ })+ data = json.loads(text)+ except Exception:+ logger.warning("teammate_mail: Outlook party read failed — refusing", exc_info=True)+ return True+ if not isinstance(data, dict) or "error" in data or _graph_theirs(data, sides):+ return True+ return False+++def _keep_private(session: Any, sides: _Sides) -> None:+ """A teammate other than the principal was shown their own mail: the+ conversation becomes theirs alone, as Act as me's do."""+ session_id = getattr(session, "session_id", None)+ if sides.reader_id is None or sides.reader_is_principal or not session_id:+ return+ from openexecutive.delegation.settings import history_len+ from openexecutive.memory.session_store import mark_mail_private++ try:+ mark_mail_private(str(session_id), sides.reader_id, history_len=history_len(session))+ except Exception:+ logger.exception("teammate_mail: couldn't mark the conversation private")+ # The rest of this turn's rows, its answer included, are theirs too.+ from openexecutive.delegation.settings import turn_delegation++ pinned = turn_delegation(session)+ if pinned is not None and pinned.person_id in (None, sides.reader_id):+ pinned.touched_mail = True+ pinned.person_id = sides.reader_id+++def guard_call_tool(call: CallTool) -> CallTool:+ """``call`` with the module's rules on every mailbox call the model makes."""+ from openexecutive.orchestrator.schedule_tools import current_session++ async def guarded(tool_input: dict[str, Any]) -> str:+ name = tool_input.get("name") if isinstance(tool_input, dict) else None+ arguments = tool_input.get("arguments", {}) if isinstance(tool_input, dict) else {}+ if isinstance(arguments, str):+ try:+ arguments = json.loads(arguments)+ except (ValueError, RecursionError):+ arguments = {}+ if not isinstance(name, str) or not is_mail_call(name, arguments):+ return await call(tool_input)+ session = current_session.get()+ sides = _sides(session)+ if sides is None:+ return _refusal(ROSTER_NOTE.format(tool=name))+ if not sides.other_addresses or not isinstance(arguments, dict):+ return await call(tool_input)+ refused, arguments = _prepare(name, arguments, sides)+ if refused is not None:+ return refused+ if _gmail(name) and await _quotes_teammate(call, arguments, sides):+ return _refusal(QUOTE_NOTE.format(tool=name))+ if not _gmail(name) and await _outlook_theirs(call, name, arguments, sides):+ return _refusal(OUTLOOK_THEIRS_NOTE.format(tool=name))+ result = await call({**tool_input, "arguments": arguments})+ if not isinstance(result, str):+ return result+ filtered = _filter(name, result, sides)+ if _reader_in_headers(name, filtered, sides):+ _keep_private(session, sides)+ return filtered++ return guarded+++def guard_in_turn(call: CallTool) -> CallTool:+ """``guard_call_tool`` for a caller that runs both inside a chat turn and+ on its own (a workflow step, the reflection pass). Outside a session the+ reader is nobody: searches and reads leave every teammate's mail out."""+ return guard_call_tool(call)diff --git a/packages/core/openexecutive/workflows/action_step.py b/packages/core/openexecutive/workflows/action_step.pyindex 132d20b0..e6e0c18f 100644--- a/packages/core/openexecutive/workflows/action_step.py+++ b/packages/core/openexecutive/workflows/action_step.py@@ -408,7 +408,13 @@ async def _dispatch(name: str, arguments: dict[str, Any], info: tool_catalog.Toogateway = get_active_gateway()if gateway is None:return json.dumps({"error": "the tool gateway is not running"})- return await gateway.call_tool({"name": name, "arguments": arguments})+ # A step reaches the mailbox the way the chat does+ # (orchestrator.teammate_mail): run from a chat turn, as that turn's+ # reader; scheduled, with no session, as nobody, so every teammate's own+ # mail stays out.+ from openexecutive.orchestrator.teammate_mail import guard_in_turn++ return await guard_in_turn(gateway.call_tool)({"name": name, "arguments": arguments})async def _call_tool(diff --git a/packages/core/openexecutive/workflows/executive_reflection.py b/packages/core/openexecutive/workflows/executive_reflection.pyindex a1495207..6642ff3f 100644--- a/packages/core/openexecutive/workflows/executive_reflection.py+++ b/packages/core/openexecutive/workflows/executive_reflection.py@@ -493,12 +493,16 @@ def _with_lead_tools(return tools, handlers, Falseif gateway is None:return tools, handlers, True+ from openexecutive.orchestrator.teammate_mail import guard_in_turn+extra = [t for t in MCP_TOOLS if t["name"] in ("search_tools", "call_tool")]tools = sorted([*tools, *extra], key=lambda t: t["name"])handlers = {**handlers,"search_tools": gateway.search_tools,- "call_tool": take_the_lead.gated_call_tool(gateway.call_tool, source="reflection"),+ # Run from a chat turn, the pass reaches the mailbox the way the chat+ # does (orchestrator.teammate_mail).+ "call_tool": guard_in_turn(take_the_lead.gated_call_tool(gateway.call_tool, source="reflection")),}return tools, handlers, Truediff --git a/packages/core/tests/unit/test_private_turns.py b/packages/core/tests/unit/test_private_turns.pyindex 2378561d..aae1f861 100644--- a/packages/core/tests/unit/test_private_turns.py+++ b/packages/core/tests/unit/test_private_turns.py@@ -30,9 +30,9 @@ from openexecutive.departments import store as dept_storefrom openexecutive.memory import episodicfrom openexecutive.orchestrator.schedule_tools import current_sessionfrom openexecutive.orchestrator.session import Session-from tests.unit.offered_tools import capture_offeredfrom openexecutive.people import registry as people_registryfrom openexecutive.people import store as people_store+from tests.unit.offered_tools import capture_offeredEXEC = "[email protected]"OWNER_EMAIL = "[email protected]"@@ -1253,6 +1253,11 @@ def _run_mcp_round(session: Session) -> tuple[_ScriptedStreams, dict[str, str],import openexecutive.orchestrator.mcp_gateway as gw_modulegateway, reached = _real_gateway()+ # The round reads message m1 as if a search had shown it: the chat reaches+ # mail only by an id it was shown (orchestrator.teammate_mail).+ from openexecutive.orchestrator.teammate_mail import allow_mail_ids++ allow_mail_ids(session, "m1")with patch.object(gw_module, "get_settings",return_value=SimpleNamespace(exec_email_address=EXEC)):provider = _run_loop(session, _mcp_round(), gateway=gateway)diff --git a/packages/core/tests/unit/test_teammate_mail.py b/packages/core/tests/unit/test_teammate_mail.pynew file mode 100644index 00000000..e1488087--- /dev/null+++ b/packages/core/tests/unit/test_teammate_mail.py@@ -0,0 +1,406 @@+"""A teammate's mail with the Executive is theirs: the chat reaches the+Executive's mailbox only around it (orchestrator/teammate_mail.py)."""+from __future__ import annotations++import asyncio+import json+from collections.abc import Iterator+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import patch++import pytest++from openexecutive.memory import episodic+from openexecutive.orchestrator import teammate_mail as tm+from openexecutive.orchestrator.schedule_tools import current_session+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store++OWNER = "[email protected]"+TEAMMATE = "[email protected]"+VENDOR = "[email protected]"+EXEC = "[email protected]"++SEARCH = "google_workspace__search_gmail_messages"+READ = "google_workspace__get_gmail_message_content"+THREAD = "google_workspace__get_gmail_thread_content"+BATCH = "google_workspace__get_gmail_messages_content_batch"+SEND = "google_workspace__send_gmail_message"+OUTLOOK_LIST = "microsoft_365__list-mail-messages"++[email protected](autouse=True)+def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]:+ path = tmp_path / "people.db"+ monkeypatch.setattr(people_store, "DB_PATH", path)+ monkeypatch.setattr(episodic, "DB_PATH", path)+ episodic.initialize_db(path)+ people_store.initialize_db()+ people_registry.invalidate()+ owner = people_store.upsert_person(full_name="Olivia Owner", is_principal=True, email=OWNER)+ ben = people_store.upsert_person(full_name="Ben Teammate", role="Ops", email=TEAMMATE)+ session = SimpleNamespace(unattended=False, mail_ids_seen=set(), caller_person_id=owner)+ token = current_session.set(session)+ yield SimpleNamespace(owner=owner, ben=ben, session=session)+ current_session.reset(token)+ people_registry.invalidate()+++def _reader(person_id: int | None): # type: ignore[no-untyped-def]+ return patch.object(tm, "_reader_id", lambda _s: person_id)+++class FakeMailbox:+ """The gateway's call_tool: canned results by tool name, calls recorded."""++ def __init__(self, results: dict[str, str]) -> None:+ self.results = results+ self.calls: list[dict[str, Any]] = []++ async def __call__(self, tool_input: dict[str, Any]) -> str:+ self.calls.append(tool_input)+ return self.results.get(tool_input["name"], "ok")+++def _run(mailbox: FakeMailbox, name: str, **arguments: Any) -> str:+ return asyncio.run(tm.guard_call_tool(mailbox)({"name": name, "arguments": arguments}))+++def _message(sender: str, to: str, body: str = "Numbers attached.", mid: str = "m1") -> str:+ return (+ f"Message ID: {mid}\nSubject: Q3 numbers\nFrom: Someone <{sender}>\n"+ f"To: {to}\nCc: [not present in Gmail response]\n\n--- BODY ---\n{body}\n"+ )+++def _listing(*senders: str) -> str:+ lines = [f"Found {len(senders)} messages matching 'q':", "", "📧 MESSAGES:"]+ for i, sender in enumerate(senders, 1):+ lines += [+ f" {i}. Message ID: m{i}",+ f" Subject: Subject {i}",+ f" From: Person {i} <{sender}>",+ " Date: Mon, 5 Oct 2026",+ f" Web Link: https://mail.google.com/m{i}",+ f" Thread ID: t{i}",+ f" Thread Link: https://mail.google.com/t{i}",+ "",+ ]+ lines += ["💡 USAGE:", " • Pass the Message IDs as a list"]+ return "\n".join(lines)+++def _thread(*messages: tuple[str, str, str]) -> str:+ text = "Thread ID: t1\nSubject: Taxes\nMessages: 2\n\n"+ for i, (sender, to, body) in enumerate(messages, 1):+ text += f"=== Message {i} ===\nFrom: {sender}\nTo: {to}\n\n{body}\n\n"+ return text+++# ── searches ──────────────────────────────────────────────────────────────+++def test_a_search_leaves_teammates_out_and_asks_for_headers(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({SEARCH: _listing(VENDOR)})+ with _reader(roster.owner):+ _run(mailbox, SEARCH, query="from:ben", user_google_email=EXEC)+ sent = mailbox.calls[0]["arguments"]+ assert sent["include_headers"] is True+ assert sent["query"].startswith("(from:ben) ")+ assert f"-{{from:{TEAMMATE} to:{TEAMMATE} cc:{TEAMMATE}}}" in sent["query"]+ assert OWNER not in sent["query"]+++def test_a_listing_drops_the_teammates_entries_and_remembers_the_rest(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({SEARCH: _listing(VENDOR, TEAMMATE)})+ with _reader(roster.owner):+ out = _run(mailbox, SEARCH, query="q")+ assert "Subject 1" in out and "Subject 2" not in out and TEAMMATE not in out+ assert "Left out 1 message involving another teammate" in out+ assert {f"{roster.owner}:m1", f"{roster.owner}:t1"} <= roster.session.mail_ids_seen+ assert not any(i.endswith(":m2") for i in roster.session.mail_ids_seen)+++def test_a_listing_without_headers_shows_nothing(roster: SimpleNamespace) -> None:+ bare = "Found 1 messages matching 'q':\n\n📧 MESSAGES:\n 1. Message ID: m9\n Thread ID: t9\n\n💡 USAGE:\n"+ with _reader(roster.owner):+ out = _run(FakeMailbox({SEARCH: bare}), SEARCH, query="q")+ assert "m9" not in out and not roster.session.mail_ids_seen+++# ── reaching mail by id ───────────────────────────────────────────────────+++def test_an_id_the_conversation_was_not_shown_is_refused(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({READ: _message(VENDOR, EXEC)})+ with _reader(roster.owner):+ out = _run(mailbox, READ, message_id="ben-private")+ assert "hasn't found" in json.loads(out)["error"]+ assert mailbox.calls == []+++def test_a_reply_into_an_unseen_thread_is_refused(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({})+ with _reader(roster.owner):+ out = _run(mailbox, SEND, to=OWNER, thread_id="ben-thread", body="x")+ assert "error" in json.loads(out) and mailbox.calls == []+++def test_quoting_a_thread_with_a_teammates_message_is_refused(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "t1")+ mailbox = FakeMailbox({THREAD: _thread((VENDOR, EXEC, "invoice"), (TEAMMATE, EXEC, "my bank details"))})+ with _reader(roster.owner):+ out = _run(mailbox, SEND, to=OWNER, thread_id="t1", quote_original=True, body="x")+ assert "can't be quoted" in json.loads(out)["error"]+ assert [c["name"] for c in mailbox.calls] == [THREAD]+++def test_the_seen_vendor_message_reads(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "m1")+ text = _message(VENDOR, EXEC)+ with _reader(roster.owner):+ assert _run(FakeMailbox({READ: text}), READ, message_id="m1") == text+++def test_the_inbound_email_a_turn_answers_is_reachable(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "inbound-m", "inbound-t")+ mailbox = FakeMailbox({SEND: "Email sent! Message ID: r1"})+ with _reader(roster.ben):+ out = _run(mailbox, SEND, to=TEAMMATE, thread_id="inbound-t", body="Got it")+ assert out == "Email sent! Message ID: r1"+++# ── reads, message by message ─────────────────────────────────────────────+++def test_a_teammates_message_is_withheld_from_the_owner(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "m1")+ with _reader(roster.owner):+ out = _run(FakeMailbox({READ: _message(TEAMMATE, EXEC)}), READ, message_id="m1")+ assert json.loads(out)["withheld"] is True and "Numbers attached" not in out+++def test_the_teammate_reads_their_own(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "m1")+ text = _message(TEAMMATE, EXEC)+ with _reader(roster.ben):+ assert _run(FakeMailbox({READ: text}), READ, message_id="m1") == text+++def test_a_teammate_in_the_body_hides_it(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "m1")+ text = _message(VENDOR, EXEC, body=f"On Monday Ben <{TEAMMATE}> wrote: my bank details")+ with _reader(roster.owner):+ assert json.loads(_run(FakeMailbox({READ: text}), READ, message_id="m1"))["withheld"] is True+++def test_a_thread_keeps_only_the_messages_that_are_not_a_teammates(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "t1")+ text = _thread((VENDOR, EXEC, "invoice due"), (TEAMMATE, EXEC, "my bank details"))+ with _reader(roster.owner):+ out = _run(FakeMailbox({THREAD: text}), THREAD, thread_id="t1")+ assert "invoice due" in out and "bank details" not in out+ assert "Left out 1 message" in out+++def test_a_cc_on_one_message_does_not_open_the_rest(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "t1")+ text = _thread((TEAMMATE, EXEC, "my bank details"), (EXEC, f"{TEAMMATE}, {OWNER}", "Looping in Olivia"))+ with _reader(roster.owner):+ out = _run(FakeMailbox({THREAD: text}), THREAD, thread_id="t1")+ assert "Looping in Olivia" in out and "bank details" not in out+++def test_a_batch_with_one_teammates_message_is_withheld(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "m1", "m2")+ text = "Retrieved 2 messages:\n\n" + _message(OWNER, EXEC) + "\n---\n\n" + _message(TEAMMATE, EXEC, mid="m2")+ with _reader(roster.owner):+ out = json.loads(_run(FakeMailbox({BATCH: text}), BATCH, message_ids=["m1", "m2"]))+ assert out["withheld"] is True and "one at a time" in out["note"]+++# ── Outlook ───────────────────────────────────────────────────────────────+++def _item(addr: str, subject: str, mid: str) -> dict[str, Any]:+ return {+ "id": mid,+ "subject": subject,+ "from": {"emailAddress": {"address": addr}},+ "toRecipients": [{"emailAddress": {"address": EXEC}}],+ }+++def test_an_outlook_list_selects_the_parties_and_drops_the_teammates_items(roster: SimpleNamespace) -> None:+ text = json.dumps({"value": [_item(VENDOR, "Invoice", "o1"), _item(TEAMMATE, "My taxes", "o2")]})+ mailbox = FakeMailbox({OUTLOOK_LIST: text})+ with _reader(roster.owner):+ out = json.loads(_run(mailbox, OUTLOOK_LIST, select="id,subject,bodyPreview"))+ assert "toRecipients" in mailbox.calls[0]["arguments"]["select"]+ assert [i["subject"] for i in out["value"]] == ["Invoice"]+ assert roster.session.mail_ids_seen == {f"{roster.owner}:o1"}+++def test_an_outlook_forward_of_an_unseen_message_is_refused(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({})+ with _reader(roster.owner):+ out = _run(mailbox, "microsoft_365__create-forward-draft", messageId="ben-private")+ assert "error" in json.loads(out) and mailbox.calls == []+++def test_an_outlook_attachment_download_of_an_unseen_message_is_refused(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({})+ with _reader(roster.owner):+ out = _run(mailbox, "microsoft_365__download-bytes", target="/me/messages/ben-private/attachments/a1/$value")+ assert "error" in json.loads(out) and mailbox.calls == []+++def test_outlook_search_is_refused(roster: SimpleNamespace) -> None:+ with _reader(roster.owner):+ out = _run(FakeMailbox({}), "microsoft_365__search-query", requests=[])+ assert "not available" in json.loads(out)["error"]+++# ── who reads, and when nothing changes ──────────────────────────────────+++def test_an_unknown_reader_sees_no_teammates_mail(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "m1")+ with _reader(None):+ out = _run(FakeMailbox({READ: _message(OWNER, EXEC)}), READ, message_id="m1")+ assert json.loads(out)["withheld"] is True++[email protected]("authenticated", [True, False])+def test_an_email_turn_reads_as_its_sender_only_when_gmail_vouches(+ roster: SimpleNamespace, authenticated: bool,+) -> None:+ session = SimpleNamespace(+ unattended=False, origin_channel="email", caller_person_id=roster.ben,+ from_web_chat=False, email_sender_authenticated=authenticated,+ )+ assert tm._reader_id(session) == (roster.ben if authenticated else None)+++def test_ids_shown_to_one_reader_are_not_the_next_readers(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({SEARCH: _listing(TEAMMATE), READ: _message(TEAMMATE, EXEC)})+ with _reader(roster.ben):+ _run(mailbox, SEARCH, query="q")+ with _reader(roster.owner):+ out = _run(mailbox, READ, message_id="m1")+ assert "hasn't found" in json.loads(out)["error"]+++def test_an_outlook_forward_of_a_teammates_message_is_refused(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "o2")+ mailbox = FakeMailbox({"microsoft_365__get-mail-message": json.dumps(_item(TEAMMATE, "My taxes", "o2"))})+ with _reader(roster.owner):+ out = _run(mailbox, "microsoft_365__forward-mail-message", messageId="o2",+ body={"ToRecipients": [{"emailAddress": {"address": OWNER}}]})+ assert "private to them" in json.loads(out)["error"]+ assert [c["name"] for c in mailbox.calls] == ["microsoft_365__get-mail-message"]+++def test_an_unbalanced_query_is_refused(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({})+ with _reader(roster.owner):+ out = _run(mailbox, SEARCH, query='subject:"taxes OR (')+ assert "bracket" in json.loads(out)["error"] and mailbox.calls == []+++def test_a_trimmed_thread_drops_its_subject(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "t1")+ text = _thread((VENDOR, EXEC, "invoice due"), (TEAMMATE, EXEC, "my bank details"))+ with _reader(roster.owner):+ out = _run(FakeMailbox({THREAD: text}), THREAD, thread_id="t1")+ assert "Taxes" not in out and "Thread ID: t1" in out+++def test_a_teammate_shown_their_own_mail_keeps_the_conversation(roster: SimpleNamespace) -> None:+ roster.session.session_id = "s-ben"+ tm.allow_mail_ids(roster.session, "m1")+ with _reader(roster.ben), patch("openexecutive.memory.session_store.mark_mail_private") as mark:+ _run(FakeMailbox({READ: _message(TEAMMATE, EXEC)}), READ, message_id="m1")+ assert mark.call_args.args == ("s-ben", roster.ben)+++def test_the_owner_reading_outside_mail_keeps_nothing_private(roster: SimpleNamespace) -> None:+ roster.session.session_id = "s-owner"+ tm.allow_mail_ids(roster.session, "m1")+ with _reader(roster.owner), patch("openexecutive.memory.session_store.mark_mail_private") as mark:+ _run(FakeMailbox({READ: _message(VENDOR, f"{EXEC}, {OWNER}")}), READ, message_id="m1")+ mark.assert_not_called()+++def test_a_background_run_reads_as_the_principal(roster: SimpleNamespace) -> None:+ session = SimpleNamespace(unattended=True, caller_person_id=None)+ assert tm._reader_id(session) == roster.owner+++def test_a_step_outside_any_session_sees_no_teammates_mail(roster: SimpleNamespace) -> None:+ current_session.set(None)+ text = _message(TEAMMATE, EXEC)+ out = asyncio.run(tm.guard_in_turn(FakeMailbox({READ: text}))(+ {"name": READ, "arguments": {"message_id": "m1"}}+ ))+ assert json.loads(out)["withheld"] is True+ vendor = _message(VENDOR, EXEC)+ out = asyncio.run(tm.guard_in_turn(FakeMailbox({READ: vendor}))(+ {"name": READ, "arguments": {"message_id": "m1"}}+ ))+ assert out == vendor++[email protected]("arguments", [+ {"body": {"conditions": {"fromAddresses": [{"emailAddress": {"address": TEAMMATE}}]}}},+ {"body": {"actions": {"forwardTo": [{"emailAddress": {"address": OWNER}}]}}},+])+def test_an_outlook_rule_that_could_pass_on_a_teammates_mail_is_refused(+ roster: SimpleNamespace, arguments: dict[str, Any],+) -> None:+ mailbox = FakeMailbox({})+ with _reader(roster.owner):+ out = _run(mailbox, "microsoft_365__create-mail-rule", **arguments)+ assert "rule" in json.loads(out)["error"] and mailbox.calls == []+++def test_the_rest_of_the_turn_is_kept_to_the_teammate(roster: SimpleNamespace) -> None:+ roster.session.session_id = "s-ben"+ tm.allow_mail_ids(roster.session, "m1")+ pinned = SimpleNamespace(person_id=roster.ben, touched_mail=False)+ with _reader(roster.ben), patch("openexecutive.memory.session_store.mark_mail_private"), \+ patch("openexecutive.delegation.settings.turn_delegation", lambda _s: pinned):+ _run(FakeMailbox({READ: _message(TEAMMATE, EXEC)}), READ, message_id="m1")+ assert pinned.touched_mail is True+++def test_other_tools_pass(roster: SimpleNamespace) -> None:+ text = f"Event with {TEAMMATE}"+ with _reader(roster.owner):+ assert _run(FakeMailbox({"google_workspace__get_events": text}), "google_workspace__get_events") == text+++def test_a_roster_failure_refuses(roster: SimpleNamespace) -> None:+ mailbox = FakeMailbox({})+ with _reader(roster.owner), patch.object(people_store, "list_people", side_effect=RuntimeError):+ out = _run(mailbox, READ, message_id="m1")+ assert "roster" in json.loads(out)["error"] and mailbox.calls == []+++def test_a_quoted_header_line_in_a_body_does_not_count(roster: SimpleNamespace) -> None:+ tm.allow_mail_ids(roster.session, "m1")+ text = _message(TEAMMATE, EXEC, body=f"Forwarding this:\nTo: {OWNER}\nmy bank details")+ with _reader(roster.owner):+ out = _run(FakeMailbox({READ: text}), READ, message_id="m1")+ assert json.loads(out)["withheld"] is True+++def test_a_teammate_named_only_in_an_outside_body_keeps_nothing_private(roster: SimpleNamespace) -> None:+ roster.session.session_id = "s-ben"+ tm.allow_mail_ids(roster.session, "m1")+ text = _message(VENDOR, EXEC, body=f"cc'ing {TEAMMATE} later")+ with _reader(roster.ben), patch("openexecutive.memory.session_store.mark_mail_private") as mark:+ _run(FakeMailbox({READ: text}), READ, message_id="m1")+ mark.assert_not_called()