AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(mcp): answer MCP clients as the signed-in caller (#498)
Rufus07ffd1edd467
diff --git a/README.md b/README.mdindex b664e337..b3aac583 100644--- a/README.md+++ b/README.md@@ -301,12 +301,24 @@ claude mcp add --transport http open-executive http://localhost:8000/mcp \Connected clients get eight read-only resources (company profile, today'sbriefing and activity, people roster, department state, and episodic memory for-decisions, initiatives and advice) and four tools, of which `consult_specialist`-is the primary one: domain analysis from any of the ten specialists, each-grounded in your company's knowledge base. The full inventory is on the **MCP-Server** section of the `/architecture` page. With-[signed callers](docs/auth.md#signed-callers) on, an MCP client holds only the-shared secret, so it is never the owner: `ask_executive` asks as no one.+decisions, initiatives and advice) and four tools: `consult_specialist` (domain+analysis from any of the ten specialists, each grounded in your company's+knowledge base), `search_knowledge`, `list_workflows` and `ask_executive`. The+full inventory is on the **MCP Server** section of the `/architecture` page.++`/mcp` answers as the caller the API verified, by the web app's rules. With no+`x-caller-email` (open mode) the client is the owner, as the CLI is. A request+that carries a signed-in person (a deployment that puts its own sign-in in+front of `/mcp` and stamps the caller as the web UI's proxy does; see+[signed callers](docs/auth.md#signed-callers)) gets that person's answers: the+owner's episodic memory and recent activity go to the owner alone, the briefing+and roster to someone on the roster (the briefing narrowed as the web app+narrows it), and the company profile, departments, specialists, knowledge and+workflow catalog to anyone. With signed callers on, a client holding only the+shared secret is a service: never the owner, and `ask_executive` asks as no+one. `ask_executive` only reads and advises: on its turn the Executive is not+offered anything that sends, posts, books, schedules, runs or changes stored+data, and of the connected MCP servers' tools only the reads.This is the inverse of the `MCP_ENABLED` and `MCP_SERVERS_CONFIG_PATH` settingsunder [Configuration](#configuration), which configure the MCP *gateway*: Opendiff --git a/docs/auth.md b/docs/auth.mdindex f0f7d9b9..031b1c9d 100644--- a/docs/auth.md+++ b/docs/auth.md@@ -295,7 +295,10 @@ With the keys set:and query it was signed for, expires within 30 seconds, and works once.- **No caller header at all is a service.** A script, `curl` with only `x-api-key`, or anMCP client can still use the API, but it is **never the owner**. For MCP,- `ask_executive` asks as no one, and its `caller_email` is ignored.+ `ask_executive` asks as no one, and the owner's memory and activity, the+ briefing and the roster are refused. `/mcp` reads the caller the gate+ verified, so a sign-in in front of it that sends a signed assertion gets+ that person's answers.- **The UI's local-login session is the operator.** It is signed, names no one and runs asthe owner, as before.- **Refusals are 401.** You get one for:diff --git a/packages/core/openexecutive/api/caller.py b/packages/core/openexecutive/api/caller.pyindex 756c8347..6c1ef944 100644--- a/packages/core/openexecutive/api/caller.py+++ b/packages/core/openexecutive/api/caller.py@@ -109,6 +109,37 @@ def caller(request: Any) -> Caller:return Caller("open", raw.strip().lower())+def person_id_for(who: Caller) -> int | None:+ """The People entry ``who`` asks as, by the rule every route shares+ (``api.routes.chat._resolve_caller_person_id``):++ - a signed-in email → that person, or None when no entry has it (a+ signed-in but unrostered user must not be fused with the principal);+ - a caller that ``defaults_to_principal`` → the principal (None when the+ roster has none yet);+ - a service names no one and is never the principal → None.++ A roster that can't be read answers None (fails closed)."""+ import sqlite3++ try:+ from openexecutive.people.store import (+ find_person_by_email,+ find_principal_person,+ )++ if who.email:+ person = find_person_by_email(who.email)+ return person.id if person is not None else None+ if not who.defaults_to_principal:+ return None+ principal = find_principal_person()+ return principal.id if principal is not None else None+ except (OSError, sqlite3.Error) as exc:+ logger.warning("caller_lookup_failed err=%s", exc)+ return None++def caller_email(request: Any) -> str:"""The signed-in caller's email, lowercased; "" when there is none."""return caller(request).emaildiff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.pyindex 6972cf3a..ce61f9c5 100644--- a/packages/core/openexecutive/api/routes/chat.py+++ b/packages/core/openexecutive/api/routes/chat.py@@ -5,7 +5,6 @@ import contextlibimport jsonimport loggingimport re-import sqlite3import timeimport uuidfrom collections.abc import Callable@@ -911,22 +910,7 @@ def _resolve_caller_person_id(request: Request) -> int | None:- a verified service call (``api.caller``) names no one and is neverthe principal → None."""- who = api_caller.caller(request)- try:- from openexecutive.people.store import (- find_person_by_email,- find_principal_person,- )- if who.email:- person = find_person_by_email(who.email)- return person.id if person is not None else None- if not who.defaults_to_principal:- return None- principal = find_principal_person()- return principal.id if principal is not None else None- except (OSError, sqlite3.Error) as exc:- logger.warning("caller_lookup_failed err=%s", exc)- return None+ return api_caller.person_id_for(api_caller.caller(request))def _caller_is_principal_or_unclaimed(request: Request) -> bool:diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 985f3beb..8bb0d16d 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -7395,8 +7395,11 @@ auth:500 to every call. Neither falls back to the header.Other consequences:- - MCP ask_executive ignores caller_email and asks as no one- (person_id None).+ - An MCP client holding only the shared secret is a service: /mcp+ refuses it the owner's records, the briefing and the roster, and+ ask_executive asks as no one (person_id None). A sign-in in front+ of /mcp that sends a signed assertion gets that person's answers+ (see mcp_server).- Setup's api_secret check warns when a shared secret is setwithout the keys.- scripts/make-caller-keys.py makes a pair, and@@ -8847,6 +8850,65 @@ integrations:a browser rebinding attack cannot supply the key, and traffic arrives behindthe deployment's TLS terminator. The shared secret is the real access control.+ WHO IS ASKING: every handler answers as the caller the API verified. The+ mounted app shares the outer request's scope state, so what caller_gate+ put on request.state reaches the handler: mcp_server._request() reads the+ Starlette request from FastMCP's request context (mcp.get_context(); a+ handler signature takes no Context, so the resource list is unchanged),+ and api_caller.caller(request) answers. The person comes from+ api.caller.person_id_for, the one rule chat._resolve_caller_person_id+ now delegates to: a signed-in email is that person (None off the+ roster); open mode with no x-caller-email, or an operator, is the+ principal; a service is no one. With no request (a direct in-process+ call) it is Caller("open"), or Caller("service") once signed callers are+ on. Rules per caller, mirroring the web app:+ - oe://memory/{decisions,initiatives,advice}, oe://today/activity: the+ principal alone (resolves to the principal, or defaults_to_principal);+ anyone else gets "Only the owner can read this." (CallerRefused,+ returned by FastMCP as the JSON-RPC error message).+ - oe://today/briefing: someone on the roster (or the principal by+ default), built as GET /today builds it: include_private for the+ principal only, viewer = viewer_for_person(caller), so a drafted+ artifact's card only for its owner. oe://people/roster: someone on+ the roster, the team only (never contacts), as GET /people gives it.+ A service or an unrostered caller gets "Only someone on the team can+ read this."+ - oe://company/profile, oe://departments/state, consult_specialist,+ search_knowledge, list_workflows (GET /workflows is public too):+ anyone who reached /mcp.+ A deployment that fronts /mcp with its own sign-in and stamps the signed+ caller (x-caller-assertion for POST /mcp/), as the UI proxy does, so gets+ per-person answers with the same rules as the web app.++ ASK_EXECUTIVE NEVER ACTS: it takes only `message` (the caller comes from+ the request, never an argument) and builds a Session with+ from_mcp_client=True and caller_person_id = the resolved person (NOBODY+ as documents_viewer when that is no one). On such a turn the chat loop+ (_stream_agent_loop) neither offers nor runs+ schedule_tools.MCP_CLIENT_WITHHELD_TOOLS = PRIVATE_TURN_WITHHELD_TOOLS |+ UNATTENDED_WITHHELD_TOOLS | the DMs (message_person, send_slack_dm,+ send_discord_dm, send_telegram_message), ack_alert, create_alert,+ leave_out_of_brief, close_open_loop, upsert_person, archive_person,+ set_department_head, remove_/tune_watchlist_entry, draft_workflow,+ propose_form_values — a fixed set dropped before the sort, so the variant+ keeps a stable cached tool prefix. What stays: the specialists and the+ list/lookup/read tools (a test pins the list). No Act as me+ (delegation.settings._offered answers False, and the loop adds no+ delegation tools), no recall_history, no extension tools. Gateway: only+ schedule_tools.MCP_CLIENT_MCP_TOOLS (PRIVATE_TURN_MCP_TOOLS without the+ Gmail/Outlook send and draft tools) — search_tools results are filtered+ to it, call_tool naming anything else and load_mcp_server are refused in+ the loop, and MCPGateway.call_tool refuses again on any path that reads+ current_session. A refused call returns a JSON error+ (mcp_client_withheld_error: the conversation comes from another AI app,+ so it can read and advise but can't send, post, book or change+ anything; tell the person to ask in Open Executive itself) and an audit+ row refused="mcp_client". The conversation itself is still recorded in+ memory, so ask_executive is annotated readOnlyHint=False,+ destructiveHint=False; the other three tools readOnlyHint=True. Every+ tool has an MCP title and annotations, and descriptions state what a+ tool does without steering a client between tools.+Surface — what's valuable beyond chat (OE already has six chat channels, soa chat-only server adds nothing): company-grounded context as READ-ONLYresources, and the specialist council as tools.@@ -8856,14 +8918,15 @@ integrations:(load_or_create_profile, today._build_today/_build_activity,people.list_people, departments.list_departments, episodic list_*); noLLM calls. The warm ChromaDB store is handed to handlers via- mcp_server.set_store() from the lifespan (handlers have no Request).+ mcp_server.set_store() from the lifespan (handlers take no Request+ argument; only the caller read goes through the request context).Tools: consult_specialist (flagship — orchestrator.router.route_to_specialist,stateless, the specialist enum is a Literal pinned to SPECIALIST_REGISTRYby a unit test), search_knowledge (knowledge.retriever.retrieve),list_workflows (workflows.list_workflows → Workflow.meta), and ask_executive- (Executive.chat fallback — non-streaming, resolves caller to principal or- by caller_email). All reads — no tool here mutates company state, the same- read-only posture as the resources.+ (Executive.chat, non-streaming, as the verified caller, never acting —+ see ASK_EXECUTIVE NEVER ACTS). No tool here sends or mutates company+ state; ask_executive's conversation is recorded in memory.DEFERRED by design: workflow EXECUTION is not exposed — workflows arelong-running async generators (minutes) that would exceed a single MCPdiff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex 9e149723..e8206d8f 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. When to call it is spelled out in the persona's Domain Expertise section (\"Going deeper\") and in the tool's own description: any question that asks for judgment in a specialist's area (a decision, plan, analysis, negotiation, hire, contract term, pricing or fundraising move, board message, or a department's own targets and stance, since the specialist holds that department's memory) is consulted before the answer, several at once across areas; lookups in mail, calendar or documents, scheduling, status checks, routine drafting and questions about how the Executive works are answered without one. Chat eval scenarios hold this: `required_routing` names specialists the turn must consult and `no_routing: true` says it must consult none, and the runner fails a scenario that misses either (`evals.scenarios.routing_check`). 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 owner is told once on their own channel when someone else assigns it, and the result's `notified` says how that went, so the Executive reports it rather than messaging them as well. 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, except on mail the reader is also on, 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. Their own chats are theirs too: every audit row of a teammate's verified turn is theirs (`people_tools.teammate_turn_owner`, see Audit; the principal sees the actions, never the words), and a teammate's web chat or DM opens for them alone (`chat._session_access`), the principal included. 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. A send or edit on a team member's turn also meets their department's authority first (`orchestrator.department_gate`, see Org), and so does one on a turn whose speaker is on no People entry: a signed-in web caller or a chat-channel sender, which in practice is Google Chat, since Slack, Telegram and Discord turn unmatched senders away. Google Chat names a matched sender to the gate alone (`gate_sender_person_id`), so the principal there is not held. Email turns are left to the mailbox's own gates. *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 (or the department gate on a team member's turn, see Org), 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`) — and `my_calendar` their own calendar while Read my calendar is on, 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, unless it was registered with `after_mail_read=True`: a tool that only reads the install's own data and carries nothing the model wrote anywhere outside. 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. For questions about the product itself, the always-offered `read_user_guide` tool (`orchestrator/guide_tools.py`) returns any `guide/prebuilt/<id>.json` section; its description lists the section ids, fixed at import, so it never changes the cached tools prefix.\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`.\n\n**AI disclosure.** Nothing the Executive sends to people outside the web chat goes without saying it is an AI: plain code adds the line in the MCP gateway (mail) and at each chat send (Slack, Telegram, Discord, Google Chat replies, its DMs and room posts), never the prompt, so the persona and the cached system blocks are unchanged and a reply the model writes can't drop it. Replies the inbox watcher writes as a person carry their own line by that person's switches. See Integrations → **AI disclosure** and Act as me → **AI line on replies**.\n",+ "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. When to call it is spelled out in the persona's Domain Expertise section (\"Going deeper\") and in the tool's own description: any question that asks for judgment in a specialist's area (a decision, plan, analysis, negotiation, hire, contract term, pricing or fundraising move, board message, or a department's own targets and stance, since the specialist holds that department's memory) is consulted before the answer, several at once across areas; lookups in mail, calendar or documents, scheduling, status checks, routine drafting and questions about how the Executive works are answered without one. Chat eval scenarios hold this: `required_routing` names specialists the turn must consult and `no_routing: true` says it must consult none, and the runner fails a scenario that misses either (`evals.scenarios.routing_check`). 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 owner is told once on their own channel when someone else assigns it, and the result's `notified` says how that went, so the Executive reports it rather than messaging them as well. 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, except on mail the reader is also on, 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. Their own chats are theirs too: every audit row of a teammate's verified turn is theirs (`people_tools.teammate_turn_owner`, see Audit; the principal sees the actions, never the words), and a teammate's web chat or DM opens for them alone (`chat._session_access`), the principal included. 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. A send or edit on a team member's turn also meets their department's authority first (`orchestrator.department_gate`, see Org), and so does one on a turn whose speaker is on no People entry: a signed-in web caller or a chat-channel sender, which in practice is Google Chat, since Slack, Telegram and Discord turn unmatched senders away. Google Chat names a matched sender to the gate alone (`gate_sender_person_id`), so the principal there is not held. Email turns are left to the mailbox's own gates. *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.\n\nA turn another AI app asks over the MCP server (`Session.from_mcp_client`, set by `ask_executive`) reads and advises but never acts. It is neither offered nor allowed to run `schedule_tools.MCP_CLIENT_WITHHELD_TOOLS`: the private-turn and unattended sets, plus every direct message (`message_person`, the Slack, Discord and Telegram DMs), alert acks and new alerts, brief edits, closing open loops, roster and department-head writes, watchlist changes, workflow drafts and form proposals. It gets no Act as me, `recall_history` or extension tools, and of the gateway tools only `schedule_tools.MCP_CLIENT_MCP_TOOLS`: the private-turn reads without the Gmail and Outlook send and draft tools. The set is fixed, so the variant keeps a stable cached tool prefix. A call the model emits anyway, through `use_tool` or `call_tool` included, gets an error tool_result telling it the conversation comes from another AI app, so it can read and advise but not send, post, book or change anything, and writes an audit row (`refused: mcp_client`); `MCPGateway.call_tool` refuses the same calls again.\n\nOn 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 (or the department gate on a team member's turn, see Org), 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`) — and `my_calendar` their own calendar while Read my calendar is on, 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, unless it was registered with `after_mail_read=True`: a tool that only reads the install's own data and carries nothing the model wrote anywhere outside. 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. For questions about the product itself, the always-offered `read_user_guide` tool (`orchestrator/guide_tools.py`) returns any `guide/prebuilt/<id>.json` section; its description lists the section ids, fixed at import, so it never changes the cached tools prefix.\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`.\n\n**AI disclosure.** Nothing the Executive sends to people outside the web chat goes without saying it is an AI: plain code adds the line in the MCP gateway (mail) and at each chat send (Slack, Telegram, Discord, Google Chat replies, its DMs and room posts), never the prompt, so the persona and the cached system blocks are unchanged and a reply the model writes can't drop it. Replies the inbox watcher writes as a person carry their own line by that person's switches. See Integrations → **AI disclosure** and Act as me → **AI line on replies**.\n","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-15T21:00:00Z"+ "generated_at": "2026-10-16T12:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex f524b453..38e05f0b 100644--- a/packages/core/openexecutive/architecture/prebuilt/api.json+++ b/packages/core/openexecutive/architecture/prebuilt/api.json@@ -1,7 +1,7 @@{"section_id": "api","title": "API Reference",- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's Your month tally (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |\n\n**What it may do** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it may do.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is set up) a second middleware answers 403 to any request whose raw `Host` is not `localhost`, `127.0.0.1` or `[::1]` (except a webhook that verifies its caller: Google Chat and Slack always, Telegram only with a `TELEGRAM_WEBHOOK_SECRET` Telegram can send), and to any write whose `Sec-Fetch-Site` is present and not `same-origin`/`none`. The UI signs that owner in with no password and this API usually has no secret, so without it a web page in the owner's browser could drive the API as the principal — by DNS-rebinding its own hostname to 127.0.0.1, or by posting a plain form from another site or localhost port. CORS is restricted to the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. After the reply — a stopped or timed-out one too, before the `stopped` / `error` / `done` frames — a turn that looked at anything sends one `sources` event, `{type, session_id, sources: [{kind, title, url}], unavailable: [area]}`: `kind` is `company`, `knowledge`, `notion`, `research`, `document` or `web`, `url` is only ever an http(s) link or, for an earlier document, `/artifacts/<id>`, at most 12 sources (6 from the web, pages the reply cites first), and `unavailable` names parts of the analysis (\"finance\") whose specialist failed or said nothing every time it was asked. It is persisted with the reply as `chat_messages.sources`. A request that carries `x-caller-email` marks its turn signed in (`Session.web_caller_signed_in`), which Act as me needs on a deployment without local login. |\n| `sessions` | `GET /sessions`, `GET /sessions/shared-with-me`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). Messages from `GET /sessions/{id}/messages` carry each assistant reply's saved `sources` (the same shape as the chat stream's `sources` event, without `type`), so a reloaded chat shows them again. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review` | Morning-brief aggregation, recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's Your month tally (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `GET /today` carries the viewer's cached \"What's going on\" `narrative` with `narrative_generated_at` (when it was written) and `narrative_stale` (a fresher one is being written — the page re-polls; see Today). A proposal backed by a roster request carries `roster_request` (the new sender's server-derived details and held-message previews; the principal's only) and is answered through the `people` routes below. `brief-delivery` returns the latest morning brief or end-of-day digest that didn't reach the owner, as `{brief, at, problem, fix, readable}` in plain language (`readable` is false when it couldn't be written, so there is nothing to read), or null — null while briefs go out, once the cause is fixed, while the scheduler is off, and for anyone but the owner (`chat._caller_is_principal_or_unclaimed`); it carries no address or channel id. `top-three` and `weekly-review` feed the solo Briefing's own cards and answer only in solo mode and only to the principal (`workflows._caller_is_the_principal`: a principal match or no caller header, never an unclaimed roster); anyone else, and team mode, get null. `top-three` returns `{items: [{key, kind, text, why, slot}]}` — the morning brief's top three from the same code (`build_top_three(principal_due_soon())`), `slot` a free block like `10:00–11:00`, `\"\"` when none is left, null when no calendar was read — and is kept off `GET /today` because its calendar read may take up to 4 s. `weekly-review` returns the latest completed `weekly_review` run as `{run_id, completed_at, period, top_three, excerpt}` (next week's top three as plain text; `excerpt` when that list is empty), or null when none has completed. |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/requests`, `GET /people/requests/{id}`, `POST /people/requests/{id}/approve`, `POST /people/requests/{id}/decline`, `GET\\|POST /people/{id}/open-loops` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Every `Person` carries `kind` (`team` / `contact`). `GET /people` lists team members only unless `?include_contacts=true` (the People page asks for both; the department-head and workflow pickers keep the default); `POST` / `PATCH` accept `kind`, and a principal contact is a 422 either way. They also take `email_aliases` (other addresses the person writes from, at most 10; on `PATCH` the full list replaces the current one, omitted leaves it): an alias matches their mail and may be emailed but never signs in; a malformed one is a 422, and an alias — or a new primary `email` — that is already someone else's address or alias is a 409. Every `POST` / `PATCH` then closes any pending roster request whose sender now matches someone and replays its held messages. Adding, editing and archiving (`POST`, `PATCH`, `/archive`) are the principal's only, or anyone's while no one is principal yet so a first setup can add its owner (`chat._caller_is_principal_or_unclaimed`, the check behind `PUT /workspace`; a request with no `x-caller-email`, such as the CLI or local login, counts as the principal). Anyone else, a person editing their own row included, gets 403 before the person lookup, so it can't probe which ids exist. Contacts are private to the principal (`caller_is_principal`: the signed-in email is the principal's, or no `x-caller-email`; stricter than the owner rule above, so while no one is principal nobody is): for anyone else `include_contacts` is ignored, a contact's id is a 404 on `GET /people/{id}` and open-loops (exactly as for a missing id; `PATCH` and archive are already a 403 for them), and creating a contact or turning someone into one is a 403, even on a first setup with no principal yet. `GET /people/me` returns `{person_id, is_principal}` so the UI offers contacts to the principal only. `GET /people/by-scope/{token}` never returns a contact. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `POST /people/{id}/open-loops` `{task, due_date?}` assigns that person a task (201 with the loop; `due_date` is a local date, due 17:00 in the user's timezone, clamped to 60 days, default 2 days): any active team member may assign anyone on the team, 403 for anyone else; 409 for an archived person, a contact (as seen by the principal), a person at the open-loop cap, a duplicate or open loops turned off; 422 for an empty task. Nobody is messaged at assignment — the owner is chased once it is due. `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style and frees their aliases. The **roster-request** routes (declared before `/people/{person_id}`) are the principal's alone (`caller_is_principal`; anyone else gets 404, as for a missing id): `GET /people/requests?status=pending|approved|linked|declined|expired|superseded|all` lists up to 100 (`id`, `channel`, `channel_ref`, sanitised `display_name`, `profile_email`, `on_company_domain`, `suggested_kind`, `suggested_person_id` / `_name`, `status`, `resolved_person_id` / `_kind`, `message_count`, timestamps, `ack_sent`, and `previews` of the held messages while pending — shown to the principal, never to a model); `approve` takes either `link_person_id` (+ `replace_channel_id`) or `full_name` + `kind` (no default: 422 without both) + optional `role`; `decline` takes no body. An answered request is a 409, a chat id or address already on someone else is a 409; the held messages are replayed (or dropped) in the background. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. A new `head_person_id` must be a team member: an unknown id and one of the principal's contacts get the same name-free 422 (`person_id N is not on the team.`), so the route — open to any signed-in user — never reveals that a contact exists; an unchanged head is not re-checked. `POST .../goals` requires only `key_result`: a missing or blank `period_value` is filled with the current period for `period_type` in the user's zone (the same label `create_goal` uses), and `target` defaults to empty. `PATCH .../goals/{id}` rejects a blank `key_result` or `period_value` with a 422; `target` may be cleared. |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `GET /agents/presets`, `POST /agents/presets/{id}`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. `AgentDetail` carries `instructions` (additional instructions, appended after `prompt`, which stays the built-in prompt or its replacement); `PATCH` and `/test` accept `instructions` (max 4,000 chars, blank clears it). `GET /agents/presets` lists the Fast, Balanced and Thorough quality presets (each with `available` and the resolved `model` for this install) plus `active` (null when the council is Custom), `base` and `custom_agents`; `POST /agents/presets/{id}` applies one by writing per-agent model and deep-reasoning overrides and returns the same shape (404 unknown preset, 409 when the install allows none of its models). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `GET /artifacts/{id}`, `GET /artifacts/{id}/download?as=`, `POST /artifacts/{id}/archive`, `POST /artifacts/{id}/restore`, `DELETE /artifacts/{id}` | Browsable deliverables in any format — Markdown, HTML, Word, Excel, or a link into a connected app — with `format`, `downloads`, `external_url`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `download` renders the file (Word/Excel built at request time from the stored text; any Markdown artifact, workflow output included, can export `?as=docx`) and is always an attachment with `nosniff` and a sandbox CSP. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET`/`PUT /decisions/classes/meeting_scheduling`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. An approval whose caller resolves to the principal runs the booking inside `grant_contact_egress()`, so a meeting the principal proposed with a contact can be created. Such a booking's payload is marked `private`: it is proposed to the principal, left out of anyone else's `GET /decisions`, and a 404 for them on `GET /decisions/{id}` and every action route. Reviewed in the briefing — there is no separate proposals page. The class routes read and set how meetings are handled: both return `{decision_class: \"meeting_scheduling\", mode: \"propose\" \\| \"auto_execute\"}` (default `propose`); the `PUT` body is `{mode}`, principal-only (403 otherwise, open before a principal exists — but then only `propose` can be set: `auto_execute` is a 409 until a non-archived principal is on the roster), 422 on any other mode, and a change writes a `decision_class_mode_changed` audit row. In solo mode the class mode decides a booking, and `auto_execute` applies only to a turn the principal started on a verified surface — any other turn gets a proposal. |\n| `delegation` | `GET`/`PUT /delegation`, `GET`/`PUT`/`DELETE /delegation/voice`, `POST /delegation/voice/learn`, `POST /delegation/voice/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `PUT /delegation/replies/{id}/text`, `GET /delegation/actions`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days; a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?}` (any other field is a 422) and returns the `GET /delegation` shape; putting Replies or Follow-ups in, or Suggested actions out, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `status` is `connected`, `not_configured`, `needs_reconnect`, `mismatch`, `no_email`, `shared_mailbox` or `error`, checked live with Google on each call. `PUT` takes `{enabled}` (any other field is a 422); turning it on needs the caller's own Gmail connected, otherwise a 409 whose code says why (`gmail_not_connected`, `gmail_needs_reconnect`, `gmail_mismatch`, `no_email`, `shared_mailbox`, `gmail_error`). The voice routes show, learn (from the caller's sent mail, one pass at a time — a 409 `in_progress`, `locked`, `too_soon`, `not_enough_mail`, `no_profile` or `changed` when it was locked or edited while learning, or a Gmail code), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), edit and lock, and reset \"How I write\": a typed field that fails validation is a 422 `invalid_voice` listing each `rejected` field, and `clear_exemplars` / `clear_signature` drop those. `POST /delegation/voice/signature` reads the signature from the caller's Gmail settings again and changes nothing else (a locked profile stays locked), with the same Gmail codes as learning: a 409 when their mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. A caller `can_delegate` refuses — anyone but the principal, for now — gets 403 `not_available_yet`, which hides the Settings card. A request with no `x-caller-email` is a 403 `sign_in_required` unless the API runs under local login — a header-less call is not a sign-in (the caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. **Send + allow** adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for Approve + allow while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. Rows private to the principal (`private_to_principal`: a turn about their private mail, or a row naming one of their contacts on their own turn) are theirs alone: for any other caller, resolved as for `/alerts`, the usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\n| `setup_status` | `GET /setup/status` | Settings → Setup status: one light per part of the install — AI model, company setup, owner, the Executive's address, API protection, Gmail, your own mailbox (Act as me), Slack, Discord, Telegram, Google Chat, the scheduler, the daily brief (when and where it goes) and Honcho — as `{checked_at, checks: [{id, label, state, summary, fix, link, last_activity}]}`, where `state` is `ok`, `warn`, `error` or `off` (optional and not set up), `fix` says what to do in plain language, `link` is an in-app page that helps (`/people`, `/onboard`) and `last_activity` is the channel's latest `integration_inbound` audit time. It tests live, with at most one free read-only call per service, each bounded to 5 s: Anthropic `models.list` (so an organisation key missing `ANTHROPIC_WORKSPACE_ID` shows up), Slack `auth.test`, Telegram `getMe` and `getWebhookInfo`, Discord `users/@me` only while the bot is still connecting, and — once the owner's own Gmail credential exists — Google's token refresh and Gmail `users/me/profile`. It also reads the listeners the lifespan leaves on `app.state` (Slack's socket, the Discord bot and its task, the MCP gateway), the scheduler heartbeat and the pause switch. When `google_workspace` is configured, the lifespan also starts `MCPGateway.prime_pinned_tools()` in the background (held on `app.state.mcp_prime_task`, cancelled at shutdown), so the pinned Google tools named in the prompt are callable without a search. With `DRIVE_SYNC_ENABLED` the lifespan also bootstraps the `drive_sync_scan` heartbeat beside Notion's (see Scheduler); the Drive folder sync has no HTTP route, only the `openexecutive sync-drive` / `purge-drive` CLI. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. Sample values copied from `.env.example` are named as such without being sent anywhere. No token reaches a response or a log line: probes report a status code, a service's short error code or an exception's class name. Requests within 5 s of a run get that run's answer and concurrent requests share one run (kept per app on `app.state`), so the button can't become a stream of calls to those services. Gated like every other route; the UI adds a sign-in light of its own, from its own settings. |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}`, `GET /documents/sources`, `POST /documents/sources/{drive\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|notion}/{id}` | Upload, list, view extracted text, and delete indexed company docs. `GET /documents` rows carry `source: \"upload\"` and the `domain` the upload was indexed under. The connected-source routes back the knowledge page's single Company documents list: `/documents/sources` gives each source's `{id, label, enabled, syncing, last_run, last_error, interval_minutes, file_count}`; `/documents/drive`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) for an id on record (the path comes from the state, never the caller). They are read-only — a synced file is removed where it lives. `POST …/sync` starts one tick of the same sync the scheduler runs as a background task (202); 409 when the source is not connected or a tick is already running (every sync holds a per-process run lock, so a manual run never overlaps the heartbeat; the route also keeps its own started task per source and re-checks just before starting one, so two simultaneous requests start one tick, not two), 429 with `Retry-After` within 60 s of the last successful run or of the end of the last tick in this process, failed ones included, so a failing or slow source can't be re-run back-to-back. The page's text view never loads images from synced content (a remote image would be a read beacon for whoever edits the shared folder). Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the nine specialist domains (including `sales`) or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. A scanned PDF is converted (`knowledge.pdf_reader`) before it is indexed and in the text view, as are scanned PDFs in `POST /chat/upload` and the client / onboarding intake uploads. The upload is streamed to disk 1 MB at a time and refused with a 413 once it passes 50 MB, and the file is parsed in a short-lived child process (see the RAG section), so a large document does not stay in the API process's memory. A Word or Excel file that cannot be parsed, or whose parse runs out of time, is a 422 with a readable reason. When every parser is busy, the response is a 503 with `Retry-After`. |\n| `executive` | `GET /executive/status`, `POST /executive/pause`, `POST /executive/resume` | Operator pause switch for all autonomous work (scheduler, Gmail poller, workflow resumer); inbound chat and DMs stay live. Status returns `{paused, paused_at, paused_by, reason, held_actions, can_resume}` — `held_actions` counts due `pending` rows that fire on resume. `pause` takes an optional `reason` (≤200 chars) and is idempotent (re-pausing keeps the original start and reason); `paused_by` is the UI proxy's `x-caller-email`, else `api`. Behind the shared-secret middleware — not `SCHEDULED_ADMIN_TOKEN`, which the UI cannot send. Any caller may pause; `resume` is principal-only (`is_principal_or_self`, 403 otherwise; open while no principal is rostered; a header-less caller resolves to the principal as in `chat`), and status carries `can_resume` for the viewer so the UI hides Resume from everyone else. |\n| `workspace` | `GET /workspace`, `PUT /workspace` | Solo/team mode, the user's time zone and the principal's role (`memory.workspace_settings`). Both return `{mode, timezone, effective_timezone, role_kind, role_title, reports_to, remit, measured_on, company_domains, company_domains_custom}` — `timezone` is what the user set (null when unset), `effective_timezone` the zone in effect (`timezone`, else `USER_TIMEZONE`, else UTC), and each role field is null until set. `PUT` is a partial update: only the fields sent change; `mode` is `solo` or `team` (not null), `timezone` an IANA zone, or null/blank to clear it; `role_kind` is `owner`, `in_house`, `independent` or `other`, and `role_title` / `reports_to` / `remit` / `measured_on` are free text (trimmed, at most 120 / 120 / 500 / 300 characters), each null or blank to clear it; an unknown zone, a bad mode or role kind, an over-long role field or an unknown field is a 422 and changes nothing. Switching to solo cancels every pending department check-in, switching to team re-schedules them, and a new zone re-times the pending briefs and reflection; a role change has no side effects (the next turn reads it). `company_domains` is the company's own email domains (a teammate matches by local part on them — see Org): `GET` returns the ones in effect (the stored list, or the domain of the principal's primary address, with `company_domains_custom` false) only to the same caller the role is shown to, `[]` for anyone else; `PUT` takes a list (at most 10 plain domain names, never a free-mail provider's — 422 otherwise, the value never quoted) or null / `[]` to go back to deriving them, and a change is audited with the new list. Each change writes a `workspace_settings_changed` audit row (a role change adds `details.role_fields_changed`, the names of the fields that changed — never their text). The role is the principal's: `GET` returns it only to a caller `PUT` would accept and reads it as nulls for anyone else. `PUT` is the principal's alone (`is_principal_or_self`, 403 otherwise; a header-less caller resolves to the principal as in `chat`) and open while no principal is rostered, so first-run setup can pick a mode. Both work before onboarding — unlike `company-profile`, nothing here needs a profile. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). `DELETE /scheduled/{id}` cancels a `pending` row (409 otherwise). Like pause it only stops work, so any signed-in user may — the UI proxy's `x-caller-email` is trusted when the request also carries the `BACKEND_SHARED_SECRET` `x-api-key` — as may a matching `X-Admin-Token` (`SCHEDULED_ADMIN_TOKEN`) or a loopback caller with no token set; otherwise 401 (token set) or 503. Audited as `scheduled_action_cancelled`. |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/{name}/runs` is a 403 (\"Only the principal can run this workflow.\"), audited, before any run row exists, when the workflow is one only the principal may start in the workspace's mode (`weekly_review` always, `morning_brief` in solo) and the caller is not the principal. A request with no `x-caller-email` counts as the principal; with no principal on the roster, no signed-in caller does. This governs starting a run only. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search`, `/skills/{name}/restore` | Skill registry (the UI's **Playbooks**) CRUD and search. `PUT` on a built-in saves a company customization that shadows it; `DELETE` returns `{name, outcome}` — `deleted`, `reverted` (customization removed, built-in back) or `hidden` (built-in hidden for this company); `restore` un-hides; `GET /skills?include_hidden=true` lists hidden built-ins. List and detail carry `used_by` — `[{name, title, is_custom}]` of the workflows that follow the playbook (switched-off custom ones included) (`WorkflowMeta.playbooks` is the other direction). |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. `POST /evals/runs` is a 403 when a workflow scenario names a workflow that only the principal may start in the mode it runs in (the weekly review; the morning brief in solo) and the caller is not the principal — the Jobs page's rule for starting a run; stored results are read under the existing `/evals/runs` rules. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/facts`, `POST /memories/facts/{fact_id}/{retire,approve,decline}`, `GET /memories/facts/approval`, `PUT /memories/facts/approval/{person_id}`, `GET /memories/people`, `GET /memories/people/{person_id}/conclusions` | Episodic-memory record management; the standing facts the Pulse Corrections tab reads (`{facts: [...], can_retire, retirable_ids, can_review}`; each fact carries `recorded_by_role` / `recorded_by_name`; `?include_inactive=` default true, honoured for the principal only; anyone else gets the active rows plus their own `proposed` ones, with the provenance (`session_id`, `turn_id`, `recorded_by_person_id`, `retired_reason`, and `source_quote` except on their own facts) blanked, never retired, replaced or declined text; `?limit=` 1–500) and their retire (the principal any fact, a teammate only one they recorded that the principal has not approved — else 403; the audit row names the teammate; 404 for an unknown or `profile` row, 409 when no longer active; writes a private `fact_retired` audit row); approve / decline a teammate's `proposed` fact (principal only, else 403; 409 when it is not proposed; private `fact_reviewed` row); and the per-teammate \"needs my approval\" switch (on by default; `GET` lists `[{person_id, full_name, needs_approval}]` for every active team member but the principal, `true` for anyone not yet set; `PUT` takes `{needs_approval}`, 404 for anyone else; both principal only; private `fact_approval_changed` row); plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller is a 404. |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `commit` answers 403 when the draft would make a different person the owner and the caller is not the current owner (setup demotes the old principal, and any signed-in user can open it). It also takes an optional `owner_email` — the principal's sign-in email, which the review screen pre-fills from the signed-in user — checked before anything is written (422 if it is malformed, already another person's, or would replace the principal's existing email — setup only fills in a missing one; 403 if the caller is not the owner and it is not the address they signed in with, since the roster is the sign-in allow-list) and saved on the principal's People row, so the owner's chats resolve to them from the first turn. |\n| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. Its final answer saves the profile and adds people with their emails and a principal, so once there is an owner only they can send it (403, and the session rolls back so the owner can still finish it). `/onboard/start` reads the workspace mode once for the session: solo skips the Team Size, Team Members and Fractional Executives steps. Each status response's `current_step` / `total_steps` count only the steps that session asks, and `optional` says whether the current step can be skipped. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `alerts` (private cards) | `POST /alerts/{id}/ack`, `/reopen`, `/alerts/bulk-ack` | An alert tagged `private:principal` (see Today) is a 404 on ack and reopen for anyone but the principal, and their bulk sweep skips it. A roster-request card (source `roster_request`) is a 409 on `ack` even for the principal — it is answered at `/people/requests/{id}`, since acking would leave the sender waiting with nothing to show it — and, as an exempt source, `bulk-ack` and `reopen` skip it. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived **team members** with an email, offered to the UI's sign-in gate — a contact is never on it, so adding a client to reach them by email no longer lets them sign in. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. With local login (`make dev` with Google sign-in not set up — the UI then listens on 127.0.0.1 only) the UI signs in without an email, sends no `x-caller-email`, and the backend resolves the caller to the principal, as it does for the CLI. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools, answered as the verified caller (`api.caller`) by the web app's rules. See the MCP Server section. |\n\n**What it may do** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it may do.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them. Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.","mermaid": null,- "generated_at": "2026-10-15T21:05:35Z"+ "generated_at": "2026-10-16T12:00:00Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/mcp_server.json b/packages/core/openexecutive/architecture/prebuilt/mcp_server.jsonindex e540f543..0fbaef10 100644--- a/packages/core/openexecutive/architecture/prebuilt/mcp_server.json+++ b/packages/core/openexecutive/architecture/prebuilt/mcp_server.json@@ -1,7 +1,7 @@{"section_id": "mcp_server","title": "MCP Server",- "markdown": "Open Executive can run **as an MCP server**, the inverse of the MCP *gateway* (which lets the Executive consume external MCP servers). The server exposes Open Executive's company-grounded context and its specialist council to external MCP clients — Claude Desktop, Cursor, Claude Code, or any other agent — so they can ground themselves in *this* company and pull domain analysis **inside their own loop**, without re-explaining anything.\n\nThis is deliberately *not* another chat channel: Open Executive already has six of those (web, Slack, Discord, Telegram, email, Google Chat). The value here is structured, attachable context plus on-demand specialist analysis.\n\n## Transport & mount\n\nThe server speaks **Streamable-HTTP** and is mounted into the existing FastAPI app at `/mcp` (built with the `FastMCP` SDK, `streamable_http_path=\"/\"` mounted under `/mcp` so the endpoint is exactly `/mcp`). Mounting a sub-app does not run its lifespan, so the API lifespan runs `mcp.session_manager.run()` for the life of the process — without it every `/mcp` request would fail. The module lives at `openexecutive/mcp_server/` and is wired in `api/main.py`.\n\n## Auth\n\nThe `/mcp` endpoint is **not** exempt from the shared-secret middleware, so it is gated exactly like every other route: clients send `x-api-key: $BACKEND_SHARED_SECRET`. There is no second auth system. With signed callers on (`CALLER_ASSERTION_PUBLIC_KEYS`), an MCP client is a *service*: the secret vouches for no one, so it is never the principal. FastMCP's DNS-rebinding (Host-header) check is disabled because the endpoint authenticates with a header secret rather than a cookie — a browser rebinding attack cannot supply the key — and traffic arrives through the deployment's TLS terminator.\n\n## Resources (read-only context)\n\nThe highest-value surface: curated company state, pure reads, no LLM calls.\n\n| Resource URI | Contents |\n|---|---|\n| `oe://company/profile` | Structured company profile, as a prompt block |\n| `oe://today/briefing` | Morning-brief snapshot: department health, roster, proposals |\n| `oe://today/activity` | Recent self-initiated Executive activity |\n| `oe://people/roster` | Active people on the roster |\n| `oe://departments/state` | Departments with goals and cadences |\n| `oe://memory/decisions` · `…/initiatives` · `…/advice` | Episodic memory |\n\n## Tools (capabilities)\n\n| Tool | What it does |\n|---|---|\n| `consult_specialist(specialist, query, context)` | **Flagship.** Domain analysis from one of ten specialists (cso, cfo, chro, gc, coo, cmo, cpo, sales, board_comms, triage), each grounded in company knowledge. Stateless. |\n| `search_knowledge(query)` | Raw retrieval over the MBA knowledge base + indexed company docs |\n| `list_workflows()` | Catalog of multi-step executive workflows and their input schemas |\n| `ask_executive(message, caller_email?)` | A single synthesized Executive answer — a fallback; prefer the specialist tool and resources. `caller_email` picks whose person-scoped memory it uses (default: the principal). With signed callers on, it is ignored and the question is asked as no one, who reads and publishes no one's documents |\n\n\n## What's intentionally deferred\n\n**Workflow *execution*** is not exposed over MCP yet. Workflows are long-running async generators (minutes), which would exceed a single tool call's request/response window. The catalog is listed via `list_workflows()`; if execution is added later it will use a job-handle pattern (`start_workflow` → `run_id`, then poll) over the existing run persistence. MCP *prompts* are also skipped — OE workflows are server-executed orchestrations, not message templates.\n\n## Why prompt caching is unaffected\n\nThis path is parallel to chat. Resources are pure reads; `consult_specialist` delegates to the same `BaseAgent.analyze` that the chat path uses, reusing the existing cached system blocks. Nothing here touches the cache layout.",- "mermaid": "flowchart TD\n Client[\"External MCP client<br/>(Claude Desktop / Cursor / agent)\"]:::entry\n Gate[\"Shared-secret middleware<br/>x-api-key\"]:::entry\n Mount[\"/mcp Streamable-HTTP<br/>(FastMCP, mounted in FastAPI)\"]:::compute\n Res[\"Resources<br/>profile · today · people<br/>departments · memory\"]:::compute\n Tools[\"Tools<br/>consult_specialist · search_knowledge<br/>list_workflows · ask_executive\"]:::compute\n Spec[\"Specialist council<br/>route_to_specialist → BaseAgent.analyze\"]:::compute\n Store[(\"ChromaDB + SQLite<br/>company state\")]:::storage\n\n Client -->|x-api-key| Gate --> Mount\n Mount --> Res\n Mount --> Tools\n Res --> Store\n Tools --> Spec\n Tools --> Store\n Spec --> Store\n\n classDef entry fill:#1e3a8a,stroke:#60a5fa,color:#fff;\n classDef compute fill:#312e81,stroke:#a5b4fc,color:#fff;\n classDef storage fill:#365314,stroke:#a3e635,color:#fff;",- "generated_at": "2026-10-03T15:21:27Z"+ "markdown": "Open Executive can run **as an MCP server**, the inverse of the MCP *gateway* (which lets the Executive consume external MCP servers). The server exposes Open Executive's company-grounded context and its specialist council to external MCP clients — Claude Desktop, Cursor, Claude Code, or any other agent — so they can ground themselves in *this* company and pull domain analysis **inside their own loop**, without re-explaining anything.\n\nThis is deliberately *not* another chat channel: Open Executive already has six of those (web, Slack, Discord, Telegram, email, Google Chat). The value here is structured, attachable context plus on-demand specialist analysis.\n\n## Transport & mount\n\nThe server speaks **Streamable-HTTP** and is mounted into the existing FastAPI app at `/mcp` (built with the `FastMCP` SDK, `streamable_http_path=\"/\"` mounted under `/mcp` so the endpoint is exactly `/mcp`). Mounting a sub-app does not run its lifespan, so the API lifespan runs `mcp.session_manager.run()` for the life of the process — without it every `/mcp` request would fail. The module lives at `openexecutive/mcp_server/` and is wired in `api/main.py`.\n\n## Auth\n\nThe `/mcp` endpoint is **not** exempt from the shared-secret middleware, so it is gated exactly like every other route: clients send `x-api-key: $BACKEND_SHARED_SECRET`. There is no second auth system. FastMCP's DNS-rebinding (Host-header) check is disabled because the endpoint authenticates with a header secret rather than a cookie — a browser rebinding attack cannot supply the key — and traffic arrives through the deployment's TLS terminator.\n\n## Who is asking\n\nEvery handler answers as the caller the API already verified. The mounted app shares the outer request's state, so what `caller_gate` decided reaches the handler through FastMCP's request context, and `api.caller.person_id_for` resolves the person by the same rule as the web chat:\n\n| Caller | Asks as |\n|---|---|\n| Open mode, no `x-caller-email` (direct use, local) | the principal |\n| Open mode with `x-caller-email`, or a signed-in person (`x-caller-assertion`) | that person; no one when they are not on the roster |\n| Operator (signed local login) | the principal |\n| Service (signed callers on, only the shared secret) | no one, never the principal |\n\nA deployment that fronts `/mcp` with its own sign-in and stamps the signed caller, as the UI proxy does, therefore gets per-person answers with the web app's rules.\n\n## Resources (read-only context)\n\nCurated company state, pure reads, no LLM calls.\n\n| Resource URI | Contents | Who may read it |\n|---|---|---|\n| `oe://company/profile` | Structured company profile, as a prompt block | anyone |\n| `oe://departments/state` | Departments with goals and cadences | anyone |\n| `oe://today/briefing` | Morning-brief snapshot: department health, roster, proposals | someone on the roster, built as `GET /today` builds it for them (the principal's private rows for the principal alone, an artifact's card for its owner) |\n| `oe://people/roster` | The team on the roster (never contacts) | someone on the roster |\n| `oe://today/activity` | Recent self-initiated Executive activity | the principal alone |\n| `oe://memory/decisions` · `…/initiatives` · `…/advice` | Episodic memory | the principal alone |\n\nA refused read is a JSON-RPC error: \"Only the owner can read this.\" or \"Only someone on the team can read this.\"\n\n## Tools (capabilities)\n\nEach tool carries an MCP title and annotations; descriptions say what a tool does without steering a client between tools.\n\n| Tool | What it does | Annotations |\n|---|---|---|\n| `consult_specialist(specialist, query, context)` | Domain analysis from one of ten specialists (cso, cfo, chro, gc, coo, cmo, cpo, sales, board_comms, triage), each grounded in company knowledge. Stateless. | read-only, closed world |\n| `search_knowledge(query)` | Raw retrieval over the curated knowledge base + indexed company docs | read-only, closed world |\n| `list_workflows()` | Catalog of multi-step executive workflows and their input schemas | read-only, closed world |\n| `ask_executive(message)` | One synthesized Executive answer, as the verified caller | not read-only (the conversation is recorded in memory), not destructive, not idempotent, closed world |\n\n`ask_executive` takes no caller argument. Its session is marked `from_mcp_client`, so the turn reads and advises but never acts: the chat loop neither offers nor runs `schedule_tools.MCP_CLIENT_WITHHELD_TOOLS` (everything that sends, posts, books, schedules, runs or changes stored state: the private-turn and unattended sets plus direct messages, alert acks, roster writes and the rest), offers no Act as me, `recall_history` or extension tools, and reaches only gateway reads (`MCP_CLIENT_MCP_TOOLS`, no send or draft). A call the model emits anyway is refused with an error that tells it to send the person to Open Executive itself. A caller that resolves to no one reads and publishes no one's documents.\n\n## What's intentionally deferred\n\n**Workflow *execution*** is not exposed over MCP yet. Workflows are long-running async generators (minutes), which would exceed a single tool call's request/response window. The catalog is listed via `list_workflows()`; if execution is added later it will use a job-handle pattern (`start_workflow` → `run_id`, then poll) over the existing run persistence. MCP *prompts* are also skipped — OE workflows are server-executed orchestrations, not message templates.\n\n## Why prompt caching is unaffected\n\nThis path is parallel to chat. Resources are pure reads; `consult_specialist` delegates to the same `BaseAgent.analyze` that the chat path uses, reusing the existing cached system blocks. `ask_executive`'s turn withholds a fixed tool set before the sort, so it has a stable cached tool prefix of its own, like a private or unattended turn.",+ "mermaid": "flowchart TD\n Client[\"External MCP client<br/>(Claude Desktop / Cursor / agent)\"]:::entry\n Gate[\"Shared-secret middleware<br/>x-api-key\"]:::entry\n Caller[\"caller_gate<br/>request.state.caller\"]:::entry\n Mount[\"/mcp Streamable-HTTP<br/>(FastMCP, mounted in FastAPI)\"]:::compute\n Who[\"Who is asking<br/>api.caller.person_id_for\"]:::compute\n Res[\"Resources<br/>owner-only · roster-only · anyone\"]:::compute\n Tools[\"Tools<br/>consult_specialist · search_knowledge<br/>list_workflows · ask_executive\"]:::compute\n Exec[\"Executive.chat<br/>from_mcp_client: reads only\"]:::compute\n Spec[\"Specialist council<br/>route_to_specialist → BaseAgent.analyze\"]:::compute\n Store[(\"ChromaDB + SQLite<br/>company state\")]:::storage\n\n Client -->|x-api-key| Gate --> Caller --> Mount\n Mount --> Who\n Who --> Res\n Who --> Tools\n Res --> Store\n Tools --> Spec\n Tools --> Exec\n Exec --> Spec\n Tools --> Store\n Spec --> Store\n\n classDef entry fill:#1e3a8a,stroke:#60a5fa,color:#fff;\n classDef compute fill:#312e81,stroke:#a5b4fc,color:#fff;\n classDef storage fill:#365314,stroke:#a3e635,color:#fff;",+ "generated_at": "2026-10-16T12:00:00Z"}diff --git a/packages/core/openexecutive/delegation/settings.py b/packages/core/openexecutive/delegation/settings.pyindex b2458674..4911e5ea 100644--- a/packages/core/openexecutive/delegation/settings.py+++ b/packages/core/openexecutive/delegation/settings.py@@ -390,6 +390,9 @@ def _offered(session: Any, person: Person | None, enabled: bool) -> bool:return Falseif getattr(session, "private_to_principal", False) is True:return False+ # Another AI app asking over the MCP server: nobody is here to approve.+ if getattr(session, "from_mcp_client", False) is True:+ return Falseoverride = getattr(session, "delegation_override", None)if isinstance(override, DelegationOverride):return override.gmail is not Nonediff --git a/packages/core/openexecutive/guide/prebuilt/integrations.json b/packages/core/openexecutive/guide/prebuilt/integrations.jsonindex 922e7245..5f27a249 100644--- a/packages/core/openexecutive/guide/prebuilt/integrations.json+++ b/packages/core/openexecutive/guide/prebuilt/integrations.json@@ -1,7 +1,7 @@{"section_id": "integrations","title": "Integrations",- "markdown": "**What it is:** The channels that connect the Executive to where your team already works, so proposals, updates and replies reach people in familiar tools instead of only the web app.\n\n**What it does:**\n\n- **Slack / Google Chat:** receive direct messages and mentions, reply in threads, and send proposals and alerts.\n- **Discord / Telegram:** direct-message conversations for questions, proposals and approvals.\n- **Email:** the Executive reads its own inbox on a regular poll and replies from its own address.\n- **Google Workspace:** the Executive can send and draft Gmail (recipients limited to your People roster) and manage Calendar events, including Google Meet links.\n- **Microsoft 365:** the Executive can send, reply to and draft Outlook mail and manage Outlook calendar events with Teams links (recipients and attendees limited to your People roster). Its own inbox and calendar can run on either Google or Microsoft. This is a per-install setting, not a per-message choice.\n- **MCP:** expose the Executive's specialist council and company context to external AI tools.\n- Everything the Executive sends on these channels as itself ends with a line saying it is an AI assistant, unless the install turns that off.\n\n**How to use:**\n\n*Before anyone can use a channel,* an administrator turns it on with environment settings (see *Setup* below) and restarts the app. There is no page in the app for turning channels on or off. Then add each person's channel ID under **People → Contact & routing** (**Slack user ID**, **Discord user ID**, **Telegram chat ID**). The person's **Preferred channel** there decides where proposals routed to them are sent. **Settings → Advanced → Setup status** then shows whether each channel is working, when it last received a message, and what to do if it isn't working.\n\n*Talking to the Executive*\n\n- **Slack**: DM the app, or @mention it in a channel; it replies in a thread. Keep replying in that thread without mentioning it again.\n- **Discord**: DM the bot, or @mention it in a server channel (it answers in a new thread). Or use the slash commands `/ask` and `/today`.\n- **Telegram**: message the bot directly in a private chat. Text, documents and photos all work.\n- **Google Chat**: DM the app, or add it to a space and @mention it.\n- **Email**: send mail to the Executive's address. It picks up unread inbox mail on a regular poll (every 60 seconds unless the install changes it).\n- **Signing off a paused workflow**: reply in the thread on Slack, Discord or Telegram: \"yes\", \"LGTM\", \"no\", \"not now\".\n\n*Who it answers*\n\n- Slack, Discord, Telegram and email answer only people on your People list.\n- When someone who isn't on the list writes to it directly, their message is held. They get one fixed reply saying it arrived and is waiting for confirmation. The owner gets a card on Home and a message on their preferred channel asking who it is. Once the owner confirms them, the held messages are answered.\n- In a Slack channel the \"waiting\" reply is shown only to the sender. In a Telegram group, nothing is sent.\n- Google Chat answers anyone in a space it is in. It reads attached files only from people on your People list.\n- Files shared on Slack, Discord, Telegram and Google Chat are read only for people on your People list.\n\n*Writing as you*\n\n- **Act as me** (under **Delegate**) works in a direct message to the Executive on Slack or Discord and in a private Telegram chat, as well as in the web app. It does not work in a shared channel or thread, on Google Chat or by email. See the Delegate section of this guide.\n\n**Example (Slack):** *\"@Executive what's blocking the Q3 hiring plan?\"* The answer arrives in a thread, and you can follow up there.\n\n*Setup (administrators)* — each channel is switched on with environment settings:\n\n| Channel | Settings |\n|---|---|\n| Slack | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` (Socket Mode). Or, on a server Slack can reach, leave `SLACK_APP_TOKEN` unset, set `SLACK_SIGNING_SECRET` and point the app's Event Subscriptions at `/webhook/slack` |\n| Discord | `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`; enable the bot's Message Content intent (see the README). Optional: `DISCORD_NOTIFY_CHANNEL_ID` for alerts |\n| Telegram | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`; webhook at `/webhook/telegram`; see `docs/telegram_setup.md` |\n| Google Chat | `GOOGLE_CHAT_PROJECT_NUMBER` plus a service account (`GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` or `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL`); webhook at `/webhook/google-chat`; see `docs/google_chat_setup.md` |\n| Email, Gmail & Calendar | `EXEC_EMAIL_ADDRESS` plus the Google Workspace connection — see `docs/deployment.md`. `EMAIL_POLL_INTERVAL_SECONDS` sets how often the inbox is read |\n| Microsoft 365 | `MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, `MS365_MCP_EXPECTED_USERNAME`, then a one-time sign-in with `ms365-mcp-launch.sh --login` — see `docs/deployment.md`. `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` choose whether the Executive's own inbox and calendar are Google or Microsoft |\n\n*Use the Executive from other AI tools (MCP)* — the API serves an MCP endpoint at `/mcp`; clients authenticate with the backend shared secret. In Claude Code:\n\n```bash\nclaude mcp add --transport http open-executive http://localhost:8000/mcp \\\n --header \"x-api-key: YOUR_BACKEND_SHARED_SECRET\"\n```\n\nOther MCP clients take the same URL and `x-api-key` header. They get `ask_executive`, `consult_specialist`, `search_knowledge` and `list_workflows`, plus read-only company context: the company profile, the Today briefing, recent activity, the People roster, department state, and remembered decisions, initiatives and advice.\n\n*Note: every channel is recorded in the Audit Log. Replying to approve a paused workflow works on Slack, Discord and Telegram only, not email or Google Chat. While the Executive is paused, chat and direct messages on every channel still get answers.*\n",+ "markdown": "**What it is:** The channels that connect the Executive to where your team already works, so proposals, updates and replies reach people in familiar tools instead of only the web app.\n\n**What it does:**\n\n- **Slack / Google Chat:** receive direct messages and mentions, reply in threads, and send proposals and alerts.\n- **Discord / Telegram:** direct-message conversations for questions, proposals and approvals.\n- **Email:** the Executive reads its own inbox on a regular poll and replies from its own address.\n- **Google Workspace:** the Executive can send and draft Gmail (recipients limited to your People roster) and manage Calendar events, including Google Meet links.\n- **Microsoft 365:** the Executive can send, reply to and draft Outlook mail and manage Outlook calendar events with Teams links (recipients and attendees limited to your People roster). Its own inbox and calendar can run on either Google or Microsoft. This is a per-install setting, not a per-message choice.\n- **MCP:** expose the Executive's specialist council and company context to external AI tools.\n- Everything the Executive sends on these channels as itself ends with a line saying it is an AI assistant, unless the install turns that off.\n\n**How to use:**\n\n*Before anyone can use a channel,* an administrator turns it on with environment settings (see *Setup* below) and restarts the app. There is no page in the app for turning channels on or off. Then add each person's channel ID under **People → Contact & routing** (**Slack user ID**, **Discord user ID**, **Telegram chat ID**). The person's **Preferred channel** there decides where proposals routed to them are sent. **Settings → Advanced → Setup status** then shows whether each channel is working, when it last received a message, and what to do if it isn't working.\n\n*Talking to the Executive*\n\n- **Slack**: DM the app, or @mention it in a channel; it replies in a thread. Keep replying in that thread without mentioning it again.\n- **Discord**: DM the bot, or @mention it in a server channel (it answers in a new thread). Or use the slash commands `/ask` and `/today`.\n- **Telegram**: message the bot directly in a private chat. Text, documents and photos all work.\n- **Google Chat**: DM the app, or add it to a space and @mention it.\n- **Email**: send mail to the Executive's address. It picks up unread inbox mail on a regular poll (every 60 seconds unless the install changes it).\n- **Signing off a paused workflow**: reply in the thread on Slack, Discord or Telegram: \"yes\", \"LGTM\", \"no\", \"not now\".\n\n*Who it answers*\n\n- Slack, Discord, Telegram and email answer only people on your People list.\n- When someone who isn't on the list writes to it directly, their message is held. They get one fixed reply saying it arrived and is waiting for confirmation. The owner gets a card on Home and a message on their preferred channel asking who it is. Once the owner confirms them, the held messages are answered.\n- In a Slack channel the \"waiting\" reply is shown only to the sender. In a Telegram group, nothing is sent.\n- Google Chat answers anyone in a space it is in. It reads attached files only from people on your People list.\n- Files shared on Slack, Discord, Telegram and Google Chat are read only for people on your People list.\n\n*Writing as you*\n\n- **Act as me** (under **Delegate**) works in a direct message to the Executive on Slack or Discord and in a private Telegram chat, as well as in the web app. It does not work in a shared channel or thread, on Google Chat or by email. See the Delegate section of this guide.\n\n**Example (Slack):** *\"@Executive what's blocking the Q3 hiring plan?\"* The answer arrives in a thread, and you can follow up there.\n\n*Setup (administrators)* — each channel is switched on with environment settings:\n\n| Channel | Settings |\n|---|---|\n| Slack | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` (Socket Mode). Or, on a server Slack can reach, leave `SLACK_APP_TOKEN` unset, set `SLACK_SIGNING_SECRET` and point the app's Event Subscriptions at `/webhook/slack` |\n| Discord | `DISCORD_BOT_TOKEN`, `DISCORD_APP_ID`; enable the bot's Message Content intent (see the README). Optional: `DISCORD_NOTIFY_CHANNEL_ID` for alerts |\n| Telegram | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`; webhook at `/webhook/telegram`; see `docs/telegram_setup.md` |\n| Google Chat | `GOOGLE_CHAT_PROJECT_NUMBER` plus a service account (`GOOGLE_CHAT_SERVICE_ACCOUNT_FILE` or `GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL`); webhook at `/webhook/google-chat`; see `docs/google_chat_setup.md` |\n| Email, Gmail & Calendar | `EXEC_EMAIL_ADDRESS` plus the Google Workspace connection — see `docs/deployment.md`. `EMAIL_POLL_INTERVAL_SECONDS` sets how often the inbox is read |\n| Microsoft 365 | `MS365_MCP_CLIENT_ID`, `MS365_MCP_TENANT_ID`, `MS365_MCP_EXPECTED_USERNAME`, then a one-time sign-in with `ms365-mcp-launch.sh --login` — see `docs/deployment.md`. `EMAIL_PROVIDER` / `CALENDAR_PROVIDER` choose whether the Executive's own inbox and calendar are Google or Microsoft |\n\n*Use the Executive from other AI tools (MCP)* — the API serves an MCP endpoint at `/mcp`; clients authenticate with the backend shared secret. In Claude Code:\n\n```bash\nclaude mcp add --transport http open-executive http://localhost:8000/mcp \\\n --header \"x-api-key: YOUR_BACKEND_SHARED_SECRET\"\n```\n\nOther MCP clients take the same URL and `x-api-key` header. They get `ask_executive`, `consult_specialist`, `search_knowledge` and `list_workflows`, plus read-only company context: the company profile, the Today briefing, recent activity, the People roster, department state, and remembered decisions, initiatives and advice.\n\n- They answer as the person signed in, with the same rules as the web app: remembered decisions, initiatives and advice and recent activity are the owner's alone, and the Today briefing and People roster need someone on your People list. With no sign-in in front of the endpoint, the client is the owner.\n- `ask_executive` reads and advises only. It never sends, posts, books or changes anything; to do that, ask in Open Executive itself.\n\n*Note: every channel is recorded in the Audit Log. Replying to approve a paused workflow works on Slack, Discord and Telegram only, not email or Google Chat. While the Executive is paused, chat and direct messages on every channel still get answers.*\n","mermaid": null,"generated_at": "2026-10-15T21:00:00Z"}diff --git a/packages/core/openexecutive/mcp_server/server.py b/packages/core/openexecutive/mcp_server/server.pyindex 46e22373..c756a339 100644--- a/packages/core/openexecutive/mcp_server/server.py+++ b/packages/core/openexecutive/mcp_server/server.py@@ -15,6 +15,26 @@ Design notes``_UNAUTHENTICATED_PATHS``; the existing shared-secret middleware gates it,so clients pass ``x-api-key: $BACKEND_SHARED_SECRET`` like the UI does.+* **Who is asking.** Every handler answers as the caller the API already+ verified (``api.caller``): the mounted app shares the outer request's+ ``request.state``, so ``caller_gate``'s verdict reaches the handler through+ FastMCP's request context (``_request``). A deployment that fronts ``/mcp``+ with its own sign-in and stamps the signed caller, as the UI proxy does,+ gets per-person answers by the web app's rules: a signed-in email is that+ person (no one when off the roster); open mode with no ``x-caller-email``,+ or an operator, is the principal; a service (signed callers on, no+ assertion) is no one. The principal's own records (episodic memory, the+ activity feed) go to the principal alone; the briefing and roster to a+ rostered caller, the briefing narrowed as ``GET /today`` narrows it; the+ company profile, departments, specialists, knowledge and the workflow+ catalog to anyone who reached ``/mcp``.++* **ask_executive never acts.** Its turn is marked+ ``Session.from_mcp_client``: the chat loop offers and runs no tool that+ sends, posts, books, schedules, runs or changes stored state+ (``schedule_tools.MCP_CLIENT_WITHHELD_TOOLS``), no Act as me or extension+ tool, and of the gateway tools only reads (``MCP_CLIENT_MCP_TOOLS``).+* **DNS-rebinding protection** (FastMCP's Host-header check) is disabled: theendpoint authenticates with a header secret (not a cookie), so a browserrebinding attack cannot supply credentials, and the server runs behind the@@ -25,7 +45,8 @@ Design notespure reads; ``consult_specialist`` delegates to ``BaseAgent.analyze`` whichreuses the existing cached system blocks unchanged.-* **State.** Handlers get no FastAPI ``Request``. Most service functions build+* **State.** Handlers get no FastAPI ``Request`` argument (only the caller+ read above goes through the request). Most service functions buildtheir own SQLite/ChromaDB handles; the one that benefits from the app's warmstore (``search_knowledge``) reads it from the ``set_store`` singleton."""@@ -34,13 +55,16 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-import sqlite3from collections.abc import AsyncIteratorfrom contextlib import asynccontextmanager+from dataclasses import dataclassfrom typing import Any, Literal, get_argsfrom mcp.server.fastmcp import FastMCPfrom mcp.server.transport_security import TransportSecuritySettings+from mcp.types import ToolAnnotations++from openexecutive.api import caller as api_callerlogger = logging.getLogger(__name__)@@ -52,17 +76,18 @@ SpecialistKey = Literal[]_INSTRUCTIONS = (- "Open Executive exposed as an MCP server. It surfaces a company's "- "executive context and a council of specialist analysts so another agent "- "can ground itself in this company without re-explaining it.\n\n"- "Resources (read-only, company-internal): company profile, today's "- "briefing and recent activity, the people roster, department state, "- "and episodic memory (past decisions, initiatives, advice).\n\n"- "Tools: `consult_specialist` (domain analysis from a CFO/CSO/etc., grounded "- "in company knowledge), `search_knowledge` (curated MBA + company-doc "- "retrieval), `list_workflows` (catalog of multi-step executive workflows), "- "and `ask_executive` (a single synthesized answer from the Executive — a "- "fallback; prefer the specialist tool and resources)."+ "Open Executive as an MCP server: a company's executive context and a "+ "council of specialist analysts, answered as the person signed in.\n\n"+ "Resources (read-only): the company profile, today's briefing and recent "+ "activity, the people roster, department state, and episodic memory (past "+ "decisions, initiatives, advice). Recent activity and episodic memory are "+ "the owner's alone; the briefing and roster need someone on the roster.\n\n"+ "Tools: `consult_specialist` (domain analysis from one specialist, grounded "+ "in company knowledge), `search_knowledge` (retrieval over the curated "+ "business knowledge base and company documents), `list_workflows` (the "+ "catalog of multi-step executive workflows), and `ask_executive` (one "+ "synthesized answer from the Executive). None of them sends, posts, books "+ "or changes anything.")mcp = FastMCP(@@ -98,6 +123,94 @@ def _json(payload: Any) -> str:return json.dumps(payload, default=str, ensure_ascii=False)+# ---------------------------------------------------------------------------+# Who is asking.+# ---------------------------------------------------------------------------+OWNER_ONLY = "Only the owner can read this."+ROSTER_ONLY = "Only someone on the team can read this."+++class CallerRefused(PermissionError):+ """This caller may not read what it asked for. FastMCP returns the+ message to the client as the error."""+++@dataclass(frozen=True)+class McpCaller:+ """Who an MCP request asks as: their People entry (None for no one) and+ whether they are the principal, by the web app's rules."""++ person_id: int | None+ is_principal: bool+++# No MCP request is in progress: a direct in-process call (tests, scripts).+_NO_MCP_REQUEST = object()+++def _request() -> Any:+ """The HTTP request behind the MCP call in progress; None when the call+ has a request context but no HTTP request; ``_NO_MCP_REQUEST`` outside+ any MCP request. Read in the handler's own task, where FastMCP's request+ context is set."""+ try:+ context = mcp.get_context().request_context+ except (LookupError, ValueError):+ return _NO_MCP_REQUEST+ return getattr(context, "request", None)+++def _who() -> api_caller.Caller:+ """The verified caller of the request in progress. Outside any MCP+ request (a direct in-process call) it is what a request naming no one+ would be: the principal, or no one once signed callers are on. An MCP+ call that carries no HTTP request names no one (fails closed)."""+ request = _request()+ if request is _NO_MCP_REQUEST:+ return api_caller.Caller("service") if api_caller.signing_on() else api_caller.Caller("open")+ if request is None:+ return api_caller.Caller("service")+ return api_caller.caller(request)+++def _resolve(who: api_caller.Caller) -> McpCaller:+ """``who`` on the roster, by ``api.caller.person_id_for``. Fails closed:+ a roster that can't be read makes them no principal."""+ from openexecutive.people.store import is_principal_or_self++ person_id = api_caller.person_id_for(who)+ if who.defaults_to_principal:+ return McpCaller(person_id, True)+ try:+ principal = person_id is not None and is_principal_or_self(person_id, None)+ except Exception:+ logger.warning("mcp_server: principal check failed — answering no", exc_info=True)+ principal = False+ return McpCaller(person_id, principal)+++async def current_caller() -> McpCaller:+ """Who the MCP request in progress asks as."""+ who = _who()+ return await asyncio.to_thread(_resolve, who)+++async def _require_principal() -> McpCaller:+ resolved = await current_caller()+ if not resolved.is_principal:+ raise CallerRefused(OWNER_ONLY)+ return resolved+++async def _require_person() -> McpCaller:+ """The principal, or someone on the roster; a service or an unrostered+ caller names no one, so reads nothing about the people here."""+ resolved = await current_caller()+ if resolved.person_id is None and not resolved.is_principal:+ raise CallerRefused(ROSTER_ONLY)+ return resolved++# ---------------------------------------------------------------------------# Resources — company-grounded context. Read-only, no LLM calls. The unique# thing OE has that a generic agent does not.@@ -120,25 +233,37 @@ async def company_profile() -> str:@mcp.resource("oe://today/briefing",name="Today briefing",- description="The morning-brief snapshot: department health, roster, proposals.",+ description=(+ "The morning-brief snapshot: department health, roster, proposals. "+ "For someone on the roster, as the web app shows it to them."+ ),mime_type="application/json",)async def today_briefing() -> str:+ """As ``GET /today`` gives it: the principal's private rows for the+ principal alone, a drafted artifact's card for its owner."""from openexecutive.api.routes.today import _build_today+ from openexecutive.orchestrator.artifact_records import viewer_for_person- today = await asyncio.to_thread(_build_today)+ who = await _require_person()+ viewer = await asyncio.to_thread(viewer_for_person, who.person_id)+ today = await asyncio.to_thread(+ _build_today, include_private=who.is_principal, viewer=viewer+ )+ today.caller_person_id = who.person_idreturn _json(today.model_dump(mode="json"))@mcp.resource("oe://today/activity",name="Recent activity",- description="Recent self-initiated Executive activity (last 20 actions).",+ description="Recent self-initiated Executive activity (last 20 actions). The owner's alone.",mime_type="application/json",)async def today_activity() -> str:from openexecutive.api.routes.today import _build_activity+ await _require_principal()activity = await asyncio.to_thread(_build_activity, 20)return _json(activity.model_dump(mode="json"))@@ -146,12 +271,14 @@ async def today_activity() -> str:@mcp.resource("oe://people/roster",name="People roster",- description="Active people on the company roster.",+ description="Active team members on the company roster. For someone on the roster.",mime_type="application/json",)async def people_roster() -> str:from openexecutive.people.store import list_people+ # The team, never the principal's contacts (as GET /people gives it).+ await _require_person()people = await asyncio.to_thread(list_people)return _json([p.model_dump(mode="json") for p in people])@@ -172,12 +299,13 @@ async def departments_state() -> str:@mcp.resource("oe://memory/decisions",name="Episodic memory: decisions",- description="Past decisions recorded in episodic memory.",+ description="Past decisions recorded in episodic memory. The owner's alone.",mime_type="application/json",)async def memory_decisions() -> str:from openexecutive.memory.episodic import list_decisions+ await _require_principal()rows = await asyncio.to_thread(list_decisions)return _json([r.model_dump(mode="json") for r in rows])@@ -185,12 +313,13 @@ async def memory_decisions() -> str:@mcp.resource("oe://memory/initiatives",name="Episodic memory: initiatives",- description="Tracked initiatives recorded in episodic memory.",+ description="Tracked initiatives recorded in episodic memory. The owner's alone.",mime_type="application/json",)async def memory_initiatives() -> str:from openexecutive.memory.episodic import list_initiatives+ await _require_principal()rows = await asyncio.to_thread(list_initiatives)return _json([r.model_dump(mode="json") for r in rows])@@ -198,20 +327,25 @@ async def memory_initiatives() -> str:@mcp.resource("oe://memory/advice",name="Episodic memory: advice",- description="Advice given, recorded in episodic memory.",+ description="Advice given, recorded in episodic memory. The owner's alone.",mime_type="application/json",)async def memory_advice() -> str:from openexecutive.memory.episodic import list_advice+ await _require_principal()rows = await asyncio.to_thread(list_advice)return _json([r.model_dump(mode="json") for r in rows])# ----------------------------------------------------------------------------# Tools — structured capabilities. The flagship is consult_specialist.+# Tools — structured capabilities. None of them sends, posts, books or+# changes anything; ask_executive records the conversation in memory.# ---------------------------------------------------------------------------+_READ_ONLY = ToolAnnotations(readOnlyHint=True, openWorldHint=False)++[email protected](title="Consult a specialist", annotations=_READ_ONLY)async def consult_specialist(specialist: SpecialistKey, query: str, context: str = "") -> str:@@ -244,27 +378,25 @@ async def consult_specialist()[email protected](title="Search knowledge", annotations=_READ_ONLY)async def search_knowledge(query: str) -> str:- """Search Open Executive's curated MBA knowledge base and indexed company docs.+ """Search Open Executive's curated business knowledge base and indexed company docs.Returns the most relevant retrieved chunks, each prefixed with its- ``[source]``. No LLM call — this is raw retrieval you can cite or feed back- into your own reasoning.+ ``[source]``. No LLM call: raw retrieval to cite or reason over."""from openexecutive.knowledge.retriever import retrievereturn await asyncio.to_thread(retrieve, query=query, store=get_store())[email protected](title="List workflows", annotations=_READ_ONLY)async def list_workflows() -> str:"""List the available multi-step executive workflows and their input schemas.Returns a JSON array of workflow metadata (name, title, description,- estimated minutes, input schema, steps). Execution is intentionally not- exposed over MCP yet — workflows are long-running and would exceed a single- tool-call's timeout.+ estimated minutes, input schema, steps). Workflows are run from Open+ Executive itself, not over MCP."""from openexecutive.workflows import list_workflows as _list@@ -272,59 +404,50 @@ async def list_workflows() -> str:return _json([w.meta().model_dump(mode="json") for w in workflows])-async def ask_executive(message: str, caller_email: str = "") -> str:- """Ask the Executive a question and get one synthesized answer (fallback tool).+ title="Ask the Executive",+ annotations=ToolAnnotations(+ readOnlyHint=False,+ destructiveHint=False,+ idempotentHint=False,+ openWorldHint=False,+ ),+)+async def ask_executive(message: str) -> str:+ """Ask the Executive a question and get one synthesized, cross-domain answer.- Prefer ``consult_specialist`` and the company resources — this duplicates- OE's existing chat channels and is non-streaming. Use it only when you want- a single coherent, cross-domain answer.+ The Executive answers as it would in Open Executive for the person signed+ in, drawing on the specialists, company knowledge and memory. It reads and+ advises only: it does not send, post, book or change anything. The+ conversation is recorded in Open Executive's memory. Non-streaming.Args:- message: Your question for the Executive.- caller_email: Optional — resolve the caller to a known person for- person-scoped memory; defaults to the company principal. Ignored- when the API checks signed callers: an MCP client then holds only- the shared secret, which vouches for no one, so it asks as no one.+ message: The question for the Executive."""- from openexecutive.api.caller import signing_on+ from openexecutive.orchestrator.artifact_records import NOBODYfrom openexecutive.orchestrator.executive import Executivefrom openexecutive.orchestrator.mcp_gateway import get_active_gatewayfrom openexecutive.orchestrator.session import Session- from openexecutive.people.store import (- find_person_by_email,- find_principal_person,- )- def _resolve_person() -> int | None:- if signing_on():- return None- # Degrade to None on a DB error rather than surfacing it to the client,- # matching the chat route's caller resolution (api/routes/chat.py).- try:- person = (- find_person_by_email(caller_email.strip().lower())- if caller_email.strip()- else find_principal_person()- )- except (OSError, sqlite3.Error):- logger.warning("ask_executive caller lookup failed", exc_info=True)- return None- return person.id if person is not None else None-- person_id = await asyncio.to_thread(_resolve_person)+ # Who is asking comes from the verified request, never from the message:+ # a signed-in person, the principal for a request that names no one in+ # open mode, no one for a service.+ who = _who()+ person_id = await asyncio.to_thread(api_caller.person_id_for, who)from openexecutive.onboarding.profile_builder import load_or_create_profileprofile = await asyncio.to_thread(load_or_create_profile)- from openexecutive.orchestrator.artifact_records import NOBODY-session = Session(company_profile=profile if not profile.is_empty() else None,# A client that resolves to no one reads and publishes no one's# documents (``artifact_records.current_viewer`` would otherwise take# a speakerless session for the principal's own work).documents_viewer=NOBODY if person_id is None else None,+ # Another AI app is asking: the turn reads and advises but never+ # sends, posts, books or changes anything (Session.from_mcp_client).+ from_mcp_client=True,+ caller_person_id=person_id,)executive = Executive(mcp_gateway=get_active_gateway())@@ -367,8 +490,9 @@ async def run_session_manager() -> AsyncIterator[None]:Production starts one app once, so this runs the manager for the app's life.The guard makes it a no-op on any *subsequent* lifespan entry in the sameprocess — which only happens in the test suite, where apps are rebuilt via- ``create_app()`` and never exercise the live ``/mcp`` protocol — instead of- raising ``RuntimeError``.+ ``create_app()`` (a test that drives the live ``/mcp`` protocol gives the+ endpoint a session manager of its own) — instead of raising+ ``RuntimeError``."""global _session_startedif _session_started:diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.pyindex 577ee3e1..bec8ab34 100644--- a/packages/core/openexecutive/orchestrator/executive.py+++ b/packages/core/openexecutive/orchestrator/executive.py@@ -143,12 +143,16 @@ from openexecutive.orchestrator.router import (route_parallel,)from openexecutive.orchestrator.schedule_tools import (+ MCP_CLIENT_WITHHELD_TOOLS,PRIVATE_TURN_WITHHELD_TOOLS,SCHEDULE_TOOL_HANDLERS,SCHEDULE_TOOLS,UNATTENDED_WITHHELD_TOOLS,current_session,filter_tools_for_workspace_mode,+ mcp_client_allows_mcp_tool,+ mcp_client_withheld_error,+ mcp_client_withholds,private_turn_allows_mcp_tool,private_turn_withheld_error,private_turn_withholds,@@ -2110,7 +2114,17 @@ class Executive:# Python jobs need the sandbox the API image installs: without it the# tool is not offered (fixed per process, so the prefix stays stable).sandbox_missing = frozenset() if python_job.available() else frozenset({python_job.TOOL_NAME})- not_offered = unattended_withheld | private_withheld | principal_withheld | sandbox_missing+ # Another AI app asking over Open Executive's MCP server+ # (`Session.from_mcp_client`): it reads and advises, and nothing that+ # sends, posts, books, schedules, runs or changes stored state is+ # offered or run (`MCP_CLIENT_WITHHELD_TOOLS`) — a fixed set, so the+ # variant keeps a stable tool prefix of its own.+ mcp_client = bool(getattr(current_session.get(), "from_mcp_client", False))+ mcp_client_withheld = MCP_CLIENT_WITHHELD_TOOLS if mcp_client else frozenset()+ not_offered = (+ unattended_withheld | private_withheld | principal_withheld | sandbox_missing+ | mcp_client_withheld+ )withheld_tools = tools_withheld_in_mode(workspace_mode) | not_offered# Act as me: ghostwrite_email joins the toolkit only on a turn# pin_turn_delegation offered it to. Its own registry, never@@ -2118,7 +2132,9 @@ class Executive:# any other turn a call to it is an unknown tool, not a refusal to argue# with.pinned_delegation = turn_delegation(current_session.get())- ghostwrite_offered = pinned_delegation is not None and pinned_delegation.offered+ ghostwrite_offered = (+ not mcp_client and pinned_delegation is not None and pinned_delegation.offered+ )delegation_tools = DELEGATION_TOOLS if ghostwrite_offered else []turn_handlers = ({**_ALL_SKILL_HANDLERS, **DELEGATION_TOOL_HANDLERS}@@ -2127,14 +2143,14 @@ class Executive:)# Always in the loop: recall_history joins the same way, only on a# turn whose speaker may read their own notes here (history_tools).- history_offered = recall_person(current_session.get()) is not None+ history_offered = not mcp_client and recall_person(current_session.get()) is not Noneif history_offered:delegation_tools = [*delegation_tools, *HISTORY_TOOLS]turn_handlers = {**turn_handlers, **HISTORY_TOOL_HANDLERS}# Tools an installed extension adds (orchestrator/extensions.py): only# on a turn someone is in, never an unattended run or a turn private# to the principal, and only where each tool says it is offered.- if not unattended_withheld and not private_turn:+ if not unattended_withheld and not private_turn and not mcp_client:extra_tools = extensions.offered_tools(current_session.get())if extra_tools:delegation_tools = [*delegation_tools, *(t.definition for t in extra_tools)]@@ -2394,7 +2410,7 @@ class Executive:]# A turn private to the principal is not offered run_script# (PRIVATE_TURN_WITHHELD_TOOLS); the same guard refuses it.- if private_turn and script_tool_uses:+ if (private_turn or mcp_client) and script_tool_uses:withheld_uses = [*withheld_uses, *script_tool_uses]script_tool_uses = []# list_saved_tools is principal-only (PRINCIPAL_ONLY_TOOLS).@@ -2415,6 +2431,14 @@ class Executive:tu for tu in mcp_tool_usesif tu["name"] in principal_withheld and tu not in withheld_mcp_uses]+ # A turn from another AI app: gateway reads only+ # (MCP_CLIENT_MCP_TOOLS), never load_mcp_server.+ withheld_mcp_uses += [+ tu for tu in mcp_tool_uses+ if mcp_client+ and mcp_client_withholds(tu["name"], tu["input"])+ and tu not in withheld_mcp_uses+ ]if withheld_mcp_uses:mcp_tool_uses = [tu for tu in mcp_tool_uses if tu not in withheld_mcp_uses]withheld_uses = [*withheld_uses, *withheld_mcp_uses]@@ -2553,6 +2577,35 @@ class Executive:)results_by_id[tu["id"]] = mail_touched_withheld_error(label)for tu in withheld_uses:+ if mcp_client and mcp_client_withholds(tu["name"], tu["input"]):+ # Fail closed: never run, and leave a trace. A call_tool+ # is named by the tool it asked for.+ kind = "mcp" if tu["name"] in MCP_TOOL_NAMES else "skill"+ label = tu["name"]+ if label == "call_tool" and isinstance(tu["input"], dict):+ named = tu["input"].get("name")+ label = named[:200] if isinstance(named, str) and named else label+ logger.warning(+ "%s:%s refused — the turn comes from an MCP client",+ kind, _loggable_tool(label),+ )+ audit_log(+ "tool_invocation",+ f"{kind}:{label} refused: the turn comes from another AI app",+ session_id=session_id,+ turn_id=turn_id,+ actor="executive",+ details={+ "tool": label,+ "kind": kind,+ "iteration": iteration,+ "ok": False,+ "refused": "mcp_client",+ },+ private=private_turn,+ )+ results_by_id[tu["id"]] = mcp_client_withheld_error(label)+ continueif private_turn and private_turn_withholds(tu["name"], tu["input"]):# Fail closed: never run, and leave a trace — private to# the principal like every row this turn writes. A@@ -2893,6 +2946,9 @@ class Executive:if private_turn and tu["name"] == "search_tools":# Offer a private turn PRIVATE_TURN_MCP_TOOLS only.result = filter_search_results(result, private_turn_allows_mcp_tool)+ if mcp_client and tu["name"] == "search_tools":+ # And a turn from another AI app MCP_CLIENT_MCP_TOOLS.+ result = filter_search_results(result, mcp_client_allows_mcp_tool)logger.info("← %s result=%s", tool_label, _log_value(tool_label, result))results_by_id[tu["id"]] = result# MCP chip emission. search_tools is read-only (getsdiff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.pyindex 649938eb..02fa67f9 100644--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py@@ -3076,6 +3076,19 @@ class MCPGateway:)if refused is not None:return refused+ # A turn another AI app asked over Open Executive's MCP server runs+ # gateway reads only (schedule_tools.MCP_CLIENT_MCP_TOOLS). The chat+ # loop already refuses anything else; this holds for any other path.+ from openexecutive.orchestrator.schedule_tools import (+ current_session,+ mcp_client_withheld_error,+ mcp_client_withholds,+ )++ if getattr(current_session.get(), "from_mcp_client", False) is True and mcp_client_withholds(+ "call_tool", tool_input+ ):+ return mcp_client_withheld_error(str(tool_input.get("name") or "call_tool")[:200])session = self._require_session()arguments = tool_input.get("arguments", {})if isinstance(arguments, str):diff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.pyindex 777e7e8d..cf596717 100644--- a/packages/core/openexecutive/orchestrator/schedule_tools.py+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py@@ -2034,6 +2034,87 @@ def private_turn_withheld_error(tool_name: str) -> str:})+# What a turn asked from another AI app over Open Executive's own MCP server+# (`Session.from_mcp_client`, set by `mcp_server.ask_executive`) is never+# offered. Such a turn reads and advises; it never sends, posts, books,+# schedules, runs or changes anything, because nobody is in Open Executive to+# see it happen and the other app's text is whatever that app put there. It+# starts from everything a turn private to the principal and an unattended+# run are denied, and adds every other tool that reaches someone or writes:+# - message_person, send_slack_dm, send_discord_dm, send_telegram_message:+# direct messages.+# - ack_alert, create_alert, leave_out_of_brief: change the briefing.+# - close_open_loop: stops a loop being chased.+# - upsert_person, archive_person, set_department_head: roster writes.+# - remove_watchlist_entry, tune_watchlist_entry: monitoring writes.+# - draft_workflow: drafts a definition only save_workflow (withheld) keeps.+# - propose_form_values: fills a form on a screen this turn has none of.+# The Act as me tools (`propose_actions`, `ghostwrite_email`, the mailbox+# reads), recall_history and extension tools are not offered either: the chat+# loop leaves those registries out of such a turn. Of the gateway tools, only+# the reads in `MCP_CLIENT_MCP_TOOLS`. The loop drops this set before the+# sort, so the variant has a stable tool prefix of its own, and refuses a call+# the model emits anyway (`mcp_client_withholds`, `mcp_client_withheld_error`).+MCP_CLIENT_WITHHELD_TOOLS: frozenset[str] = PRIVATE_TURN_WITHHELD_TOOLS | UNATTENDED_WITHHELD_TOOLS | frozenset({+ "ack_alert",+ "archive_person",+ "close_open_loop",+ "create_alert",+ "draft_workflow",+ "leave_out_of_brief",+ "message_person",+ "propose_form_values",+ "remove_watchlist_entry",+ "send_discord_dm",+ "send_slack_dm",+ "send_telegram_message",+ "set_department_head",+ "tune_watchlist_entry",+ "upsert_person",+})++# The gateway tools such a turn may call: the private-turn reads, without the+# mail tools that send or leave a draft in a mailbox.+MCP_CLIENT_MCP_TOOLS: frozenset[str] = PRIVATE_TURN_MCP_TOOLS - frozenset({+ "google_workspace__draft_gmail_message",+ "google_workspace__send_gmail_message",+ "microsoft_365__create-draft-email",+ "microsoft_365__send-mail",+})++MCP_CLIENT_REFUSAL = (+ "This conversation comes from another AI app, so here you can read and "+ "advise but can't send, post, book or change anything. Tell the person to "+ "ask for it in Open Executive itself."+)+++def mcp_client_allows_mcp_tool(tool_name: object) -> bool:+ """Whether a turn from another AI app may call the gateway tool+ ``tool_name``: one of ``MCP_CLIENT_MCP_TOOLS``, and nothing else."""+ return isinstance(tool_name, str) and tool_name in MCP_CLIENT_MCP_TOOLS+++def mcp_client_withholds(tool_name: str, tool_input: Any) -> bool:+ """Whether a turn from another AI app may not run this tool use: a tool+ in ``MCP_CLIENT_WITHHELD_TOOLS``, or a gateway ``call_tool`` naming+ anything but ``MCP_CLIENT_MCP_TOOLS`` or a OneDrive file read."""+ if tool_name in MCP_CLIENT_WITHHELD_TOOLS:+ return True+ if tool_name != "call_tool":+ return False+ named = tool_input.get("name") if isinstance(tool_input, dict) else None+ return not (mcp_client_allows_mcp_tool(named) or is_onedrive_file_read(tool_input))+++def mcp_client_withheld_error(tool_name: str) -> str:+ """The JSON error tool_result for a call a turn from another AI app may+ not make."""+ return json.dumps({+ "error": f"{tool_name} is not available on this turn. {MCP_CLIENT_REFUSAL} Do not retry."+ })++def handlers_for_offered_tools(tools: list[dict[str, Any]], handlers: dict[str, Any]) -> dict[str, Any]:diff --git a/packages/core/openexecutive/orchestrator/session.py b/packages/core/openexecutive/orchestrator/session.pyindex 203d3c49..504b0c86 100644--- a/packages/core/openexecutive/orchestrator/session.py+++ b/packages/core/openexecutive/orchestrator/session.py@@ -65,6 +65,15 @@ class Session:# which runs on the host itself — the principal's own surface for# `content_trust.principal_speaking`, as the web chat is.from_cli: bool = False+ # True only for a session minted by Open Executive's own MCP server+ # (`mcp_server.ask_executive`): another AI app is asking, on behalf of+ # `caller_person_id`. Such a turn reads and advises but never sends,+ # posts, books, schedules, runs or changes anything: the chat loop+ # neither offers nor runs `schedule_tools.MCP_CLIENT_WITHHELD_TOOLS`, Act+ # as me, recall_history or extension tools, and of the gateway tools only+ # the reads in `schedule_tools.MCP_CLIENT_MCP_TOOLS`. Never the+ # principal's own surface for `content_trust.principal_speaking`.+ from_mcp_client: bool = False# The rostered Person behind this conversation, when one is resolved. The# adapters already pass this to `Executive.chat(person_id=...)`; holding it# on the session too lets tool handlers running mid-turn tell "the approverdiff --git a/packages/core/tests/integration/test_mcp_server_caller.py b/packages/core/tests/integration/test_mcp_server_caller.pynew file mode 100644index 00000000..2986a924--- /dev/null+++ b/packages/core/tests/integration/test_mcp_server_caller.py@@ -0,0 +1,191 @@+"""/mcp answers as the caller the API verified, through the real mounted app.++Drives MCP's streamable HTTP JSON-RPC over the FastAPI app ``create_app``+builds (shared-secret gate, ``caller_gate``, the ``/mcp`` mount), so what+``caller_gate`` puts on ``request.state`` is what the MCP handlers read.+"""+from __future__ import annotations++import asyncio+import json+from collections.abc import Iterator+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock, patch++import httpx+import pytest+from mcp.server.streamable_http_manager import StreamableHTTPSessionManager+from mcp.server.transport_security import TransportSecuritySettings++from openexecutive.api import caller_signing+from openexecutive.memory import episodic+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store++VECTORS = json.loads(+ (Path(__file__).parents[1] / "unit" / "caller_assertion_vectors.json").read_text()+)+OWNER = "[email protected]"+TEAMMATE = "[email protected]"+++def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, int]]:+ db = tmp_path / "mcp_http.db"+ monkeypatch.setattr(episodic, "DB_PATH", db)+ monkeypatch.setattr(people_store, "DB_PATH", db)+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **kw: None)+ episodic.initialize_db(db)+ people_store.initialize_db()+ people_registry.invalidate()+ ids = {+ "principal": people_store.upsert_person(+ full_name="Olivia Owner", is_principal=True, email=OWNER+ ),+ "teammate": people_store.upsert_person(full_name="Ben Teammate", email=TEAMMATE),+ }+ people_registry.invalidate()+ yield ids+ people_registry.invalidate()+++def _app(monkeypatch: pytest.MonkeyPatch, *, signed: bool) -> Any:+ """The API app, and the /mcp endpoint whose session manager each request+ replaces: a manager runs once per instance, and FastMCP's cached one is+ the process's (``run_session_manager``)."""+ from openexecutive.api.main import create_app+ from openexecutive.mcp_server import server as mcp_server++ monkeypatch.delenv("BACKEND_SHARED_SECRET", raising=False)+ if signed:+ monkeypatch.setenv("CALLER_ASSERTION_PUBLIC_KEYS", VECTORS["public_keys"])+ else:+ monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)+ app = create_app()+ endpoint = next(+ getattr(r, "endpoint", None) or getattr(r, "app", None)+ for r in mcp_server._http_app.routes+ if hasattr(getattr(r, "endpoint", None) or getattr(r, "app", None), "session_manager")+ )+ # Restored after the test; each request installs a fresh manager.+ monkeypatch.setattr(endpoint, "session_manager", endpoint.session_manager)+ return app, endpoint+++def _fresh_manager(endpoint: Any) -> StreamableHTTPSessionManager:+ from openexecutive.mcp_server import server as mcp_server++ manager = StreamableHTTPSessionManager(+ app=mcp_server.mcp._mcp_server,+ stateless=True,+ security_settings=TransportSecuritySettings(enable_dns_rebinding_protection=False),+ )+ endpoint.session_manager = manager+ return manager+++def _signed_as(kind: str, email: str = "") -> dict[str, str]:+ token = caller_signing.mint_assertion(+ VECTORS["test_signing_key"], kind=kind, email=email, method="POST", target="/mcp/"+ )+ return {"x-caller-assertion": str(token)}+++def _rpc(app: Any, endpoint: Any, method: str, params: dict[str, Any], headers: dict[str, str]) -> dict[str, Any]:+ manager = _fresh_manager(endpoint)++ async def _go() -> dict[str, Any]:+ async with manager.run():+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ response = await client.post(+ "/mcp/",+ json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params},+ headers={+ "accept": "application/json, text/event-stream",+ "mcp-protocol-version": "2025-06-18",+ **headers,+ },+ )+ assert response.status_code == 200, response.text+ data = [line[5:].strip() for line in response.text.splitlines() if line.startswith("data:")]+ return dict(json.loads(data[-1] if data else response.text))++ return asyncio.run(_go())+++def _read(app: Any, endpoint: Any, uri: str, headers: dict[str, str]) -> dict[str, Any]:+ return _rpc(app, endpoint, "resources/read", {"uri": uri}, headers)+++ ("headers", "allowed"),+ [+ (lambda: _signed_as("user", OWNER), True),+ (lambda: _signed_as("operator"), True),+ (lambda: _signed_as("user", TEAMMATE), False),+ (lambda: {}, False), # a service: signed callers on, no assertion+ ],+)+def test_signed_callers_reach_the_mcp_handlers(+ roster: dict[str, int], monkeypatch: pytest.MonkeyPatch, headers: Any, allowed: bool+) -> None:+ app, endpoint = _app(monkeypatch, signed=True)+ with patch("openexecutive.memory.episodic.list_decisions", return_value=[]):+ out = _read(app, endpoint, "oe://memory/decisions", headers())+ if allowed:+ assert json.loads(out["result"]["contents"][0]["text"]) == []+ else:+ assert "Only the owner can read this." in out["error"]["message"]+++def test_a_signed_in_teammate_reads_the_roster_and_a_service_does_not(+ roster: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ app, endpoint = _app(monkeypatch, signed=True)+ out = _read(app, endpoint, "oe://people/roster", _signed_as("user", TEAMMATE))+ names = {p["full_name"] for p in json.loads(out["result"]["contents"][0]["text"])}+ assert names == {"Olivia Owner", "Ben Teammate"}+ refused = _read(app, endpoint, "oe://people/roster", {})+ assert "Only someone on the team can read this." in refused["error"]["message"]+++def test_open_mode_takes_the_caller_header_at_its_word(+ roster: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ app, endpoint = _app(monkeypatch, signed=False)+ with patch("openexecutive.memory.episodic.list_advice", return_value=[]):+ mine = _read(app, endpoint, "oe://memory/advice", {})+ theirs = _read(app, endpoint, "oe://memory/advice", {"x-caller-email": TEAMMATE})+ assert "result" in mine+ assert "Only the owner can read this." in theirs["error"]["message"]+++ ("headers", "expected"),+ [+ (lambda: _signed_as("user", TEAMMATE), "teammate"),+ (lambda: _signed_as("operator"), "principal"),+ (lambda: {}, None),+ ],+)+def test_ask_executive_asks_as_the_signed_caller(+ roster: dict[str, int], monkeypatch: pytest.MonkeyPatch, headers: Any, expected: str | None+) -> None:+ app, endpoint = _app(monkeypatch, signed=True)+ chat = AsyncMock(return_value="An answer")+ with (+ patch("openexecutive.orchestrator.executive.Executive.chat", new=chat),+ patch("openexecutive.orchestrator.mcp_gateway.get_active_gateway", return_value=None),+ ):+ out = _rpc(+ app, endpoint, "tools/call",+ {"name": "ask_executive", "arguments": {"message": "Top risk?"}}, headers(),+ )+ assert out["result"]["content"][0]["text"] == "An answer"+ kwargs = chat.await_args.kwargs+ person_id = roster[expected] if expected else None+ assert kwargs["person_id"] == person_id+ assert kwargs["session"].from_mcp_client is True+ assert kwargs["session"].caller_person_id == person_iddiff --git a/packages/core/tests/unit/test_caller_assertion.py b/packages/core/tests/unit/test_caller_assertion.pyindex a47acf5b..4d321738 100644--- a/packages/core/tests/unit/test_caller_assertion.py+++ b/packages/core/tests/unit/test_caller_assertion.py@@ -408,11 +408,11 @@ async def test_mcp_asks_as_no_one_once_callers_are_signed(monkeypatch: pytest.Mopatch("openexecutive.orchestrator.executive.Executive.chat", new=chat),):monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)- await mcp_server.ask_executive("hi", caller_email=OWNER)+ await mcp_server.ask_executive("hi")assert chat.await_args.kwargs["person_id"] == 42+ # A call with no request names no one once callers are signed; over+ # HTTP the gate's verdict decides (tests/integration/test_mcp_server_caller.py).monkeypatch.setenv("CALLER_ASSERTION_PUBLIC_KEYS", VECTORS["public_keys"])- await mcp_server.ask_executive("hi", caller_email=OWNER)- assert chat.await_args.kwargs["person_id"] is Noneawait mcp_server.ask_executive("hi")assert chat.await_args.kwargs["person_id"] is Nonediff --git a/packages/core/tests/unit/test_mcp_client_turns.py b/packages/core/tests/unit/test_mcp_client_turns.pynew file mode 100644index 00000000..8731e0ea--- /dev/null+++ b/packages/core/tests/unit/test_mcp_client_turns.py@@ -0,0 +1,369 @@+"""A turn another AI app asks over Open Executive's MCP server+(``Session.from_mcp_client``, set by ``mcp_server.ask_executive``) reads and+advises but never sends, posts, books, schedules, runs or changes anything:+the chat loop neither offers nor runs ``MCP_CLIENT_WITHHELD_TOOLS``, Act as+me or extension tools, and of the gateway tools only the reads in+``MCP_CLIENT_MCP_TOOLS``."""+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 AsyncMock, patch++import pytest++from openexecutive.audit import logger as audit_logger+from openexecutive.audit.logger import AuditLogger, log_event+from openexecutive.departments import registry as dept_registry+from openexecutive.departments import store as dept_store+from openexecutive.memory import episodic+from openexecutive.orchestrator.schedule_tools import (+ MCP_CLIENT_MCP_TOOLS,+ MCP_CLIENT_REFUSAL,+ MCP_CLIENT_WITHHELD_TOOLS,+ PRIVATE_TURN_MCP_TOOLS,+ PRIVATE_TURN_WITHHELD_TOOLS,+ UNATTENDED_WITHHELD_TOOLS,+ current_session,+)+from openexecutive.orchestrator.session import Session+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store+from tests.unit.offered_tools import capture_offered++EXEC = "[email protected]"+OWNER_EMAIL = "[email protected]"+TEAM_EMAIL = "[email protected]"++[email protected](autouse=True)+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:+ path = tmp_path / "mcp_client.db"+ monkeypatch.setattr(people_store, "DB_PATH", path)+ monkeypatch.setattr(episodic, "DB_PATH", path)+ monkeypatch.setattr(dept_store, "DB_PATH", path)+ episodic.initialize_db(path)+ people_store.initialize_db()+ dept_store.initialize_db()+ people_registry.invalidate()+ dept_registry.invalidate()+ monkeypatch.setattr(audit_logger, "_default_logger", AuditLogger(db_path=path))+ token = current_session.set(None)+ yield path+ current_session.reset(token)+ people_registry.invalidate()+ dept_registry.invalidate()+++def roster() -> SimpleNamespace:+ principal = people_store.upsert_person(+ full_name="Olivia Owner", is_principal=True, email=OWNER_EMAIL, slack_user_id="U_OWNER"+ )+ teammate = people_store.upsert_person(+ full_name="Ben Teammate", role="Ops", email=TEAM_EMAIL, slack_user_id="U_BEN"+ )+ people_registry.invalidate()+ return SimpleNamespace(principal=principal, teammate=teammate)+++def _mcp_turn(person_id: int | None) -> Session:+ return Session(from_mcp_client=True, caller_person_id=person_id)+++class _ScriptedStreams:+ def __init__(self, finals: list[Any]) -> None:+ self._finals = list(finals)+ self.calls: list[dict[str, Any]] = []+ self.offered: list[list[str]] = []++ def messages_stream(self, **kwargs: Any) -> Any:+ self.calls.append(kwargs)+ final = self._finals.pop(0)++ class _Stream:+ async def __aenter__(self) -> _Stream:+ return self++ async def __aexit__(self, *_a: Any) -> None:+ return None++ def __aiter__(self) -> _Stream:+ return self++ async def __anext__(self) -> Any:+ raise StopAsyncIteration++ async def get_final_message(self) -> Any:+ return final++ return _Stream()+++def _gateway() -> Any:+ gateway = AsyncMock()+ gateway.load_mcp_server = AsyncMock(return_value=json.dumps({"ok": True}))+ return gateway+++def _run_loop(session: Session, tool_uses: list[Any], gateway: Any = None) -> _ScriptedStreams:+ from openexecutive.orchestrator.executive import Executive+ from openexecutive.orchestrator.schedule_tools import set_session++ finals = []+ if tool_uses:+ finals.append(SimpleNamespace(content=tool_uses, stop_reason="tool_use", usage=None))+ finals.append(+ SimpleNamespace(+ content=[SimpleNamespace(type="text", text="ok")], stop_reason="end_turn", usage=None+ )+ )+ provider = _ScriptedStreams(finals)++ async def _go() -> None:+ with (+ capture_offered() as offered,+ patch("openexecutive.orchestrator.executive.get_provider", return_value=provider),+ patch("openexecutive.orchestrator.executive.audit_log", log_event),+ set_session(session),+ ):+ async for _item in Executive(mcp_gateway=gateway)._stream_agent_loop(+ system_blocks=[],+ messages=[{"role": "user", "content": "x"}],+ model="claude-test",+ workspace_mode="team",+ principal_role_tag="",+ turn_id="t-mcp",+ ):+ pass+ provider.offered = offered++ asyncio.run(_go())+ return provider+++def _results(provider: _ScriptedStreams) -> dict[str, str]:+ return {r["tool_use_id"]: r["content"] for r in provider.calls[1]["messages"][-1]["content"]}+++def _refusals() -> list[Any]:+ return [+ e+ for e in audit_logger.get_audit_logger().query(event_type="tool_invocation", limit=200)+ if e.details.get("refused") == "mcp_client"+ ]+++# --- the sets ---------------------------------------------------------------+++def test_the_withheld_set_starts_from_the_private_and_unattended_sets() -> None:+ assert PRIVATE_TURN_WITHHELD_TOOLS | UNATTENDED_WITHHELD_TOOLS <= MCP_CLIENT_WITHHELD_TOOLS+ for name in (+ "message_person", "send_slack_dm", "send_discord_dm", "send_telegram_message",+ "create_calendar_event", "cancel_calendar_event", "ack_alert", "upsert_person",+ "archive_person", "set_department_head", "close_open_loop", "create_alert",+ ):+ assert name in MCP_CLIENT_WITHHELD_TOOLS+++def test_every_withheld_name_is_a_real_tool() -> None:+ from openexecutive.orchestrator.executive import _ALL_SKILL_HANDLERS, _ALL_SKILL_TOOLS+ from openexecutive.orchestrator.mcp_gateway import MCP_TOOL_NAMES+ from openexecutive.workflows.step_script import LIST_SAVED_TOOLS_TOOL, RUN_SCRIPT_TOOL++ gateway_side = MCP_TOOL_NAMES | {RUN_SCRIPT_TOOL, LIST_SAVED_TOOLS_TOOL}+ assert {t["name"] for t in _ALL_SKILL_TOOLS} | gateway_side >= MCP_CLIENT_WITHHELD_TOOLS+ assert set(_ALL_SKILL_HANDLERS) | gateway_side >= MCP_CLIENT_WITHHELD_TOOLS+++def test_every_tool_left_offered_only_reads() -> None:+ """Pins what such a turn may still run: a new tool that writes must be+ added to the withheld set, not slip in."""+ from openexecutive.orchestrator.executive import _ALL_SKILL_TOOLS++ offered = {t["name"] for t in _ALL_SKILL_TOOLS} - MCP_CLIENT_WITHHELD_TOOLS+ assert offered == {+ "ask_about_person", "find_alerts", "get_artifact", "list_artifacts",+ "list_department_goals", "list_followups", "list_open_loops", "list_people",+ "list_watchlist", "list_workflows", "load_skill", "lookup_person",+ "read_user_guide", "search_skills",+ }+++def test_the_gateway_allow_list_holds_no_send_or_draft() -> None:+ assert MCP_CLIENT_MCP_TOOLS < PRIVATE_TURN_MCP_TOOLS+ for name in MCP_CLIENT_MCP_TOOLS:+ assert "send" not in name and "draft" not in name+++# --- the chat loop ----------------------------------------------------------+++def test_an_mcp_client_turn_is_not_offered_the_withheld_tools(roster: SimpleNamespace) -> None:+ mcp_turn = _run_loop(_mcp_turn(roster.teammate), [], _gateway())+ offered = mcp_turn.offered[0]+ normal = _run_loop(Session(caller_person_id=roster.teammate), [], _gateway()).offered[0]+ assert not MCP_CLIENT_WITHHELD_TOOLS & set(offered)+ # Withheld before the sort: the normal list minus the set, still sorted.+ assert offered == sorted(offered)+ assert offered == [n for n in normal if n not in MCP_CLIENT_WITHHELD_TOOLS]+ assert {"consult_specialist", "search_tools", "call_tool", "list_people"} <= set(offered)+ # Stable: the same prefix on the next such turn.+ assert _run_loop(_mcp_turn(roster.teammate), [], _gateway()).offered[0] == offered+ tools = mcp_turn.calls[0]["tools"]+ client = [t for t in tools if "input_schema" in t]+ assert "cache_control" in client[-1]+++ "tool",+ ["message_person", "send_slack_dm", "create_calendar_event", "ack_alert", "upsert_person"],+)+def test_an_mcp_client_turn_refuses_a_withheld_tool_the_model_emits_anyway(+ roster: SimpleNamespace, tool: str+) -> None:+ from openexecutive.orchestrator import executive as executive_module++ handler = AsyncMock(return_value=json.dumps({"status": "sent"}))+ tool_use = SimpleNamespace(type="tool_use", id="tu-1", name=tool, input={"text": "hi"})+ with patch.dict(executive_module._ALL_SKILL_HANDLERS, {tool: handler}):+ provider = _run_loop(_mcp_turn(roster.principal), [tool_use])+ handler.assert_not_awaited()+ error = json.loads(_results(provider)["tu-1"])["error"]+ assert tool in error and MCP_CLIENT_REFUSAL in error+ assert [e.details["tool"] for e in _refusals()] == [tool]+++def test_an_mcp_client_turn_refuses_through_use_tool(roster: SimpleNamespace) -> None:+ from openexecutive.orchestrator import executive as executive_module++ handler = AsyncMock(return_value=json.dumps({"status": "sent"}))+ use = SimpleNamespace(+ type="tool_use", id="tu-1", name="use_tool",+ input={"name": "send_company_broadcast", "input": {"text": "hi"}},+ )+ with patch.dict(executive_module._ALL_SKILL_HANDLERS, {"send_company_broadcast": handler}):+ provider = _run_loop(_mcp_turn(roster.principal), [use])+ handler.assert_not_awaited()+ assert MCP_CLIENT_REFUSAL in json.loads(_results(provider)["tu-1"])["error"]+++def test_an_mcp_client_turn_gets_no_act_as_me_or_extension_tools(+ roster: SimpleNamespace,+) -> None:+ from openexecutive.delegation import settings as delegation_settings+ from openexecutive.orchestrator.delegation_tools import DELEGATION_TOOL_HANDLERS++ # Even with Act as me on and pinned as offered, the turn is not offered it.+ pinned = SimpleNamespace(offered=True)+ with (+ patch("openexecutive.orchestrator.executive.turn_delegation", return_value=pinned),+ patch(+ "openexecutive.orchestrator.executive.extensions.offered_tools",+ side_effect=AssertionError("extensions are not offered"),+ ),+ ):+ offered = _run_loop(_mcp_turn(roster.principal), []).offered[0]+ assert not set(DELEGATION_TOOL_HANDLERS) & set(offered)+ assert "recall_history" not in offered+ # And Act as me is never pinned as offered on such a turn.+ assert delegation_settings._offered(_mcp_turn(roster.principal), None, True) is False+++def test_an_mcp_client_turn_refuses_load_mcp_server(roster: SimpleNamespace) -> None:+ gateway = _gateway()+ tool_use = SimpleNamespace(+ type="tool_use", id="tu-1", name="load_mcp_server",+ input={"name": "x", "url": "https://collector.example/mcp"},+ )+ provider = _run_loop(_mcp_turn(roster.principal), [tool_use], gateway)+ gateway.load_mcp_server.assert_not_awaited()+ assert "load_mcp_server" not in provider.offered[0]+ assert MCP_CLIENT_REFUSAL in json.loads(_results(provider)["tu-1"])["error"]+++# --- gateway tools: reads only ----------------------------------------------++_SEARCH_TEXT = (+ "Found 3 matching tool(s). Use `call_tool` with the tool name and arguments "+ "to invoke one.\n\n"+ + "\n".join(+ "\n".join([f"## {name}", f"**Description:** {desc}", "**Parameters:**",+ '```json\n{"type": "object"}\n```', "**Similarity:** 0.800", ""])+ for name, desc in [+ ("google_workspace__send_gmail_message", "Send an email."),+ ("google_workspace__search_drive_files", "Search Drive."),+ ("slack__post_message", "Post to Slack."),+ ]+ )+)+++def _real_gateway() -> tuple[Any, list[tuple[str, dict[str, Any]]]]:+ from openexecutive.orchestrator.mcp_gateway import MCPGateway++ reached: list[tuple[str, dict[str, Any]]] = []++ async def _call(name: str, args: dict[str, Any]) -> Any:+ reached.append((name, args))+ text = _SEARCH_TEXT if name == "search_tools" else json.dumps({"ok": True})+ return SimpleNamespace(content=[SimpleNamespace(text=text)])++ gateway = MCPGateway()+ gateway._session = SimpleNamespace(call_tool=_call)+ return gateway, reached+++def test_an_mcp_client_turn_reaches_gateway_reads_only(roster: SimpleNamespace) -> None:+ import openexecutive.orchestrator.mcp_gateway as gw_module++ def _call(i: int, tool: str, arguments: dict[str, Any]) -> Any:+ return SimpleNamespace(+ type="tool_use", id=f"tu-{i}", name="call_tool",+ input={"name": tool, "arguments": arguments},+ )++ uses = [+ SimpleNamespace(type="tool_use", id="tu-1", name="search_tools", input={"query": "x"}),+ _call(2, "google_workspace__send_gmail_message",+ {"to": OWNER_EMAIL, "subject": "s", "body": "b"}),+ _call(3, "google_workspace__draft_gmail_message",+ {"to": OWNER_EMAIL, "subject": "s", "body": "b"}),+ _call(4, "slack__post_message", {"channel": "#all", "text": "hi"}),+ _call(5, "google_workspace__search_drive_files", {"query": "plan", "user_google_email": EXEC}),+ ]+ gateway, reached = _real_gateway()+ with patch.object(+ gw_module, "get_settings", return_value=SimpleNamespace(exec_email_address=EXEC)+ ):+ provider = _run_loop(_mcp_turn(roster.principal), uses, gateway)+ results = _results(provider)+ # A search shows only the reads.+ assert "google_workspace__search_drive_files" in results["tu-1"]+ assert "send_gmail_message" not in results["tu-1"] and "slack__" not in results["tu-1"]+ for refused in ("tu-2", "tu-3", "tu-4"):+ assert MCP_CLIENT_REFUSAL in json.loads(results[refused])["error"]+ called = [args["tool_name"] for name, args in reached if name == "call_tool"]+ assert called == ["google_workspace__search_drive_files"]+++def test_the_gateway_itself_refuses_a_send_on_an_mcp_client_turn(roster: SimpleNamespace) -> None:+ from openexecutive.orchestrator.schedule_tools import set_session++ gateway, reached = _real_gateway()++ async def _go() -> str:+ with set_session(_mcp_turn(roster.principal)):+ return str(await gateway.call_tool({+ "name": "google_workspace__send_gmail_message",+ "arguments": {"to": OWNER_EMAIL, "subject": "s", "body": "b"},+ }))++ out = asyncio.run(_go())+ assert MCP_CLIENT_REFUSAL in json.loads(out)["error"]+ assert reached == []diff --git a/packages/core/tests/unit/test_mcp_server.py b/packages/core/tests/unit/test_mcp_server.pyindex 09ee0f36..b8dc6547 100644--- a/packages/core/tests/unit/test_mcp_server.py+++ b/packages/core/tests/unit/test_mcp_server.py@@ -14,7 +14,46 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from openexecutive.api.caller import Callerfrom openexecutive.mcp_server import server as mcp_server+from openexecutive.memory import episodic+from openexecutive.people import registry as people_registry+from openexecutive.people import store as people_store++OWNER = "[email protected]"+TEAMMATE = "[email protected]"++[email protected](autouse=True)+def roster_db(tmp_path: Any, monkeypatch: pytest.MonkeyPatch) -> Any:+ """Every handler resolves its caller against the roster: keep that read+ on a tmp file, never ./episodic_memory.db."""+ path = tmp_path / "mcp_server.db"+ monkeypatch.setattr(people_store, "DB_PATH", path)+ monkeypatch.setattr(episodic, "DB_PATH", path)+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **kw: None)+ episodic.initialize_db(path)+ people_store.initialize_db()+ people_registry.invalidate()+ yield path+ people_registry.invalidate()+++def roster() -> dict[str, int]:+ ids = {+ "principal": people_store.upsert_person(+ full_name="Olivia Owner", is_principal=True, email=OWNER+ ),+ "teammate": people_store.upsert_person(full_name="Ben Teammate", email=TEAMMATE),+ }+ people_registry.invalidate()+ return ids+++def _as(who: Caller) -> Any:+ """Run a handler as if the verified request named ``who``."""+ return patch.object(mcp_server, "_who", return_value=who)class _Dumpable:@@ -174,30 +213,182 @@ async def test_list_workflows_returns_catalog() -> None:assert all("name" in w for w in data)-async def test_ask_executive_resolves_principal_and_calls_chat() -> None:+def _ask(who: Caller) -> tuple[str, Any]:profile = _Dumpable({})profile.is_empty = lambda: True # type: ignore[attr-defined]-- class _Person:- id = 42-chat = AsyncMock(return_value="Executive answer")- with (- patch(- "openexecutive.onboarding.profile_builder.load_or_create_profile",- return_value=profile,- ),- patch(- "openexecutive.people.store.find_principal_person",- return_value=_Person(),- ),- patch("openexecutive.orchestrator.mcp_gateway.get_active_gateway", return_value=None),- patch("openexecutive.orchestrator.executive.Executive.chat", new=chat),- ):- out = await mcp_server.ask_executive("What's our top risk?")++ async def _go() -> str:+ with (+ _as(who),+ patch(+ "openexecutive.onboarding.profile_builder.load_or_create_profile",+ return_value=profile,+ ),+ patch("openexecutive.orchestrator.mcp_gateway.get_active_gateway", return_value=None),+ patch("openexecutive.orchestrator.executive.Executive.chat", new=chat),+ ):+ return await mcp_server.ask_executive("What's our top risk?")++ import asyncio++ return asyncio.run(_go()), chat+++ ("who", "expected"),+ [+ (Caller("open"), "principal"),+ (Caller("operator"), "principal"),+ (Caller("open", TEAMMATE), "teammate"),+ (Caller("user", TEAMMATE), "teammate"),+ (Caller("user", OWNER), "principal"),+ (Caller("user", "[email protected]"), None),+ (Caller("service"), None),+ ],+)+def test_ask_executive_asks_as_the_verified_caller(+ roster: dict[str, int], who: Caller, expected: str | None+) -> None:+ out, chat = _ask(who)assert out == "Executive answer"- assert chat.await_args.kwargs["person_id"] == 42+ person_id = roster[expected] if expected else None+ kwargs = chat.await_args.kwargs+ assert kwargs["person_id"] == person_id+ session = kwargs["session"]+ assert session.from_mcp_client is True+ assert session.caller_person_id == person_id+ from openexecutive.orchestrator.artifact_records import NOBODY++ assert (session.documents_viewer is NOBODY) is (person_id is None)+++def test_ask_executive_takes_no_caller_argument() -> None:+ import inspect++ assert list(inspect.signature(mcp_server.ask_executive).parameters) == ["message"]+++def test_with_no_request_the_caller_is_who_a_request_naming_no_one_would_be(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)+ assert mcp_server._who() == Caller("open")+ monkeypatch.setenv("CALLER_ASSERTION_PUBLIC_KEYS", "k:" + "A" * 43)+ assert mcp_server._who() == Caller("service")+++# ---------------------------------------------------------------------------+# Who may read what.+# ---------------------------------------------------------------------------+_OWNER_ONLY = ["memory_decisions", "memory_initiatives", "memory_advice", "today_activity"]+_ROSTER_ONLY = ["today_briefing", "people_roster"]+++def _read(name: str, who: Caller) -> str:+ import asyncio++ async def _go() -> str:+ with (+ _as(who),+ patch("openexecutive.memory.episodic.list_decisions", return_value=[]),+ patch("openexecutive.memory.episodic.list_initiatives", return_value=[]),+ patch("openexecutive.memory.episodic.list_advice", return_value=[]),+ patch(+ "openexecutive.api.routes.today._build_activity",+ return_value=_Dumpable({"items": []}),+ ),+ patch(+ "openexecutive.api.routes.today._build_today",+ return_value=_Dumpable({"people": []}),+ ),+ patch("openexecutive.departments.store.list_departments", return_value=[]),+ ):+ return str(await getattr(mcp_server, name)())++ return asyncio.run(_go())++[email protected]("name", _OWNER_ONLY)+ "who", [Caller("open"), Caller("operator"), Caller("user", OWNER), Caller("open", OWNER)]+)+def test_the_owner_reads_their_own_records(roster: dict[str, int], name: str, who: Caller) -> None:+ json.loads(_read(name, who))++[email protected]("name", _OWNER_ONLY)+ "who",+ [+ Caller("user", TEAMMATE),+ Caller("open", TEAMMATE),+ Caller("user", "[email protected]"),+ Caller("service"),+ ],+)+def test_no_one_else_reads_the_owners_records(+ roster: dict[str, int], name: str, who: Caller+) -> None:+ with pytest.raises(mcp_server.CallerRefused, match="Only the owner can read this."):+ _read(name, who)++[email protected]("name", _ROSTER_ONLY)+def test_a_teammate_reads_the_briefing_and_roster_but_a_service_does_not(+ roster: dict[str, int], name: str+) -> None:+ json.loads(_read(name, Caller("user", TEAMMATE)))+ for nobody in (Caller("service"), Caller("user", "[email protected]")):+ with pytest.raises(mcp_server.CallerRefused):+ _read(name, nobody)+++def test_anyone_reads_the_departments(roster: dict[str, int]) -> None:+ assert json.loads(_read("departments_state", Caller("service"))) == []+++def test_the_briefing_is_narrowed_as_get_today_narrows_it(roster: dict[str, int]) -> None:+ import asyncio++ def _briefing(who: Caller) -> Any:+ build = patch(+ "openexecutive.api.routes.today._build_today",+ return_value=_Dumpable({"people": []}),+ )++ async def _go() -> Any:+ with _as(who), build as built:+ await mcp_server.today_briefing()+ return built++ return asyncio.run(_go())++ owner = _briefing(Caller("user", OWNER)).call_args.kwargs+ assert owner["include_private"] is True+ assert owner["viewer"].person_id == roster["principal"] and owner["viewer"].is_principal+ mate = _briefing(Caller("user", TEAMMATE)).call_args.kwargs+ assert mate["include_private"] is False+ assert mate["viewer"].person_id == roster["teammate"] and not mate["viewer"].is_principal+++async def test_tools_carry_titles_and_annotations() -> None:+ tools = {t.name: t for t in await mcp_server.mcp.list_tools()}+ for name in ("consult_specialist", "search_knowledge", "list_workflows"):+ ann = tools[name].annotations+ assert tools[name].title+ assert ann is not None and ann.readOnlyHint is True and ann.openWorldHint is False+ ask = tools["ask_executive"]+ assert ask.title and ask.annotations is not None+ assert ask.annotations.readOnlyHint is False+ assert ask.annotations.destructiveHint is False+ assert ask.annotations.idempotentHint is False+ assert ask.annotations.openWorldHint is False+ # Factual descriptions: no steering between tools.+ for tool in tools.values():+ assert "fallback" not in (tool.description or "").lower()+ assert "prefer" not in (tool.description or "").lower()# ---------------------------------------------------------------------------@@ -241,3 +432,12 @@ def test_mcp_endpoint_is_gated_by_shared_secret(follow_redirects=False,)assert with_key.status_code != 401+++def test_an_mcp_call_with_no_http_request_names_no_one(monkeypatch: pytest.MonkeyPatch) -> None:+ from types import SimpleNamespace++ monkeypatch.delenv("CALLER_ASSERTION_PUBLIC_KEYS", raising=False)+ context = SimpleNamespace(request_context=SimpleNamespace(request=None))+ with patch.object(mcp_server.mcp, "get_context", return_value=context):+ assert mcp_server._who() == Caller("service")